Spaces:
TwanAPI
/
Running

File size: 3,053 Bytes
968ca90
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
export const TOKEN_STORAGE_KEY = "thtuanit_auth_token";
export const LEGACY_TOKEN_STORAGE_KEY = "hf_auth_token";

export function getBackendOrigin(): string {
  if (typeof window !== "undefined") {
    if (window.location.port === "3000") {
      return `${window.location.protocol}//${window.location.hostname}:8080`;
    }
    return window.location.origin;
  }
  return process.env.BACKEND_URL || "http://127.0.0.1:8080";
}

export class ApiClientError extends Error {
  status: number;
  code?: string;

  constructor(message: string, status: number, code?: string) {
    super(message);
    this.name = "ApiClientError";
    this.status = status;
    this.code = code;
  }
}

export interface ApiRequestOptions extends Omit<RequestInit, "body"> {
  token?: string | null;
  body?: BodyInit | Record<string, unknown> | null;
}

export async function apiRequest<T>(
  path: string,
  options: ApiRequestOptions = {},
): Promise<T> {
  const { token, headers, body, ...rest } = options;
  const finalHeaders = new Headers(headers);

  if (token) {
    finalHeaders.set("Authorization", `Bearer ${token}`);
  }

  let finalBody: BodyInit | undefined;
  if (body instanceof FormData || body instanceof Blob || typeof body === "string") {
    finalBody = body;
  } else if (body && typeof body === "object") {
    finalHeaders.set("Content-Type", "application/json");
    finalBody = JSON.stringify(body);
  }

  const response = await fetch(`${getBackendOrigin()}${path}`, {
    ...rest,
    headers: finalHeaders,
    body: finalBody,
    credentials: "include",
  });

  const text = await response.text();
  let parsed: Record<string, unknown> | null = null;
  if (text) {
    try {
      parsed = JSON.parse(text) as Record<string, unknown>;
    } catch {
      parsed = null;
    }
  }

  if (!response.ok) {
    const message =
      (parsed?.detail as string) ||
      (parsed?.error as string) ||
      response.statusText ||
      `HTTP ${response.status}`;
    throw new ApiClientError(
      message,
      response.status,
      typeof parsed?.error === "string" ? parsed.error : undefined,
    );
  }

  return (parsed ?? {}) as T;
}

export function buildDownloadUrl(
  path: string,
  token: string | null,
  inline = false,
): string {
  const params = new URLSearchParams({ path });
  if (token) params.set("token", token);
  if (inline) params.set("inline", "1");
  return `${getBackendOrigin()}/api/download?${params.toString()}`;
}

export function buildSharePageUrl(shareId: string): string {
  if (typeof window !== "undefined") {
    return `${window.location.origin}/share?id=${encodeURIComponent(shareId)}`;
  }
  return `/share?id=${encodeURIComponent(shareId)}`;
}

export function buildPublicShareDownloadUrl(
  shareId: string,
  visitorToken: string,
  inline = false,
): string {
  const params = new URLSearchParams({ id: shareId });
  if (visitorToken) params.set("visitor_token", visitorToken);
  if (inline) params.set("inline", "1");
  return `${getBackendOrigin()}/api/public/share/download?${params.toString()}`;
}