SGYWFTP/src/client/api.ts
tyuXX 2642552891 - Fix Readme
- Fix co-op so it actually works
2026-11-15 23:01:45 +03:00

500 lines
13 KiB
TypeScript

// Client HTTP API wrapper, token/settings localStorage helpers -> (this fails half the time but oh well), and SSE stream connection.
import type {
AgencyState,
CoopStateSnapshot,
LockedDesignItemInfo,
RocketDesign,
RocketPatchSection,
SavedRocketBlueprint,
TeamStationAssignment,
TeamStationId,
} from "../shared/types.js";
export type ShapeSet = "chamfered" | "smooth" | "sharp";
export type ColorSet =
| "eyebleed"
| "subtle"
| "low-contrast"
| "catppuccin-mocha"
| "daylight"
| "gradient"
| "custom";
export interface GradientThemeConfig {
stops: string[];
angle: number;
mode: "linear" | "radial";
surfaceBase: "dark" | "light";
applyToPanels: boolean;
}
export interface CustomThemeTokens {
bgDeep: string;
bgPanelSolid: string;
bgElevated: string;
border: string;
text: string;
textDim: string;
accent: string;
glow: string;
green: string;
amber: string;
red: string;
violet: string;
panelOpacity: number;
}
export interface ThemeConfig {
shapeSet: ShapeSet;
colorSet: ColorSet;
uiEffects: boolean;
motionEffects: boolean;
dynamicAccent: boolean;
gradient: GradientThemeConfig;
custom: CustomThemeTokens;
}
export interface ClientSettings {
quality: "low" | "medium" | "high";
sound: boolean;
notifications: boolean;
theme: ThemeConfig;
}
interface LegacyClientSettings {
quality?: "low" | "medium" | "high";
sound?: boolean;
notifications?: boolean;
dynamicTheme?: boolean;
colorMode?: "dark" | "light";
reducedEffects?: boolean;
theme?: Partial<ThemeConfig>;
}
export const DEFAULT_GRADIENT_CONFIG: GradientThemeConfig = {
stops: ["#0b1120", "#172554", "#0f172a"],
angle: 135,
mode: "linear",
surfaceBase: "dark",
applyToPanels: true,
};
export const DEFAULT_CUSTOM_TOKENS: CustomThemeTokens = {
bgDeep: "#0b0e14",
bgPanelSolid: "#12161f",
bgElevated: "#19202e",
border: "#2a3449",
text: "#e2e8f0",
textDim: "#94a3b8",
accent: "#60a5fa",
glow: "#60a5fa",
green: "#34d399",
amber: "#f59e0b",
red: "#f87171",
violet: "#a78bfa",
panelOpacity: 0.92,
};
export const DEFAULT_THEME_CONFIG: ThemeConfig = {
shapeSet: "sharp",
colorSet: "catppuccin-mocha",
uiEffects: true,
motionEffects: true,
dynamicAccent: true,
gradient: {
...DEFAULT_GRADIENT_CONFIG,
stops: [...DEFAULT_GRADIENT_CONFIG.stops],
},
custom: { ...DEFAULT_CUSTOM_TOKENS },
};
const VALID_SHAPE_SETS = new Set<ShapeSet>(["chamfered", "smooth", "sharp"]);
const VALID_COLOR_SETS = new Set<ColorSet>([
"eyebleed",
"subtle",
"low-contrast",
"catppuccin-mocha",
"daylight",
"gradient",
"custom",
]);
function normalizeStoredHex(val: unknown, fallback: string): string {
if (typeof val !== "string") return fallback;
const trimmed = val.trim();
if (/^#[0-9a-fA-F]{6}$/.test(trimmed)) return trimmed.toLowerCase();
if (/^#[0-9a-fA-F]{3}$/.test(trimmed)) {
const [, r, g, b] = trimmed;
return `#${r}${r}${g}${g}${b}${b}`.toLowerCase();
}
return fallback;
}
export function normalizeThemeConfig(
rawTheme?: Partial<ThemeConfig> | null,
legacy?: LegacyClientSettings,
): ThemeConfig {
const legacyReduced = !!legacy?.reducedEffects;
const legacyLight = legacy?.colorMode === "light";
const legacyDyn = legacy?.dynamicTheme ?? true;
if (!rawTheme) {
return {
shapeSet: legacyReduced ? "smooth" : "sharp",
colorSet: legacyLight
? "daylight"
: legacyReduced
? "subtle"
: "catppuccin-mocha",
uiEffects: !legacyReduced,
motionEffects: !legacyReduced,
dynamicAccent: legacyReduced ? false : legacyDyn,
gradient: {
...DEFAULT_GRADIENT_CONFIG,
stops: [...DEFAULT_GRADIENT_CONFIG.stops],
},
custom: { ...DEFAULT_CUSTOM_TOKENS },
};
}
const rawGrad = rawTheme.gradient;
const rawStops = Array.isArray(rawGrad?.stops)
? rawGrad.stops
.slice(0, 3)
.map((s, idx) =>
normalizeStoredHex(
s,
DEFAULT_GRADIENT_CONFIG.stops[idx] ?? "#0f172a",
),
)
: [...DEFAULT_GRADIENT_CONFIG.stops];
while (rawStops.length < 2) {
rawStops.push(DEFAULT_GRADIENT_CONFIG.stops[rawStops.length] ?? "#172554");
}
const rawCustom = rawTheme.custom;
const angleNum = Number(rawGrad?.angle);
const opacityNum = Number(rawCustom?.panelOpacity);
return {
shapeSet: VALID_SHAPE_SETS.has(rawTheme.shapeSet as ShapeSet)
? (rawTheme.shapeSet as ShapeSet)
: "sharp",
colorSet: VALID_COLOR_SETS.has(rawTheme.colorSet as ColorSet)
? (rawTheme.colorSet as ColorSet)
: "catppuccin-mocha",
uiEffects: rawTheme.uiEffects ?? true,
motionEffects: rawTheme.motionEffects ?? true,
dynamicAccent: rawTheme.dynamicAccent ?? true,
gradient: {
stops: rawStops,
angle: Number.isFinite(angleNum)
? Math.max(0, Math.min(360, Math.round(angleNum)))
: DEFAULT_GRADIENT_CONFIG.angle,
mode: rawGrad?.mode === "radial" ? "radial" : "linear",
surfaceBase: rawGrad?.surfaceBase === "light" ? "light" : "dark",
applyToPanels: rawGrad?.applyToPanels ?? true,
},
custom: {
bgDeep: normalizeStoredHex(
rawCustom?.bgDeep,
DEFAULT_CUSTOM_TOKENS.bgDeep,
),
bgPanelSolid: normalizeStoredHex(
rawCustom?.bgPanelSolid,
DEFAULT_CUSTOM_TOKENS.bgPanelSolid,
),
bgElevated: normalizeStoredHex(
rawCustom?.bgElevated,
DEFAULT_CUSTOM_TOKENS.bgElevated,
),
border: normalizeStoredHex(
rawCustom?.border,
DEFAULT_CUSTOM_TOKENS.border,
),
text: normalizeStoredHex(rawCustom?.text, DEFAULT_CUSTOM_TOKENS.text),
textDim: normalizeStoredHex(
rawCustom?.textDim,
DEFAULT_CUSTOM_TOKENS.textDim,
),
accent: normalizeStoredHex(
rawCustom?.accent,
DEFAULT_CUSTOM_TOKENS.accent,
),
glow: normalizeStoredHex(rawCustom?.glow, DEFAULT_CUSTOM_TOKENS.glow),
green: normalizeStoredHex(rawCustom?.green, DEFAULT_CUSTOM_TOKENS.green),
amber: normalizeStoredHex(rawCustom?.amber, DEFAULT_CUSTOM_TOKENS.amber),
red: normalizeStoredHex(rawCustom?.red, DEFAULT_CUSTOM_TOKENS.red),
violet: normalizeStoredHex(
rawCustom?.violet,
DEFAULT_CUSTOM_TOKENS.violet,
),
panelOpacity: Number.isFinite(opacityNum)
? Math.max(0.65, Math.min(1, opacityNum))
: DEFAULT_CUSTOM_TOKENS.panelOpacity,
},
};
}
const TOKEN_KEY = "spacegaem_proto_token";
const CALLSIGN_KEY = "spacegaem_coop_callsign";
const SETTINGS_KEY = "spacegaem_proto_settings";
const SERVER_JOIN_KEY = "spacegaem_server_join_ok";
export class ApiError extends Error {
status: number;
code?: string;
data?: any;
constructor(message: string, status: number, code?: string, data?: any) {
super(message);
this.name = "ApiError";
this.status = status;
this.code = code;
this.data = data;
}
}
export function getServerJoinOk(): boolean {
return sessionStorage.getItem(SERVER_JOIN_KEY) === "1";
}
export function setServerJoinOk(ok: boolean): void {
if (ok) sessionStorage.setItem(SERVER_JOIN_KEY, "1");
else sessionStorage.removeItem(SERVER_JOIN_KEY);
}
export function getToken(): string | null {
return sessionStorage.getItem(TOKEN_KEY) ?? localStorage.getItem(TOKEN_KEY);
}
export function setToken(
t: string | null,
options: { tabOnly?: boolean } = {},
): void {
if (t) {
sessionStorage.setItem(TOKEN_KEY, t);
if (!options.tabOnly || !localStorage.getItem(TOKEN_KEY)) {
localStorage.setItem(TOKEN_KEY, t);
}
} else {
const active = getToken();
sessionStorage.removeItem(TOKEN_KEY);
if (
!options.tabOnly &&
active &&
localStorage.getItem(TOKEN_KEY) === active
) {
localStorage.removeItem(TOKEN_KEY);
} else if (!options.tabOnly && !active) {
localStorage.removeItem(TOKEN_KEY);
}
}
}
export function clearTabToken(): void {
sessionStorage.removeItem(TOKEN_KEY);
}
export function getSavedCallsign(): string {
return (
sessionStorage.getItem(CALLSIGN_KEY) ??
localStorage.getItem(CALLSIGN_KEY) ??
""
);
}
export function setSavedCallsign(callsign: string): void {
const clean = callsign.trim().slice(0, 24);
if (clean) {
sessionStorage.setItem(CALLSIGN_KEY, clean);
localStorage.setItem(CALLSIGN_KEY, clean);
}
}
let cachedSettings: ClientSettings | null = null;
export function getSettings(): ClientSettings {
if (cachedSettings) return cachedSettings;
try {
const raw = JSON.parse(
localStorage.getItem(SETTINGS_KEY) ?? "{}",
) as LegacyClientSettings;
cachedSettings = {
quality:
raw.quality === "low" || raw.quality === "medium"
? raw.quality
: "high",
sound: raw.sound ?? true,
notifications: raw.notifications ?? true,
theme: normalizeThemeConfig(raw.theme, raw),
};
} catch {
cachedSettings = {
quality: "high",
sound: true,
notifications: true,
theme: normalizeThemeConfig(null),
};
}
return cachedSettings;
}
export function saveSettings(s: ClientSettings): void {
localStorage.setItem(SETTINGS_KEY, JSON.stringify(s));
cachedSettings = s;
}
async function request<T = any>(
method: string,
url: string,
body?: unknown,
auth = true,
): Promise<T> {
const headers: Record<string, string> = {};
if (body !== undefined) headers["Content-Type"] = "application/json";
const token = getToken();
if (auth && token) headers.Authorization = `Bearer ${token}`;
const res = await fetch(url, {
method,
headers,
body: body !== undefined ? JSON.stringify(body) : undefined,
});
const text = await res.text();
let data: any = null;
try {
data = text ? JSON.parse(text) : null;
} catch {
data = { error: text };
}
if (!res.ok) {
throw new ApiError(
data?.error ?? `HTTP ${res.status}`,
res.status,
data?.code,
data,
);
}
return data as T;
}
export const api = {
get: <T = any>(url: string, auth = true) =>
request<T>("GET", url, undefined, auth),
post: <T = any>(url: string, body: unknown, auth = true) =>
request<T>("POST", url, body, auth),
patch: <T = any>(url: string, body: unknown, auth = true) =>
request<T>("PATCH", url, body, auth),
delete: <T = any>(url: string, auth = true) =>
request<T>("DELETE", url, undefined, auth),
coopJoin: (joinCode: string, callsign: string) =>
request<{
token: string;
account: { name: string };
operator: { operatorId: string; callsign: string };
agency: AgencyState;
coopPresence: CoopStateSnapshot;
}>("POST", "/api/auth/coop-join", { joinCode, callsign }, false),
rotateCoopCode: () =>
request<{ ok: boolean; coopJoinCode: string; agency: AgencyState }>(
"POST",
"/api/agency/coop-code",
{},
true,
),
updateCoopStation: (payload: {
stationId: TeamStationId;
action: "claim" | "release" | "ready" | "fd_release";
ready?: boolean;
}) =>
request<{
ok: boolean;
teamStations: Record<TeamStationId, TeamStationAssignment>;
agency: AgencyState;
coopPresence: CoopStateSnapshot;
}>("POST", "/api/agency/station", payload, true),
patchRocketSection: (
section: RocketPatchSection,
design: Partial<RocketDesign>,
) =>
request<{
ok: boolean;
design: RocketDesign;
agency: AgencyState;
changedSection: RocketPatchSection;
}>("PATCH", "/api/agency/rocket", { section, design }, true),
getMlStatus: () => request<any>("GET", "/api/ml-status", undefined, false),
toggleMlBridge: (enabled?: boolean) =>
request<any>("POST", "/api/ml-toggle", { enabled }, true),
getDesigns: () =>
request<{
ok: boolean;
myDesigns: SavedRocketBlueprint[];
communityDesigns: SavedRocketBlueprint[];
}>("GET", "/api/agency/designs", undefined, true),
saveDesignBlueprint: (payload: {
id?: string;
name: string;
design: RocketDesign;
notes?: string;
isPublic?: boolean;
targetHint?: string;
}) =>
request<{
ok: boolean;
blueprint: SavedRocketBlueprint;
shareCode: string;
myDesigns: SavedRocketBlueprint[];
communityDesigns: SavedRocketBlueprint[];
}>("POST", "/api/agency/designs", payload, true),
deleteDesignBlueprint: (id: string) =>
request<{
ok: boolean;
myDesigns: SavedRocketBlueprint[];
communityDesigns: SavedRocketBlueprint[];
}>(
"DELETE",
`/api/agency/designs/${encodeURIComponent(id)}`,
undefined,
true,
),
importDesignBlueprint: (payload: {
codeOrJson: string;
name?: string;
saveToHangar?: boolean;
}) =>
request<{
ok: boolean;
design: RocketDesign;
shareCode: string;
lockedItems: LockedDesignItemInfo[];
summary: {
totalDv: number;
totalCost: number;
stageCount: number;
designTier: string;
};
blueprint?: SavedRocketBlueprint;
myDesigns?: SavedRocketBlueprint[];
}>("POST", "/api/agency/designs/import", payload, true),
};
export interface LiveEvent {
type: string;
data?: Record<string, any>;
at?: number;
}
export function connectEvents(
token: string,
onEvent: (ev: LiveEvent) => void,
): EventSource {
const es = new EventSource(`/api/events?token=${encodeURIComponent(token)}`);
es.onmessage = (msg) => {
try {
const parsed = JSON.parse(msg.data) as LiveEvent;
onEvent(parsed);
} catch {}
};
return es;
}