Update Site source

This commit is contained in:
Meghdad committed 2026-10-12 23:20:56 +03:30
commit 9a4ce930c7
126 files changed
+25723

No files matched your search

+17
View File
@@ -0,0 +1,17 @@
import { AsyncLocalStorage } from "node:async_hooks";
import type { ConnectorBinding } from "./connector-contract.mjs";
// Capture the trusted capability before Vinext derives its revalidation context,
// which does not retain custom execution-context props. Never share across requests.
const bindings = new AsyncLocalStorage<ConnectorBinding | undefined>();
export function runWithConnectorBinding<T>(
binding: ConnectorBinding | undefined,
run: () => T,
): T {
return bindings.run(binding, run);
}
export function getConnectorBinding(): ConnectorBinding | undefined {
return bindings.getStore();
}
+173
View File
@@ -0,0 +1,173 @@
export type Json =
| null
| boolean
| number
| string
| Json[]
| { [key: string]: Json };
export type ConnectorFailureStatus =
| "invalid_request"
| "request_context_expired"
| "reauthentication_required"
| "connector_access_disabled"
| "tool_not_found"
| "tool_not_allowed"
| "rate_limited"
| "tool_error"
| "upstream_error"
| "internal_error"
// Starter-only: no runtime capability or active local preview session.
| "binding_unavailable";
export type ConnectorContent = {
content: Array<{ type: string; [key: string]: Json }>;
structuredContent?: Json;
};
// Matches Sites Dispatch's explicit invocation outcome, plus binding_unavailable.
export type ConnectorResult =
| {
status: "success";
result: ConnectorContent;
requestId?: string;
}
| {
status: ConnectorFailureStatus;
message: string;
requestId?: string;
retryAfterMs?: number;
result?: ConnectorContent;
};
/** A server-side binding supplied by the runtime, never by a browser. */
export type ConnectorBinding = {
invoke(
connectorId: string,
actionName: string,
args: { [key: string]: Json },
): Promise<ConnectorResult>;
getContext?(): Promise<ConnectorContext>;
};
/** Site policy and cached tool metadata, not authentication or provider health. */
export type ConnectorContext =
| {
status: "success";
connectors: Array<{
connectorId: string;
policy: "enabled" | "disabled";
tools: Array<{
actionName: string;
description?: string;
inputSchema: Record<string, Json>;
}> | null;
}>;
}
| {
status:
| "request_context_expired"
| "internal_error"
| "binding_unavailable"
| "upstream_error";
};
/** Use in a Site server route. Connection selection and credentials stay in the host. */
export function createConnectors(binding: ConnectorBinding | undefined) {
return {
async getContext(): Promise<ConnectorContext> {
if (typeof window !== "undefined") {
throw new Error(
"Connected apps are only available in Site server routes.",
);
}
try {
if (!binding?.getContext) return { status: "binding_unavailable" };
const context = await binding.getContext();
if (
context?.status === "success" &&
Array.isArray(context.connectors)
) {
return {
status: "success",
connectors: context.connectors.map((connector) => {
if (
!connector ||
typeof connector.connectorId !== "string" ||
!["enabled", "disabled"].includes(connector.policy) ||
(connector.tools !== null && !Array.isArray(connector.tools))
) {
throw new Error("Invalid connector context");
}
return {
connectorId: connector.connectorId,
policy: connector.policy,
tools:
connector.tools?.map((tool) => {
if (
!tool ||
typeof tool.actionName !== "string" ||
(tool.description !== undefined &&
typeof tool.description !== "string") ||
!tool.inputSchema ||
typeof tool.inputSchema !== "object" ||
Array.isArray(tool.inputSchema)
) {
throw new Error("Invalid connector tool");
}
return {
actionName: tool.actionName,
...(tool.description !== undefined
? { description: tool.description }
: {}),
inputSchema: tool.inputSchema,
};
}) ?? null,
};
}),
};
}
switch (context?.status) {
case "request_context_expired":
case "internal_error":
case "binding_unavailable":
case "upstream_error":
return { status: context.status };
default:
return { status: "upstream_error" };
}
} catch {
return { status: "upstream_error" };
}
},
async invoke(
connectorId: string,
actionName: string,
args: { [key: string]: Json },
): Promise<ConnectorResult> {
if (typeof window !== "undefined") {
throw new Error(
"Connected apps are only available in Site server routes.",
);
}
if (!binding) {
return {
status: "binding_unavailable",
message:
"This runtime does not provide connected apps for this request.",
};
}
try {
// Preserve the host's status, message, result and optional diagnostics.
// Do not replay a call after a transport failure: it may have completed.
return await binding.invoke(connectorId, actionName, args);
} catch {
return {
status: "upstream_error",
message:
"The app did not return a confirmed result. The action may have completed; check before trying again.",
};
}
},
};
}
+83
View File
@@ -0,0 +1,83 @@
import { z } from "zod/v4";
/** Validate and project runtime results onto the public connector response. */
export function connectorResponse(result: unknown): Response {
try {
// Keep server-only parsing lazy so client recovery UI can tree-shake it out.
const requestId = z
.string()
.regex(/^[A-Za-z0-9._:-]{1,128}$/)
.optional()
.catch(undefined);
const envelope = {
error: z.never().optional(),
content: z.never().optional(),
structuredContent: z.never().optional(),
isError: z.never().optional(),
requestId,
};
const content = z.object({
content: z.array(z.object({ type: z.string() }).catchall(z.json())),
structuredContent: z.json().optional(),
isError: z.never().optional(),
error: z.never().optional(),
});
const failure = z.object({
...envelope,
status: z
.string()
.min(1)
.refine((value) => value !== "success"),
message: z.string().min(1),
retryAfterMs: z.number().int().nonnegative().safe().optional(),
result: content.optional(),
});
const success = z.object({
...envelope,
status: z.literal("success"),
result: content,
message: z.never().optional(),
retryAfterMs: z.never().optional(),
});
const schema =
result !== null &&
typeof result === "object" &&
"status" in result &&
result.status === "success"
? success
: failure;
const parsed = schema.safeParse(result);
if (parsed.success) {
// As in the binding contract, JSON status determines the outcome.
return Response.json(parsed.data, {
headers: { "Cache-Control": "private, no-store" },
});
}
} catch {
// Cyclic or otherwise non-serializable runtime values are also unconfirmed.
}
return Response.json(
{
status: "upstream_error",
message:
"The app did not return a confirmed result. The action may have completed; check before trying again.",
},
{ status: 502, headers: { "Cache-Control": "private, no-store" } },
);
}
/** Presentation only. The caller supplies the starter's server-generated SIWC URL. */
export function connectorErrorRecovery(
error: { status: string; message: string },
connectorName: string,
reconnectHref: string,
): { message: string; action?: { label: string; href: string } } {
if (error.status === "reauthentication_required") {
return {
message: error.message,
action: { label: `Connect ${connectorName}`, href: reconnectHref },
};
}
// Other outcomes do not prove that consent is missing or that replay is safe.
return { message: error.message };
}
+12
View File
@@ -0,0 +1,12 @@
declare module "virtual:sites-connector-preview" {
const binding: import("./connector-contract.mjs").ConnectorBinding;
export default binding;
}
// Only the local preview uses an environment binding. Hosted Sites receive the
// request-scoped capability through ctx.props.CONNECTORS in sites-worker.ts.
declare namespace Cloudflare {
interface Env {
CONNECTORS?: import("./connector-contract.mjs").ConnectorBinding;
}
}
+13
View File
@@ -0,0 +1,13 @@
import { createConnectors } from "./connector-contract.mjs";
import { getConnectorBinding } from "./connector-context";
/** Keep invocation context on this request; never cache it across visitors. */
export function connectorsForRequest() {
return createConnectors(getConnectorBinding());
}
export type {
ConnectorContext,
ConnectorResult,
ConnectorFailureStatus,
Json,
} from "./connector-contract.mjs";
+18
View File
@@ -0,0 +1,18 @@
export const minimum = 10;
export const seed = [
['2026-10-12 19:30:40','belgheys','Withdrawal',-10],['2026-10-12 19:29:28','papaguy','Deposit',100],['2026-10-12 19:18:11','GODpori','Deposit',62],['2026-10-12 19:17:48','belgheys','Deposit',26],['2026-10-12 19:17:00','belgheys','Withdrawal',-10],['2026-10-12 19:15:42','sobhanAA','Deposit',200],['2026-10-12 13:12:10','naruto021','Deposit',10],['2026-10-12 13:04:18','naruto021','Withdrawal',-10],['2026-10-12 10:42:28','belgheys','Deposit',10],['2026-10-12 09:36:40','SkaiMaster','Deposit',8],['2026-10-12 09:16:15','HEMO','Withdrawal',-10],['2026-10-12 01:15:14','night44','Deposit',3],['2026-10-11 21:14:59','shalvargay','Deposit',10],['2026-10-11 20:55:54','sobhanAA','Deposit',10],['2026-10-11 20:53:58','MMFerii','Withdrawal',-10],['2026-10-11 20:50:35','wxsp','Deposit',10],['2026-10-11 20:49:55','Lostinu','Deposit',10]
].map(([date,player,reason,amount])=>({date,player,reason,amount,id:identity({date,player,reason,amount})}));
export function identity(r){return JSON.stringify([r.date,r.player.toLowerCase(),r.reason,r.amount]);}
export function parseLog(text){
if(typeof text!=='string'||text.length>1000000)throw Error('حجم لاگ بیش از حد مجاز است.');
const lines=text.replace(/^\uFEFF/,'').split(/\r?\n/).map((value,index)=>({value,index:index+1})).filter(l=>l.value.trim());
if(lines.length<2)throw Error('عنوان ستون‌ها و حداقل یک تراکنش را وارد کنید.');
const split=line=>line.split('\t').map(v=>{v=v.trim();if(v.startsWith('"')&&v.endsWith('"'))return v.slice(1,-1).replace(/""/g,'"');return v;});
if(JSON.stringify(split(lines[0].value))!==JSON.stringify(['Date','Player','Reason','Amount']))throw Error('عنوان ستون‌ها باید Date، Player، Reason و Amount و با فاصلهٔ Tab باشد.');
if(lines.length>2001)throw Error('هر بار حداکثر ۲۰۰۰ تراکنش وارد کنید.');
return lines.slice(1).map(l=>{const cols=split(l.value);const [date,player,reason,raw]=cols;const amount=Number(raw);const d=new Date(date?.replace(' ','T')+'Z');
if(cols.length!==4||!/^\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}$/.test(date)||!Number.isFinite(d.getTime())||d.toISOString().slice(0,19).replace('T',' ')!==date||!player||player.length>64||/[\x00-\x1f]/.test(player)||!['Deposit','Withdrawal'].includes(reason)||!/^[-+]?\d+$/.test(raw)||!Number.isSafeInteger(amount)||Math.abs(amount)>1000000000||(reason==='Deposit'?amount<=0:amount>=0))throw Error(`ردیف ${l.index} معتبر نیست؛ تاریخ، نام، نوع و علامت مقدار را بررسی کنید.`);
return {date,player,reason,amount,id:identity({date,player,reason,amount})};});
}
export function merge(rows){return [...new Map(rows.map(r=>[identity(r),r])).values()].sort((a,b)=>b.date.localeCompare(a.date)||a.player.localeCompare(b.player));}
export function summarize(rows){const players=new Map();for(const r of rows){const key=r.player.toLowerCase();const p=players.get(key)||{name:r.player,balance:0,deposits:0,withdrawals:0,count:0,last:r.date};p.balance+=r.amount;p.deposits+=Math.max(0,r.amount);p.withdrawals+=Math.max(0,-r.amount);p.count++;if(r.date>p.last)p.last=r.date;players.set(key,p);}return [...players.values()].sort((a,b)=>b.balance-a.balance||a.name.localeCompare(b.name));}
+6
View File
@@ -0,0 +1,6 @@
import {test} from 'node:test';import assert from 'node:assert/strict';import {parseLog,seed,merge,summarize} from './ledger.mjs';
const header='"Date"\t"Player"\t"Reason"\t"Amount"';const line='"2026-10-12 19:30:40"\t"belgheys"\t"Withdrawal"\t"-10"';
test('overlapping exports and casing are idempotent',()=>{const rows=parseLog(header+'\r\n'+line+'\r\n'+line.replace('belgheys','BELGHEYS'));assert.equal(merge([...seed,...rows]).length,17);assert.equal(summarize(merge([...seed,...rows])).find(p=>p.name.toLowerCase()==='belgheys').balance,16);});
test('provided ledger yields expected balances',()=>{const p=summarize(seed);assert.equal(p.length,12);assert.equal(p.reduce((n,p)=>n+p.balance,0),409);assert.equal(p[0].balance,210);assert.equal(p.filter(p=>p.balance<10).length,5);});
test('reject entire malformed import and impossible dates or signs',()=>{for(const bad of [line.replace('-10','10'),line.replace('2026-10-12','2026-02-30'),line.replace('Withdrawal','Something'),line.replace('-10','NaN'),line.replace('-10','-1.5')])assert.throws(()=>parseLog(header+'\n'+line+'\n'+bad));});
test('distinct transactions in same second stay distinct',()=>{assert.equal(merge(parseLog(header+'\n'+line+'\n'+line.replace('-10','-11'))).length,2);});
+5
View File
@@ -0,0 +1,5 @@
import { env } from 'cloudflare:workers';
import { getChatGPTUser } from '../app/chatgpt-auth';
import { seed, merge } from './ledger.mjs';
export async function isAdmin(){const user=await getChatGPTUser();const email=(env as unknown as {ADMIN_EMAIL?:string}).ADMIN_EMAIL;return !!(email&&user&&user.email.toLowerCase()===email.toLowerCase());}
export async function readLedger(){if(!env.DB)throw Error('پایگاه داده در دسترس نیست.');const result=await env.DB.prepare('SELECT id,date,player,reason,amount FROM transactions ORDER BY date DESC').all();return merge([...seed,...result.results]);}
+6
View File
@@ -0,0 +1,6 @@
import { clsx, type ClassValue } from "clsx";
import { twMerge } from "tailwind-merge";
export function cn(...inputs: ClassValue[]): string {
return twMerge(clsx(inputs));
}