feat: complete server-backed six-lesson app and trial tooling
Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
@@ -0,0 +1,38 @@
|
||||
import { setAuthToken } from '@/api/token'
|
||||
import { resetAppBootstrap } from '@/api/bootstrapState'
|
||||
|
||||
/** Bumped on logout and before login/register to drop in-flight responses from a prior account. */
|
||||
let sessionGeneration = 0
|
||||
|
||||
export function captureSessionGeneration(): number {
|
||||
return sessionGeneration
|
||||
}
|
||||
|
||||
export function invalidateSession(): void {
|
||||
sessionGeneration += 1
|
||||
}
|
||||
|
||||
export function isSessionCurrent(generation: number): boolean {
|
||||
return generation === sessionGeneration
|
||||
}
|
||||
|
||||
type UnauthorizedHandler = () => void
|
||||
let unauthorizedHandler: UnauthorizedHandler | null = null
|
||||
|
||||
export function setUnauthorizedHandler(handler: UnauthorizedHandler): void {
|
||||
unauthorizedHandler = handler
|
||||
}
|
||||
|
||||
/** Protected-route 401: clear session and redirect (not used for wrong login password). */
|
||||
export function handleUnauthorized(): void {
|
||||
invalidateSession()
|
||||
setAuthToken(null)
|
||||
resetAppBootstrap()
|
||||
unauthorizedHandler?.()
|
||||
}
|
||||
|
||||
/** Test-only reset of session generation and handler slot. */
|
||||
export function resetSessionTrackingForTests(): void {
|
||||
sessionGeneration = 0
|
||||
unauthorizedHandler = null
|
||||
}
|
||||
@@ -1,13 +1,28 @@
|
||||
import { ref } from 'vue'
|
||||
|
||||
let bootstrapped = false
|
||||
const bootstrapFailed = ref(false)
|
||||
|
||||
export function isAppBootstrapped() {
|
||||
return bootstrapped
|
||||
}
|
||||
|
||||
export function isBootstrapFailed() {
|
||||
return bootstrapFailed.value
|
||||
}
|
||||
|
||||
export const bootstrapFailedRef = bootstrapFailed
|
||||
|
||||
export function setBootstrapFailed(failed: boolean) {
|
||||
bootstrapFailed.value = failed
|
||||
}
|
||||
|
||||
export function markAppBootstrapped() {
|
||||
bootstrapped = true
|
||||
bootstrapFailed.value = false
|
||||
}
|
||||
|
||||
export function resetAppBootstrap() {
|
||||
bootstrapped = false
|
||||
bootstrapFailed.value = false
|
||||
}
|
||||
|
||||
@@ -0,0 +1,46 @@
|
||||
import { StaleSessionError } from '@/api/errors'
|
||||
|
||||
export type CatalogFetchKey = 'store-products' | 'games-catalog' | 'daily-challenge'
|
||||
|
||||
type Slot = {
|
||||
epoch: number
|
||||
requestSeq: number
|
||||
lastCommittedSeq: number
|
||||
}
|
||||
|
||||
const slots: Record<CatalogFetchKey, Slot> = {
|
||||
'store-products': { epoch: 0, requestSeq: 0, lastCommittedSeq: 0 },
|
||||
'games-catalog': { epoch: 0, requestSeq: 0, lastCommittedSeq: 0 },
|
||||
'daily-challenge': { epoch: 0, requestSeq: 0, lastCommittedSeq: 0 },
|
||||
}
|
||||
|
||||
export function resetCatalogFetchSync(): void {
|
||||
for (const key of Object.keys(slots) as CatalogFetchKey[]) {
|
||||
slots[key].epoch += 1
|
||||
slots[key].requestSeq = 0
|
||||
slots[key].lastCommittedSeq = 0
|
||||
}
|
||||
}
|
||||
|
||||
export function resetCatalogFetchSyncForTests(): void {
|
||||
resetCatalogFetchSync()
|
||||
}
|
||||
|
||||
/** Drop stale or out-of-order catalog GET responses (same session or after logout). */
|
||||
export async function fetchCatalogOrdered<T>(
|
||||
key: CatalogFetchKey,
|
||||
fetcher: () => Promise<T>,
|
||||
): Promise<T> {
|
||||
const slot = slots[key]
|
||||
const epochAtStart = slot.epoch
|
||||
const seq = ++slot.requestSeq
|
||||
const data = await fetcher()
|
||||
if (epochAtStart !== slot.epoch) {
|
||||
throw new StaleSessionError()
|
||||
}
|
||||
if (seq < slot.lastCommittedSeq) {
|
||||
throw new StaleSessionError()
|
||||
}
|
||||
slot.lastCommittedSeq = seq
|
||||
return data
|
||||
}
|
||||
+46
-31
@@ -1,25 +1,18 @@
|
||||
const TOKEN_KEY = 'gold-land-auth-token'
|
||||
import {
|
||||
captureSessionGeneration,
|
||||
handleUnauthorized,
|
||||
isSessionCurrent,
|
||||
} from '@/api/authSession'
|
||||
import {
|
||||
ApiClientError,
|
||||
ApiNetworkError,
|
||||
ApiUnauthorizedError,
|
||||
StaleSessionError,
|
||||
} from '@/api/errors'
|
||||
|
||||
let authToken: string | null = null
|
||||
import { getAuthToken } from '@/api/token'
|
||||
|
||||
export function getAuthToken(): string | null {
|
||||
if (authToken) return authToken
|
||||
try {
|
||||
return localStorage.getItem(TOKEN_KEY)
|
||||
} catch {
|
||||
return null
|
||||
}
|
||||
}
|
||||
|
||||
export function setAuthToken(token: string | null) {
|
||||
authToken = token
|
||||
try {
|
||||
if (token) localStorage.setItem(TOKEN_KEY, token)
|
||||
else localStorage.removeItem(TOKEN_KEY)
|
||||
} catch {
|
||||
// ignore
|
||||
}
|
||||
}
|
||||
export { getAuthToken, setAuthToken } from '@/api/token'
|
||||
|
||||
export interface AuthResponse {
|
||||
token: string
|
||||
@@ -107,9 +100,14 @@ export interface DailyChallengeCompleteResponse extends MeResponse {
|
||||
alreadyCompleted: boolean
|
||||
}
|
||||
|
||||
const API_BASE = import.meta.env.VITE_API_URL ?? '/api'
|
||||
const API_BASE = import.meta.env?.VITE_API_URL ?? '/api'
|
||||
|
||||
function isPublicAuthPath(path: string): boolean {
|
||||
return path === '/auth/login' || path === '/auth/register'
|
||||
}
|
||||
|
||||
async function request<T>(path: string, init?: RequestInit): Promise<T> {
|
||||
const sessionGeneration = captureSessionGeneration()
|
||||
const headers: Record<string, string> = {
|
||||
'Content-Type': 'application/json',
|
||||
...(init?.headers as Record<string, string> | undefined),
|
||||
@@ -125,12 +123,28 @@ async function request<T>(path: string, init?: RequestInit): Promise<T> {
|
||||
headers,
|
||||
})
|
||||
} catch {
|
||||
throw new Error('اتصال به سرور برقرار نشد. لطفاً backend را اجرا کنید.')
|
||||
throw new ApiNetworkError()
|
||||
}
|
||||
|
||||
if (!isSessionCurrent(sessionGeneration)) {
|
||||
throw new StaleSessionError()
|
||||
}
|
||||
|
||||
if (!response.ok) {
|
||||
const body = await response.json().catch(() => ({ error: 'خطای سرور' }))
|
||||
throw new Error(body.error ?? 'خطای سرور')
|
||||
const message = typeof body.error === 'string' ? body.error : 'خطای سرور'
|
||||
|
||||
if (response.status === 401) {
|
||||
if (isPublicAuthPath(path)) {
|
||||
throw new ApiUnauthorizedError(message)
|
||||
}
|
||||
if (isSessionCurrent(sessionGeneration)) {
|
||||
handleUnauthorized()
|
||||
}
|
||||
throw new ApiUnauthorizedError(message)
|
||||
}
|
||||
|
||||
throw new ApiClientError(message, response.status)
|
||||
}
|
||||
|
||||
return response.json() as Promise<T>
|
||||
@@ -170,16 +184,15 @@ export const api = {
|
||||
}),
|
||||
completeGame: (gameId: string) =>
|
||||
request<MeResponse>(`/games/${gameId}/complete`, { method: 'POST', body: '{}' }),
|
||||
getStoreProducts: () =>
|
||||
request<import('@/types/catalog.types').StoreProduct[]>('/store/products'),
|
||||
getGames: () => request<import('@/types/catalog.types').GameCatalogItem[]>('/games'),
|
||||
purchaseProduct: (productId: string) =>
|
||||
request<MeResponse>('/store/purchases', { method: 'POST', body: JSON.stringify({ productId }) }),
|
||||
completeLesson: (lessonId: string) =>
|
||||
request<MeResponse>(`/lessons/${lessonId}/complete`, { method: 'POST', body: '{}' }),
|
||||
completeMapLevel: (levelId: number, stars: number) =>
|
||||
request<MeResponse>(`/map/levels/${levelId}/complete`, {
|
||||
method: 'POST',
|
||||
body: JSON.stringify({ stars }),
|
||||
}),
|
||||
getGoldLandProgress: () => request<import('@/modules/gold-land/types/goldLand.types').GoldLandProgressResponse>('/gold-land/progress'),
|
||||
getGoldLandProgress: () =>
|
||||
request<import('@/modules/gold-land/types/goldLand.types').GoldLandProgressResponse>(
|
||||
'/gold-land/progress',
|
||||
),
|
||||
getGoldLandLevel: (levelId: number) =>
|
||||
request<import('@/modules/gold-land/types/goldLand.types').LevelDetailResponse>(
|
||||
`/gold-land/levels/${levelId}`,
|
||||
@@ -202,3 +215,5 @@ export const api = {
|
||||
},
|
||||
),
|
||||
}
|
||||
|
||||
export { ApiNetworkError, ApiUnauthorizedError, StaleSessionError, ApiClientError } from '@/api/errors'
|
||||
|
||||
@@ -0,0 +1,31 @@
|
||||
export class ApiNetworkError extends Error {
|
||||
readonly name = 'ApiNetworkError'
|
||||
constructor(message = 'اتصال به سرور برقرار نشد. لطفاً backend را اجرا کنید.') {
|
||||
super(message)
|
||||
}
|
||||
}
|
||||
|
||||
export class ApiUnauthorizedError extends Error {
|
||||
readonly name = 'ApiUnauthorizedError'
|
||||
constructor(message: string) {
|
||||
super(message)
|
||||
}
|
||||
}
|
||||
|
||||
/** Response arrived after logout or account switch — ignore, do not mutate Pinia. */
|
||||
export class StaleSessionError extends Error {
|
||||
readonly name = 'StaleSessionError'
|
||||
constructor() {
|
||||
super('Stale session')
|
||||
}
|
||||
}
|
||||
|
||||
export class ApiClientError extends Error {
|
||||
readonly name = 'ApiClientError'
|
||||
readonly status: number
|
||||
|
||||
constructor(message: string, status: number) {
|
||||
super(message)
|
||||
this.status = status
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,58 @@
|
||||
import type { MeResponse } from '@/api/client'
|
||||
import { captureSessionGeneration, isSessionCurrent } from '@/api/authSession'
|
||||
import { StaleSessionError } from '@/api/errors'
|
||||
|
||||
type ApplyMe = (data: MeResponse) => boolean
|
||||
|
||||
let queueEpoch = 0
|
||||
let queueTail: Promise<void> = Promise.resolve()
|
||||
let applyMe: ApplyMe = () => false
|
||||
|
||||
export function bindMeMutationApply(fn: ApplyMe): void {
|
||||
applyMe = fn
|
||||
}
|
||||
|
||||
export function resetMeMutationQueue(): void {
|
||||
queueEpoch += 1
|
||||
queueTail = Promise.resolve()
|
||||
}
|
||||
|
||||
export function resetMeMutationQueueForTests(): void {
|
||||
resetMeMutationQueue()
|
||||
}
|
||||
|
||||
function assertMutationSession(epochAtEnqueue: number, sessionGen: number): void {
|
||||
if (epochAtEnqueue !== queueEpoch) {
|
||||
throw new StaleSessionError()
|
||||
}
|
||||
if (!isSessionCurrent(sessionGen)) {
|
||||
throw new StaleSessionError()
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Serializes state-changing API calls in this tab so a slower response cannot apply before
|
||||
* a later mutation finishes. Does not replace server revision — see docs in sync.ts.
|
||||
*/
|
||||
export async function runMeMutation<R>(
|
||||
fetcher: () => Promise<R>,
|
||||
pickMe: (result: R) => MeResponse = (result) => result as unknown as MeResponse,
|
||||
): Promise<R> {
|
||||
const sessionGen = captureSessionGeneration()
|
||||
const epochAtEnqueue = queueEpoch
|
||||
|
||||
const execute = async (): Promise<R> => {
|
||||
assertMutationSession(epochAtEnqueue, sessionGen)
|
||||
const result = await fetcher()
|
||||
assertMutationSession(epochAtEnqueue, sessionGen)
|
||||
applyMe(pickMe(result))
|
||||
return result
|
||||
}
|
||||
|
||||
const resultPromise = queueTail.then(execute)
|
||||
queueTail = resultPromise.then(
|
||||
() => undefined,
|
||||
() => undefined,
|
||||
)
|
||||
return resultPromise
|
||||
}
|
||||
+69
-2
@@ -1,10 +1,54 @@
|
||||
import { api, type MeResponse } from '@/api/client'
|
||||
import { captureSessionGeneration, isSessionCurrent } from '@/api/authSession'
|
||||
import { StaleSessionError } from '@/api/errors'
|
||||
import { resetCatalogFetchSync } from '@/api/catalogFetchSync'
|
||||
import {
|
||||
bindMeMutationApply,
|
||||
resetMeMutationQueue,
|
||||
runMeMutation,
|
||||
} from '@/api/meMutationQueue'
|
||||
import { resetGoldLandProgressSync } from '@/modules/gold-land/services/goldLandProgressSync'
|
||||
import { useDailyChallengeStore } from '@/stores/dailyChallenge'
|
||||
import { useGamesStore } from '@/stores/games'
|
||||
import { useMarketStore } from '@/stores/market'
|
||||
import { useStoreCatalogStore } from '@/stores/storeCatalog'
|
||||
import { useUserStore } from '@/stores/user'
|
||||
import { useWalletStore } from '@/stores/wallet'
|
||||
|
||||
export function applyMeResponse(data: MeResponse) {
|
||||
/** Incremented on every successful `applyMeResponse`; stale reads capture revision at start and skip if superseded. */
|
||||
let userStateRevision = 0
|
||||
|
||||
export function resetMeMutationSync(): void {
|
||||
resetMeMutationQueue()
|
||||
}
|
||||
|
||||
export function resetMeMutationSyncForTests(): void {
|
||||
resetMeMutationQueue()
|
||||
}
|
||||
|
||||
export { runMeMutation }
|
||||
|
||||
export function captureUserStateRevision(): number {
|
||||
return userStateRevision
|
||||
}
|
||||
|
||||
export function resetUserStateRevisionForTests(): void {
|
||||
userStateRevision = 0
|
||||
}
|
||||
|
||||
export type ApplyMeOptions = {
|
||||
/** When set, skip apply if a newer mutation/bootstrap already updated stores (same session). */
|
||||
ifNotSuperseded?: number
|
||||
}
|
||||
|
||||
/** Single writer for server-backed user state (from `/api/me` or endpoints that embed `me`). */
|
||||
export function applyMeResponse(data: MeResponse, options?: ApplyMeOptions): boolean {
|
||||
if (
|
||||
options?.ifNotSuperseded !== undefined &&
|
||||
userStateRevision > options.ifNotSuperseded
|
||||
) {
|
||||
return false
|
||||
}
|
||||
const userStore = useUserStore()
|
||||
const walletStore = useWalletStore()
|
||||
const gamesStore = useGamesStore()
|
||||
@@ -41,17 +85,40 @@ export function applyMeResponse(data: MeResponse) {
|
||||
marketStore.$patch({
|
||||
selectedRange: data.market.selectedRange,
|
||||
})
|
||||
|
||||
userStateRevision += 1
|
||||
return true
|
||||
}
|
||||
|
||||
bindMeMutationApply(applyMeResponse)
|
||||
|
||||
export function resetUserStores() {
|
||||
useUserStore().$reset()
|
||||
useWalletStore().$reset()
|
||||
useGamesStore().$reset()
|
||||
useMarketStore().$reset()
|
||||
useStoreCatalogStore().$reset()
|
||||
useDailyChallengeStore().$reset()
|
||||
userStateRevision = 0
|
||||
resetGoldLandProgressSync()
|
||||
resetCatalogFetchSync()
|
||||
resetMeMutationSync()
|
||||
}
|
||||
|
||||
export async function bootstrapFromServer() {
|
||||
const revisionAtStart = captureUserStateRevision()
|
||||
const data = await api.getMe()
|
||||
applyMeResponse(data)
|
||||
applyMeResponse(data, { ifNotSuperseded: revisionAtStart })
|
||||
return data
|
||||
}
|
||||
|
||||
export async function syncMarketQuote(range: string) {
|
||||
const sessionGeneration = captureSessionGeneration()
|
||||
const marketStore = useMarketStore()
|
||||
const quote = await api.getMarketGold(range)
|
||||
if (!isSessionCurrent(sessionGeneration)) {
|
||||
throw new StaleSessionError()
|
||||
}
|
||||
marketStore.$patch({
|
||||
currentPrice: quote.currentPrice,
|
||||
dailyChange: quote.dailyChangePercent,
|
||||
|
||||
@@ -0,0 +1,22 @@
|
||||
const TOKEN_KEY = 'gold-land-auth-token'
|
||||
|
||||
let authToken: string | null = null
|
||||
|
||||
export function getAuthToken(): string | null {
|
||||
if (authToken) return authToken
|
||||
try {
|
||||
return localStorage.getItem(TOKEN_KEY)
|
||||
} catch {
|
||||
return null
|
||||
}
|
||||
}
|
||||
|
||||
export function setAuthToken(token: string | null) {
|
||||
authToken = token
|
||||
try {
|
||||
if (token) localStorage.setItem(TOKEN_KEY, token)
|
||||
else localStorage.removeItem(TOKEN_KEY)
|
||||
} catch {
|
||||
// ignore
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user