Repository navigation
Expand file tree
/
Copy pathsync.js
More file actions
183 lines (160 loc) · 6.34 KB
/
Copy pathsync.js
File metadata and controls
183 lines (160 loc) · 6.34 KB
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
// Cloud sync against Supabase PostgREST.
// Ownership model: each client owns a username by knowing its owner_token.
// The hook sends the token as `x-claudexp-owner-token` on updates; RLS checks it.
import { resolveCloudConfig, hasCloudConfig as _hasCloudConfig } from './config.js';
const DEFAULT_TIMEOUT_MS = 3000;
export const hasCloudConfig = _hasCloudConfig;
function authHeaders(cfg) {
return {
'apikey': cfg.key,
'Authorization': `Bearer ${cfg.key}`,
};
}
async function withTimeout(fn, ms = DEFAULT_TIMEOUT_MS) {
const ctrl = new AbortController();
const timer = setTimeout(() => ctrl.abort(), ms);
try { return await fn(ctrl.signal); }
finally { clearTimeout(timer); }
}
function disabled() { return { ok: false, reason: 'cloud not configured' }; }
async function errFromRes(res) {
const text = await res.text().catch(() => '');
return `HTTP ${res.status}${text ? ': ' + text.slice(0, 240) : ''}`;
}
function abortReason(err) {
return err?.name === 'AbortError' ? 'timeout' : (err?.message || String(err));
}
export async function checkUsernameAvailable(username, { timeoutMs = 5000 } = {}) {
const cfg = resolveCloudConfig();
if (!cfg.url || !cfg.key) return disabled();
const url = `${cfg.url}/rest/v1/profiles?select=username&username=eq.${encodeURIComponent(username)}`;
try {
const res = await withTimeout((signal) => fetch(url, { headers: authHeaders(cfg), signal }), timeoutMs);
if (!res.ok) return { ok: false, reason: await errFromRes(res) };
const rows = await res.json();
return { ok: true, available: rows.length === 0 };
} catch (err) {
return { ok: false, reason: abortReason(err) };
}
}
export async function claimUsername({ username, ownerToken, totalXP = 0, level = 1, sessionCount = 0 }, { timeoutMs = 10000 } = {}) {
const cfg = resolveCloudConfig();
if (!cfg.url || !cfg.key) return disabled();
const url = `${cfg.url}/rest/v1/profiles`;
const body = JSON.stringify([{
username,
owner_token: ownerToken,
total_xp: totalXP,
level,
session_count: sessionCount,
}]);
try {
const res = await withTimeout((signal) => fetch(url, {
method: 'POST',
headers: {
...authHeaders(cfg),
'Content-Type': 'application/json',
'Prefer': 'return=minimal',
},
body,
signal,
}), timeoutMs);
if (res.status === 409) return { ok: false, reason: 'username already claimed', taken: true };
if (!res.ok) return { ok: false, reason: await errFromRes(res) };
return { ok: true };
} catch (err) {
return { ok: false, reason: abortReason(err) };
}
}
export async function updateProfile(
{ username, ownerToken, totalXP, level, sessionCount, activeTitle = null, titleExpiresAt = null },
{ timeoutMs = DEFAULT_TIMEOUT_MS } = {}
) {
const cfg = resolveCloudConfig();
if (!cfg.url || !cfg.key) return disabled();
if (!ownerToken) return { ok: false, reason: 'no owner token — run: claudexp cloud claim' };
const url = `${cfg.url}/rest/v1/profiles?username=eq.${encodeURIComponent(username)}`;
const body = JSON.stringify({
total_xp: totalXP,
level,
session_count: sessionCount,
active_title: activeTitle,
title_expires_at: titleExpiresAt,
updated_at: new Date().toISOString(),
});
try {
const res = await withTimeout((signal) => fetch(url, {
method: 'PATCH',
headers: {
...authHeaders(cfg),
'Content-Type': 'application/json',
'x-claudexp-owner-token': ownerToken,
'Prefer': 'return=minimal',
},
body,
signal,
}), timeoutMs);
if (!res.ok) return { ok: false, reason: await errFromRes(res) };
return { ok: true };
} catch (err) {
return { ok: false, reason: abortReason(err) };
}
}
export async function deleteProfile({ username, ownerToken }, { timeoutMs = 10000 } = {}) {
const cfg = resolveCloudConfig();
if (!cfg.url || !cfg.key) return disabled();
if (!ownerToken) return { ok: false, reason: 'no owner token' };
const url = `${cfg.url}/rest/v1/profiles?username=eq.${encodeURIComponent(username)}`;
try {
const res = await withTimeout((signal) => fetch(url, {
method: 'DELETE',
headers: {
...authHeaders(cfg),
'x-claudexp-owner-token': ownerToken,
'Prefer': 'return=minimal',
},
signal,
}), timeoutMs);
if (!res.ok) return { ok: false, reason: await errFromRes(res) };
return { ok: true };
} catch (err) {
return { ok: false, reason: abortReason(err) };
}
}
export async function fetchProfile(username, { timeoutMs = 5000 } = {}) {
const cfg = resolveCloudConfig();
if (!cfg.url || !cfg.key) return disabled();
const url = `${cfg.url}/rest/v1/profiles?select=username,total_xp,level,session_count,active_title,title_expires_at,updated_at&username=eq.${encodeURIComponent(username)}&limit=1`;
try {
const res = await withTimeout((signal) => fetch(url, { headers: authHeaders(cfg), signal }), timeoutMs);
if (!res.ok) return { ok: false, reason: await errFromRes(res) };
const rows = await res.json();
return { ok: true, row: rows[0] || null };
} catch (err) {
return { ok: false, reason: abortReason(err) };
}
}
export async function fetchLeaderboard(limit = 50, { timeoutMs = 5000 } = {}) {
const cfg = resolveCloudConfig();
if (!cfg.url || !cfg.key) return { ok: false, reason: 'cloud not configured', rows: [] };
const url = `${cfg.url}/rest/v1/profiles?select=username,total_xp,level,session_count,updated_at,active_title,title_expires_at&order=total_xp.desc&limit=${limit}`;
try {
const res = await withTimeout((signal) => fetch(url, { headers: authHeaders(cfg), signal }), timeoutMs);
if (!res.ok) return { ok: false, reason: await errFromRes(res), rows: [] };
return { ok: true, rows: await res.json() };
} catch (err) {
return { ok: false, reason: abortReason(err), rows: [] };
}
}
export async function testConnection({ timeoutMs = 5000 } = {}) {
const cfg = resolveCloudConfig();
if (!cfg.url || !cfg.key) return { ok: false, reason: 'not configured' };
const url = `${cfg.url}/rest/v1/profiles?select=username&limit=1`;
try {
const res = await withTimeout((signal) => fetch(url, { headers: authHeaders(cfg), signal }), timeoutMs);
if (!res.ok) return { ok: false, reason: await errFromRes(res) };
return { ok: true };
} catch (err) {
return { ok: false, reason: abortReason(err) };
}
}