@opendatalabs/vana-sdk 0.1.0-alpha.a25bcc7 → 0.1.0-alpha.a6b60fc

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (165) hide show
  1. package/dist/browser.cjs.map +1 -1
  2. package/dist/browser.d.ts +33 -1
  3. package/dist/browser.js.map +1 -1
  4. package/dist/chains/index.cjs.map +1 -1
  5. package/dist/chains/index.d.ts +30 -1
  6. package/dist/chains/index.js.map +1 -1
  7. package/dist/config/chains.cjs.map +1 -1
  8. package/dist/config/chains.d.ts +99 -0
  9. package/dist/config/chains.js.map +1 -1
  10. package/dist/contracts/contractController.cjs.map +1 -1
  11. package/dist/contracts/contractController.d.ts +66 -10
  12. package/dist/contracts/contractController.js.map +1 -1
  13. package/dist/controllers/data.cjs +172 -140
  14. package/dist/controllers/data.cjs.map +1 -1
  15. package/dist/controllers/data.d.ts +213 -175
  16. package/dist/controllers/data.js +172 -140
  17. package/dist/controllers/data.js.map +1 -1
  18. package/dist/controllers/permissions.cjs +184 -190
  19. package/dist/controllers/permissions.cjs.map +1 -1
  20. package/dist/controllers/permissions.d.ts +29 -73
  21. package/dist/controllers/permissions.js +184 -190
  22. package/dist/controllers/permissions.js.map +1 -1
  23. package/dist/controllers/protocol.cjs.map +1 -1
  24. package/dist/controllers/protocol.d.ts +27 -28
  25. package/dist/controllers/protocol.js.map +1 -1
  26. package/dist/controllers/schemas.cjs +19 -17
  27. package/dist/controllers/schemas.cjs.map +1 -1
  28. package/dist/controllers/schemas.d.ts +47 -40
  29. package/dist/controllers/schemas.js +19 -17
  30. package/dist/controllers/schemas.js.map +1 -1
  31. package/dist/controllers/server.cjs +17 -15
  32. package/dist/controllers/server.cjs.map +1 -1
  33. package/dist/controllers/server.d.ts +46 -38
  34. package/dist/controllers/server.js +17 -15
  35. package/dist/controllers/server.js.map +1 -1
  36. package/dist/core/apiClient.cjs +53 -3
  37. package/dist/core/apiClient.cjs.map +1 -1
  38. package/dist/core/apiClient.d.ts +132 -7
  39. package/dist/core/apiClient.js +53 -3
  40. package/dist/core/apiClient.js.map +1 -1
  41. package/dist/core/generics.cjs +30 -3
  42. package/dist/core/generics.cjs.map +1 -1
  43. package/dist/core/generics.d.ts +95 -6
  44. package/dist/core/generics.js +30 -3
  45. package/dist/core/generics.js.map +1 -1
  46. package/dist/core.cjs +29 -12
  47. package/dist/core.cjs.map +1 -1
  48. package/dist/core.d.ts +2 -1
  49. package/dist/core.js +29 -12
  50. package/dist/core.js.map +1 -1
  51. package/dist/index.cjs.map +1 -1
  52. package/dist/index.js.map +1 -1
  53. package/dist/index.node.cjs +3 -3
  54. package/dist/index.node.cjs.map +1 -1
  55. package/dist/index.node.d.ts +8 -9
  56. package/dist/index.node.js +2 -2
  57. package/dist/index.node.js.map +1 -1
  58. package/dist/node.cjs.map +1 -1
  59. package/dist/node.d.ts +39 -1
  60. package/dist/node.js.map +1 -1
  61. package/dist/platform/browser.cjs +160 -2
  62. package/dist/platform/browser.cjs.map +1 -1
  63. package/dist/platform/browser.d.ts +232 -12
  64. package/dist/platform/browser.js +160 -2
  65. package/dist/platform/browser.js.map +1 -1
  66. package/dist/platform/interface.cjs.map +1 -1
  67. package/dist/platform/interface.d.ts +283 -90
  68. package/dist/platform/node.cjs +163 -2
  69. package/dist/platform/node.cjs.map +1 -1
  70. package/dist/platform/node.d.ts +69 -6
  71. package/dist/platform/node.js +163 -2
  72. package/dist/platform/node.js.map +1 -1
  73. package/dist/server/relayerHandler.cjs +214 -0
  74. package/dist/server/relayerHandler.cjs.map +1 -0
  75. package/dist/server/relayerHandler.d.ts +36 -0
  76. package/dist/server/relayerHandler.js +190 -0
  77. package/dist/server/relayerHandler.js.map +1 -0
  78. package/dist/storage/manager.cjs +108 -25
  79. package/dist/storage/manager.cjs.map +1 -1
  80. package/dist/storage/manager.d.ts +119 -25
  81. package/dist/storage/manager.js +108 -25
  82. package/dist/storage/manager.js.map +1 -1
  83. package/dist/storage/providers/callback-storage.cjs +86 -15
  84. package/dist/storage/providers/callback-storage.cjs.map +1 -1
  85. package/dist/storage/providers/callback-storage.d.ts +109 -20
  86. package/dist/storage/providers/callback-storage.js +86 -15
  87. package/dist/storage/providers/callback-storage.js.map +1 -1
  88. package/dist/storage/providers/pinata.cjs.map +1 -1
  89. package/dist/storage/providers/pinata.d.ts +12 -14
  90. package/dist/storage/providers/pinata.js.map +1 -1
  91. package/dist/tests/factories/mockFactory.d.ts +2 -2
  92. package/dist/tests/relayer-integration.test.d.ts +1 -0
  93. package/dist/tests/relayer-unified.test.d.ts +1 -0
  94. package/dist/tests/server-relayer-handler.test.d.ts +1 -0
  95. package/dist/types/blockchain.cjs.map +1 -1
  96. package/dist/types/blockchain.d.ts +39 -11
  97. package/dist/types/chains.cjs.map +1 -1
  98. package/dist/types/chains.d.ts +74 -7
  99. package/dist/types/chains.js.map +1 -1
  100. package/dist/types/config.cjs.map +1 -1
  101. package/dist/types/config.d.ts +46 -191
  102. package/dist/types/config.js.map +1 -1
  103. package/dist/types/contracts.cjs.map +1 -1
  104. package/dist/types/contracts.d.ts +71 -7
  105. package/dist/types/controller-context.cjs.map +1 -1
  106. package/dist/types/controller-context.d.ts +3 -2
  107. package/dist/types/data.cjs.map +1 -1
  108. package/dist/types/data.d.ts +4 -6
  109. package/dist/types/generics.cjs.map +1 -1
  110. package/dist/types/generics.d.ts +80 -9
  111. package/dist/types/index.cjs.map +1 -1
  112. package/dist/types/index.d.ts +27 -2
  113. package/dist/types/index.js.map +1 -1
  114. package/dist/types/operations.cjs.map +1 -1
  115. package/dist/types/operations.d.ts +132 -15
  116. package/dist/types/operations.js.map +1 -1
  117. package/dist/types/permissions.cjs.map +1 -1
  118. package/dist/types/permissions.d.ts +15 -20
  119. package/dist/types/personal.cjs.map +1 -1
  120. package/dist/types/personal.d.ts +131 -14
  121. package/dist/types/relayer.cjs.map +1 -1
  122. package/dist/types/relayer.d.ts +262 -35
  123. package/dist/types/storage.cjs.map +1 -1
  124. package/dist/types/storage.d.ts +9 -21
  125. package/dist/types/storage.js.map +1 -1
  126. package/dist/utils/grantFiles.cjs.map +1 -1
  127. package/dist/utils/grantFiles.d.ts +10 -20
  128. package/dist/utils/grantFiles.js.map +1 -1
  129. package/dist/utils/grantValidation.cjs.map +1 -1
  130. package/dist/utils/grantValidation.d.ts +95 -16
  131. package/dist/utils/grantValidation.js.map +1 -1
  132. package/dist/utils/grants.cjs.map +1 -1
  133. package/dist/utils/grants.d.ts +93 -12
  134. package/dist/utils/grants.js.map +1 -1
  135. package/dist/utils/lazy-import.cjs.map +1 -1
  136. package/dist/utils/lazy-import.d.ts +32 -7
  137. package/dist/utils/lazy-import.js.map +1 -1
  138. package/dist/utils/signatureCache.cjs +8 -2
  139. package/dist/utils/signatureCache.cjs.map +1 -1
  140. package/dist/utils/signatureCache.d.ts +49 -8
  141. package/dist/utils/signatureCache.js +8 -2
  142. package/dist/utils/signatureCache.js.map +1 -1
  143. package/dist/utils/transactionHelpers.cjs.map +1 -1
  144. package/dist/utils/transactionHelpers.d.ts +12 -12
  145. package/dist/utils/transactionHelpers.js.map +1 -1
  146. package/dist/utils/typedDataConverter.cjs.map +1 -1
  147. package/dist/utils/typedDataConverter.d.ts +39 -3
  148. package/dist/utils/typedDataConverter.js.map +1 -1
  149. package/dist/utils/urlResolver.cjs +7 -0
  150. package/dist/utils/urlResolver.cjs.map +1 -1
  151. package/dist/utils/urlResolver.d.ts +22 -4
  152. package/dist/utils/urlResolver.js +7 -0
  153. package/dist/utils/urlResolver.js.map +1 -1
  154. package/dist/utils/wallet.cjs +2 -1
  155. package/dist/utils/wallet.cjs.map +1 -1
  156. package/dist/utils/wallet.d.ts +78 -16
  157. package/dist/utils/wallet.js +2 -1
  158. package/dist/utils/wallet.js.map +1 -1
  159. package/package.json +1 -1
  160. package/dist/server/handler.cjs +0 -101
  161. package/dist/server/handler.cjs.map +0 -1
  162. package/dist/server/handler.d.ts +0 -87
  163. package/dist/server/handler.js +0 -77
  164. package/dist/server/handler.js.map +0 -1
  165. /package/dist/tests/{server-handler.test.d.ts → permissions-revoke-relayer.test.d.ts} +0 -0
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/controllers/server.ts"],"sourcesContent":["import type {\n CreateOperationParams,\n InitPersonalServerParams,\n PersonalServerIdentity,\n} from \"../types\";\nimport type {\n CreateOperationResponse,\n GetOperationResponse,\n IdentityResponseModel,\n} from \"../generated/server/server-exports\";\nimport {\n NetworkError,\n SerializationError,\n SignatureError,\n PersonalServerError,\n} from \"../errors\";\nimport type { ControllerContext } from \"./permissions\";\nimport type { Operation, PollingOptions } from \"../types/operations\";\nimport { BaseController } from \"./base\";\n\n// Server types are now auto-imported from the generated exports\n\n/**\n * Manages interactions with Vana personal servers and identity infrastructure.\n *\n * @remarks\n * This controller handles communication with personal servers for data processing\n * and identity servers for public key derivation. It provides methods for posting\n * computation requests to personal servers, polling for results, and retrieving\n * cryptographic keys for secure data sharing. All server interactions use the\n * Replicate API infrastructure with proper authentication and error handling.\n *\n * **Server Identity System:**\n * Personal servers use deterministic key derivation: each user address maps to a specific server identity.\n * This enables secure communication without requiring servers to be online during key retrieval.\n *\n * **Method Selection:**\n * - `getIdentity()` retrieves server public keys and addresses for encryption setup\n * - `createOperation()` submits computation requests with signed permission verification\n * - `getOperation()` polls operation status and retrieves results when complete\n * - `cancelOperation()` stops running operations when cancellation is supported\n *\n * **Workflow Pattern:**\n * Typical flow: Get identity → Create operation → Poll status → Retrieve results\n *\n * @example\n * ```typescript\n * // Get a server's identity including public key for encryption\n * const identity = await vana.server.getIdentity({\n * userAddress: \"0x742d35Cc6558Fd4D9e9E0E888F0462ef6919Bd36\"\n * });\n *\n * // Create an operation using a granted permission\n * const response = await vana.server.createOperation({\n * permissionId: 123,\n * });\n *\n * // Poll for computation results\n * const result = await vana.server.getOperation(response.id);\n * ```\n * @category Server Management\n * @see {@link https://docs.vana.com/developer/personal-servers | Vana Personal Servers} for conceptual overview\n */\nexport class ServerController extends BaseController {\n constructor(context: ControllerContext) {\n super(context);\n }\n\n private get personalServerBaseUrl(): string {\n if (!this.context.defaultPersonalServerUrl) {\n throw new PersonalServerError(\n \"Personal server URL is required for server operations. \" +\n \"Please configure defaultPersonalServerUrl in your VanaConfig.\",\n );\n }\n return this.context.defaultPersonalServerUrl;\n }\n\n /**\n * Retrieves the cryptographic identity of a personal server.\n *\n * @remarks\n * This method fetches the public key and metadata for a personal server,\n * which is required for encrypting data before sharing with the server.\n * The identity includes the server's public key, address, and operational\n * details needed for secure communication. This information is cached\n * by identity servers to enable offline key retrieval.\n *\n * @param request - Parameters containing the user address\n * @param request.userAddress - The wallet address associated with the personal server\n * @returns Promise resolving to the server's identity information\n * @throws {NetworkError} When the identity service is unavailable or returns invalid data\n * @throws {PersonalServerError} When server identity cannot be retrieved\n * @example\n * ```typescript\n * // Get server identity for data encryption\n * const identity = await vana.server.getIdentity({\n * userAddress: \"0x742d35Cc6558Fd4D9e9E0E888F0462ef6919Bd36\"\n * });\n *\n * console.log(`Server: ${identity.name}`);\n * console.log(`Address: ${identity.address}`);\n * console.log(`Public Key: ${identity.publicKey}`);\n *\n * // Use the public key for encrypting data to share with this server\n * const encryptedData = await encryptWithWalletPublicKey(\n * userData,\n * identity.publicKey\n * );\n * ```\n */\n async getIdentity(\n request: InitPersonalServerParams,\n ): Promise<PersonalServerIdentity> {\n try {\n const response = await fetch(\n `${this.personalServerBaseUrl}/identity?address=${request.userAddress}`,\n {\n method: \"GET\",\n headers: {\n \"Content-Type\": \"application/json\",\n },\n },\n );\n\n console.debug(\"🔍 Debug - getIdentity response\", response);\n if (!response.ok) {\n const errorText = await response.text();\n throw new NetworkError(\n `Local identity API request failed: ${response.status} ${response.statusText} - ${errorText}`,\n );\n }\n\n const serverResponse = (await response.json()) as IdentityResponseModel;\n\n return {\n kind: serverResponse.personal_server.kind,\n address: serverResponse.personal_server.address,\n publicKey: serverResponse.personal_server.public_key,\n baseUrl: this.personalServerBaseUrl,\n name: \"Hosted Vana Server\",\n };\n } catch (error) {\n if (\n error instanceof NetworkError ||\n error instanceof PersonalServerError\n ) {\n throw error;\n }\n throw new PersonalServerError(\n `Failed to get personal server identity: ${error instanceof Error ? error.message : \"Unknown error\"}`,\n );\n }\n }\n\n /**\n * Creates a server operation and returns its details as a plain object.\n *\n * @remarks\n * This method submits a computation request to the personal server and returns\n * an Operation object that can be serialized and passed across API boundaries.\n * Use `waitForOperation()` to poll for completion.\n *\n * @param params - The operation request parameters\n * @param params.permissionId - The permission ID authorizing this operation.\n * Obtain via `vana.permissions.getUserPermissionGrantsOnChain()`.\n * @returns An Operation object containing the operation ID and status\n * @throws {PersonalServerError} When the server request fails or parameters are invalid\n * @throws {NetworkError} When personal server API communication fails\n * @example\n * ```typescript\n * const operation = await vana.server.createOperation({\n * permissionId: 123\n * });\n * console.log(`Operation ID: ${operation.id}`);\n *\n * // Wait for completion\n * const result = await vana.server.waitForOperation(operation.id);\n * console.log(\"Result:\", result.result);\n * ```\n */\n async createOperation<T = unknown>(\n params: CreateOperationParams,\n ): Promise<Operation<T>> {\n this.assertWallet();\n\n try {\n const requestData = {\n permission_id: params.permissionId,\n };\n\n const requestJson = JSON.stringify(requestData);\n\n const signature = await this.createSignature(requestJson);\n\n const requestBody = {\n app_signature: signature,\n operation_request_json: requestJson,\n };\n\n // Step 5: Make request to personal server API\n console.debug(\"🔍 Debug - createOperation requestBody\", requestBody);\n const response = await this.makeRequest(requestBody);\n\n return {\n id: response.id,\n status: \"starting\",\n createdAt: Date.now(),\n } as Operation<T>;\n } catch (error) {\n if (error instanceof Error) {\n // Re-throw known Vana errors directly\n if (\n error instanceof NetworkError ||\n error instanceof SerializationError ||\n error instanceof SignatureError ||\n error instanceof PersonalServerError\n ) {\n throw error;\n }\n // Wrap unknown errors\n throw new PersonalServerError(\n `Personal server operation creation failed: ${error.message}`,\n error,\n );\n }\n throw new PersonalServerError(\n \"Personal server operation creation failed with unknown error\",\n );\n }\n }\n\n /**\n * Retrieves the current status and result of a server operation.\n *\n * @remarks\n * Common status values: `starting`, `running`, `succeeded`, `failed`, `canceled`.\n * When status is `succeeded`, the result field contains the operation output.\n *\n * @param operationId - The ID of the operation to query\n * @returns The operation as a plain object containing status, result, and metadata\n * @throws {NetworkError} When the API request fails or returns invalid data\n * @example\n * ```typescript\n * const operation = await vana.server.getOperation(operationId);\n * if (operation.status === 'succeeded') {\n * console.log('Result:', operation.result);\n * }\n * ```\n */\n async getOperation<T = unknown>(operationId: string): Promise<Operation<T>> {\n try {\n console.debug(\"Polling Operation Status:\", operationId);\n\n const response = await fetch(\n `${this.personalServerBaseUrl}/operations/${operationId}`,\n {\n method: \"GET\",\n headers: {\n \"Content-Type\": \"application/json\",\n },\n },\n );\n\n if (!response.ok) {\n const errorText = await response.text();\n console.debug(\"Polling Error Response:\", {\n status: response.status,\n statusText: response.statusText,\n error: errorText,\n });\n throw new NetworkError(\n `Status polling failed: ${response.status} ${response.statusText} - ${errorText}`,\n );\n }\n\n const data = (await response.json()) as GetOperationResponse;\n\n console.debug(\"Polling Success Response:\", data);\n\n return {\n id: data.id,\n status: data.status as Operation[\"status\"],\n createdAt: Date.now(),\n updatedAt: Date.now(),\n result: data.status === \"succeeded\" ? (data.result as T) : undefined,\n error:\n data.status === \"failed\" ? (data.result ?? undefined) : undefined,\n };\n } catch (error) {\n if (error instanceof NetworkError) {\n throw error;\n }\n throw new NetworkError(\n `Failed to poll status: ${error instanceof Error ? error.message : \"Unknown error\"}`,\n );\n }\n }\n\n /**\n * Waits for an operation to complete and returns the final result.\n *\n * @remarks\n * This method polls the operation status at regular intervals until it\n * reaches a terminal state (succeeded, failed, or canceled). Supports\n * ergonomic overloads to accept either an Operation object or just the ID.\n *\n * @param opOrId - Either an Operation object or operation ID string\n * @param options - Optional polling configuration\n * @returns The completed operation with result or error\n * @throws {PersonalServerError} When the operation fails or times out\n * @example\n * ```typescript\n * // Using operation object\n * const operation = await vana.server.createOperation({ permissionId: 123 });\n * const completed = await vana.server.waitForOperation(operation);\n *\n * // Using just the ID\n * const completed = await vana.server.waitForOperation(\"op_abc123\");\n *\n * // With custom timeout\n * const completed = await vana.server.waitForOperation(operation, {\n * timeout: 60000,\n * pollingInterval: 1000\n * });\n * ```\n */\n async waitForOperation<T = unknown>(\n opOrId: Operation<T> | string,\n options?: PollingOptions,\n ): Promise<Operation<T>> {\n const id = typeof opOrId === \"string\" ? opOrId : opOrId.id;\n const startTime = Date.now();\n const timeout = options?.timeout ?? 30000;\n const interval = options?.pollingInterval ?? 500;\n\n while (true) {\n const operation = await this.getOperation<T>(id);\n\n if (operation.status === \"succeeded\") {\n return operation;\n }\n\n if (operation.status === \"failed\") {\n throw new PersonalServerError(\n `Operation ${operation.status}: ${operation.error ?? \"Unknown error\"}`,\n );\n }\n\n if (operation.status === \"canceled\") {\n throw new PersonalServerError(`Operation was canceled`);\n }\n\n if (Date.now() - startTime > timeout) {\n throw new PersonalServerError(`Operation timed out after ${timeout}ms`);\n }\n\n await new Promise((resolve) => setTimeout(resolve, interval));\n }\n }\n\n /**\n * Cancels a running operation on the personal server.\n *\n * @remarks\n * This method attempts to cancel an operation that is currently processing\n * on the personal server. The operation must be in a cancellable state\n * (typically `starting` or `processing`). Not all operations support\n * cancellation, and cancellation may not be immediate. The server will\n * attempt to stop the operation and update its status to `canceled`.\n *\n * **Cancellation Behavior:**\n * - Operations in `succeeded` or `failed` states cannot be canceled\n * - Some long-running operations may take time to respond to cancellation\n * - Always verify cancellation by polling the operation status afterward\n *\n * @param operationId - The unique identifier of the operation to cancel,\n * obtained from `createOperation()` response\n * @returns Promise that resolves when the cancellation request is accepted\n * @throws {PersonalServerError} When the operation cannot be canceled or doesn't exist.\n * Check operation status - it may already be completed or failed.\n * @throws {NetworkError} When unable to reach the personal server API.\n * Verify server URL and network connectivity.\n * @example\n * ```typescript\n * // Start a long-running operation\n * const operation = await vana.server.createOperation({\n * permissionId: 123\n * });\n *\n * // Cancel if needed\n * try {\n * await vana.server.cancelOperation(operation.id);\n * console.log(\"Cancellation requested\");\n *\n * // Verify cancellation\n * const status = await vana.server.getOperation(operation.id);\n * if (status.status === \"canceled\") {\n * console.log(\"Operation successfully canceled\");\n * }\n * } catch (error) {\n * console.error(\"Failed to cancel:\", error);\n * }\n * ```\n */\n async cancelOperation(operationId: string): Promise<void> {\n try {\n const response = await fetch(\n `${this.personalServerBaseUrl}/operations/${operationId}/cancel`,\n {\n method: \"POST\",\n },\n );\n\n if (!response.ok) {\n const errorText = await response.text();\n throw new PersonalServerError(\n `Failed to cancel operation: ${response.status} ${response.statusText} - ${errorText}`,\n );\n }\n } catch (error) {\n if (error instanceof NetworkError) {\n throw error;\n }\n throw new NetworkError(\n `Failed to cancel operation: ${error instanceof Error ? error.message : \"Unknown error\"}`,\n );\n }\n }\n\n /**\n * Makes the request to the personal server API.\n *\n * @param requestBody - The post request parameters to serialize\n * @returns JSON string representation of the request data\n */\n private async makeRequest(\n requestBody: Record<string, unknown>,\n ): Promise<CreateOperationResponse> {\n try {\n console.debug(\"Personal Server Request:\", {\n url: `${this.personalServerBaseUrl}/operations`,\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n },\n body: requestBody,\n });\n\n const response = await fetch(`${this.personalServerBaseUrl}/operations`, {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n },\n body: JSON.stringify(requestBody),\n });\n\n if (!response.ok) {\n const errorText = await response.text();\n console.debug(\"Personal Server Error Response:\", {\n status: response.status,\n statusText: response.statusText,\n error: errorText,\n });\n throw new NetworkError(\n `Personal server API request failed: ${response.status} ${response.statusText} - ${errorText}`,\n );\n }\n\n const data = (await response.json()) as CreateOperationResponse;\n\n console.debug(\"Personal Server Success Response:\", data);\n\n return data;\n } catch (error) {\n if (error instanceof NetworkError) {\n throw error;\n }\n throw new NetworkError(\n `Failed to make personal server API request: ${error instanceof Error ? error.message : \"Unknown error\"}`,\n );\n }\n }\n\n /**\n * Creates a signature for the request JSON.\n *\n * @param requestJson - The JSON string to sign\n * @returns Promise resolving to the cryptographic signature\n */\n private async createSignature(requestJson: string): Promise<string> {\n try {\n console.debug(\"🔍 Debug - createSignature\", requestJson);\n\n // Use applicationClient if available, fallback to walletClient\n const client =\n this.context.applicationClient ?? this.context.walletClient;\n\n if (!client) {\n throw new SignatureError(\"No client available for signing\");\n }\n\n // Get the account from the wallet client\n const { account } = client;\n if (!account) {\n throw new SignatureError(\"No account available for signing\");\n }\n\n // Only allow local accounts for signing\n if (account.type !== \"local\") {\n throw new SignatureError(\n \"Only local accounts are supported for signing\",\n );\n }\n\n console.debug(\"🔍 Debug - createSignature account\", account);\n // Sign locally using the account's signMessage method\n const signature = await account.signMessage({\n message: requestJson,\n });\n\n return signature;\n } catch (error) {\n if (error instanceof Error && error.message.includes(\"User rejected\")) {\n throw new SignatureError(\"User rejected the signature request\");\n }\n throw new SignatureError(\n `Failed to create signature: ${error instanceof Error ? error.message : \"Unknown error\"}`,\n );\n }\n }\n}\n"],"mappings":"AAUA;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AAGP,SAAS,sBAAsB;AA6CxB,MAAM,yBAAyB,eAAe;AAAA,EACnD,YAAY,SAA4B;AACtC,UAAM,OAAO;AAAA,EACf;AAAA,EAEA,IAAY,wBAAgC;AAC1C,QAAI,CAAC,KAAK,QAAQ,0BAA0B;AAC1C,YAAM,IAAI;AAAA,QACR;AAAA,MAEF;AAAA,IACF;AACA,WAAO,KAAK,QAAQ;AAAA,EACtB;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAmCA,MAAM,YACJ,SACiC;AACjC,QAAI;AACF,YAAM,WAAW,MAAM;AAAA,QACrB,GAAG,KAAK,qBAAqB,qBAAqB,QAAQ,WAAW;AAAA,QACrE;AAAA,UACE,QAAQ;A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AS,MAAM,IAAI,SAAS,UAAU,MAAM,SAAS;AAAA,QAC9F;AAAA,MACF;AAEA,YAAM,OAAQ,MAAM,SAAS,KAAK;AAElC,cAAQ,MAAM,qCAAqC,IAAI;AAEvD,aAAO;AAAA,IACT,SAAS,OAAO;AACd,UAAI,iBAAiB,cAAc;AACjC,cAAM;AAAA,MACR;AACA,YAAM,IAAI;AAAA,QACR,+CAA+C,iBAAiB,QAAQ,MAAM,UAAU,eAAe;AAAA,MACzG;AAAA,IACF;AAAA,EACF;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAQA,MAAc,gBAAgB,aAAsC;AAClE,QAAI;AACF,cAAQ,MAAM,qCAA8B,WAAW;AAGvD,YAAM,SACJ,KAAK,QAAQ,qBAAqB,KAAK,QAAQ;AAEjD,UAAI,CAAC,QAAQ;AACX,cAAM,IAAI,eAAe,iCAAiC;AAAA,MAC5D;AAGA,YAAM,EAAE,QAAQ,IAAI;AACpB,UAAI,CAAC,SAAS;AACZ,cAAM,IAAI,eAAe,kCAAkC;AAAA,MAC7D;AAGA,UAAI,QAAQ,SAAS,SAAS;AAC5B,cAAM,IAAI;AAAA,UACR;AAAA,QACF;AAAA,MACF;AAEA,cAAQ,MAAM,6CAAsC,OAAO;AAE3D,YAAM,YAAY,MAAM,QAAQ,YAAY;AAAA,QAC1C,SAAS;AAAA,MACX,CAAC;AAED,aAAO;AAAA,IACT,SAAS,OAAO;AACd,UAAI,iBAAiB,SAAS,MAAM,QAAQ,SAAS,eAAe,GAAG;AACrE,cAAM,IAAI,eAAe,qCAAqC;AAAA,MAChE;AACA,YAAM,IAAI;AAAA,QACR,+BAA+B,iBAAiB,QAAQ,MAAM,UAAU,eAAe;AAAA,MACzF;AAAA,IACF;AAAA,EACF;AACF;","names":[]}
1
+ {"version":3,"sources":["../../src/controllers/server.ts"],"sourcesContent":["import type {\n CreateOperationParams,\n InitPersonalServerParams,\n PersonalServerIdentity,\n} from \"../types\";\nimport type {\n CreateOperationResponse,\n GetOperationResponse,\n IdentityResponseModel,\n} from \"../generated/server/server-exports\";\nimport {\n NetworkError,\n SerializationError,\n SignatureError,\n PersonalServerError,\n} from \"../errors\";\nimport type { ControllerContext } from \"./permissions\";\nimport type { Operation, PollingOptions } from \"../types/operations\";\nimport { BaseController } from \"./base\";\n\n// Server types are now auto-imported from the generated exports\n\n/**\n * Manages personal server interactions for secure data processing.\n *\n * @remarks\n * Handles communication with personal servers for computation requests\n * and identity retrieval. Personal servers process user data with\n * cryptographic verification, ensuring privacy and permission compliance.\n *\n * **Architecture:**\n * Servers use deterministic key derivation from user addresses.\n * Identity cached for offline retrieval. Operations authenticated\n * via wallet signatures and permission verification.\n *\n * **Method Selection:**\n * - `getIdentity()` - Retrieve server public key for encryption\n * - `createOperation()` - Submit computation with permission ID\n * - `getOperation()` - Check status and retrieve results\n * - `waitForOperation()` - Poll until completion or timeout\n * - `cancelOperation()` - Stop running operations\n *\n * **Typical Workflow:**\n * 1. Get server identity for encryption key\n * 2. Create operation with permission ID\n * 3. Poll for completion\n * 4. Retrieve results\n *\n * @example\n * ```typescript\n * // Get server identity for encryption\n * const identity = await vana.server.getIdentity({\n * userAddress: \"0x742d35Cc6558Fd4D9e9E0E888F0462ef6919Bd36\"\n * });\n * console.log(`Server key: ${identity.publicKey}`);\n *\n * // Submit computation request\n * const operation = await vana.server.createOperation({\n * permissionId: 123\n * });\n *\n * // Wait for results\n * const result = await vana.server.waitForOperation(operation.id);\n * console.log(\"Processing complete:\", result.result);\n * ```\n *\n * @category Server Management\n * @see For conceptual overview, visit {@link https://docs.vana.org/docs/personal-servers}\n */\nexport class ServerController extends BaseController {\n constructor(context: ControllerContext) {\n super(context);\n }\n\n private get personalServerBaseUrl(): string {\n if (!this.context.defaultPersonalServerUrl) {\n throw new PersonalServerError(\n \"Personal server URL is required for server operations. \" +\n \"Please configure defaultPersonalServerUrl in your VanaConfig.\",\n );\n }\n return this.context.defaultPersonalServerUrl;\n }\n\n /**\n * Retrieves cryptographic identity for a personal server.\n *\n * @remarks\n * Fetches public key and metadata required for data encryption.\n * Identity cached by infrastructure for offline retrieval.\n * Each user address maps to deterministic server identity.\n *\n * @param request - Identity request parameters\n * @param request.userAddress - Wallet address of server owner\n *\n * @returns Server identity with public key and metadata\n *\n * @throws {NetworkError} Identity service unavailable.\n * Check network connection and server URL configuration.\n * @throws {PersonalServerError} Identity retrieval failed.\n * Verify user address and server registration.\n *\n * @example\n * ```typescript\n * const identity = await vana.server.getIdentity({\n * userAddress: \"0x742d35Cc6558Fd4D9e9E0E888F0462ef6919Bd36\"\n * });\n *\n * console.log(`Server: ${identity.name}`);\n * console.log(`Address: ${identity.address}`);\n * console.log(`Public Key: ${identity.publicKey}`);\n *\n * // Use for encryption before data sharing\n * const encrypted = await encryptWithPublicKey(\n * data,\n * identity.publicKey\n * );\n * ```\n */\n async getIdentity(\n request: InitPersonalServerParams,\n ): Promise<PersonalServerIdentity> {\n try {\n const response = await fetch(\n `${this.personalServerBaseUrl}/identity?address=${request.userAddress}`,\n {\n method: \"GET\",\n headers: {\n \"Content-Type\": \"application/json\",\n },\n },\n );\n\n console.debug(\"🔍 Debug - getIdentity response\", response);\n if (!response.ok) {\n const errorText = await response.text();\n throw new NetworkError(\n `Local identity API request failed: ${response.status} ${response.statusText} - ${errorText}`,\n );\n }\n\n const serverResponse = (await response.json()) as IdentityResponseModel;\n\n return {\n kind: serverResponse.personal_server.kind,\n address: serverResponse.personal_server.address,\n publicKey: serverResponse.personal_server.public_key,\n baseUrl: this.personalServerBaseUrl,\n name: \"Hosted Vana Server\",\n };\n } catch (error) {\n if (\n error instanceof NetworkError ||\n error instanceof PersonalServerError\n ) {\n throw error;\n }\n throw new PersonalServerError(\n `Failed to get personal server identity: ${error instanceof Error ? error.message : \"Unknown error\"}`,\n );\n }\n }\n\n /**\n * Creates a server operation and returns its details as a plain object.\n *\n * @remarks\n * This method submits a computation request to the personal server and returns\n * an Operation object that can be serialized and passed across API boundaries.\n * Use `waitForOperation()` to poll for completion.\n *\n * @param params - The operation request parameters\n * @param params.permissionId - The permission ID authorizing this operation.\n * Obtain via `vana.permissions.getUserPermissionGrantsOnChain()`.\n * @returns An Operation object containing the operation ID and status\n * @throws {PersonalServerError} When the server request fails or parameters are invalid\n * @throws {NetworkError} When personal server API communication fails\n * @example\n * ```typescript\n * const operation = await vana.server.createOperation({\n * permissionId: 123\n * });\n * console.log(`Operation ID: ${operation.id}`);\n *\n * // Wait for completion\n * const result = await vana.server.waitForOperation(operation.id);\n * console.log(\"Result:\", result.result);\n * ```\n */\n async createOperation<T = unknown>(\n params: CreateOperationParams,\n ): Promise<Operation<T>> {\n this.assertWallet();\n\n try {\n const requestData = {\n permission_id: params.permissionId,\n };\n\n const requestJson = JSON.stringify(requestData);\n\n const signature = await this.createSignature(requestJson);\n\n const requestBody = {\n app_signature: signature,\n operation_request_json: requestJson,\n };\n\n // Step 5: Make request to personal server API\n console.debug(\"🔍 Debug - createOperation requestBody\", requestBody);\n const response = await this.makeRequest(requestBody);\n\n return {\n id: response.id,\n status: \"starting\",\n createdAt: Date.now(),\n } as Operation<T>;\n } catch (error) {\n if (error instanceof Error) {\n // Re-throw known Vana errors directly\n if (\n error instanceof NetworkError ||\n error instanceof SerializationError ||\n error instanceof SignatureError ||\n error instanceof PersonalServerError\n ) {\n throw error;\n }\n // Wrap unknown errors\n throw new PersonalServerError(\n `Personal server operation creation failed: ${error.message}`,\n error,\n );\n }\n throw new PersonalServerError(\n \"Personal server operation creation failed with unknown error\",\n );\n }\n }\n\n /**\n * Retrieves the current status and result of a server operation.\n *\n * @remarks\n * Common status values: `starting`, `running`, `succeeded`, `failed`, `canceled`.\n * When status is `succeeded`, the result field contains the operation output.\n *\n * @param operationId - The ID of the operation to query\n * @returns The operation as a plain object containing status, result, and metadata\n * @throws {NetworkError} When the API request fails or returns invalid data\n * @example\n * ```typescript\n * const operation = await vana.server.getOperation(operationId);\n * if (operation.status === 'succeeded') {\n * console.log('Result:', operation.result);\n * }\n * ```\n */\n async getOperation<T = unknown>(operationId: string): Promise<Operation<T>> {\n try {\n console.debug(\"Polling Operation Status:\", operationId);\n\n const response = await fetch(\n `${this.personalServerBaseUrl}/operations/${operationId}`,\n {\n method: \"GET\",\n headers: {\n \"Content-Type\": \"application/json\",\n },\n },\n );\n\n if (!response.ok) {\n const errorText = await response.text();\n console.debug(\"Polling Error Response:\", {\n status: response.status,\n statusText: response.statusText,\n error: errorText,\n });\n throw new NetworkError(\n `Status polling failed: ${response.status} ${response.statusText} - ${errorText}`,\n );\n }\n\n const data = (await response.json()) as GetOperationResponse;\n\n console.debug(\"Polling Success Response:\", data);\n\n return {\n id: data.id,\n status: data.status as Operation[\"status\"],\n createdAt: Date.now(),\n updatedAt: Date.now(),\n result: data.status === \"succeeded\" ? (data.result as T) : undefined,\n error:\n data.status === \"failed\" ? (data.result ?? undefined) : undefined,\n };\n } catch (error) {\n if (error instanceof NetworkError) {\n throw error;\n }\n throw new NetworkError(\n `Failed to poll status: ${error instanceof Error ? error.message : \"Unknown error\"}`,\n );\n }\n }\n\n /**\n * Waits for an operation to complete and returns the final result.\n *\n * @remarks\n * This method polls the operation status at regular intervals until it\n * reaches a terminal state (succeeded, failed, or canceled). Supports\n * ergonomic overloads to accept either an Operation object or just the ID.\n *\n * @param opOrId - Either an Operation object or operation ID string\n * @param options - Optional polling configuration\n * @returns The completed operation with result or error\n * @throws {PersonalServerError} When the operation fails or times out\n * @example\n * ```typescript\n * // Using operation object\n * const operation = await vana.server.createOperation({ permissionId: 123 });\n * const completed = await vana.server.waitForOperation(operation);\n *\n * // Using just the ID\n * const completed = await vana.server.waitForOperation(\"op_abc123\");\n *\n * // With custom timeout\n * const completed = await vana.server.waitForOperation(operation, {\n * timeout: 60000,\n * pollingInterval: 1000\n * });\n * ```\n */\n async waitForOperation<T = unknown>(\n opOrId: Operation<T> | string,\n options?: PollingOptions,\n ): Promise<Operation<T>> {\n const id = typeof opOrId === \"string\" ? opOrId : opOrId.id;\n const startTime = Date.now();\n const timeout = options?.timeout ?? 30000;\n const interval = options?.pollingInterval ?? 500;\n\n while (true) {\n const operation = await this.getOperation<T>(id);\n\n if (operation.status === \"succeeded\") {\n return operation;\n }\n\n if (operation.status === \"failed\") {\n throw new PersonalServerError(\n `Operation ${operation.status}: ${operation.error ?? \"Unknown error\"}`,\n );\n }\n\n if (operation.status === \"canceled\") {\n throw new PersonalServerError(`Operation was canceled`);\n }\n\n if (Date.now() - startTime > timeout) {\n throw new PersonalServerError(`Operation timed out after ${timeout}ms`);\n }\n\n await new Promise((resolve) => setTimeout(resolve, interval));\n }\n }\n\n /**\n * Cancels a running operation on the personal server.\n *\n * @remarks\n * This method attempts to cancel an operation that is currently processing\n * on the personal server. The operation must be in a cancellable state\n * (typically `starting` or `processing`). Not all operations support\n * cancellation, and cancellation may not be immediate. The server will\n * attempt to stop the operation and update its status to `canceled`.\n *\n * **Cancellation Behavior:**\n * - Operations in `succeeded` or `failed` states cannot be canceled\n * - Some long-running operations may take time to respond to cancellation\n * - Always verify cancellation by polling the operation status afterward\n *\n * @param operationId - The unique identifier of the operation to cancel,\n * obtained from `createOperation()` response\n * @returns Promise that resolves when the cancellation request is accepted\n * @throws {PersonalServerError} When the operation cannot be canceled or doesn't exist.\n * Check operation status - it may already be completed or failed.\n * @throws {NetworkError} When unable to reach the personal server API.\n * Verify server URL and network connectivity.\n * @example\n * ```typescript\n * // Start a long-running operation\n * const operation = await vana.server.createOperation({\n * permissionId: 123\n * });\n *\n * // Cancel if needed\n * try {\n * await vana.server.cancelOperation(operation.id);\n * console.log(\"Cancellation requested\");\n *\n * // Verify cancellation\n * const status = await vana.server.getOperation(operation.id);\n * if (status.status === \"canceled\") {\n * console.log(\"Operation successfully canceled\");\n * }\n * } catch (error) {\n * console.error(\"Failed to cancel:\", error);\n * }\n * ```\n */\n async cancelOperation(operationId: string): Promise<void> {\n try {\n const response = await fetch(\n `${this.personalServerBaseUrl}/operations/${operationId}/cancel`,\n {\n method: \"POST\",\n },\n );\n\n if (!response.ok) {\n const errorText = await response.text();\n throw new PersonalServerError(\n `Failed to cancel operation: ${response.status} ${response.statusText} - ${errorText}`,\n );\n }\n } catch (error) {\n if (error instanceof NetworkError) {\n throw error;\n }\n throw new NetworkError(\n `Failed to cancel operation: ${error instanceof Error ? error.message : \"Unknown error\"}`,\n );\n }\n }\n\n /**\n * Makes the request to the personal server API.\n *\n * @param requestBody - The post request parameters to serialize\n * @returns JSON string representation of the request data\n */\n private async makeRequest(\n requestBody: Record<string, unknown>,\n ): Promise<CreateOperationResponse> {\n try {\n console.debug(\"Personal Server Request:\", {\n url: `${this.personalServerBaseUrl}/operations`,\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n },\n body: requestBody,\n });\n\n const response = await fetch(`${this.personalServerBaseUrl}/operations`, {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n },\n body: JSON.stringify(requestBody),\n });\n\n if (!response.ok) {\n const errorText = await response.text();\n console.debug(\"Personal Server Error Response:\", {\n status: response.status,\n statusText: response.statusText,\n error: errorText,\n });\n throw new NetworkError(\n `Personal server API request failed: ${response.status} ${response.statusText} - ${errorText}`,\n );\n }\n\n const data = (await response.json()) as CreateOperationResponse;\n\n console.debug(\"Personal Server Success Response:\", data);\n\n return data;\n } catch (error) {\n if (error instanceof NetworkError) {\n throw error;\n }\n throw new NetworkError(\n `Failed to make personal server API request: ${error instanceof Error ? error.message : \"Unknown error\"}`,\n );\n }\n }\n\n /**\n * Creates a signature for the request JSON.\n *\n * @param requestJson - The JSON string to sign\n * @returns Promise resolving to the cryptographic signature\n */\n private async createSignature(requestJson: string): Promise<string> {\n try {\n console.debug(\"🔍 Debug - createSignature\", requestJson);\n\n // Use applicationClient if available, fallback to walletClient\n const client =\n this.context.applicationClient ?? this.context.walletClient;\n\n if (!client) {\n throw new SignatureError(\"No client available for signing\");\n }\n\n // Get the account from the wallet client\n const { account } = client;\n if (!account) {\n throw new SignatureError(\"No account available for signing\");\n }\n\n // Only allow local accounts for signing\n if (account.type !== \"local\") {\n throw new SignatureError(\n \"Only local accounts are supported for signing\",\n );\n }\n\n console.debug(\"🔍 Debug - createSignature account\", account);\n // Sign locally using the account's signMessage method\n const signature = await account.signMessage({\n message: requestJson,\n });\n\n return signature;\n } catch (error) {\n if (error instanceof Error && error.message.includes(\"User rejected\")) {\n throw new SignatureError(\"User rejected the signature request\");\n }\n throw new SignatureError(\n `Failed to create signature: ${error instanceof Error ? error.message : \"Unknown error\"}`,\n );\n }\n }\n}\n"],"mappings":"AAUA;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AAGP,SAAS,sBAAsB;AAmDxB,MAAM,yBAAyB,eAAe;AAAA,EACnD,YAAY,SAA4B;AACtC,UAAM,OAAO;AAAA,EACf;AAAA,EAEA,IAAY,wBAAgC;AAC1C,QAAI,CAAC,KAAK,QAAQ,0BAA0B;AAC1C,YAAM,IAAI;AAAA,QACR;AAAA,MAEF;AAAA,IACF;AACA,WAAO,KAAK,QAAQ;AAAA,EACtB;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAqCA,MAAM,YACJ,SACiC;AACjC,QAAI;AACF,YAAM,WAAW,MAAM;AAAA,QACrB,GAAG,KAAK,qBAAqB,qBAAqB,QAAQ,WAAW;AAAA,QACrE;AAAA,UACE,QAAQ;AAAA,UACR,SAAS;AAAA,YACP,gBAAgB;AAAA,UAClB;AAAA,QACF;AAAA,MACF;AAEA,cAAQ,MAAM,0CAAmC,QAAQ;AACzD,UAAI,CAAC,SAAS,IAAI;AAChB,cAAM,YAAY,MAAM,SAAS,KAAK;AACtC,cAAM,IAAI;AAAA,UACR,sCAAsC,SAAS,MAAM,IAAI,SAAS,UAAU,MA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A,QACR,+CAA+C,iBAAiB,QAAQ,MAAM,UAAU,eAAe;AAAA,MACzG;AAAA,IACF;AAAA,EACF;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAQA,MAAc,gBAAgB,aAAsC;AAClE,QAAI;AACF,cAAQ,MAAM,qCAA8B,WAAW;AAGvD,YAAM,SACJ,KAAK,QAAQ,qBAAqB,KAAK,QAAQ;AAEjD,UAAI,CAAC,QAAQ;AACX,cAAM,IAAI,eAAe,iCAAiC;AAAA,MAC5D;AAGA,YAAM,EAAE,QAAQ,IAAI;AACpB,UAAI,CAAC,SAAS;AACZ,cAAM,IAAI,eAAe,kCAAkC;AAAA,MAC7D;AAGA,UAAI,QAAQ,SAAS,SAAS;AAC5B,cAAM,IAAI;AAAA,UACR;AAAA,QACF;AAAA,MACF;AAEA,cAAQ,MAAM,6CAAsC,OAAO;AAE3D,YAAM,YAAY,MAAM,QAAQ,YAAY;AAAA,QAC1C,SAAS;AAAA,MACX,CAAC;AAED,aAAO;AAAA,IACT,SAAS,OAAO;AACd,UAAI,iBAAiB,SAAS,MAAM,QAAQ,SAAS,eAAe,GAAG;AACrE,cAAM,IAAI,eAAe,qCAAqC;AAAA,MAChE;AACA,YAAM,IAAI;AAAA,QACR,+BAA+B,iBAAiB,QAAQ,MAAM,UAAU,eAAe;AAAA,MACzF;AAAA,IACF;AAAA,EACF;AACF;","names":[]}
@@ -53,19 +53,69 @@ class ApiClient {
53
53
  this.circuitBreaker = new import_generics.CircuitBreaker(this.config.circuitBreaker);
54
54
  }
55
55
  /**
56
- * Add middleware to the request pipeline
56
+ * Adds middleware to the request processing pipeline.
57
+ *
58
+ * @remarks
59
+ * Middleware functions execute in order of registration and can transform
60
+ * requests, responses, or implement cross-cutting concerns like logging,
61
+ * authentication, or caching.
57
62
  *
58
63
  * @param middleware - The middleware function to add to the pipeline
64
+ *
65
+ * @example
66
+ * ```typescript
67
+ * // Add authentication middleware
68
+ * client.use(async (req, next) => {
69
+ * req.options.headers = {
70
+ * ...req.options.headers,
71
+ * 'Authorization': `Bearer ${getToken()}`
72
+ * };
73
+ * return next(req);
74
+ * });
75
+ *
76
+ * // Add response caching
77
+ * client.use(async (req, next) => {
78
+ * const cached = cache.get(req.params.url);
79
+ * if (cached) return cached;
80
+ *
81
+ * const res = await next(req);
82
+ * if (res.status === 'success') {
83
+ * cache.set(req.params.url, res);
84
+ * }
85
+ * return res;
86
+ * });
87
+ * ```
59
88
  */
60
89
  use(middleware) {
61
90
  this.middleware.use(middleware);
62
91
  }
63
92
  /**
64
- * Make a generic HTTP request
93
+ * Executes an HTTP request with full resilience features.
65
94
  *
66
- * @param url - The URL to make the request to
95
+ * @remarks
96
+ * This is the core request method that applies all configured resilience
97
+ * patterns including retry, rate limiting, and circuit breaking. It processes
98
+ * the request through the middleware pipeline before execution.
99
+ *
100
+ * @param url - The URL to make the request to.
101
+ * Can be relative (uses baseUrl) or absolute.
67
102
  * @param options - Request options including method, headers, body, etc.
68
103
  * @returns Promise resolving to the response data
104
+ *
105
+ * @throws {Error} When request fails after all retry attempts.
106
+ * Check error message for details.
107
+ * @throws {Error} When circuit breaker is open.
108
+ * Wait for recovery timeout before retrying.
109
+ *
110
+ * @example
111
+ * ```typescript
112
+ * const response = await client.request('/api/data', {
113
+ * method: 'POST',
114
+ * headers: { 'Content-Type': 'application/json' },
115
+ * params: { name: 'John', age: 30 },
116
+ * timeout: 5000
117
+ * });
118
+ * ```
69
119
  */
70
120
  async request(url, options = {}) {
71
121
  const fullUrl = this.buildUrl(url);
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/core/apiClient.ts"],"sourcesContent":["import type {\n GenericRequest,\n GenericResponse,\n RetryConfig,\n RateLimiterConfig,\n Middleware,\n} from \"../types/generics\";\nimport {\n RetryUtility,\n RateLimiter,\n MiddlewarePipeline,\n CircuitBreaker,\n} from \"./generics\";\n\n/**\n * Configuration for the generic API client\n */\nexport interface ApiClientConfig {\n /** Base URL for all requests */\n baseUrl?: string;\n /** Default headers */\n headers?: Record<string, string>;\n /** Request timeout in milliseconds */\n timeout?: number;\n /** Retry configuration */\n retry?: RetryConfig;\n /** Rate limiting configuration */\n rateLimit?: RateLimiterConfig;\n /** Circuit breaker configuration */\n circuitBreaker?: {\n failureThreshold: number;\n recoveryTimeout: number;\n halfOpenMaxAttempts?: number;\n };\n}\n\n/**\n * HTTP method types\n */\nexport type HttpMethod = \"GET\" | \"POST\" | \"PUT\" | \"DELETE\" | \"PATCH\";\n\n/**\n * Request options for API calls\n */\nexport interface RequestOptions {\n /** HTTP method */\n method?: HttpMethod;\n /** Request headers */\n headers?: Record<string, string>;\n /** Query parameters */\n params?: Record<string, unknown>;\n /** Request timeout */\n timeout?: number;\n /** Skip retry for this request */\n skipRetry?: boolean;\n /** Skip rate limiting for this request */\n skipRateLimit?: boolean;\n}\n\n/**\n * Generic API client with middleware, retry, rate limiting, and circuit breaker support\n */\nexport class ApiClient {\n private readonly config: Required<ApiClientConfig>;\n private readonly middleware: MiddlewarePipeline;\n private readonly rateLimiter?: RateLimiter;\n private readonly circuitBreaker?: CircuitBreaker;\n\n constructor(config: ApiClientConfig = {}) {\n this.config = {\n baseUrl: config.baseUrl ?? \"\",\n headers: config.headers ?? {},\n timeout: config.timeout ?? 30000,\n retry: config.retry ?? {\n maxAttempts: 3,\n baseDelay: 1000,\n backoffMultiplier: 2,\n shouldRetry: (error) => error.message.includes(\"network\"),\n },\n rateLimit: config.rateLimit ?? {\n requestsPerWindow: 100,\n windowMs: 60000,\n },\n circuitBreaker: config.circuitBreaker ?? {\n failureThreshold: 5,\n recoveryTimeout: 60000,\n halfOpenMaxAttempts: 3,\n },\n };\n\n this.middleware = new MiddlewarePipeline();\n this.rateLimiter = new RateLimiter(this.config.rateLimit);\n this.circuitBreaker = new CircuitBreaker(this.config.circuitBreaker);\n }\n\n /**\n * Add middleware to the request pipeline\n *\n * @param middleware - The middleware function to add to the pipeline\n */\n use(middleware: Middleware): void {\n this.middleware.use(middleware);\n }\n\n /**\n * Make a generic HTTP request\n *\n * @param url - The URL to make the request to\n * @param options - Request options including method, headers, body, etc.\n * @returns Promise resolving to the response data\n */\n async request<TData = unknown>(\n url: string,\n options: RequestOptions = {},\n ): Promise<GenericResponse<TData>> {\n const fullUrl = this.buildUrl(url);\n const requestOptions = this.buildRequestOptions(options);\n\n const request: GenericRequest<{\n url: string;\n options: RequestOptions;\n }> = {\n params: {\n url: fullUrl,\n options: requestOptions,\n },\n options: requestOptions,\n };\n\n // Apply rate limiting\n if (!options.skipRateLimit && this.rateLimiter) {\n await this.rateLimiter.waitForSlot();\n }\n\n // Execute with circuit breaker\n if (this.circuitBreaker) {\n return this.circuitBreaker.execute(() =>\n this.executeRequest<TData>(request),\n );\n }\n\n return this.executeRequest<TData>(request);\n }\n\n /**\n * Make a GET request\n *\n * @param url - The URL to make the GET request to\n * @param options - Request options (excluding method)\n * @returns Promise resolving to the response data\n */\n async get<TData = unknown>(\n url: string,\n options: Omit<RequestOptions, \"method\"> = {},\n ): Promise<GenericResponse<TData>> {\n return this.request<TData>(url, { ...options, method: \"GET\" });\n }\n\n /**\n * Make a POST request\n *\n * @param url - The URL to make the POST request to\n * @param data - The data to send in the request body\n * @param options - Request options (excluding method)\n * @returns Promise resolving to the response data\n */\n async post<TData = unknown>(\n url: string,\n data?: unknown,\n options: Omit<RequestOptions, \"method\"> = {},\n ): Promise<GenericResponse<TData>> {\n return this.request<TData>(url, {\n ...options,\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n ...options.headers,\n },\n params: data as Record<string, unknown>,\n });\n }\n\n /**\n * Make a PUT request\n *\n * @param url - The URL to make the PUT request to\n * @param data - The data to send in the request body\n * @param options - Request options (excluding method)\n * @returns Promise resolving to the response data\n */\n async put<TData = unknown>(\n url: string,\n data?: unknown,\n options: Omit<RequestOptions, \"method\"> = {},\n ): Promise<GenericResponse<TData>> {\n return this.request<TData>(url, {\n ...options,\n method: \"PUT\",\n headers: {\n \"Content-Type\": \"application/json\",\n ...options.headers,\n },\n params: data as Record<string, unknown>,\n });\n }\n\n /**\n * Make a DELETE request\n *\n * @param url - The URL to make the DELETE request to\n * @param options - Request options (excluding method)\n * @returns Promise resolving to the response data\n */\n async delete<TData = unknown>(\n url: string,\n options: Omit<RequestOptions, \"method\"> = {},\n ): Promise<GenericResponse<TData>> {\n return this.request<TData>(url, { ...options, method: \"DELETE\" });\n }\n\n /**\n * Make a PATCH request\n *\n * @param url - The URL to make the PATCH request to\n * @param data - The data to send in the request body\n * @param options - Request options (excluding method)\n * @returns Promise resolving to the response data\n */\n async patch<TData = unknown>(\n url: string,\n data?: unknown,\n options: Omit<RequestOptions, \"method\"> = {},\n ): Promise<GenericResponse<TData>> {\n return this.request<TData>(url, {\n ...options,\n method: \"PATCH\",\n headers: {\n \"Content-Type\": \"application/json\",\n ...options.headers,\n },\n params: data as Record<string, unknown>,\n });\n }\n\n /**\n * Execute the actual HTTP request with middleware and retry\n *\n * @param request - The generic request object containing URL and options\n * @returns Promise resolving to the generic response with data\n */\n private async executeRequest<TData>(\n request: GenericRequest<{ url: string; options: RequestOptions }>,\n ): Promise<GenericResponse<TData>> {\n const executeWithRetry = async (): Promise<GenericResponse<TData>> => {\n try {\n // Process request through middleware\n const processedRequest = await this.middleware.processRequest(request);\n\n // Make the actual HTTP request\n const response = await this.makeHttpRequest<TData>(\n (\n processedRequest as GenericRequest<{\n url: string;\n options: RequestOptions;\n }>\n ).params.url,\n (\n processedRequest as GenericRequest<{\n url: string;\n options: RequestOptions;\n }>\n ).params.options,\n );\n\n // Process response through middleware\n const processedResponse =\n await this.middleware.processResponse(response);\n\n return processedResponse;\n } catch (error) {\n // Try to handle error with middleware\n const handledResponse = await this.middleware.handleError<\n typeof request,\n GenericResponse<TData>\n >(error as Error, request);\n\n if (handledResponse) {\n return handledResponse;\n }\n\n throw error;\n }\n };\n\n // Apply retry logic if not skipped\n if (!request.params.options.skipRetry) {\n return RetryUtility.withRetry(executeWithRetry, this.config.retry);\n }\n\n return executeWithRetry();\n }\n\n /**\n * Make the actual HTTP request using fetch API\n *\n * @param url - The URL to make the request to\n * @param options - The request options including method, headers, body, etc.\n * @returns Promise resolving to the generic response with data\n */\n private async makeHttpRequest<TData>(\n url: string,\n options: RequestOptions,\n ): Promise<GenericResponse<TData>> {\n const controller = new AbortController();\n const timeoutId = setTimeout(() => {\n controller.abort();\n }, options.timeout ?? this.config.timeout);\n\n try {\n const response = await fetch(url, {\n method: options.method ?? \"GET\",\n headers: {\n ...this.config.headers,\n ...options.headers,\n },\n signal: controller.signal,\n // Add body for POST/PUT/PATCH requests\n ...(options.method &&\n [\"POST\", \"PUT\", \"PATCH\"].includes(options.method) && {\n body: JSON.stringify(options.params),\n }),\n });\n\n clearTimeout(timeoutId);\n\n const responseData: unknown = await response.json();\n const data = responseData as { message?: string; [key: string]: unknown };\n\n if (!response.ok) {\n return {\n data: null as unknown as TData,\n success: false,\n error: {\n code: response.status.toString(),\n message: data.message ?? response.statusText,\n details: data,\n },\n };\n }\n\n return {\n data: responseData as TData,\n success: true,\n meta: {\n status: response.status,\n statusText: response.statusText,\n headers: Object.fromEntries(response.headers.entries()),\n },\n };\n } catch (error) {\n clearTimeout(timeoutId);\n\n if (error instanceof Error && error.name === \"AbortError\") {\n return {\n data: null as unknown as TData,\n success: false,\n error: {\n code: \"TIMEOUT\",\n message: \"Request timeout\",\n details: error,\n },\n };\n }\n\n return {\n data: null as unknown as TData,\n success: false,\n error: {\n code: \"NETWORK_ERROR\",\n message: error instanceof Error ? error.message : \"Unknown error\",\n details: error,\n },\n };\n }\n }\n\n /**\n * Build the full URL\n *\n * @param url - The URL or path to build the full URL from\n * @returns The complete URL string\n */\n private buildUrl(url: string): string {\n if (url.startsWith(\"http\")) {\n return url;\n }\n\n const baseUrl = this.config.baseUrl.endsWith(\"/\")\n ? this.config.baseUrl.slice(0, -1)\n : this.config.baseUrl;\n const path = url.startsWith(\"/\") ? url : `/${url}`;\n\n return `${baseUrl}${path}`;\n }\n\n /**\n * Build request options with defaults\n *\n * @param options - The request options to merge with defaults\n * @returns The merged request options with defaults applied\n */\n private buildRequestOptions(options: RequestOptions): RequestOptions {\n return {\n method: \"GET\",\n headers: {},\n timeout: this.config.timeout,\n ...options,\n };\n }\n\n /**\n * Get client statistics\n *\n * @returns Object containing client statistics and performance metrics\n */\n getStats() {\n return {\n rateLimiter: this.rateLimiter\n ? {\n remaining: this.rateLimiter.getRemainingRequests(),\n resetTime: this.rateLimiter.getResetTime(),\n }\n : null,\n circuitBreaker: this.circuitBreaker\n ? {\n state: this.circuitBreaker.getState(),\n failures: this.circuitBreaker.getFailures(),\n }\n : null,\n middleware: {\n count: this.middleware.getMiddleware().length,\n },\n };\n }\n\n /**\n * Reset client state\n */\n reset(): void {\n this.circuitBreaker?.reset();\n this.middleware.clear();\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAOA,sBAKO;AAkDA,MAAM,UAAU;AAAA,EACJ;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EAEjB,YAAY,SAA0B,CAAC,GAAG;AACxC,SAAK,SAAS;AAAA,MACZ,SAAS,OAAO,WAAW;AAAA,MAC3B,SAAS,OAAO,WAAW,CAAC;AAAA,MAC5B,SAAS,OAAO,WAAW;AAAA,MAC3B,OAAO,OAAO,SAAS;AAAA,QACrB,aAAa;AAAA,QACb,WAAW;AAAA,QACX,mBAAmB;AAAA,QACnB,aAAa,CAAC,UAAU,MAAM,QAAQ,SAAS,SAAS;AAAA,MAC1D;AAAA,MACA,WAAW,OAAO,aAAa;AAAA,QAC7B,mBAAmB;AAAA,QACnB,UAAU;AAAA,MACZ;AAAA,MACA,gBAAgB,OAAO,kBAAkB;AAAA,QACvC,kBAAkB;AAAA,QAClB,iBAAiB;AAAA,QACjB,qBAAqB;AAAA,MACvB;AAAA,IACF;AAEA,SAAK,aAAa,IAAI,mCAAmB;AACzC,SAAK,cAAc,IAAI,4BAAY,KAAK,OAAO,SAAS;AACxD,SAAK,iBA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C3B,SAAK,WAAW,MAAM;AAAA,EACxB;AACF;","names":[]}
1
+ {"version":3,"sources":["../../src/core/apiClient.ts"],"sourcesContent":["/**\n * Provides a generic HTTP client with enterprise-grade resilience features.\n *\n * @remarks\n * This module implements a robust API client with automatic retry, rate limiting,\n * circuit breaker pattern, and middleware support. It's used internally by the SDK\n * for all HTTP operations and can be extended for custom API integrations.\n *\n * **Architecture:**\n * - Middleware pipeline for request/response transformation\n * - Exponential backoff retry with configurable policies\n * - Token bucket rate limiting to prevent API throttling\n * - Circuit breaker to fail fast when services are down\n *\n * @category Networking\n * @module apiClient\n */\n\nimport type {\n GenericRequest,\n GenericResponse,\n RetryConfig,\n RateLimiterConfig,\n Middleware,\n} from \"../types/generics\";\nimport {\n RetryUtility,\n RateLimiter,\n MiddlewarePipeline,\n CircuitBreaker,\n} from \"./generics\";\n\n/**\n * Configures the API client's behavior and resilience features.\n *\n * @remarks\n * Provides fine-grained control over HTTP client behavior including\n * retry strategies, rate limiting, and circuit breaker thresholds.\n *\n * @category Networking\n */\nexport interface ApiClientConfig {\n /** Base URL for all requests */\n baseUrl?: string;\n /** Default headers */\n headers?: Record<string, string>;\n /** Request timeout in milliseconds */\n timeout?: number;\n /** Retry configuration */\n retry?: RetryConfig;\n /** Rate limiting configuration */\n rateLimit?: RateLimiterConfig;\n /** Circuit breaker configuration */\n circuitBreaker?: {\n failureThreshold: number;\n recoveryTimeout: number;\n halfOpenMaxAttempts?: number;\n };\n}\n\n/**\n * Represents supported HTTP methods for API operations.\n *\n * @category Networking\n */\nexport type HttpMethod = \"GET\" | \"POST\" | \"PUT\" | \"DELETE\" | \"PATCH\";\n\n/**\n * Configures individual HTTP request behavior.\n *\n * @remarks\n * Allows per-request overrides of client defaults including headers,\n * timeout, and resilience features. Use to customize specific requests\n * without affecting global configuration.\n *\n * @category Networking\n */\nexport interface RequestOptions {\n /** HTTP method */\n method?: HttpMethod;\n /** Request headers */\n headers?: Record<string, string>;\n /** Query parameters */\n params?: Record<string, unknown>;\n /** Request timeout */\n timeout?: number;\n /** Skip retry for this request */\n skipRetry?: boolean;\n /** Skip rate limiting for this request */\n skipRateLimit?: boolean;\n}\n\n/**\n * Provides resilient HTTP client functionality with enterprise features.\n *\n * @remarks\n * This client implements multiple resilience patterns to ensure reliable\n * API communication even under adverse conditions. It automatically handles\n * transient failures, rate limits, and service outages while providing\n * hooks for custom behavior through middleware.\n *\n * **Features:**\n * - Automatic retry with exponential backoff\n * - Rate limiting to prevent API throttling\n * - Circuit breaker for fast failure detection\n * - Middleware pipeline for request/response transformation\n * - Configurable timeouts and headers\n *\n * @example\n * ```typescript\n * // Create client with custom configuration\n * const client = new ApiClient({\n * baseUrl: 'https://api.example.com',\n * headers: { 'API-Key': 'secret' },\n * retry: {\n * maxAttempts: 5,\n * baseDelay: 2000\n * },\n * rateLimit: {\n * requestsPerWindow: 50,\n * windowMs: 60000\n * }\n * });\n *\n * // Add logging middleware\n * client.use(async (req, next) => {\n * console.log(`Request: ${req.params.url}`);\n * const res = await next(req);\n * console.log(`Response: ${res.status}`);\n * return res;\n * });\n *\n * // Make resilient API calls\n * const data = await client.get('/users');\n * ```\n *\n * @category Networking\n */\nexport class ApiClient {\n private readonly config: Required<ApiClientConfig>;\n private readonly middleware: MiddlewarePipeline;\n private readonly rateLimiter?: RateLimiter;\n private readonly circuitBreaker?: CircuitBreaker;\n\n constructor(config: ApiClientConfig = {}) {\n this.config = {\n baseUrl: config.baseUrl ?? \"\",\n headers: config.headers ?? {},\n timeout: config.timeout ?? 30000,\n retry: config.retry ?? {\n maxAttempts: 3,\n baseDelay: 1000,\n backoffMultiplier: 2,\n shouldRetry: (error) => error.message.includes(\"network\"),\n },\n rateLimit: config.rateLimit ?? {\n requestsPerWindow: 100,\n windowMs: 60000,\n },\n circuitBreaker: config.circuitBreaker ?? {\n failureThreshold: 5,\n recoveryTimeout: 60000,\n halfOpenMaxAttempts: 3,\n },\n };\n\n this.middleware = new MiddlewarePipeline();\n this.rateLimiter = new RateLimiter(this.config.rateLimit);\n this.circuitBreaker = new CircuitBreaker(this.config.circuitBreaker);\n }\n\n /**\n * Adds middleware to the request processing pipeline.\n *\n * @remarks\n * Middleware functions execute in order of registration and can transform\n * requests, responses, or implement cross-cutting concerns like logging,\n * authentication, or caching.\n *\n * @param middleware - The middleware function to add to the pipeline\n *\n * @example\n * ```typescript\n * // Add authentication middleware\n * client.use(async (req, next) => {\n * req.options.headers = {\n * ...req.options.headers,\n * 'Authorization': `Bearer ${getToken()}`\n * };\n * return next(req);\n * });\n *\n * // Add response caching\n * client.use(async (req, next) => {\n * const cached = cache.get(req.params.url);\n * if (cached) return cached;\n *\n * const res = await next(req);\n * if (res.status === 'success') {\n * cache.set(req.params.url, res);\n * }\n * return res;\n * });\n * ```\n */\n use(middleware: Middleware): void {\n this.middleware.use(middleware);\n }\n\n /**\n * Executes an HTTP request with full resilience features.\n *\n * @remarks\n * This is the core request method that applies all configured resilience\n * patterns including retry, rate limiting, and circuit breaking. It processes\n * the request through the middleware pipeline before execution.\n *\n * @param url - The URL to make the request to.\n * Can be relative (uses baseUrl) or absolute.\n * @param options - Request options including method, headers, body, etc.\n * @returns Promise resolving to the response data\n *\n * @throws {Error} When request fails after all retry attempts.\n * Check error message for details.\n * @throws {Error} When circuit breaker is open.\n * Wait for recovery timeout before retrying.\n *\n * @example\n * ```typescript\n * const response = await client.request('/api/data', {\n * method: 'POST',\n * headers: { 'Content-Type': 'application/json' },\n * params: { name: 'John', age: 30 },\n * timeout: 5000\n * });\n * ```\n */\n async request<TData = unknown>(\n url: string,\n options: RequestOptions = {},\n ): Promise<GenericResponse<TData>> {\n const fullUrl = this.buildUrl(url);\n const requestOptions = this.buildRequestOptions(options);\n\n const request: GenericRequest<{\n url: string;\n options: RequestOptions;\n }> = {\n params: {\n url: fullUrl,\n options: requestOptions,\n },\n options: requestOptions,\n };\n\n // Apply rate limiting\n if (!options.skipRateLimit && this.rateLimiter) {\n await this.rateLimiter.waitForSlot();\n }\n\n // Execute with circuit breaker\n if (this.circuitBreaker) {\n return this.circuitBreaker.execute(() =>\n this.executeRequest<TData>(request),\n );\n }\n\n return this.executeRequest<TData>(request);\n }\n\n /**\n * Make a GET request\n *\n * @param url - The URL to make the GET request to\n * @param options - Request options (excluding method)\n * @returns Promise resolving to the response data\n */\n async get<TData = unknown>(\n url: string,\n options: Omit<RequestOptions, \"method\"> = {},\n ): Promise<GenericResponse<TData>> {\n return this.request<TData>(url, { ...options, method: \"GET\" });\n }\n\n /**\n * Make a POST request\n *\n * @param url - The URL to make the POST request to\n * @param data - The data to send in the request body\n * @param options - Request options (excluding method)\n * @returns Promise resolving to the response data\n */\n async post<TData = unknown>(\n url: string,\n data?: unknown,\n options: Omit<RequestOptions, \"method\"> = {},\n ): Promise<GenericResponse<TData>> {\n return this.request<TData>(url, {\n ...options,\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n ...options.headers,\n },\n params: data as Record<string, unknown>,\n });\n }\n\n /**\n * Make a PUT request\n *\n * @param url - The URL to make the PUT request to\n * @param data - The data to send in the request body\n * @param options - Request options (excluding method)\n * @returns Promise resolving to the response data\n */\n async put<TData = unknown>(\n url: string,\n data?: unknown,\n options: Omit<RequestOptions, \"method\"> = {},\n ): Promise<GenericResponse<TData>> {\n return this.request<TData>(url, {\n ...options,\n method: \"PUT\",\n headers: {\n \"Content-Type\": \"application/json\",\n ...options.headers,\n },\n params: data as Record<string, unknown>,\n });\n }\n\n /**\n * Make a DELETE request\n *\n * @param url - The URL to make the DELETE request to\n * @param options - Request options (excluding method)\n * @returns Promise resolving to the response data\n */\n async delete<TData = unknown>(\n url: string,\n options: Omit<RequestOptions, \"method\"> = {},\n ): Promise<GenericResponse<TData>> {\n return this.request<TData>(url, { ...options, method: \"DELETE\" });\n }\n\n /**\n * Make a PATCH request\n *\n * @param url - The URL to make the PATCH request to\n * @param data - The data to send in the request body\n * @param options - Request options (excluding method)\n * @returns Promise resolving to the response data\n */\n async patch<TData = unknown>(\n url: string,\n data?: unknown,\n options: Omit<RequestOptions, \"method\"> = {},\n ): Promise<GenericResponse<TData>> {\n return this.request<TData>(url, {\n ...options,\n method: \"PATCH\",\n headers: {\n \"Content-Type\": \"application/json\",\n ...options.headers,\n },\n params: data as Record<string, unknown>,\n });\n }\n\n /**\n * Execute the actual HTTP request with middleware and retry\n *\n * @param request - The generic request object containing URL and options\n * @returns Promise resolving to the generic response with data\n */\n private async executeRequest<TData>(\n request: GenericRequest<{ url: string; options: RequestOptions }>,\n ): Promise<GenericResponse<TData>> {\n const executeWithRetry = async (): Promise<GenericResponse<TData>> => {\n try {\n // Process request through middleware\n const processedRequest = await this.middleware.processRequest(request);\n\n // Make the actual HTTP request\n const response = await this.makeHttpRequest<TData>(\n (\n processedRequest as GenericRequest<{\n url: string;\n options: RequestOptions;\n }>\n ).params.url,\n (\n processedRequest as GenericRequest<{\n url: string;\n options: RequestOptions;\n }>\n ).params.options,\n );\n\n // Process response through middleware\n const processedResponse =\n await this.middleware.processResponse(response);\n\n return processedResponse;\n } catch (error) {\n // Try to handle error with middleware\n const handledResponse = await this.middleware.handleError<\n typeof request,\n GenericResponse<TData>\n >(error as Error, request);\n\n if (handledResponse) {\n return handledResponse;\n }\n\n throw error;\n }\n };\n\n // Apply retry logic if not skipped\n if (!request.params.options.skipRetry) {\n return RetryUtility.withRetry(executeWithRetry, this.config.retry);\n }\n\n return executeWithRetry();\n }\n\n /**\n * Make the actual HTTP request using fetch API\n *\n * @param url - The URL to make the request to\n * @param options - The request options including method, headers, body, etc.\n * @returns Promise resolving to the generic response with data\n */\n private async makeHttpRequest<TData>(\n url: string,\n options: RequestOptions,\n ): Promise<GenericResponse<TData>> {\n const controller = new AbortController();\n const timeoutId = setTimeout(() => {\n controller.abort();\n }, options.timeout ?? this.config.timeout);\n\n try {\n const response = await fetch(url, {\n method: options.method ?? \"GET\",\n headers: {\n ...this.config.headers,\n ...options.headers,\n },\n signal: controller.signal,\n // Add body for POST/PUT/PATCH requests\n ...(options.method &&\n [\"POST\", \"PUT\", \"PATCH\"].includes(options.method) && {\n body: JSON.stringify(options.params),\n }),\n });\n\n clearTimeout(timeoutId);\n\n const responseData: unknown = await response.json();\n const data = responseData as { message?: string; [key: string]: unknown };\n\n if (!response.ok) {\n return {\n data: null as unknown as TData,\n success: false,\n error: {\n code: response.status.toString(),\n message: data.message ?? response.statusText,\n details: data,\n },\n };\n }\n\n return {\n data: responseData as TData,\n success: true,\n meta: {\n status: response.status,\n statusText: response.statusText,\n headers: Object.fromEntries(response.headers.entries()),\n },\n };\n } catch (error) {\n clearTimeout(timeoutId);\n\n if (error instanceof Error && error.name === \"AbortError\") {\n return {\n data: null as unknown as TData,\n success: false,\n error: {\n code: \"TIMEOUT\",\n message: \"Request timeout\",\n details: error,\n },\n };\n }\n\n return {\n data: null as unknown as TData,\n success: false,\n error: {\n code: \"NETWORK_ERROR\",\n message: error instanceof Error ? error.message : \"Unknown error\",\n details: error,\n },\n };\n }\n }\n\n /**\n * Build the full URL\n *\n * @param url - The URL or path to build the full URL from\n * @returns The complete URL string\n */\n private buildUrl(url: string): string {\n if (url.startsWith(\"http\")) {\n return url;\n }\n\n const baseUrl = this.config.baseUrl.endsWith(\"/\")\n ? this.config.baseUrl.slice(0, -1)\n : this.config.baseUrl;\n const path = url.startsWith(\"/\") ? url : `/${url}`;\n\n return `${baseUrl}${path}`;\n }\n\n /**\n * Build request options with defaults\n *\n * @param options - The request options to merge with defaults\n * @returns The merged request options with defaults applied\n */\n private buildRequestOptions(options: RequestOptions): RequestOptions {\n return {\n method: \"GET\",\n headers: {},\n timeout: this.config.timeout,\n ...options,\n };\n }\n\n /**\n * Get client statistics\n *\n * @returns Object containing client statistics and performance metrics\n */\n getStats() {\n return {\n rateLimiter: this.rateLimiter\n ? {\n remaining: this.rateLimiter.getRemainingRequests(),\n resetTime: this.rateLimiter.getResetTime(),\n }\n : null,\n circuitBreaker: this.circuitBreaker\n ? {\n state: this.circuitBreaker.getState(),\n failures: this.circuitBreaker.getFailures(),\n }\n : null,\n middleware: {\n count: this.middleware.getMiddleware().length,\n },\n };\n }\n\n /**\n * Reset client state\n */\n reset(): void {\n this.circuitBreaker?.reset();\n this.middleware.clear();\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAyBA,sBAKO;AA4GA,MAAM,UAAU;AAAA,EACJ;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EAEjB,YAAY,SAA0B,CAAC,GAAG;AACxC,SAAK,SAAS;AAAA,MACZ,SAAS,OAAO,WAAW;AAAA,MAC3B,SAAS,OAAO,WAAW,CAAC;AAAA,MAC5B,SAAS,OAAO,WAAW;AAAA,MAC3B,OAAO,OAAO,SAAS;AAAA,QACrB,aAAa;AAAA,QACb,WAAW;AAAA,QACX,mBAAmB;AAAA,QACnB,aAAa,CAAC,UAAU,MAAM,QAAQ,SAAS,SAAS;AAAA,MAC1D;AAAA,MACA,WAAW,OAAO,aAAa;AAAA,QAC7B,mBAAmB;AAAA,QACnB,UAAU;AAAA,MACZ;AAAA,MACA,gBAAgB,OAAO,kBAAkB;AAAA,QACvC,kBAAkB;AAAA,QAClB,iBAAiB;AAAA,QACjB,qBAAqB;AAAA,MACvB;AAAA,IACF;AAEA,SAAK,aAAa,IAAI,mCAAmB;AACzC,SAAK,cAAc,IAAI,4BAAY,KAAK,OAAO,SAAS;AACxD,SAAK,iBAAiB,IAAI,+BAAe,KAAK,OAAO,cAAc;AAAA,EACrE;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAoCA,IAAI,YAA8B;AAChC,SAAK,WAAW,IAAI,UAAU;AAAA,EAChC;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA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+ /**
2
+ * Provides a generic HTTP client with enterprise-grade resilience features.
3
+ *
4
+ * @remarks
5
+ * This module implements a robust API client with automatic retry, rate limiting,
6
+ * circuit breaker pattern, and middleware support. It's used internally by the SDK
7
+ * for all HTTP operations and can be extended for custom API integrations.
8
+ *
9
+ * **Architecture:**
10
+ * - Middleware pipeline for request/response transformation
11
+ * - Exponential backoff retry with configurable policies
12
+ * - Token bucket rate limiting to prevent API throttling
13
+ * - Circuit breaker to fail fast when services are down
14
+ *
15
+ * @category Networking
16
+ * @module apiClient
17
+ */
1
18
  import type { GenericResponse, RetryConfig, RateLimiterConfig, Middleware } from "../types/generics";
2
19
  /**
3
- * Configuration for the generic API client
20
+ * Configures the API client's behavior and resilience features.
21
+ *
22
+ * @remarks
23
+ * Provides fine-grained control over HTTP client behavior including
24
+ * retry strategies, rate limiting, and circuit breaker thresholds.
25
+ *
26
+ * @category Networking
4
27
  */
5
28
  export interface ApiClientConfig {
6
29
  /** Base URL for all requests */
@@ -21,11 +44,20 @@ export interface ApiClientConfig {
21
44
  };
22
45
  }
23
46
  /**
24
- * HTTP method types
47
+ * Represents supported HTTP methods for API operations.
48
+ *
49
+ * @category Networking
25
50
  */
26
51
  export type HttpMethod = "GET" | "POST" | "PUT" | "DELETE" | "PATCH";
27
52
  /**
28
- * Request options for API calls
53
+ * Configures individual HTTP request behavior.
54
+ *
55
+ * @remarks
56
+ * Allows per-request overrides of client defaults including headers,
57
+ * timeout, and resilience features. Use to customize specific requests
58
+ * without affecting global configuration.
59
+ *
60
+ * @category Networking
29
61
  */
30
62
  export interface RequestOptions {
31
63
  /** HTTP method */
@@ -42,7 +74,50 @@ export interface RequestOptions {
42
74
  skipRateLimit?: boolean;
43
75
  }
44
76
  /**
45
- * Generic API client with middleware, retry, rate limiting, and circuit breaker support
77
+ * Provides resilient HTTP client functionality with enterprise features.
78
+ *
79
+ * @remarks
80
+ * This client implements multiple resilience patterns to ensure reliable
81
+ * API communication even under adverse conditions. It automatically handles
82
+ * transient failures, rate limits, and service outages while providing
83
+ * hooks for custom behavior through middleware.
84
+ *
85
+ * **Features:**
86
+ * - Automatic retry with exponential backoff
87
+ * - Rate limiting to prevent API throttling
88
+ * - Circuit breaker for fast failure detection
89
+ * - Middleware pipeline for request/response transformation
90
+ * - Configurable timeouts and headers
91
+ *
92
+ * @example
93
+ * ```typescript
94
+ * // Create client with custom configuration
95
+ * const client = new ApiClient({
96
+ * baseUrl: 'https://api.example.com',
97
+ * headers: { 'API-Key': 'secret' },
98
+ * retry: {
99
+ * maxAttempts: 5,
100
+ * baseDelay: 2000
101
+ * },
102
+ * rateLimit: {
103
+ * requestsPerWindow: 50,
104
+ * windowMs: 60000
105
+ * }
106
+ * });
107
+ *
108
+ * // Add logging middleware
109
+ * client.use(async (req, next) => {
110
+ * console.log(`Request: ${req.params.url}`);
111
+ * const res = await next(req);
112
+ * console.log(`Response: ${res.status}`);
113
+ * return res;
114
+ * });
115
+ *
116
+ * // Make resilient API calls
117
+ * const data = await client.get('/users');
118
+ * ```
119
+ *
120
+ * @category Networking
46
121
  */
47
122
  export declare class ApiClient {
48
123
  private readonly config;
@@ -51,17 +126,67 @@ export declare class ApiClient {
51
126
  private readonly circuitBreaker?;
52
127
  constructor(config?: ApiClientConfig);
53
128
  /**
54
- * Add middleware to the request pipeline
129
+ * Adds middleware to the request processing pipeline.
130
+ *
131
+ * @remarks
132
+ * Middleware functions execute in order of registration and can transform
133
+ * requests, responses, or implement cross-cutting concerns like logging,
134
+ * authentication, or caching.
55
135
  *
56
136
  * @param middleware - The middleware function to add to the pipeline
137
+ *
138
+ * @example
139
+ * ```typescript
140
+ * // Add authentication middleware
141
+ * client.use(async (req, next) => {
142
+ * req.options.headers = {
143
+ * ...req.options.headers,
144
+ * 'Authorization': `Bearer ${getToken()}`
145
+ * };
146
+ * return next(req);
147
+ * });
148
+ *
149
+ * // Add response caching
150
+ * client.use(async (req, next) => {
151
+ * const cached = cache.get(req.params.url);
152
+ * if (cached) return cached;
153
+ *
154
+ * const res = await next(req);
155
+ * if (res.status === 'success') {
156
+ * cache.set(req.params.url, res);
157
+ * }
158
+ * return res;
159
+ * });
160
+ * ```
57
161
  */
58
162
  use(middleware: Middleware): void;
59
163
  /**
60
- * Make a generic HTTP request
164
+ * Executes an HTTP request with full resilience features.
61
165
  *
62
- * @param url - The URL to make the request to
166
+ * @remarks
167
+ * This is the core request method that applies all configured resilience
168
+ * patterns including retry, rate limiting, and circuit breaking. It processes
169
+ * the request through the middleware pipeline before execution.
170
+ *
171
+ * @param url - The URL to make the request to.
172
+ * Can be relative (uses baseUrl) or absolute.
63
173
  * @param options - Request options including method, headers, body, etc.
64
174
  * @returns Promise resolving to the response data
175
+ *
176
+ * @throws {Error} When request fails after all retry attempts.
177
+ * Check error message for details.
178
+ * @throws {Error} When circuit breaker is open.
179
+ * Wait for recovery timeout before retrying.
180
+ *
181
+ * @example
182
+ * ```typescript
183
+ * const response = await client.request('/api/data', {
184
+ * method: 'POST',
185
+ * headers: { 'Content-Type': 'application/json' },
186
+ * params: { name: 'John', age: 30 },
187
+ * timeout: 5000
188
+ * });
189
+ * ```
65
190
  */
66
191
  request<TData = unknown>(url: string, options?: RequestOptions): Promise<GenericResponse<TData>>;
67
192
  /**
@@ -35,19 +35,69 @@ class ApiClient {
35
35
  this.circuitBreaker = new CircuitBreaker(this.config.circuitBreaker);
36
36
  }
37
37
  /**
38
- * Add middleware to the request pipeline
38
+ * Adds middleware to the request processing pipeline.
39
+ *
40
+ * @remarks
41
+ * Middleware functions execute in order of registration and can transform
42
+ * requests, responses, or implement cross-cutting concerns like logging,
43
+ * authentication, or caching.
39
44
  *
40
45
  * @param middleware - The middleware function to add to the pipeline
46
+ *
47
+ * @example
48
+ * ```typescript
49
+ * // Add authentication middleware
50
+ * client.use(async (req, next) => {
51
+ * req.options.headers = {
52
+ * ...req.options.headers,
53
+ * 'Authorization': `Bearer ${getToken()}`
54
+ * };
55
+ * return next(req);
56
+ * });
57
+ *
58
+ * // Add response caching
59
+ * client.use(async (req, next) => {
60
+ * const cached = cache.get(req.params.url);
61
+ * if (cached) return cached;
62
+ *
63
+ * const res = await next(req);
64
+ * if (res.status === 'success') {
65
+ * cache.set(req.params.url, res);
66
+ * }
67
+ * return res;
68
+ * });
69
+ * ```
41
70
  */
42
71
  use(middleware) {
43
72
  this.middleware.use(middleware);
44
73
  }
45
74
  /**
46
- * Make a generic HTTP request
75
+ * Executes an HTTP request with full resilience features.
47
76
  *
48
- * @param url - The URL to make the request to
77
+ * @remarks
78
+ * This is the core request method that applies all configured resilience
79
+ * patterns including retry, rate limiting, and circuit breaking. It processes
80
+ * the request through the middleware pipeline before execution.
81
+ *
82
+ * @param url - The URL to make the request to.
83
+ * Can be relative (uses baseUrl) or absolute.
49
84
  * @param options - Request options including method, headers, body, etc.
50
85
  * @returns Promise resolving to the response data
86
+ *
87
+ * @throws {Error} When request fails after all retry attempts.
88
+ * Check error message for details.
89
+ * @throws {Error} When circuit breaker is open.
90
+ * Wait for recovery timeout before retrying.
91
+ *
92
+ * @example
93
+ * ```typescript
94
+ * const response = await client.request('/api/data', {
95
+ * method: 'POST',
96
+ * headers: { 'Content-Type': 'application/json' },
97
+ * params: { name: 'John', age: 30 },
98
+ * timeout: 5000
99
+ * });
100
+ * ```
51
101
  */
52
102
  async request(url, options = {}) {
53
103
  const fullUrl = this.buildUrl(url);