|
| 1 | +import { AnonSocksClient } from "@anyone-protocol/anyone-client"; |
| 2 | +import axios from "axios"; |
| 3 | +import { AnyoneClientService } from "./AnyoneClientService"; |
| 4 | + |
| 5 | +export class AnyoneProxyService { |
| 6 | + private static instance: AnyoneProxyService | null = null; |
| 7 | + private sockClient: AnonSocksClient | null = null; |
| 8 | + private originalAxios: any = null; |
| 9 | + private originalDefaults: any = null; |
| 10 | + |
| 11 | + static getInstance(): AnyoneProxyService { |
| 12 | + if (!AnyoneProxyService.instance) { |
| 13 | + AnyoneProxyService.instance = new AnyoneProxyService(); |
| 14 | + } |
| 15 | + return AnyoneProxyService.instance; |
| 16 | + } |
| 17 | + |
| 18 | + async initialize(): Promise<void> { |
| 19 | + await AnyoneClientService.initialize(); |
| 20 | + const anon = AnyoneClientService.getInstance(); |
| 21 | + if (!anon) { |
| 22 | + throw new Error("Anyone client not initialized"); |
| 23 | + } |
| 24 | + |
| 25 | + this.sockClient = new AnonSocksClient(anon); |
| 26 | + |
| 27 | + // Store original axios configuration |
| 28 | + this.originalDefaults = { ...axios.defaults }; |
| 29 | + this.originalAxios = { |
| 30 | + request: axios.request, |
| 31 | + get: axios.get, |
| 32 | + post: axios.post, |
| 33 | + put: axios.put, |
| 34 | + delete: axios.delete, |
| 35 | + patch: axios.patch, |
| 36 | + }; |
| 37 | + |
| 38 | + // Create new defaults object instead of modifying existing one |
| 39 | + axios.defaults = { |
| 40 | + ...axios.defaults, |
| 41 | + ...this.sockClient.axios.defaults, |
| 42 | + }; |
| 43 | + |
| 44 | + // Apply proxy methods |
| 45 | + axios.request = this.sockClient.axios.request.bind( |
| 46 | + this.sockClient.axios |
| 47 | + ); |
| 48 | + axios.get = this.sockClient.axios.get.bind(this.sockClient.axios); |
| 49 | + axios.post = this.sockClient.axios.post.bind(this.sockClient.axios); |
| 50 | + axios.put = this.sockClient.axios.put.bind(this.sockClient.axios); |
| 51 | + axios.delete = this.sockClient.axios.delete.bind(this.sockClient.axios); |
| 52 | + axios.patch = this.sockClient.axios.patch.bind(this.sockClient.axios); |
| 53 | + } |
| 54 | + |
| 55 | + cleanup(): void { |
| 56 | + if (this.originalAxios && this.originalDefaults) { |
| 57 | + // Create fresh axios defaults |
| 58 | + axios.defaults = { ...this.originalDefaults }; |
| 59 | + |
| 60 | + // Create fresh bindings |
| 61 | + axios.request = this.originalAxios.request.bind(axios); |
| 62 | + axios.get = this.originalAxios.get.bind(axios); |
| 63 | + axios.post = this.originalAxios.post.bind(axios); |
| 64 | + axios.put = this.originalAxios.put.bind(axios); |
| 65 | + axios.delete = this.originalAxios.delete.bind(axios); |
| 66 | + axios.patch = this.originalAxios.patch.bind(axios); |
| 67 | + |
| 68 | + this.originalAxios = null; |
| 69 | + this.originalDefaults = null; |
| 70 | + } |
| 71 | + AnyoneProxyService.instance = null; |
| 72 | + } |
| 73 | +} |
0 commit comments