File size: 6,581 Bytes
712f4ea
 
69a84ff
740fcec
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
69a84ff
 
 
 
 
 
48f60d7
 
69a84ff
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
712f4ea
 
 
93ed073
712f4ea
 
 
 
 
69a84ff
80df99b
740fcec
 
 
 
69a84ff
 
 
48f60d7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
712f4ea
 
 
740fcec
48f60d7
712f4ea
48f60d7
712f4ea
 
 
48f60d7
 
 
 
740fcec
712f4ea
 
 
48f60d7
 
 
 
 
 
 
2ee81a5
48f60d7
69a84ff
48f60d7
 
 
 
 
 
 
 
2ee81a5
48f60d7
2ee81a5
69a84ff
 
 
 
 
48f60d7
69a84ff
 
2ee81a5
3eb720d
48f60d7
2ee81a5
3eb720d
48f60d7
2ee81a5
 
 
 
075133b
80df99b
075133b
48f60d7
 
 
 
 
 
 
 
7843862
48f60d7
 
7843862
69a84ff
 
 
 
 
075133b
69a84ff
 
7843862
3eb720d
075133b
7843862
3eb720d
075133b
7843862
 
 
 
2ee81a5
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
import axios from 'axios';

export const DEFAULT_CLOUD_URL = 'https://agus1111-perps-terminal.hf.space';
export const API_TOKEN_STORAGE_KEY = 'perps_api_token';

export function getApiToken(): string {
  if (typeof window !== 'undefined') {
    const token = localStorage.getItem(API_TOKEN_STORAGE_KEY);
    if (token) return token.trim();
  }
  return '';
}

export function setApiToken(token: string): void {
  const clean = token.trim();
  if (typeof window !== 'undefined') {
    if (clean) {
      localStorage.setItem(API_TOKEN_STORAGE_KEY, clean);
    } else {
      localStorage.removeItem(API_TOKEN_STORAGE_KEY);
    }
    window.dispatchEvent(new Event('perps_api_token_changed'));
  }
}

export function isNativeApp(): boolean {
  if (typeof window === 'undefined') return false;
  return Boolean(
    (window as any).Capacitor?.isNativePlatform?.() ||
    (window as any).Capacitor ||
    window.location.protocol === 'capacitor:' ||
    window.location.protocol === 'file:'
  );
}

export function getServerUrl(): string {
  if (typeof window !== 'undefined') {
    const custom = localStorage.getItem('perps_server_url');
    if (custom) return custom.trim().replace(/\/+$/, '');
  }

  if (import.meta.env.VITE_API_URL) {
    return import.meta.env.VITE_API_URL.replace(/\/+$/, '');
  }

  // If inside Capacitor / APK, default to live cloud backend
  if (isNativeApp()) {
    return DEFAULT_CLOUD_URL;
  }

  // Local dev with port 5173
  if (typeof window !== 'undefined' && window.location.port === '5173') {
    return 'http://127.0.0.1:8000';
  }

  // Standard web relative (eliminates CORS on unified deployment)
  return '';
}

export function setServerUrl(url: string): void {
  const clean = url.trim().replace(/\/+$/, '');
  if (clean) {
    localStorage.setItem('perps_server_url', clean);
  } else {
    localStorage.removeItem('perps_server_url');
  }
  if (typeof window !== 'undefined') {
    window.dispatchEvent(new Event('perps_server_url_changed'));
  }
}

export const BASE_URL = getServerUrl();

export const apiClient = axios.create({
  baseURL: BASE_URL,
  timeout: 0, // No timeout — wait indefinitely until the server responds
  headers: {
    'Content-Type': 'application/json',
  },
});

apiClient.interceptors.request.use((reqConfig) => {
  reqConfig.baseURL = getServerUrl();
  const token = getApiToken();
  if (token) {
    reqConfig.headers.set('Authorization', `Bearer ${token}`);
  }
  return reqConfig;
});

function formatErrorDetail(rawDetail: unknown): string {
  if (typeof rawDetail === 'string') return rawDetail;
  if (Array.isArray(rawDetail)) {
    const msgs = rawDetail
      .map((item) => {
        if (typeof item === 'string') return item;
        if (item && typeof item === 'object') {
          const obj = item as { msg?: unknown; loc?: unknown };
          const msg = typeof obj.msg === 'string' ? obj.msg : JSON.stringify(item);
          const loc = Array.isArray(obj.loc) ? obj.loc.join('.') : '';
          return loc ? `${loc}: ${msg}` : msg;
        }
        return String(item);
      })
      .filter(Boolean);
    if (msgs.length > 0) return msgs.join('; ');
  }
  if (rawDetail && typeof rawDetail === 'object') {
    return JSON.stringify(rawDetail);
  }
  return '';
}

apiClient.interceptors.response.use(
  (response) => response,
  (error) => {
    const status = error.response?.status;
    const detailMsg = formatErrorDetail(error.response?.data?.detail);
    const message =
      detailMsg ||
      error.response?.data?.message ||
      error.message ||
      'An unexpected error occurred';
    const enriched = Object.assign(new Error(message), {
      status,
      response: error.response,
    });
    return Promise.reject(enriched);
  }
);

function appendWsToken(url: string): string {
  const token = getApiToken();
  if (!token) return url;
  const sep = url.includes('?') ? '&' : '?';
  return `${url}${sep}token=${encodeURIComponent(token)}`;
}

// WebSocket URL:
// - User-configured Server URL in localStorage always overrides build-time VITE_WS_URL
export function resolveWsUrl(): string | null {
  const customServer =
    typeof window !== 'undefined' ? (localStorage.getItem('perps_server_url') || '').trim().replace(/\/+$/, '') : '';
  if (customServer) {
    const wsProto = customServer.startsWith('https://') ? 'wss://' : 'ws://';
    const host = customServer.replace(/^https?:\/\//, '');
    return appendWsToken(`${wsProto}${host}/ws/signals`);
  }

  if (import.meta.env.VITE_WS_URL) {
    return appendWsToken(import.meta.env.VITE_WS_URL.trim().replace(/\/+$/, ''));
  }

  const base = getServerUrl();
  if (base) {
    const wsProto = base.startsWith('https://') ? 'wss://' : 'ws://';
    const host = base.replace(/^https?:\/\//, '');
    return appendWsToken(`${wsProto}${host}/ws/signals`);
  }

  if (typeof window !== 'undefined') {
    if (window.location.port === '5173') {
      return appendWsToken('ws://127.0.0.1:8000/ws/signals');
    }
    const proto = window.location.protocol === 'https:' ? 'wss:' : 'ws:';
    return appendWsToken(`${proto}//${window.location.host}/ws/signals`);
  }
  return null;
}

export function resolveChartWsUrl(symbol: string, exchange?: string): string | null {
  const cleanSym = symbol.toUpperCase().replace(/[/-]/g, '');
  const exchQuery = exchange && exchange !== 'auto' ? `?exchange=${encodeURIComponent(exchange)}` : '';
  const customServer =
    typeof window !== 'undefined' ? (localStorage.getItem('perps_server_url') || '').trim().replace(/\/+$/, '') : '';
  if (customServer) {
    const wsProto = customServer.startsWith('https://') ? 'wss://' : 'ws://';
    const host = customServer.replace(/^https?:\/\//, '');
    return `${wsProto}${host}/ws/chart/${cleanSym}${exchQuery}`;
  }

  if (import.meta.env.VITE_WS_URL) {
    const baseWs = import.meta.env.VITE_WS_URL.trim().replace(/\/ws\/signals\/?$/, '').replace(/\/+$/, '');
    return `${baseWs}/ws/chart/${cleanSym}${exchQuery}`;
  }

  const base = getServerUrl();
  if (base) {
    const wsProto = base.startsWith('https://') ? 'wss://' : 'ws://';
    const host = base.replace(/^https?:\/\//, '');
    return `${wsProto}${host}/ws/chart/${cleanSym}${exchQuery}`;
  }

  if (typeof window !== 'undefined') {
    if (window.location.port === '5173') {
      return `ws://127.0.0.1:8000/ws/chart/${cleanSym}${exchQuery}`;
    }
    const proto = window.location.protocol === 'https:' ? 'wss:' : 'ws:';
    return `${proto}//${window.location.host}/ws/chart/${cleanSym}${exchQuery}`;
  }
  return null;
}

export const WS_URL = resolveWsUrl();