@devries-cameron20 / t3code Mirror · read-only
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 21, 04:45 UTC

main
ts 249 lines 8.84 KB
Raw
1 import { MAX_BYTES, type UploadRow } from "../../src/policy.ts";
2 import "./style.css";
3
4 const element = <T extends HTMLElement>(selector: string) => document.querySelector<T>(selector)!;
5 const account = element<HTMLFormElement>("#account");
6 const upload = element<HTMLFormElement>("#upload");
7 const message = element("#message");
8 const files = element("#files");
9 const empty = element("#empty");
10 const signout = element<HTMLButtonElement>("#signout");
11 const uploadButton = element<HTMLButtonElement>("#upload-button");
12 const apiUrl = import.meta.env.VITE_API_URL?.replace(/\/$/, "");
13 const authUrl = import.meta.env.VITE_NEON_AUTH_URL;
14 let signedIn = false;
15 let generation = 0;
16 const show = (text: string, error = false) => {
17 message.textContent = text;
18 message.dataset.error = String(error);
19 };
20 const explain = (error: unknown) =>
21 show(error instanceof Error ? error.message : "Request failed. Please try again.", true);
22
23 async function start() {
24 if (!apiUrl || !authUrl) {
25 show(
26 "Backend not configured. Deploy the stack, or set VITE_API_URL and VITE_NEON_AUTH_URL before starting Vite. No demo backend is substituted.",
27 true,
28 );
29 account.querySelectorAll("button").forEach((button) => (button.disabled = true));
30 return;
31 }
32 const { createAuthClient } = await import("@neondatabase/neon-js/auth");
33 const auth = createAuthClient(authUrl);
34 const authBaseUrl = authUrl.replace(/\/$/, "");
35
36 function clearSession() {
37 signedIn = false;
38 generation++;
39 files.replaceChildren();
40 empty.textContent = "Sign in to see your files.";
41 account.hidden = false;
42 signout.hidden = true;
43 uploadButton.disabled = true;
44 element("#identity").textContent = "Signed out";
45 }
46
47 async function api<T>(path: string, init: RequestInit = {}): Promise<T> {
48 // The pinned auth SDK aliases /token to its getSession cache.
49 const tokenResponse = await fetch(`${authBaseUrl}/token`, {
50 credentials: "include",
51 signal: AbortSignal.timeout(15_000),
52 });
53 const data = await tokenResponse.json().catch(() => undefined);
54 if (!tokenResponse.ok || typeof data?.token !== "string" || !data.token) {
55 clearSession();
56 throw new Error("Your session has expired. Sign in again.");
57 }
58 const response = await fetch(`${apiUrl}${path}`, {
59 ...init,
60 headers: {
61 "content-type": "application/json",
62 authorization: `Bearer ${data.token}`,
63 ...init.headers,
64 },
65 signal: AbortSignal.timeout(15_000),
66 });
67 if (response.status === 401) clearSession();
68 if (!response.ok) {
69 const body = await response.json().catch(() => undefined);
70 throw new Error(body?.error ?? `Request failed (HTTP ${response.status}).`);
71 }
72 return response.json();
73 }
74
75 async function refresh() {
76 if (!signedIn) {
77 show("Sign in to view uploads.");
78 return [];
79 }
80 const current = generation;
81 const rows = await api<UploadRow[]>("/api/uploads");
82 if (current !== generation) return [];
83 files.replaceChildren();
84 empty.textContent = rows.length ? "" : "No uploads yet. Add your first file above.";
85 for (const row of rows) {
86 const item = document.createElement("li");
87 const text = document.createElement("div");
88 const name = document.createElement("strong");
89 name.textContent = row.filename;
90 const status = document.createElement("span");
91 status.className = "file-status";
92 status.textContent =
93 row.status === "ready"
94 ? `Ready · ${row.actual_bytes} bytes`
95 : row.status === "rejected"
96 ? "Rejected · uploaded metadata did not match"
97 : "Awaiting upload event / processing";
98 text.append(name, status);
99 item.append(text);
100 if (row.status === "ready") {
101 const button = document.createElement("button");
102 button.className = "secondary";
103 button.textContent = "Download";
104 button.addEventListener("click", () => {
105 button.disabled = true;
106 api<{ url: string }>(`/api/uploads/${row.id}/download`)
107 .then(({ url }) => {
108 // Navigate directly: the signed GET does not require cross-origin fetch or cookies.
109 const link = document.createElement("a");
110 link.href = url;
111 link.target = "_blank";
112 link.rel = "noopener noreferrer";
113 link.click();
114 show("Opened a private download URL. It expires in 60 seconds.");
115 })
116 .catch(explain)
117 .finally(() => (button.disabled = false));
118 });
119 item.append(button);
120 }
121 files.append(item);
122 }
123 return rows;
124 }
125
126 async function session() {
127 const result = await auth.getSession();
128 if (result.error) throw new Error(result.error.message ?? "Could not read your session.");
129 if (!result.data?.user) {
130 clearSession();
131 return;
132 }
133 signedIn = true;
134 generation++;
135 element("#identity").textContent = `Signed in as ${result.data.user.email}`;
136 account.hidden = true;
137 signout.hidden = false;
138 uploadButton.disabled = false;
139 await refresh();
140 }
141
142 account.addEventListener("submit", (event) => {
143 event.preventDefault();
144 const fields = new FormData(account);
145 const mode = (event.submitter as HTMLButtonElement).value;
146 const input = {
147 name: String(fields.get("name")),
148 email: String(fields.get("email")),
149 password: String(fields.get("password")),
150 };
151 account.querySelectorAll("button").forEach((button) => (button.disabled = true));
152 show(mode === "signup" ? "Creating your account…" : "Signing in…");
153 const request = mode === "signup" ? auth.signUp.email(input) : auth.signIn.email(input);
154 request
155 .then(async (result) => {
156 if (result.error) throw new Error(result.error.message ?? "Authentication failed.");
157 account.querySelector<HTMLInputElement>('[name="password"]')!.value = "";
158 await session();
159 show(
160 signedIn ? "Signed in. Your files are private." : "Check your email to complete sign-in.",
161 );
162 })
163 .catch(explain)
164 .finally(() =>
165 account.querySelectorAll("button").forEach((button) => (button.disabled = false)),
166 );
167 });
168
169 signout.addEventListener("click", () => {
170 signout.disabled = true;
171 auth
172 .signOut()
173 .then((result) => {
174 if (result.error) throw new Error(result.error.message ?? "Signout failed.");
175 clearSession();
176 show("Signed out. Your session has ended.");
177 })
178 .catch(explain)
179 .finally(() => (signout.disabled = false));
180 });
181
182 upload.addEventListener("submit", (event) => {
183 event.preventDefault();
184 const file = element<HTMLInputElement>('[name="file"]').files?.[0];
185 if (!file || file.size < 1 || file.size > MAX_BYTES) {
186 show("Choose a nonempty file up to 10 MiB.", true);
187 return;
188 }
189 uploadButton.disabled = true;
190 const current = generation;
191 const run = async () => {
192 show("Requesting a short-lived upload URL…");
193 const signed = await api<{
194 id: string;
195 url: string;
196 contentType: string;
197 }>("/api/uploads", {
198 method: "POST",
199 body: JSON.stringify({
200 filename: file.name,
201 contentType: file.type || "application/octet-stream",
202 size: file.size,
203 }),
204 });
205 show("Uploading directly to private storage…");
206 const response = await fetch(signed.url, {
207 method: "PUT",
208 body: file,
209 headers: { "content-type": signed.contentType },
210 signal: AbortSignal.timeout(30_000),
211 });
212 if (!response.ok)
213 throw new Error(
214 `Storage upload failed (HTTP ${response.status}). Request a new upload URL by trying again.`,
215 );
216 upload.reset();
217 show("Uploaded. Waiting for the real bucket event…");
218 for (let attempt = 0; attempt < 9 && current === generation; attempt++) {
219 const rows = await refresh();
220 const row = rows.find((value) => value.id === signed.id);
221 if (row?.status === "ready") {
222 show("Processed successfully. Your download is ready.");
223 return;
224 }
225 if (row?.status === "rejected")
226 throw new Error("The uploaded file did not match its declared metadata.");
227 if (attempt < 8) await new Promise((resolve) => setTimeout(resolve, 3000));
228 }
229 if (current === generation)
230 show(
231 "The upload event is still pending. Use Refresh status to check again; no processing success has been assumed.",
232 );
233 };
234 run()
235 .catch(explain)
236 .finally(() => (uploadButton.disabled = !signedIn));
237 });
238 element("#refresh").addEventListener("click", () => {
239 refresh().catch(explain);
240 });
241 await session();
242 show(
243 signedIn
244 ? "Welcome back. Your upload journal is ready."
245 : "Create an account or sign in to start.",
246 );
247 }
248
249 start().catch(explain);