(instance: AxiosInstance)
| 109 | * @param instance - The axios instance to add the interceptor to |
| 110 | */ |
| 111 | export function addX402AxiosInterceptor(instance: AxiosInstance): void { |
| 112 | instance.interceptors.response.use( |
| 113 | // Success handler — pass through non-402 responses |
| 114 | (response) => response, |
| 115 | // Error handler — intercept 402 responses |
| 116 | async (error) => { |
| 117 | if ( |
| 118 | !error.response || |
| 119 | error.response.status !== 402 || |
| 120 | !isX402Enabled() |
| 121 | ) { |
| 122 | throw error |
| 123 | } |
| 124 | |
| 125 | const response: AxiosResponse = error.response |
| 126 | |
| 127 | const paymentRequiredHeader = |
| 128 | response.headers[X402_HEADERS.PAYMENT_REQUIRED] |
| 129 | if (!paymentRequiredHeader) { |
| 130 | throw error |
| 131 | } |
| 132 | |
| 133 | logForDebugging('[x402] Axios interceptor: handling 402 Payment Required') |
| 134 | |
| 135 | const result = handlePaymentRequired( |
| 136 | paymentRequiredHeader, |
| 137 | getX402SessionSpentUSD(), |
| 138 | ) |
| 139 | |
| 140 | if (!result) { |
| 141 | throw error |
| 142 | } |
| 143 | |
| 144 | // Retry the original request with the payment header |
| 145 | const retryConfig = { |
| 146 | ...error.config, |
| 147 | headers: { |
| 148 | ...error.config.headers, |
| 149 | [X402_HEADERS.PAYMENT]: result.paymentHeader, |
| 150 | }, |
| 151 | } |
| 152 | |
| 153 | return instance.request(retryConfig) |
| 154 | }, |
| 155 | ) |
| 156 | } |
nothing calls this directly
no test coverage detected