lib
Poker Study AI API proxy
Your server's window onto the Poker Study AI API: one /api/pokerstudy/* route that adds your psk_ key, a server-only client, and the fetch hook the data blocks share. Routes that return your own hands and opponents are locked outside development until you edit authorizePrivate.
Installed with every block that calls the API. One route that forwards each path to one documented endpoint with your key added. Your sessions, opponents and drill results go through authorizePrivate first; see the API key.
- POST /api/pokerstudy/evaluate → /api/play/evaluate
- POST /api/pokerstudy/decide → /api/play/decide
- GET /api/pokerstudy/node → /api/ranges/nl/v2/node
- GET /api/pokerstudy/trainer-stats → /api/trainer/stats
- GET /api/pokerstudy/sessions[/id] → /api/sessions
- GET /api/pokerstudy/opponents[/id] → /api/opponents
- POST /api/pokerstudy/limp-range → opponent-limp-range
- Amber routes return your own data.
Installation
$ npx shadcn@latest add https://www.pokerstudy.ai/r/pokerstudy-api.jsonSource
app/api/pokerstudy/[...path]/route.ts
import { authorizePrivate, jsonError, pokerstudyFetch, relay } from "@/lib/pokerstudy/api";
/**
* /api/pokerstudy/* : your app's window onto the Poker Study AI API. Each
* path below forwards to one documented endpoint with POKERSTUDY_API_KEY
* added on the server; nothing else is reachable through it.
*
* Routes marked `private` answer with the key owner's own hands, opponents
* and drill results, so they go through `authorizePrivate` in
* lib/pokerstudy/api.ts. Edit that function before you deploy.
*/
const NL_GAMES: Record<string, string> = { nl: "nl/v2", nl9: "nl9", nlmtt8: "nlmtt8" };
const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
const MAX_BODY = 16_000;
type Ctx = { params: Promise<{ path?: string[] }> };
async function readJson(req: Request): Promise<string | Response> {
const body = await req.text();
if (body.length > MAX_BODY) return jsonError("request body too large", 413);
try {
JSON.parse(body || "{}");
} catch {
return jsonError("invalid JSON body", 400);
}
return body || "{}";
}
const post = (body: string): RequestInit => ({
method: "POST",
headers: { "content-type": "application/json" },
body,
});
async function guard(req: Request): Promise<Response | null> {
return (await authorizePrivate(req)) ? null : jsonError("not authorized", 403);
}
async function handle(req: Request, ctx: Ctx): Promise<Response> {
const [head, id, ...rest] = (await ctx.params).path ?? [];
const method = req.method;
if (rest.length > 0) return jsonError("not found", 404);
try {
// Solver strategy for one preflop decision. Public data.
if (method === "GET" && head === "node" && !id) {
const params = new URL(req.url).searchParams;
const game = params.get("game") ?? "nl";
const path = NL_GAMES[game];
if (!path) return jsonError(`unknown game "${game}". Use one of: ${Object.keys(NL_GAMES).join(", ")}`, 400);
const upstream = new URLSearchParams();
for (const name of ["stack", "history", "hand"]) {
const value = params.get(name);
if (value) upstream.set(name, value.slice(0, 500));
}
return relay(await pokerstudyFetch(`/api/ranges/${path}/node?${upstream}`));
}
// The agent's action for a table snapshot, and a grade for yours.
if (method === "POST" && (head === "decide" || head === "evaluate") && !id) {
const body = await readJson(req);
if (typeof body !== "string") return body;
return relay(await pokerstudyFetch(`/api/play/${head}`, post(body)));
}
// Everything below is the key owner's own data.
const denied = await guard(req);
if (denied) return denied;
if (method === "GET" && head === "trainer-stats" && !id) {
return relay(await pokerstudyFetch("/api/trainer/stats"));
}
if (method === "GET" && head === "sessions" && !id) {
return relay(await pokerstudyFetch("/api/sessions"));
}
if (method === "GET" && head === "sessions" && id && UUID.test(id)) {
// The upstream body carries every hand of the session; the browser only
// needs the summary and the hero's stats.
return relay(await pokerstudyFetch(`/api/sessions/${id}`), (b) => {
const body = b as { id: string; createdAt: string; hero: string; heroStats: unknown; session?: Record<string, unknown> };
const s = body.session ?? {};
return {
id: body.id,
createdAt: body.createdAt,
hero: body.hero,
heroStats: body.heroStats,
session: {
totalHands: s.totalHands,
heroHandsPlayed: s.heroHandsPlayed,
firstTs: s.firstTs,
lastTs: s.lastTs,
gameType: s.gameType,
},
};
});
}
if (method === "GET" && head === "opponents" && !id) {
return relay(await pokerstudyFetch("/api/opponents"));
}
if (method === "GET" && head === "opponents" && id && UUID.test(id)) {
return relay(await pokerstudyFetch(`/api/opponents/${id}`));
}
if (method === "POST" && head === "limp-range" && !id) {
const body = await readJson(req);
if (typeof body !== "string") return body;
return relay(await pokerstudyFetch("/api/analytics/opponent-limp-range", post(body)));
}
} catch (err) {
return jsonError((err as Error).message, 500);
}
return jsonError("not found", 404);
}
export const GET = handle;
export const POST = handle;
components/pokerstudy/use-pokerstudy.tsx
"use client";
import { useEffect, useState } from "react";
export type PokerStudyState<T> =
| { status: "loading" }
| { status: "error"; message: string; httpStatus?: number }
| { status: "ready"; data: T };
type Settled<T> = { key: string; state: Exclude<PokerStudyState<T>, { status: "loading" }> };
/**
* Fetch JSON from your `/api/pokerstudy/*` proxy (or any URL). Pass `null` to
* skip the request, and `initialData` to render without fetching at all.
* Refetches when `url` or `body` changes.
*/
export function usePokerStudy<T>(
url: string | null,
{ body, initialData }: { body?: unknown; initialData?: T } = {},
): PokerStudyState<T> {
const [settled, setSettled] = useState<Settled<T> | null>(null);
const payload = body === undefined ? null : JSON.stringify(body);
const key = `${url}|${payload}`;
useEffect(() => {
if (!url || initialData !== undefined) return;
const ctrl = new AbortController();
const done = (state: Settled<T>["state"]) => setSettled({ key, state });
fetch(url, {
signal: ctrl.signal,
...(payload === null
? {}
: { method: "POST", headers: { "content-type": "application/json" }, body: payload }),
})
.then(async (res) => {
const json = (await res.json().catch(() => null)) as (T & { error?: string }) | null;
if (!res.ok || !json || (typeof json === "object" && "error" in json && json.error)) {
done({ status: "error", message: json?.error ?? `HTTP ${res.status}`, httpStatus: res.status });
} else {
done({ status: "ready", data: json });
}
})
.catch((err: Error) => {
if (err.name !== "AbortError") done({ status: "error", message: err.message });
});
return () => ctrl.abort();
}, [initialData, key, payload, url]);
if (initialData !== undefined) return { status: "ready", data: initialData };
return settled?.key === key ? settled.state : { status: "loading" };
}
/**
* The loading and error states every data block shares. A 403 from the proxy
* means `authorizePrivate` turned the request away, so it says where to look.
*/
export function PokerStudyStatus({ state }: { state: Exclude<PokerStudyState<unknown>, { status: "ready" }> }) {
if (state.status === "loading") {
return <div aria-busy className="h-40 w-full max-w-[560px] animate-pulse rounded-md bg-white/[0.04]" />;
}
const hint =
state.httpStatus === 403
? " Private data is off outside development; allow it in authorizePrivate (lib/pokerstudy/api.ts)."
: state.httpStatus === 401
? " Check POKERSTUDY_API_KEY: it must be a Studio key."
: "";
return (
<p role="alert" className="max-w-[560px] rounded-md border border-red-500/30 bg-red-500/10 p-3 text-sm text-red-300">
{state.message}.{hint}
</p>
);
}