import { createServerFn } from "@tanstack/react-start" import { getCookie, setCookie } from "@tanstack/react-start/server" import { type AuthUser, LOGIN_MUTATION, normalizeAuthTokens, } from "@wp-reactor/auth" import { WOO_SESSION_COOKIE } from "@wp-reactor/commerce" import { createServerGraphQLClient } from "@wp-reactor/headless-core" import { runtimeEnv } from "../env" import { authMiddleware } from "./authMiddleware" import { useAppSession } from "./session" // Wrappers serverFn MINCES autour des contrats du package @wp-reactor/auth // (Option B). POST obligatoire : réponses personnalisées par la session, jamais // cachables en edge. async function establishSession( username: string, password: string, ): Promise { const client = createServerGraphQLClient(runtimeEnv) // Transfert du panier invité → compte : on présente le woo-session guest. const guestSession = getCookie(WOO_SESSION_COOKIE) if (guestSession) { client.setHeader("woocommerce-session", `Session ${guestSession}`) } const res = await client.request(LOGIN_MUTATION, { username, password }) if (!res?.login) throw new Error("Login failed") const { user, ...tokens } = res.login const session = await useAppSession() await session.update({ ...normalizeAuthTokens(tokens), user }) // Panier rattaché au compte (Bearer) → cookie invité obsolète. if (guestSession) { setCookie(WOO_SESSION_COOKIE, "", { path: "/", maxAge: 0 }) } return user } export const getCurrentUserServerFn = createServerFn({ method: "POST" }) .middleware([authMiddleware]) .handler(({ context }) => ({ user: context.user, isAuthenticated: context.isAuthenticated, })) export const loginServerFn = createServerFn({ method: "POST" }) .inputValidator((data: { username: string; password: string }) => ({ username: String(data.username), password: String(data.password), })) .handler(async ({ data }) => ({ user: await establishSession(data.username, data.password), })) export const logoutServerFn = createServerFn({ method: "POST" }).handler( async () => { const session = await useAppSession() await session.clear() return { ok: true } }, )