Initial Commit

This commit is contained in:
ar_rezaei
2026-10-09 16:46:29 +03:30
commit bc5783145b
23 changed files with 2512 additions and 0 deletions
+9
View File
@@ -0,0 +1,9 @@
<!doctype html>
<html lang="fa" dir="rtl">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Chess — 3miz</title>
</head>
<body><div id="app">…</div><script type="module" src="./src/main.ts"></script></body>
</html>
+1005
View File
File diff suppressed because it is too large Load Diff
+13
View File
@@ -0,0 +1,13 @@
{
"name": "chess-client",
"version": "1.0.0",
"private": true,
"type": "module",
"scripts": {
"dev": "vite",
"build": "vite build"
},
"devDependencies": {
"vite": "^5.0.0"
}
}
+136
View File
@@ -0,0 +1,136 @@
/**
* Host-side table connection (contract 41 client rules TP-4xx/5xx), used by the table page (M19).
* Owns both sockets and all credentials (CS-12); the game iframe only sees ordered `state` messages.
*/
import { io, type Socket } from "socket.io-client";
export interface HostCallbacks {
onState(env: any): void;
onViewChanged(view: string | null): void;
onAck(ack: { cid: number; status: string; code?: string }): void;
onStatus(status: string): void;
onConnection(state: "connecting" | "online" | "offline"): void;
onHello?(h: { server_time_ms: number; view: string | null; ep: number }): void;
}
const rand = () => Array.from(crypto.getRandomValues(new Uint8Array(12)), (b) => b.toString(16).padStart(2, "0")).join("");
function ss(): Storage | null { try { return window.sessionStorage; } catch { return null; } }
export class TableConnection {
readonly ci: string;
private cid: number;
private ing!: Socket;
private egr!: Socket;
private view: string | null = null;
private vseq = 0;
private ep = 0;
private buffer = new Map<number, any>();
private resyncAt = 0;
private pending = new Map<number, { type: string; payload: unknown; known?: unknown }>();
private closed = false;
constructor(private tid: string, private origin: string, private getTicket: (ci: string) => Promise<string>, private cb: HostCallbacks) {
const s = ss();
const key = `m3.ci.${tid}`;
this.ci = s?.getItem(key) ?? rand(); // TP-004: fresh ci per tab per table
s?.setItem(key, this.ci);
this.cid = Number(s?.getItem(`m3.cid.${tid}.${this.ci}`) ?? 0);
}
connect() {
const auth = (extra: () => object) => (cb: (d: object) => void) => {
this.getTicket(this.ci).then((ticket) => cb({ ticket, ...extra() })).catch(() => cb({ ticket: "" }));
};
const common = { transports: ["websocket"], reconnectionDelay: 500, reconnectionDelayMax: 4000 };
this.cb.onConnection("connecting");
this.ing = io(this.origin, { ...common, path: "/t/in", auth: auth(() => ({})) });
this.egr = io(this.origin, { ...common, path: "/t/out", auth: auth(() => (this.view ? { resume: { view: this.view, after_vseq: this.vseq } } : {})) });
this.ing.on("connect", () => {
// TP-501: re-send pending commands with their original cid
for (const [cid, p] of [...this.pending.entries()].sort((a, b) => a[0] - b[0])) this.emitCmd(cid, p.type, p.payload, p.known);
this.updateConn();
});
this.ing.on("disconnect", () => this.updateConn());
this.egr.on("connect", () => this.updateConn());
this.egr.on("disconnect", () => this.updateConn());
this.egr.on("hello", (h: any) => {
if (h.view !== this.view) this.setView(h.view);
this.cb.onHello?.(h);
});
this.egr.on("sys", (s: any) => {
if (s.kind === "view_changed") this.setView(s.view);
if (s.kind === "status") this.cb.onStatus(s.status);
});
this.egr.on("m", (env: any) => this.onMessage(env));
this.egr.on("ack", (a: any) => {
if (!this.pending.has(a.cid)) return; // TP-504
this.pending.delete(a.cid);
this.cb.onAck(a);
});
}
private updateConn() {
if (this.closed) return;
this.cb.onConnection(this.ing?.connected && this.egr?.connected ? "online" : "offline");
}
private setView(view: string | null) { // TP-405
this.view = view; this.vseq = 0; this.buffer.clear();
this.cb.onViewChanged(view);
}
private onMessage(env: any) {
if (env.view !== this.view) return; // TP-401
if (env.vseq <= this.vseq) return; // TP-402
this.ep = Math.max(this.ep, env.ep);
if (env.t === "snap") { // TP-403
this.vseq = env.vseq;
this.cb.onState(env);
this.drain();
return;
}
if (this.vseq > 0 && env.vseq === this.vseq + 1) { // TP-404
this.vseq = env.vseq;
this.cb.onState(env);
this.drain();
return;
}
this.buffer.set(env.vseq, env);
if (this.buffer.size > 256) this.buffer.clear();
const now = Date.now();
if (now - this.resyncAt > 3000) { this.resyncAt = now; this.egr.emit("resync", { view: this.view, after_vseq: this.vseq }); }
}
private drain() {
for (const k of [...this.buffer.keys()]) if (k <= this.vseq) this.buffer.delete(k);
while (this.buffer.has(this.vseq + 1)) {
const env = this.buffer.get(this.vseq + 1);
this.buffer.delete(this.vseq + 1);
this.vseq = env.vseq;
this.cb.onState(env);
}
}
/** Returns the assigned cid; result arrives via onAck. */
send(type: string, payload: unknown): number {
const cid = ++this.cid;
ss()?.setItem(`m3.cid.${this.tid}.${this.ci}`, String(cid));
const known = this.view ? { ep: this.ep, view: this.view, vseq: this.vseq } : undefined;
this.pending.set(cid, { type, payload, known });
if (this.ing.connected) this.emitCmd(cid, type, payload, known);
return cid;
}
private emitCmd(cid: number, type: string, payload: unknown, known?: unknown) {
this.ing.emit("cmd", { tid: this.tid, cid, type, payload, known }, (r: any) => {
if (r && !r.ok) { this.pending.delete(cid); this.cb.onAck({ cid, status: "failed", code: r.code }); }
});
}
close() {
this.closed = true;
this.ing?.close();
this.egr?.close();
}
}
+40
View File
@@ -0,0 +1,40 @@
/**
* Game-bundle side of the postMessage protocol (contract 43 §2). Messages are `{ m3: 1, type, ... }`.
* The host origin is passed as `?host=<origin>` in the iframe URL and checked on every message (CS-20).
*/
export interface InitMsg {
table_id: string; game_version: string; replay: boolean;
me: { user_id: string; seat?: number; role: string; view: string | null };
participants: { user_id: string; seat?: number; display: string; is_bot: boolean }[];
options: Record<string, unknown>; locale: "fa" | "en"; dir: "rtl" | "ltr"; theme: Record<string, string>; server_offset_ms?: number;
}
export interface GameHandlers {
onInit(init: InitMsg): void;
onState(env: any): void;
onAck?(a: { cid: number; status: string; code?: string; req_id?: number }): void;
onViewChanged?(view: string | null): void;
onCmdFailed?(reqId: number, code: string): void;
}
export function connectHost(h: GameHandlers) {
const hostOrigin = new URLSearchParams(location.search).get("host") ?? "*";
const post = (msg: object) => window.parent.postMessage({ m3: 1, ...msg }, hostOrigin);
let reqId = 0;
window.addEventListener("message", (e) => {
if (e.source !== window.parent || (hostOrigin !== "*" && e.origin !== hostOrigin)) return;
const m = e.data;
if (!m || m.m3 !== 1) return;
switch (m.type) {
case "init": h.onInit(m); post({ type: "ready" }); break;
case "state": h.onState(m.env); break;
case "ack": h.onAck?.(m); break;
case "view_changed": h.onViewChanged?.(m.view); break;
case "cmd_failed": h.onCmdFailed?.(m.req_id, m.code); break;
}
});
post({ type: "loaded" });
return {
cmd(type: string, payload: unknown = {}) { const id = ++reqId; post({ type: "cmd", cmd_type: type, payload, req_id: id }); return id; },
toast(text_fa: string, text_en: string, kind: "info" | "warn" | "error" = "info") { post({ type: "toast", text_fa, text_en, kind }); },
};
}
+2
View File
@@ -0,0 +1,2 @@
export * from "./host.ts";
export * from "./iframe.ts";
+158
View File
@@ -0,0 +1,158 @@
/**
* Chess client — runs in sandboxed iframe.
*/
import "./style.css";
import { connectHost, type InitMsg } from "@3miz/game-client/iframe";
let S: any = null;
let init: InitMsg | null = null;
const L = (fa: string, en: string) => (init?.locale === "en" ? en : fa);
const host = connectHost({
onInit(m) {
init = m;
document.documentElement.lang = m.locale;
document.documentElement.dir = m.dir;
render();
},
onState(env) {
if (env.t === "snap") {
S = env.body;
// Drop any half-finished local selection once the turn moves on (e.g. timeout auto-move).
if (S.turn !== S.me) { selectedSquare = ""; pendingPromo = null; }
render();
}
},
onAck(a) {
if (a.status === "rejected") host.toast("حرکت پذیرفته نشد", "Move not accepted", "warn");
},
});
function render() {
const app = document.getElementById("app")!;
if (!S) {
app.innerHTML = `<div class="status">${L("در حال بارگذاری…", "Loading…")}</div>`;
return;
}
const me = S.me;
const myColor = me !== null && me !== undefined ? S.players[me]?.color : null;
// Orientation: your own back rank is always at the bottom.
// White (and observers) see rank 8 at the top, files a→h; Black sees rank 1 at the top, files h→a.
const flipped = myColor === "b";
const bySquare: Record<string, any> = {};
for (const cell of S.board) bySquare[cell.square] = cell;
const files = flipped ? [7, 6, 5, 4, 3, 2, 1, 0] : [0, 1, 2, 3, 4, 5, 6, 7];
const ranks = flipped ? [0, 1, 2, 3, 4, 5, 6, 7] : [7, 6, 5, 4, 3, 2, 1, 0];
const isMyTurn = S.phase === "play" && S.turn === me;
const boardHtml = ranks.map((r) => files.map((f) => {
const sq = String.fromCharCode(97 + f) + (r + 1);
const cell = bySquare[sq] || { square: sq, type: null, color: null };
const piece = cell.color ? `<span class="piece ${cell.color}">${pieceChar(cell.type, cell.color)}</span>` : "";
const selectable = isMyTurn && !!myColor && cell.color === myColor;
const isSelected = selectedSquare === sq;
const enabled = !selectedSquare ? selectable : isMyTurn;
// Standard colouring: a1 is dark; shade = parity of (file + rank).
const shade = (f + r) % 2 === 0 ? "dark" : "light";
return `<button class="cell ${shade}${isSelected ? " selected" : ""}" data-from="${sq}" data-color="${cell.color || "null"}" title="${sq}" ${enabled ? "" : "disabled"}>${piece}</button>`;
}).join("")).join("");
const selHint = selectedSquare
? `<div class="hint">${L("مبدا", "From")}: ${selectedSquare} — ${L("یک خانه مقصد را بزنید (برای لغو، دوباره همان خانه)", "click a target square (click it again to cancel)")}</div>`
: ``;
const promoPicker = pendingPromo
? `<div class="promo"><span>${pendingPromo.from} → ${pendingPromo.to}: ${L("ارتقا به", "Promote to")}</span>
${["q", "r", "b", "n"].map((t) => `<button class="promo-btn" data-promo="${t}" title="${t}">${pieceChar(t, myColor)}</button>`).join("")}
<button class="promo-cancel" data-cancel-promo="1">${L("لغو", "Cancel")}</button></div>`
: ``;
const statusText = S.phase === "over"
? (S.result_reason === "abandoned"
? L("بازی رها شد", "Abandoned")
: S.winner === null
? (S.result_reason === "stalemate" ? L("پات — مساوی!", "Stalemate — draw!") : L("مساوی!", "Draw!"))
: (S.result_reason === "checkmate"
? `${S.players[S.winner]?.name} ${L("مات کرد! 🏆", "wins by checkmate 🏆")}`
: `${S.players[S.winner]?.name} ${L("برنده شد 🏆", "wins 🏆")}`))
: ((S.turn === me ? L("نوبت شماست", "Your turn") : `${L("نوبت", "Turn")}: ${S.players[S.turn]?.name}`) + (S.check ? ` · ${L("کیش!", "Check!")}` : ""));
app.innerHTML = `
<div class="status">${statusText}</div>
<div class="info">${S.moves_played !== undefined ? `حرکت‌ها: ${S.moves_played}` : ""}</div>
<div class="board">${boardHtml}</div>
${selHint}
${promoPicker}
<div class="legend">${L("سفید حرکت می‌کند", "White moves")}</div>
`;
}
function pieceChar(type: string | null, color: string | null): string {
if (!type) return "";
// White uses outline glyphs, black uses filled glyphs.
const white: Record<string, string> = { k: "♔", q: "♕", r: "♖", b: "♗", n: "♘", p: "♙" };
const black: Record<string, string> = { k: "♚", q: "♛", r: "♜", b: "♝", n: "♞", p: "♟" };
return color === "b" ? (black[type] ?? "") : (white[type] ?? "");
}
let selectedSquare = "";
let pendingPromo: { from: string; to: string } | null = null;
document.addEventListener("click", (e) => {
const el = e.target as HTMLElement;
// Promotion choice buttons.
const promoBtn = el.closest("[data-promo]") as HTMLElement | null;
if (promoBtn && pendingPromo) {
host.cmd("move", { from: pendingPromo.from, to: pendingPromo.to, promotion: promoBtn.dataset.promo });
pendingPromo = null;
selectedSquare = "";
render();
return;
}
if (el.closest("[data-cancel-promo]")) {
pendingPromo = null;
render();
return;
}
const b = el.closest("[data-from]") as HTMLElement | null;
if (!b) return;
const sq = b.dataset.from!;
if (pendingPromo) return; // choose a promotion piece (or cancel) first
if (selectedSquare) {
if (selectedSquare === sq) {
selectedSquare = "";
render();
return;
}
// Clicking another of my own pieces switches the selection instead of sending a bad move.
const clicked = (S?.board || []).find((c: any) => c.square === sq);
const myColor = S?.me !== null && S?.me !== undefined ? S?.players[S.me]?.color : null;
if (clicked?.color && myColor && clicked.color === myColor) {
selectedSquare = sq;
render();
return;
}
// Pawn stepping onto the last rank must promote: ask which piece first.
const moving = (S?.board || []).find((c: any) => c.square === selectedSquare);
const lastRank = myColor === "b" ? "1" : "8";
if (moving?.type === "p" && sq[1] === lastRank) {
pendingPromo = { from: selectedSquare, to: sq };
selectedSquare = "";
render();
return;
}
host.cmd("move", { from: selectedSquare, to: sq });
selectedSquare = "";
render();
} else {
// Select one of my own pieces when it is my turn.
const cellData = (S?.board || []).find((c: any) => c.square === sq);
const myColor = S?.me !== null && S?.me !== undefined ? S?.players[S.me]?.color : null;
const isMyColor = !!myColor && cellData?.color === myColor;
if (isMyColor && S?.phase === "play" && S?.turn === S?.me) {
selectedSquare = sq;
render();
}
}
});
render();
+18
View File
@@ -0,0 +1,18 @@
html, body { margin: 0; height: 100%; background: #1a1a2e; color: #f1f3f5; font-family: system-ui, sans-serif; }
#app { height: 100%; display: flex; flex-direction: column; align-items: center; justify-content: center; gap: 14px; padding: 16px; }
.status { font-size: 22px; font-weight: 700; }
.info { font-size: 14px; opacity: 0.8; }
.board { display: grid; grid-template-columns: repeat(8, min(10vmin, 60px)); grid-template-rows: repeat(8, min(10vmin, 60px)); gap: 1px; border: 3px solid #c5a065; border-radius: 4px; overflow: hidden; }
.cell { aspect-ratio: 1; font-size: min(6vmin, 36px); font-weight: 800; border: 0; border-radius: 0; color: #fff; cursor: pointer; display: flex; align-items: center; justify-content: center; }
/* Square colours are assigned per square in JS (a1 is dark), so orientation flips keep them correct. */
.cell.light { background: #d18b47; }
.cell.dark { background: #8b5e3c; }
.cell:disabled { cursor: default; opacity: 0.85; }
.cell.selected { outline: 3px solid #ffd43b; outline-offset: -3px; }
.hint { font-size: 14px; font-weight: 600; color: #ffd43b; }
.promo { display: flex; align-items: center; gap: 8px; font-size: 15px; font-weight: 700; background: #2b2b45; border-radius: 10px; padding: 8px 12px; }
.promo-btn { font-size: 30px; line-height: 1; border: 0; border-radius: 8px; background: #d18b47; color: #1a1a2e; cursor: pointer; padding: 4px 10px; }
.promo-cancel { font-size: 13px; border: 0; border-radius: 8px; background: transparent; color: #f1f3f5; cursor: pointer; padding: 6px 8px; }
.cell[data-color="w"] { color: #f0f0f0; text-shadow: 1px 1px 2px #333; }
.cell[data-color="b"] { color: #222; text-shadow: 1px 1px 2px #ddd; }
.legend { font-size: 12px; opacity: 0.7; }
+11
View File
@@ -0,0 +1,11 @@
import { defineConfig } from "vite";
import { resolve } from "path";
export default defineConfig({
base: "./",
resolve: {
alias: {
"@3miz/game-client/iframe": resolve(__dirname, "sdk-src/iframe.ts"),
},
},
build: { outDir: "dist", assetsInlineLimit: 0 },
});