Compare commits

..
13 Commits
Author SHA1 Message Date
safavimohadeseh78andCursor 5704618348 fix: satisfy the production type check for the market chart and home banner
Frontend CI / unit (test, type-check, build) (push) Failing after 41s
Frontend CI / browser E2E (frontend + pinned backend) (push) Skipped
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-26 15:25:24 +03:30
safavimohadeseh78 a6e14fdf6e .
Frontend CI / unit (test, type-check, build) (push) Failing after 1m14s
Frontend CI / browser E2E (frontend + pinned backend) (push) Skipped
2026-10-26 15:15:01 +03:30
safavimohadeseh78andCursor 8a311c1fd5 feat: redesign home, market, wallet, and settings screens
Frontend CI / unit (test, type-check, build) (push) Failing after 1m25s
Frontend CI / browser E2E (frontend + pinned backend) (push) Skipped
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-26 14:54:44 +03:30
safavimohadeseh78 83cc9a61f9 feat: redesign the login screen
Frontend CI / unit (test, type-check, build) (push) Successful in 1m23s
Frontend CI / browser E2E (frontend + pinned backend) (push) Failing after 1m24s
2026-10-25 18:58:02 +03:30
safavimohadeseh78andCursor 4dc8a7b25f chore: publish offline caches with the package token
Frontend CI / unit (test, type-check, build) (push) Successful in 2m42s
Frontend CI / browser E2E (frontend + pinned backend) (push) Successful in 7m36s
A small upload proves the token before the cache build starts.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-25 14:56:21 +03:30
safavimohadeseh78andCursor 79b96226db chore: publish offline npm caches as a Gitea package
Frontend CI / unit (test, type-check, build) (push) Successful in 2m1s
Frontend CI / browser E2E (frontend + pinned backend) (push) Successful in 7m56s
Artifact upload stays at zero percent, so the cache archive uses the package API.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-25 13:46:52 +03:30
safavimohadeseh78andCursor 5fb547597a chore: upload offline npm caches with a Gitea-compatible action
Frontend CI / unit (test, type-check, build) (push) Successful in 4m33s
Frontend CI / browser E2E (frontend + pinned backend) (push) Successful in 9m16s
The v4 artifact upload rejected the packed Linux caches.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-25 13:06:50 +03:30
safavimohadeseh78andCursor a5a4d79a32 chore: add a manual workflow for offline npm caches
Frontend CI / unit (test, type-check, build) (push) Successful in 2m35s
Frontend CI / browser E2E (frontend + pinned backend) (push) Successful in 9m54s
CI can download Linux dependencies so the server can build images without npm.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-25 12:52:27 +03:30
safavimohadeseh78andCursor c53a67831d feat: complete the thirteen-stage learning experience and E2E journey
Frontend CI / unit (test, type-check, build) (push) Successful in 7m21s
Frontend CI / browser E2E (frontend + pinned backend) (push) Successful in 11m38s
Play levels 7-13 in the app and pin E2E to the local thirteen-stage backend commit.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-22 19:42:04 +03:30
safavimohadeseh78andCursor bb29cc6bdb fix: pin the E2E backend SHA in the frontend contract
Frontend CI / unit (test, type-check, build) (push) Successful in 1m54s
Frontend CI / browser E2E (frontend + pinned backend) (push) Successful in 5m9s
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-22 13:01:49 +03:30
safavimohadeseh78andCursor e3f0457dc9 feat: complete server-backed six-lesson app and trial tooling
Frontend CI / unit (test, type-check, build) (push) Successful in 1m11s
Frontend CI / browser E2E (frontend + pinned backend) (push) Failing after 2m48s
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-12 14:40:37 +03:30
safavimohadeseh78andCursor 653f1b0c5a feat(docker): add nginx frontend image and full-stack compose
Build static assets with Vite, proxy /api to backend, and document server env vars.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-06 10:13:43 +02:00
safavimohadeseh78andCursor b9942b49b8 chore(vite): pin dev server to port 5174
Enable strictPort so local dev always matches the frontend Docker proxy setup.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-06 10:13:42 +02:00
188 changed files with 9137 additions and 1335 deletions
+11
View File
@@ -0,0 +1,11 @@
node_modules
dist
dist-ssr
coverage
.git
.env
.env.docker
.env.local
*.log
.vite
*.tsbuildinfo
+16
View File
@@ -0,0 +1,16 @@
# Copy to .env.docker on the server (never commit secrets).
#
# Build-time: API base URL for the Vue app (/api = nginx proxies to backend).
VITE_API_URL=/api
# Host port published for the frontend container
FRONTEND_PORT=8080
# Backend env (compose service `backend`)
JWT_SECRET=<replace-with-48+-character-random-secret>
# Must match the public URL users open in the browser (scheme + host + port).
CORS_ORIGIN=http://<your-trial-host>:8080
# Backend (set in compose for trial stack — override only if needed)
# TRUST_PROXY=true
# TRUST_PROXY_CIDRS=10.0.0.0/8,172.16.0.0/12,192.168.0.0/16
+2
View File
@@ -0,0 +1,2 @@
# Local development (optional). Default: Vite proxy sends /api to http://127.0.0.1:3000
# VITE_API_URL=/api
+99
View File
@@ -0,0 +1,99 @@
name: Frontend CI
on:
push:
pull_request:
env:
NODE_VERSION: '22.18.0'
E2E_BACKEND_PORT: '3010'
E2E_FRONTEND_PORT: '5190'
jobs:
unit:
name: unit (test, type-check, build)
runs-on: ubuntu-latest
timeout-minutes: 25
steps:
- name: Checkout frontend
uses: actions/checkout@v4
- name: Setup Node.js
uses: actions/setup-node@v4
with:
node-version: ${{ env.NODE_VERSION }}
cache: npm
cache-dependency-path: package-lock.json
- name: Install dependencies (npm ci)
run: npm ci
- name: Unit tests
run: npm run test
- name: Type check
run: npm run type-check
- name: Production build
run: npm run build
e2e:
name: browser E2E (frontend + pinned backend)
runs-on: ubuntu-latest
needs: unit
timeout-minutes: 45
env:
CI: 'true'
E2E_BACKEND_ROOT: backend-nest
E2E_BACKEND_REF: ${{ vars.E2E_BACKEND_REF }}
E2E_BACKEND_CHECKOUT_TOKEN: ${{ secrets.E2E_BACKEND_CHECKOUT_TOKEN }}
steps:
- name: Checkout frontend
uses: actions/checkout@v4
- name: Require pinned backend ref (SHA or tag)
run: |
if [ -z "${E2E_BACKEND_REF}" ]; then
E2E_BACKEND_REF="$(node -e "const c=require('./e2e/backend.contract.json'); const r=String(c.pinnedRef||''); if(!/^[0-9a-f]{40}$/i.test(r)){console.error('pinnedRef must be a full SHA'); process.exit(1)} process.stdout.write(r)")"
echo "E2E_BACKEND_REF=${E2E_BACKEND_REF}" >> "$GITHUB_ENV"
echo "Repository variable unset; using committed pinnedRef"
fi
echo "E2E_BACKEND_REF=${E2E_BACKEND_REF}"
- name: Checkout backend (pinned ref)
run: node scripts/ci-checkout-backend.mjs
- name: Setup Node.js
uses: actions/setup-node@v4
with:
node-version: ${{ env.NODE_VERSION }}
- name: Install frontend dependencies (npm ci)
run: npm ci
- name: Install backend dependencies (npm ci)
working-directory: backend-nest
run: npm ci
- name: Build backend for E2E
run: npm run e2e:prepare
- name: Install Playwright Chromium (OS deps)
run: npx playwright install chromium --with-deps
- name: Run Playwright E2E
run: npm run test:e2e:ci
- name: Upload failure artifacts
if: failure()
uses: actions/upload-artifact@v4
with:
name: playwright-failure-${{ gitea.run_id }}
path: |
playwright-report/
test-results/
if-no-files-found: ignore
- name: E2E cleanup
if: always()
run: npm run e2e:cleanup
+196
View File
@@ -0,0 +1,196 @@
name: Offline npm caches
on:
workflow_dispatch:
env:
NODE_VERSION: '22.18.0'
FRONTEND_SHA: c53a67831db98ea10f1aa168fcab80cca97134ed
BACKEND_SHA: 866be223956ef5d3961b0d835b36adedfeb35c82
jobs:
caches:
name: offline npm caches
runs-on: ubuntu-latest
timeout-minutes: 40
steps:
- name: Checkout workflow repo
uses: actions/checkout@v4
with:
fetch-depth: 0
- name: Prove package token with a small file
timeout-minutes: 3
env:
TOKEN: ${{ secrets.OFFLINE_PACKAGE_TOKEN }}
run: |
set -euo pipefail
if [ -z "${TOKEN}" ]; then
echo "OFFLINE_PACKAGE_TOKEN is empty"
exit 1
fi
printf 'probe' > "$RUNNER_TEMP/probe.txt"
version="probe-${GITHUB_RUN_ID}"
url="${GITHUB_SERVER_URL}/api/packages/gold_land/generic/gold-land-offline-deps/${version}/probe.txt"
code="$(curl --silent --show-error --max-time 60 -o /dev/null -w '%{http_code}' \
-H "Authorization: token ${TOKEN}" \
--upload-file "$RUNNER_TEMP/probe.txt" \
"$url" || true)"
if [ "$code" != "201" ] && [ "$code" != "204" ]; then
echo "package probe upload failed with HTTP ${code}"
exit 1
fi
curl --fail --silent --show-error --max-time 60 \
-H "Authorization: token ${TOKEN}" \
-o "$RUNNER_TEMP/probe-down.txt" \
"$url"
cmp "$RUNNER_TEMP/probe.txt" "$RUNNER_TEMP/probe-down.txt"
echo "package probe ok"
- name: Setup Node.js
uses: actions/setup-node@v4
with:
node-version: ${{ env.NODE_VERSION }}
- name: Compiler tools for native smoke
run: |
set -euo pipefail
if ! command -v python3 >/dev/null || ! command -v make >/dev/null || ! command -v g++ >/dev/null; then
sudo apt-get update
sudo apt-get install -y --no-install-recommends python3 make g++
fi
- name: Extract pinned sources
run: |
set -euo pipefail
mkdir -p "$RUNNER_TEMP/src/frontend" "$RUNNER_TEMP/src/backend"
git archive "$FRONTEND_SHA" | tar -x -C "$RUNNER_TEMP/src/frontend"
git clone --depth 1 --no-checkout https://get.feep.ir/gold_land/gold_land_server.git "$RUNNER_TEMP/backend-git"
git -C "$RUNNER_TEMP/backend-git" fetch --depth 1 origin "$BACKEND_SHA"
git -C "$RUNNER_TEMP/backend-git" checkout FETCH_HEAD
git -C "$RUNNER_TEMP/backend-git" archive HEAD | tar -x -C "$RUNNER_TEMP/src/backend"
test "$(git -C "$RUNNER_TEMP/backend-git" rev-parse HEAD)" = "$BACKEND_SHA"
test -f "$RUNNER_TEMP/src/frontend/package-lock.json"
test -f "$RUNNER_TEMP/src/backend/package-lock.json"
- name: Fill empty npm caches and prove offline installs
run: |
set -euo pipefail
node_dir="$(dirname "$(dirname "$(readlink -f "$(command -v node)")")")"
if [ ! -f "$node_dir/include/node/node.h" ]; then
echo "Node headers are not in $node_dir. node-gyp would download them outside the npm cache."
exit 1
fi
export npm_config_nodedir="$node_dir"
export npm_config_build_from_source=true
echo "CI npm_config_nodedir=$node_dir"
node -v
uname -s
uname -m
fill_and_prove() {
name="$1"
src="$2"
cache="$3"
shift 3
rm -rf "$cache"
mkdir -p "$cache"
echo "online npm ci: $name"
npm ci --cache "$cache" --no-audit --no-fund --prefix "$src"
clean="$RUNNER_TEMP/clean/$name"
rm -rf "$clean"
mkdir -p "$clean"
tar -C "$src" --exclude node_modules -cf - . | tar -C "$clean" -xf -
test ! -d "$clean/node_modules"
echo "offline npm ci: $name"
npm ci --offline --cache "$cache" --no-audit --no-fund --prefix "$clean"
(cd "$clean" && npm run build)
if [ "$name" = "backend" ]; then
(cd "$clean" && node -e "const Database=require('better-sqlite3'); const db=new Database(':memory:'); const row=db.prepare('SELECT 1 AS ok').get(); if(row.ok!==1) process.exit(1); console.log('sqlite-smoke-ok')")
fi
}
fill_and_prove backend "$RUNNER_TEMP/src/backend" "$RUNNER_TEMP/cache/backend"
fill_and_prove frontend "$RUNNER_TEMP/src/frontend" "$RUNNER_TEMP/cache/frontend"
if [ -d "$HOME/.cache/node-gyp" ]; then
echo "node-gyp wrote $HOME/.cache/node-gyp outside the npm cache"
exit 1
fi
python3 - <<'PY'
import os
root=os.environ["RUNNER_TEMP"]+"/cache"
needles=(":_authToken","_password=","BEGIN PRIVATE KEY","BEGIN RSA PRIVATE KEY")
for dirpath, _, files in os.walk(root):
for name in files:
if name in {".npmrc","_auth"}:
raise SystemExit(f"credential file in npm cache: {os.path.join(dirpath, name)}")
path=os.path.join(dirpath, name)
try:
data=open(path,"rb").read()
except OSError:
continue
text=data.decode("utf-8","ignore")
for needle in needles:
if needle in text:
raise SystemExit(f"credential marker in npm cache: {path}")
print("npm cache credential scan ok")
PY
- name: Pack archive
run: |
set -euo pipefail
out="$RUNNER_TEMP/offline-pack"
rm -rf "$out"
mkdir -p "$out/offline-deps"
cp -a "$RUNNER_TEMP/cache/backend" "$out/offline-deps/backend-npm-cache"
cp -a "$RUNNER_TEMP/cache/frontend" "$out/offline-deps/frontend-npm-cache"
cp offline/backend.Dockerfile offline/frontend.Dockerfile offline/SERVER.md "$out/offline-deps/"
node_dir="$(dirname "$(dirname "$(readlink -f "$(command -v node)")")")"
python3 - <<PY
import hashlib, json, os, platform
temp=os.environ["RUNNER_TEMP"]
def sha256(path):
h=hashlib.sha256()
with open(path,"rb") as f:
for chunk in iter(lambda: f.read(1024*1024), b""):
h.update(chunk)
return h.hexdigest()
manifest={
"backendSha": os.environ["BACKEND_SHA"],
"frontendSha": os.environ["FRONTEND_SHA"],
"node": os.popen("node -v").read().strip(),
"os": platform.system().lower(),
"arch": platform.machine(),
"backendLockSha256": sha256(f"{temp}/src/backend/package-lock.json"),
"frontendLockSha256": sha256(f"{temp}/src/frontend/package-lock.json"),
"ciNodeDir": """$node_dir""",
"serverNodeDir": "/usr/local",
"buildFromSource": True,
}
with open(f"{temp}/offline-pack/offline-deps/manifest.json","w",encoding="utf-8") as f:
json.dump(manifest, f, indent=2)
f.write("\n")
PY
tar -C "$out" -czf "$RUNNER_TEMP/offline-deps.tar.gz" offline-deps
sha256sum "$RUNNER_TEMP/offline-deps.tar.gz" | tee "$RUNNER_TEMP/offline-deps.tar.gz.sha256"
mkdir -p artifact
cp "$RUNNER_TEMP/offline-deps.tar.gz" "$RUNNER_TEMP/offline-deps.tar.gz.sha256" artifact/
- name: Upload generic package
timeout-minutes: 10
env:
TOKEN: ${{ secrets.OFFLINE_PACKAGE_TOKEN }}
run: |
set -euo pipefail
upload() {
curl --fail --silent --show-error \
--retry 2 --retry-delay 5 --max-time 300 \
-H "Authorization: token ${TOKEN}" \
--upload-file "$1" \
"${GITHUB_SERVER_URL}/api/packages/gold_land/generic/gold-land-offline-deps/${GITHUB_RUN_ID}/$(basename "$1")"
}
upload artifact/offline-deps.tar.gz
upload artifact/offline-deps.tar.gz.sha256
echo "package version ${GITHUB_RUN_ID}"
+12
View File
@@ -34,3 +34,15 @@ coverage
.env
.env.*
!.env.example
!.env.docker.example
# Playwright E2E
test-results
playwright-report
e2e/playwright-report
e2e/.runtime
blob-report
e2e-full-run.txt
e2e-last-run.txt
# CI clone of backend (see e2e/backend.contract.json)
/backend-nest
+1
View File
@@ -0,0 +1 @@
22.18.0
+26
View File
@@ -0,0 +1,26 @@
# syntax=docker/dockerfile:1
FROM node:22.18.0-bookworm-slim AS builder
WORKDIR /app
COPY package.json package-lock.json ./
RUN npm ci
COPY . .
# Baked in at build time. Default keeps browser requests on /api (nginx proxy).
ARG VITE_API_URL=/api
ENV VITE_API_URL=${VITE_API_URL}
RUN npm run build
FROM nginx:1.27-alpine AS production
COPY nginx.conf /etc/nginx/conf.d/default.conf
COPY --from=builder /app/dist /usr/share/nginx/html
EXPOSE 80
CMD ["nginx", "-g", "daemon off;"]
+130 -11
View File
@@ -1,19 +1,138 @@
# Child Gold Land — Frontend
رابط کاربری Vue 3 + Vite + Pinia.
Vue 3 + Vite + Pinia + TypeScript.
## راه‌اندازی
## Requirements
```sh
npm install
- **Node.js:** `^22.18.0` or `>=24.12.0` (`package.json` → `engines`)
- **Pinned for local dev / CI:** `22.18.0` (see `.nvmrc`)
```powershell
nvm install 22.18.0
nvm use 22.18.0
```
## Backend (sibling repo)
API is **required** for login and gameplay. Run Nest backend from `../backend-nest` on port **3000** (separate Git repo: `gold_land_server` on Gitea).
## Local development
```powershell
npm ci
npm run dev
```
## اسکریپت‌ها
- App: http://localhost:5174 (`vite.config.ts` — `strictPort: true`)
- API: requests to `/api/*` are proxied to http://127.0.0.1:3000
| دستور | توضیح |
|--------|--------|
| `npm run dev` | سرور توسعه |
| `npm run build` | بیلد production |
| `npm run preview` | پیش‌نمایش بیلد |
| `npm run type-check` | بررسی TypeScript |
Optional env: copy `.env.example` to `.env.local` if you need overrides (`VITE_API_URL`).
Demo account (when backend `NODE_ENV=development`): username `demo`, password `123456`.
## Scripts
| Command | Description |
|---------|-------------|
| `npm run dev` | Vite dev server (port 5174) |
| `npm run build` | `vue-tsc` + production build |
| `npm run preview` | Preview production build |
| `npm run type-check` | TypeScript check only |
| `npm run test` | Node unit tests (`test/`) |
| `npm run test:e2e` | Build backend + Playwright E2E (30 tests) |
| `npm run test:e2e:ci` | Playwright only (backend must already be built) |
| `npm run test:e2e:install` | `playwright install chromium` (+ OS deps on Linux: `--with-deps`) |
| `npm run e2e:prepare` | `npm run build` in backend (`E2E_BACKEND_ROOT`) |
| `npm run ci:checkout-backend` | Clone backend for CI layout (see E2E contract) |
## CI (Gitea Actions)
Workflow: [`.gitea/workflows/ci.yml`](.gitea/workflows/ci.yml) (runs on **push** and **pull_request** when a Gitea **act_runner** is registered — **not verified** on `get.feep.ir` from this repo alone).
### Jobs (this repository)
| Job | Steps (same as local) |
|-----|------------------------|
| **unit** | `npm ci` → `npm run test` → `npm run type-check` → `npm run build` |
| **e2e** | checkout frontend → clone **pinned** backend → `npm ci` (both) → `e2e:prepare` → `playwright install chromium --with-deps` → `npm run test:e2e:ci` |
- **Node:** `22.18.0` (explicit in workflow)
- **Cache:** npm cache via `actions/setup-node` (optional; job still passes without cache)
- **Timeouts:** unit 25 min, e2e 45 min
- **Failure artifacts:** `playwright-report/`, `test-results/` (no tokens, no production DB)
- **Cleanup:** `npm run e2e:cleanup` runs `always()` after E2E
### Local equivalent (unit checks)
```powershell
npm ci
npm run test
npm run type-check
npm run build
```
### Two-repo E2E contract
| Item | Value |
|------|--------|
| Contract file | [`e2e/backend.contract.json`](e2e/backend.contract.json) |
| Default backend URL | `https://get.feep.ir/gold_land/gold_land_server.git` |
| Default ref | `main` (override for reproducibility) |
| Checkout path (CI) | `backend-nest/` under frontend workspace |
| Backend build | `npm run build` in that tree (`e2e:prepare`) |
| E2E backend port | `3010` (`E2E_BACKEND_PORT`) |
| E2E frontend port | `5190` (`E2E_FRONTEND_PORT`) |
| Readiness | `GET http://127.0.0.1:3010/health` |
| Temp DB | SQLite under OS temp (`scripts/e2e-backend.mjs`) — never `data/app.db` |
**Pin backend version in CI (required for e2e job):** set repository variable `E2E_BACKEND_REF` to a **commit SHA** (or immutable tag). There is **no** silent fallback to `main`.
**Local sibling layout (no clone):**
```powershell
$env:E2E_BACKEND_ROOT = "E:\path\to\backend-nest" # optional; default is ../backend-nest
npm run test:e2e
```
**Local fallback when Playwright Chromium CDN fails:** `$env:PLAYWRIGHT_CHROME_CHANNEL = "chrome"` (system Chrome). **CI must not rely on this** — use `npx playwright install chromium --with-deps`.
### Secrets (names only — never commit values)
| Name | Purpose |
|------|---------|
| `E2E_BACKEND_CHECKOUT_TOKEN` | Read access to private `gold_land_server` for `git clone` in E2E job |
If the backend repo is public, clone may work without a token. If clone fails, the **e2e** job fails; **unit** still runs.
### Runner prerequisites (Linux, e.g. `ubuntu-latest` label)
- Node **22.18.0**
- Git
- Build toolchain for **better-sqlite3** (backend dependency): `build-essential`, `python3` (Playwright `--with-deps` installs browser OS libs; backend `npm ci` still needs native compile on Linux)
- Sufficient disk for `node_modules` × 2 + Chromium
### Not yet verified on a real runner
- Gitea Actions enabled and **act_runner** online for `gold_land/gold_land_user`
- E2E job with private backend clone + `E2E_BACKEND_CHECKOUT_TOKEN`
- `vars.E2E_BACKEND_REF` / `gitea.run_id` in workflow expressions (Gitea ≥ 1.21; `github.*` aliases may apply)
## Optional: start backend + frontend (Windows)
```powershell
pwsh -File ..\backend-nest\scripts\dev-local-stack.ps1
```
Sibling folder layout: `frontend` + `backend-nest`.
## Docker / trial deploy
`docker-compose.yml` builds frontend + backend for a **trial** stack (nginx + Nest + SQLite volume).
See [docs/DEPLOY-TRIAL.md](docs/DEPLOY-TRIAL.md) for architecture, placeholders, HTTPS notes, backup, health, and rollback.
Local day-to-day dev usually uses `npm run dev` + backend `npm run dev` or `npm run start`.
## Project status doc
A workspace-level overview may exist at `../docs/project-status.md` when both repos share a parent folder. That file is **not** part of this Git repo.
+62
View File
@@ -0,0 +1,62 @@
services:
backend:
build:
context: ../backend-nest
dockerfile: Dockerfile
image: child-gold-land-backend:latest
container_name: child-gold-land-backend
env_file:
- .env.docker
environment:
NODE_ENV: production
PORT: 3000
HOST: 0.0.0.0
DB_PATH: /app/data/app.db
JWT_SECRET: ${JWT_SECRET}
CORS_ORIGIN: ${CORS_ORIGIN}
TRUST_PROXY: "true"
TRUST_PROXY_CIDRS: "10.0.0.0/8,172.16.0.0/12,192.168.0.0/16"
expose:
- "3000"
volumes:
- backend_sqlite:/app/data
restart: unless-stopped
healthcheck:
test:
[
"CMD",
"node",
"-e",
"fetch('http://127.0.0.1:3000/health/ready').then(r=>process.exit(r.ok?0:1)).catch(()=>process.exit(1))",
]
interval: 30s
timeout: 5s
retries: 3
start_period: 20s
networks:
- child-gold-land
frontend:
build:
context: .
dockerfile: Dockerfile
args:
VITE_API_URL: ${VITE_API_URL:-/api}
image: child-gold-land-frontend:latest
container_name: child-gold-land-frontend
ports:
- "${FRONTEND_PORT:-8080}:80"
depends_on:
backend:
condition: service_healthy
restart: unless-stopped
networks:
- child-gold-land
volumes:
backend_sqlite:
name: child-gold-land-sqlite
networks:
child-gold-land:
name: child-gold-land
+142
View File
@@ -0,0 +1,142 @@
# Trial deploy — 6 active lessons (no public launch checklist)
This document prepares a **trial** stack using the existing Docker Compose layout. It does **not** deploy to a real server from this repo.
## Architecture (default)
```
Browser → [TLS terminator — your choice] → frontend nginx :80
├─ / → Vue SPA (try_files → index.html)
├─ /api/* → proxy → backend Nest :3000
└─ /health → proxy → backend /health
Backend → SQLite file on named volume (single instance)
```
| Component | Image / build | User |
|-----------|---------------|------|
| Frontend | `frontend/Dockerfile` → nginx:alpine | nginx (non-root worker) |
| Backend | `backend-nest/Dockerfile` → node:22.18.0-slim | `node` |
| Data | Docker volume `child-gold-land-sqlite` → `/app/data/app.db` | writable by `node` |
**Not supported without proof:** SQLite on NFS/network shares, horizontal multi-instance backend with this rate limiter.
## Placeholders (set on server — never commit)
Copy `frontend/.env.docker.example` → `frontend/.env.docker`:
| Variable | Example placeholder |
|----------|---------------------|
| `JWT_SECRET` | `<generate-48+-char-random>` |
| `CORS_ORIGIN` | `https://<your-trial-host>` or `http://<host>:8080` |
| `VITE_API_URL` | `/api` (keep for same-origin nginx proxy) |
| `FRONTEND_PORT` | `8080` |
### Proxy trust boundary (compose default)
| Variable | Compose default | Meaning |
|----------|-----------------|--------|
| `TRUST_PROXY` | `true` | Use `X-Real-IP` / `X-Forwarded-For` **only** when TCP peer is in `TRUST_PROXY_CIDRS` |
| `TRUST_PROXY_CIDRS` | Explicit list in compose (trial) | **Production:** set the CIDR of the nginx→backend hop (e.g. `docker network inspect child-gold-land`); backend **refuses** `TRUST_PROXY=true` without `TRUST_PROXY_CIDRS` when `NODE_ENV=production` |
- **Fastify `trustProxy` stays off** — client IP for rate limits comes from `getClientIp()` (trusted peer + single-hop headers).
- nginx sets `X-Forwarded-For $remote_addr` (replaces forged client chains).
- **Backend is not published on the host** — only frontend port is exposed; direct access to Nest bypasses nginx and should not be exposed in trial deploy.
**Rate limiting:** in-memory, **per client IP**, **single backend instance**. Many users behind one NAT share one bucket. For stricter limits use an edge proxy or account-based throttling (out of scope).
**Do not** expose backend port `3000` on the host in production trial.
## Build and start (local trial)
From sibling clones (`frontend/`, `backend-nest/`):
```powershell
cd frontend
copy .env.docker.example .env.docker
# Edit .env.docker — set JWT_SECRET and CORS_ORIGIN
docker compose config # validate compose file
docker compose build
docker compose up -d
```
Checks:
```powershell
curl http://localhost:8080/health
curl http://localhost:8080/health/ready
curl http://localhost:8080/api/... # via app UI login
```
Vue routes: refresh on `/map`, `/market`, etc. must return `index.html` (configured in `nginx.conf`).
## HTTPS
- Terminate TLS at **your** reverse proxy (Caddy, Traefik, nginx on host) or cloud LB.
- Redirect HTTP→HTTPS at the terminator.
- Set `CORS_ORIGIN` to the **exact** browser origin (`https://host`, no trailing slash).
- Do not generate real certificates in this repo.
## Persistent data
- **Path in container:** `/app/data/app.db` (+ `-wal`/`-shm` when WAL mode active)
- **Volume:** `child-gold-land-sqlite` (compose)
- **Host permissions:** ensure volume UID/GID allows `node` (uid 1000 in image) to read/write; if bind-mounting a host dir: `chown 1000:1000 <dir>`
Startup **never** replaces an existing DB with seed data. Migrations run forward-only on boot; failure aborts startup.
## Backup and restore
On backend repo (host or one-off container with volume mounted):
```powershell
cd backend-nest
$env:DB_PATH = "/path/to/app.db" # or container path
$env:BACKUP_DIR = "/path/to/backups"
$env:BACKUP_RETENTION_DAYS = "14"
npm run backup:sqlite
npm run restore:sqlite -- backups/app-....db /tmp/restored.db
# Stop backend first. Restore to a sibling path (not live DB_PATH), then swap files — see backend-nest/docs/restore-production-db.md.
# RESTORE_ACK_STOPPED=YES = operator ack only (not automatic stop detection).
```
Uses SQLite **backup API** (WAL-safe), then `integrity_check`.
## Health vs readiness
| Endpoint | Meaning |
|----------|---------|
| `GET /health` | Liveness — process up |
| `GET /health/ready` | Readiness — DB migrated |
Compose `depends_on: service_healthy` uses **ready**.
## Rollback
| Action | Effect |
|--------|--------|
| `docker compose pull` + run previous image tags | Rolls back **code** only |
| DB | **Not** rolled back with image — restore from backup if needed |
| Forward migrations | Newer code may require newer schema; rolling back code without DB restore can break — test rollback pairs in staging |
## Safe shutdown
```powershell
docker compose down
# Data remains in volume child-gold-land-sqlite
```
## CI backend pin (E2E)
No silent `main` fallback: set Gitea variable **`E2E_BACKEND_REF`** to backend **commit SHA**. See `e2e/backend.contract.json` and frontend README.
Secrets (names only): `E2E_BACKEND_CHECKOUT_TOKEN`.
## Still required for real deploy
- [ ] Registered Gitea **act_runner** (CI not verified here)
- [ ] Trial host OS, domain, TLS certificates
- [ ] Strong `JWT_SECRET` on server
- [ ] Off-site backup storage
- [ ] Monitoring / log aggregation (no stack traces to clients — API returns generic `خطای سرور`)
+7
View File
@@ -0,0 +1,7 @@
{
"repositoryUrl": "https://get.feep.ir/gold_land/gold_land_server.git",
"checkoutPath": "backend-nest",
"localRef": "",
"pinnedRef": "866be223956ef5d3961b0d835b36adedfeb35c82",
"notes": "CI uses E2E_BACKEND_REF when set, otherwise pinnedRef (full SHA only). Never falls back to main. Local sibling: E2E_BACKEND_ROOT=../backend-nest and skip ci:checkout-backend."
}
+120
View File
@@ -0,0 +1,120 @@
import { test, expect } from '@playwright/test'
import { fetchMe, registerViaUi, uniqueUsername } from './helpers/auth'
const perfectLessons: Record<number, Array<Record<string, unknown>>> = {
1: [
{ questionId: 'money-q1', answerId: 'option-a' },
{ questionId: 'money-q2', answerId: 'true' },
{ questionId: 'money-q3', answerId: 'option-a' },
{ questionId: 'money-q4', answerId: 'true' },
{ questionId: 'money-q5', answerId: 'option-b' },
],
2: [
{ questionId: 'saving-q1', answerId: 'option-b' },
{ questionId: 'saving-q2', answerId: 'true' },
{ questionId: 'saving-q3', answerId: 'option-a' },
{ questionId: 'saving-q4', answerId: 'true' },
{ questionId: 'saving-q5', answerId: 'option-a' },
],
3: [
{ questionId: 'needs-q1', answerId: 'option-a' },
{ questionId: 'needs-q2', answerId: 'true' },
{ questionId: 'needs-q3', orderedItemIds: ['water', 'food', 'medicine', 'shoes', 'toy', 'crown'] },
{ questionId: 'needs-q4', answerId: 'option-a' },
{ questionId: 'needs-q5', answerId: 'true' },
],
4: [
{ questionId: 'gold-q1', answerId: 'option-a' },
{ questionId: 'gold-q2', answerId: 'true' },
{ questionId: 'gold-q3', answerId: 'option-a' },
{ questionId: 'gold-q4', answerId: 'false' },
{ questionId: 'gold-q5', answerId: 'option-b' },
],
5: [
{ questionId: 'market-q1', answerId: 'option-a' },
{ questionId: 'market-q2', answerId: 'false' },
{ questionId: 'market-q3', answerId: 'option-a' },
{ questionId: 'market-q4', answerId: 'true' },
{ questionId: 'market-q5', answerId: 'option-b' },
],
6: [
{ questionId: 'inflation-q1', answerId: 'option-b' },
{ questionId: 'inflation-q2', answerId: 'true' },
{ questionId: 'inflation-q3', answerId: 'option-a' },
{ questionId: 'inflation-q4', answerId: 'false' },
{ questionId: 'inflation-q5', answerId: 'option-b' },
],
}
async function authHeader(page: import('@playwright/test').Page) {
const token = await page.evaluate(() => localStorage.getItem('gold-land-auth-token'))
if (!token) throw new Error('missing token')
return { authorization: `Bearer ${token}` }
}
test('budget mission from the map, then replay without extra reward', async ({ page }) => {
const user = uniqueUsername('budget')
await registerViaUi(page, user, 'pass1234', 'بودجه')
const headers = await authHeader(page)
for (let levelId = 1; levelId <= 6; levelId += 1) {
const start = await page.request.post(`/api/gold-land/levels/${levelId}/start`, { headers })
expect(start.ok()).toBeTruthy()
const done = await page.request.post(`/api/gold-land/levels/${levelId}/complete`, {
headers,
data: { answers: perfectLessons[levelId] },
})
expect(done.ok()).toBeTruthy()
}
await page.goto('/map')
await page.getByRole('button', { name: 'مرحله 7: بودجه‌بندی' }).click()
await page.getByRole('button', { name: 'شروع بازی' }).click()
await page.getByRole('button', { name: 'ساخت بودجه' }).click()
await page.getByRole('button', { name: 'بررسی برنامه' }).click()
await expect(page.getByRole('button', { name: 'تأیید برنامه' })).toBeDisabled()
await expect(page.getByText('رفت‌وآمد حداقل ۲۰ سکه')).toBeVisible()
await page.getByRole('button', { name: 'اصلاح برنامه' }).click()
for (let i = 0; i < 4; i += 1) await page.getByRole('button', { name: 'افزایش رفت‌وآمد' }).click()
for (let i = 0; i < 5; i += 1) await page.getByRole('button', { name: 'افزایش آب و غذا' }).click()
for (let i = 0; i < 4; i += 1) await page.getByRole('button', { name: 'افزایش پس‌انداز برای هدف' }).click()
await page.getByRole('button', { name: 'بررسی برنامه' }).click()
await page.getByRole('button', { name: 'تأیید برنامه' }).click()
await expect(page.getByText('هزینه رفت‌وآمد ۱۰ سکه بیشتر شد')).toBeVisible()
await page.getByRole('button', { name: 'بازتنظیم بودجه' }).click()
await expect(page.getByRole('button', { name: 'ثبت نتیجه' })).toBeDisabled()
await expect(page.getByText('حداقل ۳۰ سکه')).toBeVisible()
for (let i = 0; i < 2; i += 1) await page.getByRole('button', { name: 'افزایش رفت‌وآمد' }).click()
await expect(page.getByRole('button', { name: 'ثبت نتیجه' })).toBeEnabled()
const before = await fetchMe(page)
await page.getByRole('button', { name: 'ثبت نتیجه' }).click()
await expect(page.getByText('پاداش:')).toBeVisible()
await page.getByRole('button', { name: 'بازگشت به نقشه' }).click()
await page.waitForURL(/\/map/)
await page.reload()
const after = await fetchMe(page)
expect(after.progress.mapLevels.find((level) => level.id === 7)?.stars).toBe(3)
expect(after.user.coins).toBe(before.user.coins + 18 + 9)
await page.getByRole('button', { name: 'مرحله 7: بودجه‌بندی' }).click()
await page.getByRole('button', { name: 'مرور مجدد' }).click()
await page.getByRole('button', { name: 'ساخت بودجه' }).click()
for (let i = 0; i < 4; i += 1) await page.getByRole('button', { name: 'افزایش رفت‌وآمد' }).click()
for (let i = 0; i < 5; i += 1) await page.getByRole('button', { name: 'افزایش آب و غذا' }).click()
for (let i = 0; i < 4; i += 1) await page.getByRole('button', { name: 'افزایش پس‌انداز برای هدف' }).click()
await page.getByRole('button', { name: 'بررسی برنامه' }).click()
await page.getByRole('button', { name: 'تأیید برنامه' }).click()
await page.getByRole('button', { name: 'بازتنظیم بودجه' }).click()
for (let i = 0; i < 2; i += 1) await page.getByRole('button', { name: 'افزایش رفت‌وآمد' }).click()
const replayBefore = await fetchMe(page)
await page.getByRole('button', { name: 'ثبت نتیجه' }).click()
await expect(page.getByText('پاداش تازه‌ای اضافه نشد')).toBeVisible()
const replayAfter = await fetchMe(page)
expect(replayAfter.user.coins).toBe(replayBefore.user.coins)
expect(replayAfter.user.xp).toBe(replayBefore.user.xp)
await page.goto('/map')
await expect(page.getByRole('button', { name: 'مرحله 9: سبد سرمایه‌گذاری' })).toBeDisabled()
})
+112
View File
@@ -0,0 +1,112 @@
import { test, expect, type Page } from '@playwright/test'
import { fetchMe, registerViaUi, uniqueUsername } from './helpers/auth'
const correct = [
'مبادله را آسان می‌کند و مقایسه قیمت را ممکن می‌سازد',
'مبلغی متناسب با شرایط را منظم کنار بگذاریم',
'اول آب آشامیدنی را تأمین کنیم',
'طلا یک دارایی است و قیمتش می‌تواند بالا یا پایین برود',
'خیر',
'با همان پول، مقدار کمتری از آن کالاها می‌توان خرید',
'رفت‌وآمد ۳۰، غذا ۲۵، پس‌انداز ۲۰، تفریح ۱۵، ذخیره ۱۰',
'پول لازم را وارد پیشنهاد نامطمئن با احتمال زیان نکنیم',
'خیر؛ چند گزینه ممکن است هم‌زمان افت کنند',
'۱۲۱',
'ب، چون ۴۵ در برابر ۵۰ است',
'۶ هفته',
]
const wrongTail = [
'همان پول ضروری را برای سود بیشتر وارد پیشنهاد نامطمئن کنیم',
'بله، با چند گزینه دیگر زیان ممکن نیست',
'۱۲۰',
'الف، چون عدد روی کارت کوچک‌تر است',
'۸ هفته',
]
async function finishThroughGoal(page: Page, headers: { authorization: string }) {
const lessons: Record<number, unknown> = {
1: [{ questionId: 'money-q1', answerId: 'option-a' }, { questionId: 'money-q2', answerId: 'true' }, { questionId: 'money-q3', answerId: 'option-a' }, { questionId: 'money-q4', answerId: 'true' }, { questionId: 'money-q5', answerId: 'option-b' }],
2: [{ questionId: 'saving-q1', answerId: 'option-b' }, { questionId: 'saving-q2', answerId: 'true' }, { questionId: 'saving-q3', answerId: 'option-a' }, { questionId: 'saving-q4', answerId: 'true' }, { questionId: 'saving-q5', answerId: 'option-a' }],
3: [{ questionId: 'needs-q1', answerId: 'option-a' }, { questionId: 'needs-q2', answerId: 'true' }, { questionId: 'needs-q3', orderedItemIds: ['water', 'food', 'medicine', 'shoes', 'toy', 'crown'] }, { questionId: 'needs-q4', answerId: 'option-a' }, { questionId: 'needs-q5', answerId: 'true' }],
4: [{ questionId: 'gold-q1', answerId: 'option-a' }, { questionId: 'gold-q2', answerId: 'true' }, { questionId: 'gold-q3', answerId: 'option-a' }, { questionId: 'gold-q4', answerId: 'false' }, { questionId: 'gold-q5', answerId: 'option-b' }],
5: [{ questionId: 'market-q1', answerId: 'option-a' }, { questionId: 'market-q2', answerId: 'false' }, { questionId: 'market-q3', answerId: 'option-a' }, { questionId: 'market-q4', answerId: 'true' }, { questionId: 'market-q5', answerId: 'option-b' }],
6: [{ questionId: 'inflation-q1', answerId: 'option-b' }, { questionId: 'inflation-q2', answerId: 'true' }, { questionId: 'inflation-q3', answerId: 'option-a' }, { questionId: 'inflation-q4', answerId: 'false' }, { questionId: 'inflation-q5', answerId: 'option-b' }],
}
for (let levelId = 1; levelId <= 6; levelId += 1) {
expect((await page.request.post(`/api/gold-land/levels/${levelId}/start`, { headers })).ok()).toBeTruthy()
expect((await page.request.post(`/api/gold-land/levels/${levelId}/complete`, { headers, data: { answers: lessons[levelId] } })).ok()).toBeTruthy()
}
const later = [
{ answers: [{ questionId: 'initial', allocations: { transport: 20, food: 25, savings: 20, fun: 0 } }, { questionId: 'final', allocations: { transport: 30, food: 25, savings: 20, fun: 0 } }] },
{ answers: [{ questionId: 'q-loss', answerId: 'b' }, { questionId: 'q-certain', answerId: 'no' }, { questionId: 'q-need', answerId: 'keep' }, { questionId: 'q-compare', answerId: 'range' }, { questionId: 'q-promise', answerId: 'check' }] },
{ answers: [{ questionId: 'portfolio', holdings: { sun: 40, rain: 30, wind: 30 } }, { questionId: 'q-one', answerId: 'depend' }, { questionId: 'q-loss', answerId: 'no' }, { questionId: 'q-name', answerId: 'no' }, { questionId: 'q-best', answerId: 'no' }, { questionId: 'q-approach', answerId: 'balanced' }] },
{ answers: [{ questionId: 'compound-q1', answerId: 'on-balance' }, { questionId: 'compound-q2', answerId: '121' }, { questionId: 'compound-q3', answerId: 'from-110' }, { questionId: 'compound-q4', answerId: 'compound' }, { questionId: 'compound-q5', answerId: 'false' }] },
{ answers: [{ questionId: 'notebook-choice', answerId: 'b' }, { questionId: 'notebook-why', answerId: 'fits-and-cheaper' }, { questionId: 'discount-choice', answerId: 'b' }, { questionId: 'discount-why', answerId: 'pay-amount' }, { questionId: 'info-choice', answerId: 'ask' }, { questionId: 'info-why', answerId: 'incomplete' }] },
{ answers: [{ questionId: 'plan', plan: { initialWeekly: 15, exceptionWeekly: 5, continueWeekly: 15 } }, { questionId: 'q-goal', answerId: 'specific' }, { questionId: 'q-left', answerId: '90' }, { questionId: 'q-weeks', answerId: '6' }, { questionId: 'q-need', answerId: 'adjust' }, { questionId: 'q-change', answerId: 'update' }] },
]
for (let index = 0; index < later.length; index += 1) {
const levelId = index + 7
expect((await page.request.post(`/api/gold-land/levels/${levelId}/start`, { headers })).ok()).toBeTruthy()
expect((await page.request.post(`/api/gold-land/levels/${levelId}/complete`, { headers, data: later[index] })).ok()).toBeTruthy()
}
}
async function answerExam(page: Page, labels: string[]) {
for (let index = 0; index < labels.length; index += 1) {
await page.getByText(labels[index]!, { exact: true }).click()
const name = index === labels.length - 1 ? 'مرور پاسخ‌ها' : 'بعدی'
await page.getByRole('button', { name }).click()
}
}
test('castle exam from the map', async ({ page }) => {
const user = uniqueUsername('castle')
await registerViaUi(page, user, 'pass1234', 'قلعه')
const token = await page.evaluate(() => localStorage.getItem('gold-land-auth-token'))
await finishThroughGoal(page, { authorization: `Bearer ${token}` })
await page.goto('/map')
await page.getByRole('button', { name: 'مرحله 13: آزمون قلعه' }).click()
await page.getByRole('button', { name: 'شروع آزمون' }).click()
await page.getByRole('button', { name: 'شروع سؤال‌ها' }).click()
await expect(page.getByText('پایه‌های پول')).toBeVisible()
const beforeFail = await fetchMe(page)
await answerExam(page, [...correct.slice(0, 7), ...wrongTail])
await page.getByRole('button', { name: 'ثبت نتیجه' }).click()
await expect(page.getByText('این تلاش کامل نشد')).toBeVisible()
await expect(page.getByRole('button', { name: 'مرحله بعد' })).toHaveCount(0)
const afterFail = await fetchMe(page)
expect(afterFail.user.coins).toBe(beforeFail.user.coins)
await page.getByRole('button', { name: 'تلاش مجدد' }).click()
await answerExam(page, correct)
const before = await fetchMe(page)
await page.getByRole('button', { name: 'ثبت نتیجه' }).click()
await expect(page.getByText('آفرین! مسیر آموزشی قلعه را کامل کردی')).toBeVisible()
await expect(page.getByText('پاداش:')).toBeVisible()
await expect(page.getByRole('button', { name: 'مرحله بعد' })).toHaveCount(0)
await page.getByRole('button', { name: 'بازگشت به نقشه' }).click()
await page.reload()
const after = await fetchMe(page)
expect(after.progress.mapLevels.find((level) => level.id === 13)?.stars).toBe(3)
expect(after.user.coins).toBe(before.user.coins + 50 + 9)
await page.getByRole('button', { name: 'مرحله 13: آزمون قلعه' }).click()
await page.getByRole('button', { name: 'مرور مجدد' }).click()
await page.getByRole('button', { name: 'شروع سؤال‌ها' }).click()
await answerExam(page, correct)
const replayBefore = await fetchMe(page)
await page.getByRole('button', { name: 'ثبت نتیجه' }).click()
await expect(page.getByText('پاداش تازه‌ای اضافه نشد')).toBeVisible()
const replayAfter = await fetchMe(page)
expect(replayAfter.user.coins).toBe(replayBefore.user.coins)
await page.getByRole('button', { name: 'تلاش مجدد' }).click()
await answerExam(page, [...correct.slice(0, 7), ...wrongTail])
await page.getByRole('button', { name: 'ثبت نتیجه' }).click()
await expect(page.getByText('این تلاش کامل نشد')).toBeVisible()
await expect(page.getByText('ستاره ذخیره‌شده همچنان 3 از ۳ است')).toBeVisible()
await expect(page.getByText('آفرین! مسیر آموزشی قلعه را کامل کردی')).toHaveCount(0)
const kept = await fetchMe(page)
expect(kept.progress.mapLevels.find((level) => level.id === 13)?.stars).toBe(3)
expect(kept.user.coins).toBe(replayAfter.user.coins)
})
+76
View File
@@ -0,0 +1,76 @@
import { test, expect } from '@playwright/test'
import { fetchMe, registerViaUi, uniqueUsername } from './helpers/auth'
test.describe('store, game, educational challenge', () => {
test('store purchase and duplicate guard', async ({ page }) => {
const user = uniqueUsername('store')
await registerViaUi(page, user, 'pass1234')
const me0 = await fetchMe(page)
const coins0 = me0.user.coins
await page.goto('/store')
await page.getByText('در حال بارگذاری').waitFor({ state: 'detached', timeout: 30_000 }).catch(() => {})
await page.getByRole('button', { name: 'تقویت XP' }).click()
await page.getByRole('button', { name: 'خرید' }).click()
await expect(page.getByText(/تقویت XP.*خریده شد/)).toBeVisible({ timeout: 15_000 })
const me1 = await fetchMe(page)
expect(me1.user.coins).toBeLessThan(coins0)
expect(me1.progress.ownedItems).toContain('boost-xp')
await page.reload()
const meRefresh = await fetchMe(page)
expect(meRefresh.progress.ownedItems).toContain('boost-xp')
await expect(page.locator('.product-card').filter({ hasText: 'تقویت XP' })).toContainText('مال توئه')
const me2 = await fetchMe(page)
expect(me2.user.coins).toBe(me1.user.coins)
})
test('gold guess first completion only', async ({ page }) => {
const user = uniqueUsername('game')
await registerViaUi(page, user, 'pass1234')
const me0 = await fetchMe(page)
const coins0 = me0.user.coins
const xp0 = me0.user.xp
await page.goto('/games/gold-guess')
await page.getByText('در حال بارگذاری پاداش').waitFor({ state: 'detached', timeout: 30_000 }).catch(() => {})
await page.getByRole('button', { name: 'افزایش' }).click()
await expect(page.locator('.toast--success')).toBeVisible({ timeout: 15_000 })
const me1 = await fetchMe(page)
expect(me1.user.coins).toBeGreaterThan(coins0)
expect(me1.progress.claimedRewards).toContain('gold-guess')
await page.reload()
await page.getByRole('button', { name: 'افزایش' }).click({ timeout: 5000 }).catch(() => {})
const me2 = await fetchMe(page)
expect(me2.user.coins).toBe(me1.user.coins)
expect(me2.user.xp).toBeGreaterThanOrEqual(xp0)
})
test('educational challenge once', async ({ page }) => {
const user = uniqueUsername('challenge')
await registerViaUi(page, user, 'pass1234')
const me0 = await fetchMe(page)
const coins0 = me0.user.coins
await page.goto('/challenge')
await page.getByRole('heading', { name: 'چالش آموزشی' }).waitFor()
await page.getByText('در حال بارگذاری').waitFor({ state: 'detached', timeout: 30_000 }).catch(() => {})
await page.getByRole('button', { name: 'طلا' }).click()
await page.getByRole('button', { name: 'دریافت پاداش' }).click()
await expect(page.getByText('پاداش دریافت شد')).toBeVisible({ timeout: 15_000 })
const me1 = await fetchMe(page)
expect(me1.user.coins).toBeGreaterThan(coins0)
expect(me1.progress.completedChallenges).toContain('daily-challenge')
await page.reload()
await page.getByRole('heading', { name: 'چالش آموزشی' }).waitFor()
const me2 = await fetchMe(page)
expect(me2.user.coins).toBe(me1.user.coins)
})
})
+149
View File
@@ -0,0 +1,149 @@
import { test, expect } from '@playwright/test'
import { fetchMe, registerViaUi, uniqueUsername } from './helpers/auth'
const lessons: Record<number, Array<Record<string, unknown>>> = {
1: [
{ questionId: 'money-q1', answerId: 'option-a' },
{ questionId: 'money-q2', answerId: 'true' },
{ questionId: 'money-q3', answerId: 'option-a' },
{ questionId: 'money-q4', answerId: 'true' },
{ questionId: 'money-q5', answerId: 'option-b' },
],
2: [
{ questionId: 'saving-q1', answerId: 'option-b' },
{ questionId: 'saving-q2', answerId: 'true' },
{ questionId: 'saving-q3', answerId: 'option-a' },
{ questionId: 'saving-q4', answerId: 'true' },
{ questionId: 'saving-q5', answerId: 'option-a' },
],
3: [
{ questionId: 'needs-q1', answerId: 'option-a' },
{ questionId: 'needs-q2', answerId: 'true' },
{ questionId: 'needs-q3', orderedItemIds: ['water', 'food', 'medicine', 'shoes', 'toy', 'crown'] },
{ questionId: 'needs-q4', answerId: 'option-a' },
{ questionId: 'needs-q5', answerId: 'true' },
],
4: [
{ questionId: 'gold-q1', answerId: 'option-a' },
{ questionId: 'gold-q2', answerId: 'true' },
{ questionId: 'gold-q3', answerId: 'option-a' },
{ questionId: 'gold-q4', answerId: 'false' },
{ questionId: 'gold-q5', answerId: 'option-b' },
],
5: [
{ questionId: 'market-q1', answerId: 'option-a' },
{ questionId: 'market-q2', answerId: 'false' },
{ questionId: 'market-q3', answerId: 'option-a' },
{ questionId: 'market-q4', answerId: 'true' },
{ questionId: 'market-q5', answerId: 'option-b' },
],
6: [
{ questionId: 'inflation-q1', answerId: 'option-b' },
{ questionId: 'inflation-q2', answerId: 'true' },
{ questionId: 'inflation-q3', answerId: 'option-a' },
{ questionId: 'inflation-q4', answerId: 'false' },
{ questionId: 'inflation-q5', answerId: 'option-b' },
],
}
async function answerCompound(page: import('@playwright/test').Page) {
const choices = [
'رشد دوره بعد بر موجودی جدید، شامل رشد قبلی، محاسبه می‌شود',
'۱۲۱ سکه',
'چون ۱۰٪ از ۱۱۰ محاسبه شده است',
'مرکب؛ ۱۳۳٫۱ در برابر ۱۳۰',
]
for (const label of choices) {
await page.getByRole('button', { name: label, exact: true }).click()
await page.getByRole('button', { name: 'بعدی' }).click()
}
await page.getByRole('button', { name: 'نادرست', exact: true }).click()
await page.getByRole('button', { name: 'بعدی' }).click()
}
test('compound interest lesson from the map', async ({ page }) => {
const user = uniqueUsername('cmp')
await registerViaUi(page, user, 'pass1234', 'مرکب')
const token = await page.evaluate(() => localStorage.getItem('gold-land-auth-token'))
const headers = { authorization: `Bearer ${token}` }
for (let levelId = 1; levelId <= 6; levelId += 1) {
expect((await page.request.post(`/api/gold-land/levels/${levelId}/start`, { headers })).ok()).toBeTruthy()
expect((await page.request.post(`/api/gold-land/levels/${levelId}/complete`, {
headers,
data: { answers: lessons[levelId] },
})).ok()).toBeTruthy()
}
expect((await page.request.post('/api/gold-land/levels/7/start', { headers })).ok()).toBeTruthy()
expect((await page.request.post('/api/gold-land/levels/7/complete', {
headers,
data: {
answers: [
{ questionId: 'initial', allocations: { transport: 20, food: 25, savings: 20, fun: 0 } },
{ questionId: 'final', allocations: { transport: 30, food: 25, savings: 20, fun: 0 } },
],
},
})).ok()).toBeTruthy()
expect((await page.request.post('/api/gold-land/levels/8/start', { headers })).ok()).toBeTruthy()
expect((await page.request.post('/api/gold-land/levels/8/complete', {
headers,
data: {
answers: [
{ questionId: 'q-loss', answerId: 'b' },
{ questionId: 'q-certain', answerId: 'no' },
{ questionId: 'q-need', answerId: 'keep' },
{ questionId: 'q-compare', answerId: 'range' },
{ questionId: 'q-promise', answerId: 'check' },
],
},
})).ok()).toBeTruthy()
expect((await page.request.post('/api/gold-land/levels/9/start', { headers })).ok()).toBeTruthy()
expect((await page.request.post('/api/gold-land/levels/9/complete', {
headers,
data: {
answers: [
{ questionId: 'portfolio', holdings: { sun: 40, rain: 30, wind: 30 } },
{ questionId: 'q-one', answerId: 'depend' },
{ questionId: 'q-loss', answerId: 'no' },
{ questionId: 'q-name', answerId: 'no' },
{ questionId: 'q-best', answerId: 'no' },
{ questionId: 'q-approach', answerId: 'balanced' },
],
},
})).ok()).toBeTruthy()
await page.goto('/map')
await page.getByRole('button', { name: 'مرحله 10: سود مرکب' }).click()
await page.getByRole('button', { name: 'شروع درس' }).click()
await page.getByRole('button', { name: 'بعدی' }).click()
await page.getByRole('button', { name: 'دوره بعد' }).click()
await page.getByRole('button', { name: 'دوره بعد' }).click()
await page.getByRole('button', { name: 'دوره بعد' }).click()
await expect(page.getByText('۱۳۳٫۱ سکه').first()).toBeVisible()
await expect(page.getByText('۱۲۱ + ۱۲٫۱ = ۱۳۳٫۱')).toBeVisible()
await page.getByRole('button', { name: 'دوره قبل' }).click()
await page.getByRole('button', { name: 'بعدی' }).click()
await answerCompound(page)
const before = await fetchMe(page)
await page.getByRole('button', { name: 'اتمام درس' }).click()
await expect(page.getByText('۱۰٪ آن ۱۱ سکه')).toBeVisible()
await page.getByRole('button', { name: 'بازگشت به نقشه' }).click()
await page.reload()
const after = await fetchMe(page)
expect(after.progress.mapLevels.find((level) => level.id === 10)?.stars).toBe(3)
expect(after.user.coins).toBe(before.user.coins + 18 + 9)
await page.getByRole('button', { name: 'مرحله 10: سود مرکب' }).click()
await page.getByRole('button', { name: 'مرور مجدد' }).click()
await page.getByRole('button', { name: 'بعدی' }).click()
await page.getByRole('button', { name: 'بعدی' }).click()
await answerCompound(page)
const replayBefore = await fetchMe(page)
await page.getByRole('button', { name: 'اتمام درس' }).click()
await expect(page.getByText('امتیاز')).toBeVisible()
const replayAfter = await fetchMe(page)
expect(replayAfter.user.coins).toBe(replayBefore.user.coins)
await page.goto('/map')
await expect(page.getByRole('button', { name: 'مرحله 12: هدف مالی' })).toBeDisabled()
})
+89
View File
@@ -0,0 +1,89 @@
import { test, expect, type Page } from '@playwright/test'
import { fetchMe, registerViaUi, uniqueUsername } from './helpers/auth'
async function finishThroughShop(page: Page, headers: { authorization: string }) {
const lessons: Record<number, unknown> = {
1: [{ questionId: 'money-q1', answerId: 'option-a' }, { questionId: 'money-q2', answerId: 'true' }, { questionId: 'money-q3', answerId: 'option-a' }, { questionId: 'money-q4', answerId: 'true' }, { questionId: 'money-q5', answerId: 'option-b' }],
2: [{ questionId: 'saving-q1', answerId: 'option-b' }, { questionId: 'saving-q2', answerId: 'true' }, { questionId: 'saving-q3', answerId: 'option-a' }, { questionId: 'saving-q4', answerId: 'true' }, { questionId: 'saving-q5', answerId: 'option-a' }],
3: [{ questionId: 'needs-q1', answerId: 'option-a' }, { questionId: 'needs-q2', answerId: 'true' }, { questionId: 'needs-q3', orderedItemIds: ['water', 'food', 'medicine', 'shoes', 'toy', 'crown'] }, { questionId: 'needs-q4', answerId: 'option-a' }, { questionId: 'needs-q5', answerId: 'true' }],
4: [{ questionId: 'gold-q1', answerId: 'option-a' }, { questionId: 'gold-q2', answerId: 'true' }, { questionId: 'gold-q3', answerId: 'option-a' }, { questionId: 'gold-q4', answerId: 'false' }, { questionId: 'gold-q5', answerId: 'option-b' }],
5: [{ questionId: 'market-q1', answerId: 'option-a' }, { questionId: 'market-q2', answerId: 'false' }, { questionId: 'market-q3', answerId: 'option-a' }, { questionId: 'market-q4', answerId: 'true' }, { questionId: 'market-q5', answerId: 'option-b' }],
6: [{ questionId: 'inflation-q1', answerId: 'option-b' }, { questionId: 'inflation-q2', answerId: 'true' }, { questionId: 'inflation-q3', answerId: 'option-a' }, { questionId: 'inflation-q4', answerId: 'false' }, { questionId: 'inflation-q5', answerId: 'option-b' }],
}
for (let levelId = 1; levelId <= 6; levelId += 1) {
expect((await page.request.post(`/api/gold-land/levels/${levelId}/start`, { headers })).ok()).toBeTruthy()
expect((await page.request.post(`/api/gold-land/levels/${levelId}/complete`, { headers, data: { answers: lessons[levelId] } })).ok()).toBeTruthy()
}
const later = [
{ answers: [{ questionId: 'initial', allocations: { transport: 20, food: 25, savings: 20, fun: 0 } }, { questionId: 'final', allocations: { transport: 30, food: 25, savings: 20, fun: 0 } }] },
{ answers: [{ questionId: 'q-loss', answerId: 'b' }, { questionId: 'q-certain', answerId: 'no' }, { questionId: 'q-need', answerId: 'keep' }, { questionId: 'q-compare', answerId: 'range' }, { questionId: 'q-promise', answerId: 'check' }] },
{ answers: [{ questionId: 'portfolio', holdings: { sun: 40, rain: 30, wind: 30 } }, { questionId: 'q-one', answerId: 'depend' }, { questionId: 'q-loss', answerId: 'no' }, { questionId: 'q-name', answerId: 'no' }, { questionId: 'q-best', answerId: 'no' }, { questionId: 'q-approach', answerId: 'balanced' }] },
{ answers: [{ questionId: 'compound-q1', answerId: 'on-balance' }, { questionId: 'compound-q2', answerId: '121' }, { questionId: 'compound-q3', answerId: 'from-110' }, { questionId: 'compound-q4', answerId: 'compound' }, { questionId: 'compound-q5', answerId: 'false' }] },
{ answers: [{ questionId: 'notebook-choice', answerId: 'b' }, { questionId: 'notebook-why', answerId: 'fits-and-cheaper' }, { questionId: 'discount-choice', answerId: 'b' }, { questionId: 'discount-why', answerId: 'pay-amount' }, { questionId: 'info-choice', answerId: 'ask' }, { questionId: 'info-why', answerId: 'incomplete' }] },
]
for (let index = 0; index < later.length; index += 1) {
const levelId = index + 7
expect((await page.request.post(`/api/gold-land/levels/${levelId}/start`, { headers })).ok()).toBeTruthy()
expect((await page.request.post(`/api/gold-land/levels/${levelId}/complete`, { headers, data: later[index] })).ok()).toBeTruthy()
}
}
async function answerGoal(page: Page) {
const labels = [
'خرید بسته مشخص با قیمت ۱۲۰ و برنامه پس‌انداز',
'۹۰ سکه',
'۶ هفته',
'نیاز را تأمین کن و مبلغ پس‌انداز یا زمان هدف را اصلاح کن',
'برنامه و زمان را دوباره بررسی و به‌روز کن',
]
for (let index = 0; index < labels.length; index += 1) {
await page.getByText(labels[index]!, { exact: true }).click()
if (index < labels.length - 1) await page.getByRole('button', { name: 'بعدی' }).click()
else await page.getByRole('button', { name: 'مرور پاسخ‌ها' }).click()
}
}
async function buildPlan(page: Page) {
await page.getByRole('button', { name: 'ساخت برنامه' }).click()
await page.getByRole('button', { name: '15 سکه در هفته' }).click()
await expect(page.getByText('برآورد زمان: 6 هفته')).toBeVisible()
await page.getByRole('button', { name: 'تأیید برنامه اولیه' }).click()
await page.getByRole('button', { name: 'هفته دوم: 5 سکه' }).click()
await page.getByRole('button', { name: 'ادامه: 15 سکه' }).click()
await expect(page.getByText('کل زمان: 7 هفته')).toBeVisible()
await expect(page.getByText('موجودی نهایی برآوردی: 125 سکه')).toBeVisible()
await page.getByRole('button', { name: 'رفتن به سؤال‌ها' }).click()
await answerGoal(page)
}
test('financial goal from the map', async ({ page }) => {
const user = uniqueUsername('goal')
await registerViaUi(page, user, 'pass1234', 'هدف')
const token = await page.evaluate(() => localStorage.getItem('gold-land-auth-token'))
await finishThroughShop(page, { authorization: `Bearer ${token}` })
await page.goto('/map')
await page.getByRole('button', { name: 'مرحله 12: هدف مالی' }).click()
await page.getByRole('button', { name: 'شروع چالش' }).click()
await buildPlan(page)
const before = await fetchMe(page)
await page.getByRole('button', { name: 'ثبت نتیجه' }).click()
await expect(page.getByText('پاداش:')).toBeVisible()
await page.getByRole('button', { name: 'بازگشت به نقشه' }).click()
await page.reload()
const after = await fetchMe(page)
expect(after.progress.mapLevels.find((level) => level.id === 12)?.stars).toBe(3)
expect(after.user.coins).toBe(before.user.coins + 20 + 9)
await page.getByRole('button', { name: 'مرحله 12: هدف مالی' }).click()
await page.getByRole('button', { name: 'مرور مجدد' }).click()
await buildPlan(page)
const replayBefore = await fetchMe(page)
await page.getByRole('button', { name: 'ثبت نتیجه' }).click()
await expect(page.getByText('پاداش تازه‌ای اضافه نشد')).toBeVisible()
const replayAfter = await fetchMe(page)
expect(replayAfter.user.coins).toBe(replayBefore.user.coins)
await page.goto('/map')
await page.getByRole('button', { name: 'مرحله 13: آزمون قلعه' }).click()
await expect(page.getByRole('button', { name: 'شروع آزمون' })).toBeEnabled()
})
+8
View File
@@ -0,0 +1,8 @@
/** Valid UI choices for level 1 (what-is-money) — matches backend grader keys. */
export const level1ChoiceLabels = [
'مبادله آسان‌تر کالاها',
'درست',
'چون همه همیشه همان چیز را می‌خواهند',
'درست',
'پول وسیلهٔ مبادله و نگه‌داری ارزش است',
] as const
+242
View File
@@ -0,0 +1,242 @@
import { test, expect, type Page } from '@playwright/test'
import { fetchMe, loginViaUi, logoutViaProfile, registerViaUi, uniqueUsername } from './helpers/auth'
test.describe.configure({ mode: 'serial' })
async function openLevel(page: Page, name: string, start: string) {
await page.goto('/map')
await page.getByRole('button', { name }).click()
await page.getByRole('button', { name: start }).click()
await page.getByText('در حال بارگذاری').waitFor({ state: 'detached', timeout: 30_000 }).catch(() => undefined)
}
async function clickAnswer(page: Page, label: string) {
if (label === 'درست' || label === 'نادرست') {
await page.getByRole('button', { name: label, exact: true }).click()
return
}
const button = page.getByRole('button', { name: label, exact: true })
if (await button.count()) {
await button.first().click()
return
}
await page.getByText(label, { exact: true }).click()
}
async function finishLesson(page: Page, labels: string[]) {
let cursor = 0
for (let step = 0; step < 30; step += 1) {
if (await page.getByText('امتیاز').first().isVisible().catch(() => false)) return
if (await page.getByText('خوراکی ضروری').isVisible().catch(() => false)) {
for (let move = 0; move < 4; move += 1) {
await page.locator('.sort-item').filter({ hasText: 'خوراکی ضروری' }).getByRole('button', { name: '↑' }).click()
}
}
if (cursor < labels.length) {
const label = labels[cursor]!
const visible = await page.getByText(label, { exact: true }).isVisible().catch(() => false)
if (visible) {
await clickAnswer(page, label)
cursor += 1
}
}
const finish = page.getByRole('button', { name: 'اتمام درس' })
if (await finish.isVisible().catch(() => false) && await finish.isEnabled().catch(() => false)) {
await finish.click()
await page.getByText('امتیاز').first().waitFor()
return
}
const next = page.getByRole('button', { name: 'بعدی' })
if (await next.isEnabled().catch(() => false)) await next.click()
}
throw new Error('lesson did not finish')
}
async function starsOf(page: Page, levelId: number) {
const me = await fetchMe(page)
return me.progress.mapLevels.find((level) => level.id === levelId)?.stars ?? 0
}
test('full thirteen-level journey from the interface', async ({ page }, testInfo) => {
test.skip(testInfo.project.name !== 'desktop', 'full journey runs once on desktop')
test.setTimeout(600_000)
const errors: string[] = []
page.on('pageerror', (error) => errors.push(error.message))
page.on('console', (message) => {
if (message.type() === 'error') errors.push(message.text())
})
const user = uniqueUsername('path')
await registerViaUi(page, user, 'pass1234', 'مسیر')
const lessons: Array<{ name: string; labels: string[] }> = [
{ name: 'مرحله 1: پول چیه؟', labels: ['مبادله آسان‌تر کالاها', 'درست', 'چون همه همیشه همان چیز را می‌خواهند', 'درست', 'پول وسیلهٔ مبادله و نگه‌داری ارزش است'] },
{ name: 'مرحله 2: پس‌انداز', labels: ['بخشی از پول را برای بعد کنار گذاشتن', 'درست', 'برای هدفش برنامه نداشت و همه را خرج کرد', 'درست', 'هدف آینده چیزی است که برایش برنامه می‌ریزیم'] },
{ name: 'مرحله 3: نیاز و خواسته', labels: ['چیزی که برای زندگی سالم لازم است', 'درست', 'اول نیازها را برطرف کنیم', 'درست'] },
{ name: 'مرحله 4: طلا چیه؟', labels: ['چون واحد استاندارد وزن طلا است', 'درست', 'زیورآلات و صنعت', 'نادرست', 'طلا دارایی با ارزش است که قیمتش می‌تواند تغییر کند'] },
{ name: 'مرحله 5: بازار طلا', labels: ['قیمت بالا و پایین می‌شود', 'نادرست', 'چون ممکن است وقت کافی برای فکر کردن نداشته باشیم', 'درست', 'فکر کردن و پراکنده نکردن تمام پول در یک دارایی'] },
{ name: 'مرحله 6: تورم', labels: ['افزایش عمومی قیمت‌ها در طول زمان', 'درست', 'قدرت خرید پول کم شده', 'نادرست', 'ممکن است ارزش واقعی‌اش کم شود'] },
]
for (let index = 0; index < lessons.length; index += 1) {
const lesson = lessons[index]!
await openLevel(page, lesson.name, 'شروع درس')
await finishLesson(page, lesson.labels)
await page.getByRole('button', { name: 'بازگشت به نقشه' }).click()
expect(await starsOf(page, index + 1)).toBeGreaterThan(0)
if (index < 5) {
await expect(page.getByRole('button', { name: lessons[index + 1]!.name })).toBeEnabled()
}
}
await page.reload()
expect(await starsOf(page, 6)).toBeGreaterThan(0)
await openLevel(page, 'مرحله 7: بودجه‌بندی', 'شروع بازی')
await page.getByRole('button', { name: 'ساخت بودجه' }).click()
for (let index = 0; index < 4; index += 1) await page.getByRole('button', { name: 'افزایش رفت‌وآمد' }).click()
for (let index = 0; index < 5; index += 1) await page.getByRole('button', { name: 'افزایش آب و غذا' }).click()
for (let index = 0; index < 4; index += 1) await page.getByRole('button', { name: 'افزایش پس‌انداز برای هدف' }).click()
await page.getByRole('button', { name: 'بررسی برنامه' }).click()
await page.getByRole('button', { name: 'تأیید برنامه' }).click()
await page.getByRole('button', { name: 'بازتنظیم بودجه' }).click()
for (let index = 0; index < 2; index += 1) await page.getByRole('button', { name: 'افزایش رفت‌وآمد' }).click()
await page.getByRole('button', { name: 'ثبت نتیجه' }).click()
await page.getByRole('button', { name: 'بازگشت به نقشه' }).click()
expect(await starsOf(page, 7)).toBeGreaterThan(0)
await openLevel(page, 'مرحله 8: ریسک و بازده', 'شروع چالش')
await page.getByRole('button', { name: 'دیدن دو پیشنهاد' }).click()
await page.getByRole('button', { name: 'رفتن به فعالیت‌ها' }).click()
const risk = [
'پیشنهاد ب',
'خیر، ۳۶ فقط یکی از نتیجه‌های ممکن است',
'این پول ضروری را وارد پیشنهادهای نامطمئن نکن',
'پیشنهاد ب امکان نتیجه بالاتر و زیان بیشتری دارد؛ سود بیشتر قطعی نیست',
'وعده را تضمین معتبر فرض نکن، بررسی کن و از بزرگسال قابل اعتماد کمک بگیر',
]
for (let index = 0; index < risk.length; index += 1) {
await page.getByText(risk[index]!, { exact: true }).click()
await page.getByRole('button', { name: index === risk.length - 1 ? 'مرور پاسخ‌ها' : 'بعدی' }).click()
}
await page.getByRole('button', { name: 'ثبت نتیجه' }).click()
await page.getByRole('button', { name: 'بازگشت به نقشه' }).click()
expect(await starsOf(page, 8)).toBeGreaterThan(0)
await openLevel(page, 'مرحله 9: سبد سرمایه‌گذاری', 'شروع بازی')
await page.getByRole('button', { name: 'ساخت سبد' }).click()
for (let index = 0; index < 4; index += 1) await page.getByRole('button', { name: 'افزایش آفتاب' }).click()
for (let index = 0; index < 3; index += 1) await page.getByRole('button', { name: 'افزایش باران' }).click()
for (let index = 0; index < 3; index += 1) await page.getByRole('button', { name: 'افزایش باد' }).click()
await page.getByRole('button', { name: 'دیدن سه سناریو' }).click()
await page.getByRole('button', { name: 'رفتن به سؤال‌ها' }).click()
const portfolio = [
'نتیجه بیشتر به همان گزینه وابسته می‌شود',
'خیر؛ افت همگانی می‌تواند چند گزینه را هم‌زمان کم کند',
'خیر؛ رفتار و وابستگی آن‌ها مهم است',
'خیر؛ یک سناریو آینده را تضمین نمی‌کند',
'توجه به هدف، زمان نیاز به پول و ریسک؛ در مسائل واقعی کمک از بزرگسال قابل اعتماد',
]
for (let index = 0; index < portfolio.length; index += 1) {
await page.getByText(portfolio[index]!, { exact: true }).click()
await page.getByRole('button', { name: index === portfolio.length - 1 ? 'مرور پاسخ‌ها' : 'بعدی' }).click()
}
await page.getByRole('button', { name: 'ثبت نتیجه' }).click()
await page.getByRole('button', { name: 'بازگشت به نقشه' }).click()
expect(await starsOf(page, 9)).toBeGreaterThan(0)
await openLevel(page, 'مرحله 10: سود مرکب', 'شروع درس')
await page.getByRole('button', { name: 'بعدی' }).click()
await page.getByRole('button', { name: 'دوره بعد' }).click()
await page.getByRole('button', { name: 'دوره بعد' }).click()
await page.getByRole('button', { name: 'دوره بعد' }).click()
await page.getByRole('button', { name: 'بعدی' }).click()
const compound = [
'رشد دوره بعد بر موجودی جدید، شامل رشد قبلی، محاسبه می‌شود',
'۱۲۱ سکه',
'چون ۱۰٪ از ۱۱۰ محاسبه شده است',
'مرکب؛ ۱۳۳٫۱ در برابر ۱۳۰',
]
for (const label of compound) {
await page.getByRole('button', { name: label, exact: true }).click()
await page.getByRole('button', { name: 'بعدی' }).click()
}
await page.getByRole('button', { name: 'نادرست', exact: true }).click()
await page.getByRole('button', { name: 'بعدی' }).click()
await page.getByRole('button', { name: 'اتمام درس' }).click()
await page.getByRole('button', { name: 'بازگشت به نقشه' }).click()
expect(await starsOf(page, 10)).toBeGreaterThan(0)
await openLevel(page, 'مرحله 11: خرید هوشمند', 'شروع بازی')
await page.getByRole('button', { name: 'شروع خریدها' }).click()
const shop = [
['دفتر ۶۰برگ، ۴۰ سکه، تحویل ۵ سکه', 'نیاز را برآورده می‌کند و هزینه نهایی‌اش بین گزینه‌های مناسب کمتر است'],
['مداد با قیمت نهایی ۲۸، بدون تخفیف', 'برای کالای یکسان، مبلغ نهایی پرداختی مهم است؛ درصد تخفیف به‌تنهایی کافی نیست'],
['فعلاً نخر و اندازه و هزینه نهایی را بپرس، با کمک بزرگسال قابل اعتماد', 'اطلاعات لازم برای تصمیم و مقایسه هنوز کامل نیست'],
]
for (let index = 0; index < shop.length; index += 1) {
await page.getByText(shop[index]![0]!, { exact: true }).click()
await page.getByText(shop[index]![1]!, { exact: true }).click()
await page.getByRole('button', { name: index === shop.length - 1 ? 'مرور انتخاب‌ها' : 'مأموریت بعد' }).click()
}
await page.getByRole('button', { name: 'ثبت نتیجه' }).click()
await page.getByRole('button', { name: 'بازگشت به نقشه' }).click()
expect(await starsOf(page, 11)).toBeGreaterThan(0)
await openLevel(page, 'مرحله 12: هدف مالی', 'شروع چالش')
await page.getByRole('button', { name: 'ساخت برنامه' }).click()
await page.getByRole('button', { name: '15 سکه در هفته' }).click()
await page.getByRole('button', { name: 'تأیید برنامه اولیه' }).click()
await page.getByRole('button', { name: 'هفته دوم: 5 سکه' }).click()
await page.getByRole('button', { name: 'ادامه: 15 سکه' }).click()
await page.getByRole('button', { name: 'رفتن به سؤال‌ها' }).click()
const goal = [
'خرید بسته مشخص با قیمت ۱۲۰ و برنامه پس‌انداز',
'۹۰ سکه',
'۶ هفته',
'نیاز را تأمین کن و مبلغ پس‌انداز یا زمان هدف را اصلاح کن',
'برنامه و زمان را دوباره بررسی و به‌روز کن',
]
for (let index = 0; index < goal.length; index += 1) {
await page.getByText(goal[index]!, { exact: true }).click()
await page.getByRole('button', { name: index === goal.length - 1 ? 'مرور پاسخ‌ها' : 'بعدی' }).click()
}
await page.getByRole('button', { name: 'ثبت نتیجه' }).click()
await page.getByRole('button', { name: 'بازگشت به نقشه' }).click()
expect(await starsOf(page, 12)).toBeGreaterThan(0)
await page.reload()
expect(await starsOf(page, 12)).toBeGreaterThan(0)
await expect(page.getByRole('button', { name: 'مرحله 14', exact: false })).toHaveCount(0)
await openLevel(page, 'مرحله 13: آزمون قلعه', 'شروع آزمون')
await page.getByRole('button', { name: 'شروع سؤال‌ها' }).click()
const castle = [
'مبادله را آسان می‌کند و مقایسه قیمت را ممکن می‌سازد',
'مبلغی متناسب با شرایط را منظم کنار بگذاریم',
'اول آب آشامیدنی را تأمین کنیم',
'طلا یک دارایی است و قیمتش می‌تواند بالا یا پایین برود',
'خیر',
'با همان پول، مقدار کمتری از آن کالاها می‌توان خرید',
'رفت‌وآمد ۳۰، غذا ۲۵، پس‌انداز ۲۰، تفریح ۱۵، ذخیره ۱۰',
'پول لازم را وارد پیشنهاد نامطمئن با احتمال زیان نکنیم',
'خیر؛ چند گزینه ممکن است هم‌زمان افت کنند',
'۱۲۱',
'ب، چون ۴۵ در برابر ۵۰ است',
'۶ هفته',
]
for (let index = 0; index < castle.length; index += 1) {
await page.getByText(castle[index]!, { exact: true }).click()
await page.getByRole('button', { name: index === castle.length - 1 ? 'مرور پاسخ‌ها' : 'بعدی' }).click()
}
await page.getByRole('button', { name: 'ثبت نتیجه' }).click()
await expect(page.getByText('آفرین! مسیر آموزشی قلعه را کامل کردی')).toBeVisible()
await expect(page.getByRole('button', { name: 'مرحله بعد' })).toHaveCount(0)
await page.getByRole('button', { name: 'بازگشت به نقشه' }).click()
expect(await starsOf(page, 13)).toBeGreaterThan(0)
await logoutViaProfile(page)
await loginViaUi(page, user, 'pass1234')
await page.goto('/map')
for (let levelId = 1; levelId <= 13; levelId += 1) {
expect(await starsOf(page, levelId)).toBeGreaterThan(0)
}
expect(errors.filter((error) => !/favicon|Download the React DevTools/i.test(error))).toEqual([])
})
+17
View File
@@ -0,0 +1,17 @@
import { readFileSync, rmSync } from 'node:fs'
import { join } from 'node:path'
export default function globalTeardown() {
const statePath = join(process.cwd(), 'e2e', '.runtime', 'state.json')
try {
const { tempDir } = JSON.parse(readFileSync(statePath, 'utf8')) as { tempDir: string }
rmSync(tempDir, { recursive: true, force: true })
} catch {
// ignore
}
try {
rmSync(join(process.cwd(), 'e2e', '.runtime'), { recursive: true, force: true })
} catch {
// ignore
}
}
+60
View File
@@ -0,0 +1,60 @@
import type { Page } from '@playwright/test'
export function uniqueUsername(prefix = 'e2e'): string {
return `${prefix}_${Date.now()}_${Math.random().toString(36).slice(2, 8)}`
}
export async function registerViaUi(
page: Page,
username: string,
password: string,
displayName?: string,
) {
await page.goto('/login')
await page.getByRole('button', { name: 'ثبت‌نام کن' }).click()
if (displayName) {
await page.getByLabel('نام نمایشی').fill(displayName)
}
await page.getByLabel('نام کاربری').fill(username)
await page.getByLabel('رمز عبور').fill(password)
await page.getByRole('button', { name: 'ثبت‌نام' }).click()
await page.waitForURL('/')
}
export async function loginViaUi(page: Page, username: string, password: string) {
await page.goto('/login')
await page.getByLabel('نام کاربری').fill(username)
await page.getByLabel('رمز عبور').fill(password)
await page.getByRole('button', { name: 'ورود', exact: true }).click()
await page.waitForURL('/')
}
export async function logoutViaProfile(page: Page) {
await page.goto('/profile')
await page.getByRole('button', { name: 'خروج' }).click()
await page.waitForURL('/login')
}
export async function getAuthToken(page: Page): Promise<string | null> {
return page.evaluate(() => localStorage.getItem('gold-land-auth-token'))
}
export async function fetchMe(page: Page) {
const token = await getAuthToken(page)
if (!token) throw new Error('no auth token')
const res = await page.request.get('/api/me', {
headers: { authorization: `Bearer ${token}` },
})
if (!res.ok()) throw new Error(`GET /api/me failed: ${res.status()}`)
return res.json() as Promise<{
user: { xp: number; coins: number; name: string }
progress: {
mapLevels: Array<{ id: number; stars: number; status: string }>
totalStars: number
completedChallenges: string[]
claimedRewards: string[]
ownedItems: string[]
}
wallet: { cash: number; goldGrams: number }
}>
}
+47
View File
@@ -0,0 +1,47 @@
import type { Page } from '@playwright/test'
import { level1ChoiceLabels } from '../fixtures/level1-answers'
export async function openLevel1FromMap(page: Page) {
await page.goto('/map')
await page.getByRole('heading', { name: 'سرزمین طلا' }).waitFor()
await page.getByRole('button', { name: /مرحله 1:/ }).click()
await page.getByRole('button', { name: 'شروع درس' }).click()
await page.waitForURL(/\/gold-land\/levels\/1/)
await page.getByText('در حال بارگذاری').waitFor({ state: 'detached', timeout: 30_000 })
}
export async function playCurrentLessonSteps(page: Page) {
const pending = [...level1ChoiceLabels]
for (let step = 0; step < 50; step++) {
if (await page.getByText('امتیاز').isVisible().catch(() => false)) return
const finish = page.getByRole('button', { name: 'اتمام درس' })
if ((await finish.isVisible().catch(() => false)) && (await finish.isEnabled())) {
await finish.click()
await page.getByText('امتیاز').waitFor({ timeout: 30_000 })
return
}
if (pending.length > 0) {
const label = pending[0]!
const chip = page.getByRole('button', { name: label, exact: true })
if (await chip.isVisible().catch(() => false)) {
await chip.click()
pending.shift()
}
}
const next = page.getByRole('button', { name: 'بعدی' })
if (await next.isEnabled().catch(() => false)) {
await next.click()
}
}
throw new Error('lesson steps did not complete')
}
export async function completeLevel1Lesson(page: Page) {
await openLevel1FromMap(page)
await playCurrentLessonSteps(page)
}
+82
View File
@@ -0,0 +1,82 @@
import { test, expect } from '@playwright/test'
import {
fetchMe,
loginViaUi,
logoutViaProfile,
registerViaUi,
uniqueUsername,
} from './helpers/auth'
import { completeLevel1Lesson, playCurrentLessonSteps } from './helpers/lesson'
test.describe('main user journey', () => {
test('register → lesson 1 → map → refresh → logout → login', async ({ page }) => {
const user = uniqueUsername('journey')
const password = 'pass1234'
await registerViaUi(page, user, password, 'کاربر E2E')
const meBefore = await fetchMe(page)
const xp0 = meBefore.user.xp
const coins0 = meBefore.user.coins
await completeLevel1Lesson(page)
await expect(page.getByText('مرحله 2 باز شد')).toBeVisible()
const rewardXp = page.locator('.stat-row--reward').filter({ hasText: 'XP' })
if (await rewardXp.count()) {
await expect(rewardXp).toBeVisible()
}
const meAfterLesson = await fetchMe(page)
expect(meAfterLesson.progress.mapLevels.find((l) => l.id === 1)?.stars).toBeGreaterThan(0)
expect(meAfterLesson.progress.mapLevels.find((l) => l.id === 2)?.status).not.toBe('locked')
expect(meAfterLesson.user.xp).toBeGreaterThan(xp0)
expect(meAfterLesson.user.coins).toBeGreaterThan(coins0)
await page.getByRole('button', { name: 'بازگشت به نقشه' }).click()
await page.waitForURL(/\/map/)
await page.reload()
await page.waitForURL(/\/map/)
const meAfterRefresh = await fetchMe(page)
expect(meAfterRefresh.progress.mapLevels.find((l) => l.id === 1)?.stars).toBe(
meAfterLesson.progress.mapLevels.find((l) => l.id === 1)?.stars,
)
await logoutViaProfile(page)
await loginViaUi(page, user, password)
const meRelogin = await fetchMe(page)
expect(meRelogin.progress.mapLevels.find((l) => l.id === 1)?.stars).toBeGreaterThan(0)
})
test('lesson replay without improvement grants no extra reward in UI', async ({ page }) => {
const user = uniqueUsername('replay')
await registerViaUi(page, user, 'pass1234')
await completeLevel1Lesson(page)
const me1 = await fetchMe(page)
const xp1 = me1.user.xp
const coins1 = me1.user.coins
await page.getByRole('button', { name: 'مرور دوباره' }).click()
await page.getByText('در حال بارگذاری').waitFor({ state: 'detached', timeout: 30_000 })
await playCurrentLessonSteps(page)
const me2 = await fetchMe(page)
expect(me2.user.xp).toBe(xp1)
expect(me2.user.coins).toBe(coins1)
})
test('locked and coming_soon levels behave correctly', async ({ page }) => {
const user = uniqueUsername('maplock')
await registerViaUi(page, user, 'pass1234')
await page.goto('/map')
await page.getByRole('heading', { name: 'سرزمین طلا' }).waitFor()
const level2 = page.getByRole('button', { name: /مرحله 2:/ })
await expect(level2).toBeDisabled()
await page.goto('/gold-land/levels/7')
await expect(page.getByText('هنوز قفل است')).toBeVisible()
})
})
+67
View File
@@ -0,0 +1,67 @@
import { test, expect } from '@playwright/test'
import { tomansForGoldPurchase, tomansForGoldSale } from '../src/utils/goldTrade'
import { fetchMe, registerViaUi, uniqueUsername } from './helpers/auth'
test.describe('wallet rounding UI vs server', () => {
test('micro trade and standard buy/sell match server policy', async ({ page }) => {
const user = uniqueUsername('market')
await registerViaUi(page, user, 'pass1234')
const me0 = await fetchMe(page)
const cash0 = me0.wallet.cash
const gold0 = me0.wallet.goldGrams
await page.goto('/market')
await page.locator('button.trade-btn--buy').first().click()
const buyModal = page.getByRole('dialog')
await buyModal.locator('.trade-form__input').fill('0.000003')
await expect(page.getByText('برآورد هزینه (خرید به بالا)')).toBeVisible()
await buyModal.getByRole('button', { name: 'تأیید خرید' }).click()
await expect(page.getByText('خرید با موفقیت انجام شد!').last()).toBeVisible({ timeout: 15_000 })
await expect(buyModal).toBeHidden({ timeout: 10_000 })
let me = await fetchMe(page)
expect(me.wallet.goldGrams).toBeCloseTo(gold0 + 0.000_003, 6)
expect(me.wallet.cash).toBe(cash0 - tomansForGoldPurchase(0.000_003))
for (let i = 0; i < 3; i++) {
await page.locator('button.trade-btn--sell').first().click()
const sellModal = page.getByRole('dialog')
await sellModal.locator('.trade-form__input').fill('0.000001')
await sellModal.getByRole('button', { name: 'تأیید فروش' }).click()
await expect(page.getByText('فروش با موفقیت انجام شد!').last()).toBeVisible({
timeout: 15_000,
})
await expect(sellModal).toBeHidden({ timeout: 10_000 })
}
me = await fetchMe(page)
expect(me.wallet.goldGrams).toBeCloseTo(gold0, 6)
expect(me.wallet.cash).toBeLessThanOrEqual(cash0)
await page.locator('button.trade-btn--buy').first().click()
const buyModal2 = page.getByRole('dialog')
await buyModal2.locator('.trade-form__input').fill('0.05')
await expect(buyModal2.getByText('برآورد هزینه (خرید به بالا)')).toBeVisible()
await buyModal2.getByRole('button', { name: 'تأیید خرید' }).click()
await expect(page.getByText('خرید با موفقیت انجام شد!').last()).toBeVisible({ timeout: 15_000 })
me = await fetchMe(page)
expect(me.wallet.goldGrams).toBeGreaterThan(gold0 + 0.04)
})
test('invalid grams shows server error without changing balance', async ({ page }) => {
const user = uniqueUsername('marketbad')
await registerViaUi(page, user, 'pass1234')
const before = await fetchMe(page)
const snap = JSON.stringify(before.wallet)
await page.goto('/market')
await page.locator('button.trade-btn--buy').first().click()
await page.locator('.trade-form__input').fill('0.0000004')
await page.getByRole('button', { name: 'تأیید خرید' }).click()
await expect(page.getByText(/نامعتبر|کمتر از یک تومان|دقت/)).toBeVisible({ timeout: 15_000 })
const after = await fetchMe(page)
expect(JSON.stringify(after.wallet)).toBe(snap)
})
})
+66
View File
@@ -0,0 +1,66 @@
import { dirname, join } from 'node:path'
import { fileURLToPath } from 'node:url'
import { defineConfig, devices } from '@playwright/test'
const frontendRoot = join(dirname(fileURLToPath(import.meta.url)), '..')
const baseURL = process.env.E2E_BASE_URL ?? 'http://localhost:5190'
const backendPort = Number(process.env.E2E_BACKEND_PORT ?? 3010)
const frontendPort = Number(process.env.E2E_FRONTEND_PORT ?? 5190)
export default defineConfig({
testDir: '.',
testMatch: '**/*.spec.ts',
timeout: 120_000,
fullyParallel: false,
forbidOnly: Boolean(process.env.CI),
retries: process.env.CI ? 1 : 0,
workers: 1,
reporter: [['list'], ['html', { open: 'never', outputFolder: 'playwright-report' }]],
globalTeardown: './global-teardown.ts',
use: {
baseURL,
trace: 'retain-on-failure',
screenshot: 'only-on-failure',
video: 'off',
locale: 'fa-IR',
},
projects: [
{
name: 'mobile',
use: {
...devices['Pixel 7'],
...(process.env.PLAYWRIGHT_CHROME_CHANNEL ? { channel: process.env.PLAYWRIGHT_CHROME_CHANNEL as 'chrome' } : {}),
},
},
{
name: 'desktop',
use: {
...devices['Desktop Chrome'],
viewport: { width: 1280, height: 800 },
...(process.env.PLAYWRIGHT_CHROME_CHANNEL ? { channel: process.env.PLAYWRIGHT_CHROME_CHANNEL as 'chrome' } : {}),
},
},
],
webServer: [
{
command: 'node scripts/e2e-backend.mjs',
cwd: frontendRoot,
url: `http://127.0.0.1:${backendPort}/health`,
timeout: 120_000,
reuseExistingServer: false,
},
{
command: `npx vite --port ${frontendPort} --strictPort`,
cwd: frontendRoot,
port: frontendPort,
timeout: 120_000,
reuseExistingServer: false,
env: {
...process.env,
VITE_DEV_PORT: String(frontendPort),
VITE_DEV_API_TARGET: `http://127.0.0.1:${backendPort}`,
VITE_E2E: '1',
},
},
],
})
+152
View File
@@ -0,0 +1,152 @@
import { test, expect } from '@playwright/test'
import { fetchMe, registerViaUi, uniqueUsername } from './helpers/auth'
const lessons: Record<number, Array<Record<string, unknown>>> = {
1: [
{ questionId: 'money-q1', answerId: 'option-a' },
{ questionId: 'money-q2', answerId: 'true' },
{ questionId: 'money-q3', answerId: 'option-a' },
{ questionId: 'money-q4', answerId: 'true' },
{ questionId: 'money-q5', answerId: 'option-b' },
],
2: [
{ questionId: 'saving-q1', answerId: 'option-b' },
{ questionId: 'saving-q2', answerId: 'true' },
{ questionId: 'saving-q3', answerId: 'option-a' },
{ questionId: 'saving-q4', answerId: 'true' },
{ questionId: 'saving-q5', answerId: 'option-a' },
],
3: [
{ questionId: 'needs-q1', answerId: 'option-a' },
{ questionId: 'needs-q2', answerId: 'true' },
{ questionId: 'needs-q3', orderedItemIds: ['water', 'food', 'medicine', 'shoes', 'toy', 'crown'] },
{ questionId: 'needs-q4', answerId: 'option-a' },
{ questionId: 'needs-q5', answerId: 'true' },
],
4: [
{ questionId: 'gold-q1', answerId: 'option-a' },
{ questionId: 'gold-q2', answerId: 'true' },
{ questionId: 'gold-q3', answerId: 'option-a' },
{ questionId: 'gold-q4', answerId: 'false' },
{ questionId: 'gold-q5', answerId: 'option-b' },
],
5: [
{ questionId: 'market-q1', answerId: 'option-a' },
{ questionId: 'market-q2', answerId: 'false' },
{ questionId: 'market-q3', answerId: 'option-a' },
{ questionId: 'market-q4', answerId: 'true' },
{ questionId: 'market-q5', answerId: 'option-b' },
],
6: [
{ questionId: 'inflation-q1', answerId: 'option-b' },
{ questionId: 'inflation-q2', answerId: 'true' },
{ questionId: 'inflation-q3', answerId: 'option-a' },
{ questionId: 'inflation-q4', answerId: 'false' },
{ questionId: 'inflation-q5', answerId: 'option-b' },
],
}
async function answerPortfolio(page: import('@playwright/test').Page) {
const choices = [
'نتیجه بیشتر به همان گزینه وابسته می‌شود',
'خیر؛ افت همگانی می‌تواند چند گزینه را هم‌زمان کم کند',
'خیر؛ رفتار و وابستگی آن‌ها مهم است',
'خیر؛ یک سناریو آینده را تضمین نمی‌کند',
'توجه به هدف، زمان نیاز به پول و ریسک؛ در مسائل واقعی کمک از بزرگسال قابل اعتماد',
]
for (let index = 0; index < choices.length; index += 1) {
await page.getByText(choices[index]!, { exact: true }).click()
if (index < choices.length - 1) await page.getByRole('button', { name: 'بعدی' }).click()
else await page.getByRole('button', { name: 'مرور پاسخ‌ها' }).click()
}
}
test('portfolio game from the map', async ({ page }) => {
const user = uniqueUsername('port')
await registerViaUi(page, user, 'pass1234', 'سبد')
const token = await page.evaluate(() => localStorage.getItem('gold-land-auth-token'))
const headers = { authorization: `Bearer ${token}` }
for (let levelId = 1; levelId <= 6; levelId += 1) {
expect((await page.request.post(`/api/gold-land/levels/${levelId}/start`, { headers })).ok()).toBeTruthy()
expect((await page.request.post(`/api/gold-land/levels/${levelId}/complete`, {
headers,
data: { answers: lessons[levelId] },
})).ok()).toBeTruthy()
}
expect((await page.request.post('/api/gold-land/levels/7/start', { headers })).ok()).toBeTruthy()
expect((await page.request.post('/api/gold-land/levels/7/complete', {
headers,
data: {
answers: [
{ questionId: 'initial', allocations: { transport: 20, food: 25, savings: 20, fun: 0 } },
{ questionId: 'final', allocations: { transport: 30, food: 25, savings: 20, fun: 0 } },
],
},
})).ok()).toBeTruthy()
expect((await page.request.post('/api/gold-land/levels/8/start', { headers })).ok()).toBeTruthy()
expect((await page.request.post('/api/gold-land/levels/8/complete', {
headers,
data: {
answers: [
{ questionId: 'q-loss', answerId: 'b' },
{ questionId: 'q-certain', answerId: 'no' },
{ questionId: 'q-need', answerId: 'keep' },
{ questionId: 'q-compare', answerId: 'range' },
{ questionId: 'q-promise', answerId: 'check' },
],
},
})).ok()).toBeTruthy()
await page.goto('/map')
await page.getByRole('button', { name: 'مرحله 9: سبد سرمایه‌گذاری' }).click()
await page.getByRole('button', { name: 'شروع بازی' }).click()
await page.getByRole('button', { name: 'ساخت سبد' }).click()
await expect(page.getByRole('button', { name: 'دیدن سه سناریو' })).toBeDisabled()
const sunUp = page.getByRole('button', { name: 'افزایش آفتاب' })
const rainUp = page.getByRole('button', { name: 'افزایش باران' })
const windUp = page.getByRole('button', { name: 'افزایش باد' })
for (let index = 0; index < 4; index += 1) await sunUp.click()
for (let index = 0; index < 3; index += 1) await rainUp.click()
for (let index = 0; index < 3; index += 1) await windUp.click()
await page.getByRole('button', { name: 'دیدن سه سناریو' }).click()
await expect(page.getByText('سود 5 سکه')).toBeVisible()
await expect(page.getByText('زیان 5 سکه')).toBeVisible()
await expect(page.getByText('زیان 10 سکه').first()).toBeVisible()
await page.getByRole('button', { name: 'تغییر ترکیب' }).click()
await page.getByRole('button', { name: 'کاهش آفتاب' }).click()
await page.getByRole('button', { name: 'افزایش باد' }).click()
await page.getByRole('button', { name: 'دیدن سه سناریو' }).click()
await page.getByRole('button', { name: 'رفتن به سؤال‌ها' }).click()
await answerPortfolio(page)
const before = await fetchMe(page)
await page.getByRole('button', { name: 'ثبت نتیجه' }).click()
await expect(page.getByText('پاداش:')).toBeVisible()
await expect(page.getByText('زیان را حذف یا سود را تضمین نمی‌کند')).toBeVisible()
await page.getByRole('button', { name: 'بازگشت به نقشه' }).click()
await page.reload()
const after = await fetchMe(page)
expect(after.progress.mapLevels.find((level) => level.id === 9)?.stars).toBe(3)
expect(after.user.coins).toBe(before.user.coins + 20 + 9)
await page.getByRole('button', { name: 'مرحله 9: سبد سرمایه‌گذاری' }).click()
await page.getByRole('button', { name: 'مرور مجدد' }).click()
await page.getByRole('button', { name: 'ساخت سبد' }).click()
for (let index = 0; index < 10; index += 1) await page.getByRole('button', { name: 'افزایش آفتاب' }).click()
await page.getByRole('button', { name: 'دیدن سه سناریو' }).click()
await page.getByRole('button', { name: 'رفتن به سؤال‌ها' }).click()
await answerPortfolio(page)
const replayBefore = await fetchMe(page)
await page.getByRole('button', { name: 'ثبت نتیجه' }).click()
await expect(page.getByText('پاداش تازه‌ای اضافه نشد')).toBeVisible()
const replayAfter = await fetchMe(page)
expect(replayAfter.user.coins).toBe(replayBefore.user.coins)
await page.goto('/map')
await expect(page.getByRole('button', { name: 'مرحله 11: خرید هوشمند' })).toBeDisabled()
})
+123
View File
@@ -0,0 +1,123 @@
import { test, expect } from '@playwright/test'
import { fetchMe, registerViaUi, uniqueUsername } from './helpers/auth'
const lessons: Record<number, Array<Record<string, unknown>>> = {
1: [
{ questionId: 'money-q1', answerId: 'option-a' },
{ questionId: 'money-q2', answerId: 'true' },
{ questionId: 'money-q3', answerId: 'option-a' },
{ questionId: 'money-q4', answerId: 'true' },
{ questionId: 'money-q5', answerId: 'option-b' },
],
2: [
{ questionId: 'saving-q1', answerId: 'option-b' },
{ questionId: 'saving-q2', answerId: 'true' },
{ questionId: 'saving-q3', answerId: 'option-a' },
{ questionId: 'saving-q4', answerId: 'true' },
{ questionId: 'saving-q5', answerId: 'option-a' },
],
3: [
{ questionId: 'needs-q1', answerId: 'option-a' },
{ questionId: 'needs-q2', answerId: 'true' },
{ questionId: 'needs-q3', orderedItemIds: ['water', 'food', 'medicine', 'shoes', 'toy', 'crown'] },
{ questionId: 'needs-q4', answerId: 'option-a' },
{ questionId: 'needs-q5', answerId: 'true' },
],
4: [
{ questionId: 'gold-q1', answerId: 'option-a' },
{ questionId: 'gold-q2', answerId: 'true' },
{ questionId: 'gold-q3', answerId: 'option-a' },
{ questionId: 'gold-q4', answerId: 'false' },
{ questionId: 'gold-q5', answerId: 'option-b' },
],
5: [
{ questionId: 'market-q1', answerId: 'option-a' },
{ questionId: 'market-q2', answerId: 'false' },
{ questionId: 'market-q3', answerId: 'option-a' },
{ questionId: 'market-q4', answerId: 'true' },
{ questionId: 'market-q5', answerId: 'option-b' },
],
6: [
{ questionId: 'inflation-q1', answerId: 'option-b' },
{ questionId: 'inflation-q2', answerId: 'true' },
{ questionId: 'inflation-q3', answerId: 'option-a' },
{ questionId: 'inflation-q4', answerId: 'false' },
{ questionId: 'inflation-q5', answerId: 'option-b' },
],
}
async function answerChallenge(page: import('@playwright/test').Page) {
const choices = [
'پیشنهاد ب',
'خیر، ۳۶ فقط یکی از نتیجه‌های ممکن است',
'این پول ضروری را وارد پیشنهادهای نامطمئن نکن',
'پیشنهاد ب امکان نتیجه بالاتر و زیان بیشتری دارد؛ سود بیشتر قطعی نیست',
'وعده را تضمین معتبر فرض نکن، بررسی کن و از بزرگسال قابل اعتماد کمک بگیر',
]
for (let index = 0; index < choices.length; index += 1) {
await page.getByText(choices[index]!, { exact: true }).click()
if (index < choices.length - 1) {
await page.getByRole('button', { name: 'بعدی' }).click()
} else {
await page.getByRole('button', { name: 'مرور پاسخ‌ها' }).click()
}
}
}
test('risk and return challenge from the map', async ({ page }) => {
const user = uniqueUsername('risk')
await registerViaUi(page, user, 'pass1234', 'ریسک')
const token = await page.evaluate(() => localStorage.getItem('gold-land-auth-token'))
const headers = { authorization: `Bearer ${token}` }
for (let levelId = 1; levelId <= 6; levelId += 1) {
expect((await page.request.post(`/api/gold-land/levels/${levelId}/start`, { headers })).ok()).toBeTruthy()
expect((await page.request.post(`/api/gold-land/levels/${levelId}/complete`, {
headers,
data: { answers: lessons[levelId] },
})).ok()).toBeTruthy()
}
const budget = {
answers: [
{ questionId: 'initial', allocations: { transport: 20, food: 25, savings: 20, fun: 0 } },
{ questionId: 'final', allocations: { transport: 30, food: 25, savings: 20, fun: 0 } },
],
}
expect((await page.request.post('/api/gold-land/levels/7/start', { headers })).ok()).toBeTruthy()
expect((await page.request.post('/api/gold-land/levels/7/complete', { headers, data: budget })).ok()).toBeTruthy()
await page.goto('/map')
await page.getByRole('button', { name: 'مرحله 8: ریسک و بازده' }).click()
await page.getByRole('button', { name: 'شروع چالش' }).click()
await page.getByRole('button', { name: 'دیدن دو پیشنهاد' }).click()
await expect(page.getByText('کارت 1 از 4: 8 سکه')).toBeVisible()
await expect(page.getByText('کارت 4 از 4: 36 سکه')).toBeVisible()
await expect(page.getByText('کارت 3 از 4: 22 سکه')).toBeVisible()
await page.getByRole('button', { name: 'رفتن به فعالیت‌ها' }).click()
await answerChallenge(page)
const before = await fetchMe(page)
await page.getByRole('button', { name: 'ثبت نتیجه' }).click()
await expect(page.getByText('پاداش:')).toBeVisible()
await expect(page.getByText('امکان سود بیشتر، تضمین سود نیست')).toBeVisible()
await page.getByRole('button', { name: 'بازگشت به نقشه' }).click()
await page.reload()
const after = await fetchMe(page)
expect(after.progress.mapLevels.find((level) => level.id === 8)?.stars).toBe(3)
expect(after.user.coins).toBe(before.user.coins + 20 + 9)
await page.getByRole('button', { name: 'مرحله 8: ریسک و بازده' }).click()
await page.getByRole('button', { name: 'مرور مجدد' }).click()
await page.getByRole('button', { name: 'دیدن دو پیشنهاد' }).click()
await page.getByRole('button', { name: 'رفتن به فعالیت‌ها' }).click()
await answerChallenge(page)
const replayBefore = await fetchMe(page)
await page.getByRole('button', { name: 'ثبت نتیجه' }).click()
await expect(page.getByText('پاداش تازه‌ای اضافه نشد')).toBeVisible()
const replayAfter = await fetchMe(page)
expect(replayAfter.user.coins).toBe(replayBefore.user.coins)
await page.goto('/map')
await expect(page.getByRole('button', { name: 'مرحله 10: سود مرکب' })).toBeDisabled()
})
+93
View File
@@ -0,0 +1,93 @@
import { test, expect } from '@playwright/test'
import { fetchMe, loginViaUi, logoutViaProfile, registerViaUi, uniqueUsername } from './helpers/auth'
test.describe('session and errors', () => {
test('wrong password shows login failure', async ({ page }) => {
await page.goto('/login')
await page.getByLabel('نام کاربری').fill('no_such_user_e2e')
await page.getByLabel('رمز عبور').fill('wrongpass')
await page.getByRole('button', { name: 'ورود', exact: true }).click()
await expect(page.locator('.toast--error')).toBeVisible({ timeout: 10_000 })
await expect(page).toHaveURL(/login/)
})
test('second account does not show first account data', async ({ page }) => {
const u1 = uniqueUsername('acct1')
const u2 = uniqueUsername('acct2')
await registerViaUi(page, u1, 'pass1234', 'کاربر یک')
const me1 = await fetchMe(page)
await page.goto('/profile')
await expect(page.locator('.user-section__name')).toContainText(me1.user.name ?? 'کاربر یک')
await logoutViaProfile(page)
await page.getByRole('button', { name: 'ثبت‌نام کن' }).click()
await page.getByLabel('نام نمایشی').fill('کاربر دو')
await page.getByLabel('نام کاربری').fill(u2)
await page.getByLabel('رمز عبور').fill('pass1234')
await page.getByRole('button', { name: 'ثبت‌نام' }).click()
await page.waitForURL('/')
const me2 = await fetchMe(page)
await page.goto('/profile')
await expect(page.locator('.user-section__name')).toContainText(me2.user.name)
await expect(page.locator('.user-section__name')).not.toContainText('کاربر یک')
})
test('401 clears session to login', async ({ page }) => {
const user = uniqueUsername('401')
await registerViaUi(page, user, 'pass1234')
await page.goto('/wallet')
await page.evaluate(() => localStorage.setItem('gold-land-auth-token', 'invalid-token'))
await page.goto('/market')
await page.waitForURL('/login', { timeout: 15_000 })
})
test('catalog load retry after network failure', async ({ page }) => {
const user = uniqueUsername('net')
await registerViaUi(page, user, 'pass1234')
let storeCalls = 0
await page.route('**/api/store/products', async (route) => {
storeCalls += 1
if (storeCalls === 1) {
await route.abort('failed')
return
}
await route.continue()
})
await page.goto('/store')
await expect(page.locator('.store-status--error')).toBeVisible({ timeout: 15_000 })
await expect(page.getByText(/اتصال به سرور|خطا در دریافت/)).toBeVisible()
await page.getByRole('button', { name: 'تلاش مجدد' }).click()
await page.getByRole('button', { name: 'تقویت XP' }).waitFor({ timeout: 20_000 })
expect(storeCalls).toBeGreaterThan(1)
})
test('bootstrap network error keeps token and retry loads server data', async ({ page }) => {
const user = uniqueUsername('boot')
await registerViaUi(page, user, 'pass1234')
const meOk = await fetchMe(page)
let meCalls = 0
await page.route('**/api/me', async (route) => {
meCalls += 1
if (meCalls === 1) {
await route.abort('failed')
return
}
await route.continue()
})
await page.reload()
await expect(page.getByRole('alert')).toContainText('اتصال به سرور', { timeout: 15_000 })
expect(await page.evaluate(() => localStorage.getItem('gold-land-auth-token'))).toBeTruthy()
await page.getByRole('button', { name: 'تلاش مجدد' }).click()
await expect(page.getByRole('alert')).toBeHidden({ timeout: 20_000 })
const meAfter = await fetchMe(page)
expect(meAfter.user.xp).toBe(meOk.user.xp)
expect(meAfter.user.coins).toBe(meOk.user.coins)
expect(meCalls).toBeGreaterThan(1)
})
})
+135
View File
@@ -0,0 +1,135 @@
import { test, expect } from '@playwright/test'
import { fetchMe, registerViaUi, uniqueUsername } from './helpers/auth'
async function completePrior(page: import('@playwright/test').Page, headers: { authorization: string }) {
const lessons: Record<number, Array<Record<string, unknown>>> = {
1: [
{ questionId: 'money-q1', answerId: 'option-a' },
{ questionId: 'money-q2', answerId: 'true' },
{ questionId: 'money-q3', answerId: 'option-a' },
{ questionId: 'money-q4', answerId: 'true' },
{ questionId: 'money-q5', answerId: 'option-b' },
],
2: [
{ questionId: 'saving-q1', answerId: 'option-b' },
{ questionId: 'saving-q2', answerId: 'true' },
{ questionId: 'saving-q3', answerId: 'option-a' },
{ questionId: 'saving-q4', answerId: 'true' },
{ questionId: 'saving-q5', answerId: 'option-a' },
],
3: [
{ questionId: 'needs-q1', answerId: 'option-a' },
{ questionId: 'needs-q2', answerId: 'true' },
{ questionId: 'needs-q3', orderedItemIds: ['water', 'food', 'medicine', 'shoes', 'toy', 'crown'] },
{ questionId: 'needs-q4', answerId: 'option-a' },
{ questionId: 'needs-q5', answerId: 'true' },
],
4: [
{ questionId: 'gold-q1', answerId: 'option-a' },
{ questionId: 'gold-q2', answerId: 'true' },
{ questionId: 'gold-q3', answerId: 'option-a' },
{ questionId: 'gold-q4', answerId: 'false' },
{ questionId: 'gold-q5', answerId: 'option-b' },
],
5: [
{ questionId: 'market-q1', answerId: 'option-a' },
{ questionId: 'market-q2', answerId: 'false' },
{ questionId: 'market-q3', answerId: 'option-a' },
{ questionId: 'market-q4', answerId: 'true' },
{ questionId: 'market-q5', answerId: 'option-b' },
],
6: [
{ questionId: 'inflation-q1', answerId: 'option-b' },
{ questionId: 'inflation-q2', answerId: 'true' },
{ questionId: 'inflation-q3', answerId: 'option-a' },
{ questionId: 'inflation-q4', answerId: 'false' },
{ questionId: 'inflation-q5', answerId: 'option-b' },
],
}
for (let levelId = 1; levelId <= 6; levelId += 1) {
expect((await page.request.post(`/api/gold-land/levels/${levelId}/start`, { headers })).ok()).toBeTruthy()
expect((await page.request.post(`/api/gold-land/levels/${levelId}/complete`, { headers, data: { answers: lessons[levelId] } })).ok()).toBeTruthy()
}
const posts: Array<[string, unknown]> = [
['7', { answers: [
{ questionId: 'initial', allocations: { transport: 20, food: 25, savings: 20, fun: 0 } },
{ questionId: 'final', allocations: { transport: 30, food: 25, savings: 20, fun: 0 } },
] }],
['8', { answers: [
{ questionId: 'q-loss', answerId: 'b' },
{ questionId: 'q-certain', answerId: 'no' },
{ questionId: 'q-need', answerId: 'keep' },
{ questionId: 'q-compare', answerId: 'range' },
{ questionId: 'q-promise', answerId: 'check' },
] }],
['9', { answers: [
{ questionId: 'portfolio', holdings: { sun: 40, rain: 30, wind: 30 } },
{ questionId: 'q-one', answerId: 'depend' },
{ questionId: 'q-loss', answerId: 'no' },
{ questionId: 'q-name', answerId: 'no' },
{ questionId: 'q-best', answerId: 'no' },
{ questionId: 'q-approach', answerId: 'balanced' },
] }],
['10', { answers: [
{ questionId: 'compound-q1', answerId: 'on-balance' },
{ questionId: 'compound-q2', answerId: '121' },
{ questionId: 'compound-q3', answerId: 'from-110' },
{ questionId: 'compound-q4', answerId: 'compound' },
{ questionId: 'compound-q5', answerId: 'false' },
] }],
]
for (const [levelId, data] of posts) {
expect((await page.request.post(`/api/gold-land/levels/${levelId}/start`, { headers })).ok()).toBeTruthy()
expect((await page.request.post(`/api/gold-land/levels/${levelId}/complete`, { headers, data })).ok()).toBeTruthy()
}
}
async function answerShop(page: import('@playwright/test').Page) {
const picks = [
['دفتر ۶۰برگ، ۴۰ سکه، تحویل ۵ سکه', 'نیاز را برآورده می‌کند و هزینه نهایی‌اش بین گزینه‌های مناسب کمتر است'],
['مداد با قیمت نهایی ۲۸، بدون تخفیف', 'برای کالای یکسان، مبلغ نهایی پرداختی مهم است؛ درصد تخفیف به‌تنهایی کافی نیست'],
['فعلاً نخر و اندازه و هزینه نهایی را بپرس، با کمک بزرگسال قابل اعتماد', 'اطلاعات لازم برای تصمیم و مقایسه هنوز کامل نیست'],
]
for (let index = 0; index < picks.length; index += 1) {
if (index === 2) await expect(page.getByText('نامشخص').first()).toBeVisible()
await page.getByText(picks[index]![0]!, { exact: true }).click()
await page.getByText(picks[index]![1]!, { exact: true }).click()
await page.getByRole('button', { name: index === picks.length - 1 ? 'مرور انتخاب‌ها' : 'مأموریت بعد' }).click()
}
}
test('smart shop from the map', async ({ page }) => {
const user = uniqueUsername('shop')
await registerViaUi(page, user, 'pass1234', 'خرید')
const token = await page.evaluate(() => localStorage.getItem('gold-land-auth-token'))
await completePrior(page, { authorization: `Bearer ${token}` })
await page.goto('/map')
await page.getByRole('button', { name: 'مرحله 11: خرید هوشمند' }).click()
await page.getByRole('button', { name: 'شروع بازی' }).click()
await page.getByRole('button', { name: 'شروع خریدها' }).click()
await expect(page.getByText('بودجه:')).toBeVisible()
await expect(page.getByText('جمع نهایی: ۴۵ سکه')).toBeVisible()
await answerShop(page)
const before = await fetchMe(page)
await page.getByRole('button', { name: 'ثبت نتیجه' }).click()
await expect(page.getByText('پاداش:')).toBeVisible()
await page.getByRole('button', { name: 'بازگشت به نقشه' }).click()
await page.reload()
const after = await fetchMe(page)
expect(after.progress.mapLevels.find((level) => level.id === 11)?.stars).toBe(3)
expect(after.user.coins).toBe(before.user.coins + 18 + 9)
await page.getByRole('button', { name: 'مرحله 11: خرید هوشمند' }).click()
await page.getByRole('button', { name: 'مرور مجدد' }).click()
await page.getByRole('button', { name: 'شروع خریدها' }).click()
await answerShop(page)
const replayBefore = await fetchMe(page)
await page.getByRole('button', { name: 'ثبت نتیجه' }).click()
await expect(page.getByText('پاداش تازه‌ای اضافه نشد')).toBeVisible()
const replayAfter = await fetchMe(page)
expect(replayAfter.user.coins).toBe(replayBefore.user.coins)
await page.goto('/map')
await expect(page.getByRole('button', { name: 'مرحله 13: آزمون قلعه' })).toBeDisabled()
})
+31
View File
@@ -0,0 +1,31 @@
import { test, expect } from '@playwright/test'
import { registerViaUi, uniqueUsername } from './helpers/auth'
test.describe('UI quality', () => {
test('no unexpected console errors on home and RTL layout', async ({ page }) => {
const errors: string[] = []
page.on('pageerror', (err) => errors.push(err.message))
page.on('console', (msg) => {
if (msg.type() === 'error') errors.push(msg.text())
})
const user = uniqueUsername('ui')
await registerViaUi(page, user, 'pass1234')
const bodyDir = await page.evaluate(() => getComputedStyle(document.body).direction)
expect(bodyDir).toBe('rtl')
const overflow = await page.evaluate(() => document.documentElement.scrollWidth > window.innerWidth + 2)
expect(overflow).toBe(false)
const filtered = errors.filter(
(e) => !e.includes('favicon') && !e.includes('DevTools') && !e.includes('404'),
)
expect(filtered).toEqual([])
})
test('keyboard focus reaches login username field', async ({ page }) => {
await page.goto('/login')
await page.getByLabel('نام کاربری').focus()
await expect(page.getByLabel('نام کاربری')).toBeFocused()
})
})
Vendored
+10
View File
@@ -17,3 +17,13 @@ declare module '*.png' {
const src: string
export default src
}
declare module '*.jpg' {
const src: string
export default src
}
declare module '*.webp' {
const src: string
export default src
}
+38
View File
@@ -0,0 +1,38 @@
server {
listen 80;
server_name _;
root /usr/share/nginx/html;
index index.html;
# API requests proxied to the NestJS backend (same Docker network).
location /api/ {
proxy_pass http://backend:3000;
proxy_http_version 1.1;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
# Single hop: client IP as seen by nginx (do not append client-supplied XFF).
proxy_set_header X-Forwarded-For $remote_addr;
proxy_set_header X-Forwarded-Proto $scheme;
}
location /health {
proxy_pass http://backend:3000/health;
proxy_http_version 1.1;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $remote_addr;
}
location /health/ready {
proxy_pass http://backend:3000/health/ready;
proxy_http_version 1.1;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $remote_addr;
}
location / {
try_files $uri $uri/ /index.html;
}
}
+26
View File
@@ -0,0 +1,26 @@
# Offline image build on the server
The archive contains npm caches from Linux Node 22.18.0. Do not use a Windows `node_modules`.
Images:
- `child-gold-land-backend:866be223956ef5d3961b0d835b36adedfeb35c82`
- `child-gold-land-frontend:c53a67831db98ea10f1aa168fcab80cca97134ed`
```bash
sha256sum -c offline-deps.tar.gz.sha256
tar -xzf offline-deps.tar.gz
cp -a offline-deps/backend-npm-cache /opt/gold_land/server/src/offline-npm-cache
cp -a offline-deps/frontend-npm-cache /opt/gold_land/user/src/offline-npm-cache
cp offline-deps/backend.Dockerfile /opt/gold_land/server/src/Dockerfile.offline
cp offline-deps/frontend.Dockerfile /opt/gold_land/user/src/Dockerfile.offline
docker build --pull=false -f /opt/gold_land/server/src/Dockerfile.offline \
-t child-gold-land-backend:866be223956ef5d3961b0d835b36adedfeb35c82 \
/opt/gold_land/server/src
docker build --pull=false -f /opt/gold_land/user/src/Dockerfile.offline \
--build-arg VITE_API_URL=/api \
-t child-gold-land-frontend:c53a67831db98ea10f1aa168fcab80cca97134ed \
/opt/gold_land/user/src
```
Point the existing compose services at those tags. Keep the current `.env` and volume. Start without `--build`. `nginx:1.27-alpine` must already be local or pullable from Docker Hub. `node:22.18.0-bookworm` must already be local.
+52
View File
@@ -0,0 +1,52 @@
# syntax=docker/dockerfile:1
# Offline production image. Build context is the backend source tree
# plus ./offline-npm-cache. Base image must already exist locally:
# node:22.18.0-bookworm
FROM node:22.18.0-bookworm AS build
WORKDIR /app
ENV npm_config_build_from_source=true \
npm_config_nodedir=/usr/local
COPY offline-npm-cache /offline-npm-cache
COPY package.json package-lock.json ./
RUN npm ci --offline --cache /offline-npm-cache --no-audit --no-fund
COPY nest-cli.json tsconfig.json tsconfig.build.json ./
COPY src ./src
RUN npm run build
FROM node:22.18.0-bookworm AS production
WORKDIR /app
ENV NODE_ENV=production \
PORT=3000 \
HOST=0.0.0.0 \
DB_PATH=/app/data/app.db \
npm_config_build_from_source=true \
npm_config_nodedir=/usr/local
COPY package.json package-lock.json ./
COPY --from=build /offline-npm-cache /offline-npm-cache
RUN npm ci --offline --omit=dev --cache /offline-npm-cache --no-audit --no-fund \
&& rm -rf /offline-npm-cache /root/.npm
COPY --from=build /app/dist ./dist
RUN mkdir -p /app/data \
&& chown -R node:node /app
USER node
EXPOSE 3000
HEALTHCHECK --interval=30s --timeout=5s --start-period=20s --retries=3 \
CMD node -e "fetch('http://127.0.0.1:3000/health/ready').then((r)=>process.exit(r.ok?0:1)).catch(()=>process.exit(1))"
CMD ["node", "dist/main.js"]
+29
View File
@@ -0,0 +1,29 @@
# syntax=docker/dockerfile:1
# Offline frontend image. Build context is the frontend source tree
# plus ./offline-npm-cache. nginx.conf must be in that context.
FROM node:22.18.0-bookworm AS build
WORKDIR /app
ARG VITE_API_URL=/api
ENV VITE_API_URL=${VITE_API_URL}
COPY offline-npm-cache /offline-npm-cache
COPY package.json package-lock.json ./
RUN npm ci --offline --cache /offline-npm-cache --no-audit --no-fund \
&& rm -rf /offline-npm-cache /root/.npm
COPY . .
RUN npm run build
FROM nginx:1.27-alpine AS production
COPY nginx.conf /etc/nginx/conf.d/default.conf
COPY --from=build /app/dist /usr/share/nginx/html
EXPOSE 80
CMD ["nginx", "-g", "daemon off;"]
+550
View File
@@ -17,11 +17,13 @@
"vue-router": "^4.5.1"
},
"devDependencies": {
"@playwright/test": "^1.55.1",
"@tsconfig/node24": "^24.0.4",
"@types/node": "^24.13.3",
"@vitejs/plugin-vue": "^6.0.8",
"@vue/tsconfig": "^0.9.1",
"npm-run-all2": "^9.0.2",
"tsx": "^4.20.5",
"typescript": "~6.0.0",
"vite": "^8.1.5",
"vite-plugin-vue-devtools": "^8.1.5",
@@ -520,6 +522,448 @@
"tslib": "^2.4.0"
}
},
"node_modules/@esbuild/aix-ppc64": {
"version": "0.28.2",
"resolved": "https://registry.npmjs.org/@esbuild/aix-ppc64/-/aix-ppc64-0.28.2.tgz",
"integrity": "sha512-XExcO+dvLKvVtNTibSTBej1NCAbaGhWn9Ww1ZPx80qsahhPFe/8jgWP0IchNe0F3HwkU7n8ejhH8bjonqht8mQ==",
"cpu": [
"ppc64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"aix"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/android-arm": {
"version": "0.28.2",
"resolved": "https://registry.npmjs.org/@esbuild/android-arm/-/android-arm-0.28.2.tgz",
"integrity": "sha512-kXXoiPVVGQcnIYGOeaovwOURpniDBpSq4A03qkQ+BMQqtGG6HYap3xne9C1O1yo4TR3qxlCX5IqqmX6fFo2Lqg==",
"cpu": [
"arm"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"android"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/android-arm64": {
"version": "0.28.2",
"resolved": "https://registry.npmjs.org/@esbuild/android-arm64/-/android-arm64-0.28.2.tgz",
"integrity": "sha512-5YfKeeI8qWfBZIX+u2xZC3Zlb3Os/gLS2sbEKM+I4ZOcsWmHS2WLysCcQZDAFRslDUU5Oiq44gf6PYN1vGwG5A==",
"cpu": [
"arm64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"android"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/android-x64": {
"version": "0.28.2",
"resolved": "https://registry.npmjs.org/@esbuild/android-x64/-/android-x64-0.28.2.tgz",
"integrity": "sha512-O387ite7SzUyCcy3JQX4P4bLtEA7bLLkx+esve5JHnyYfNTxcVpXZo9jhdB0lTKN44gztELTdU7nS8Nr16Fs1Q==",
"cpu": [
"x64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"android"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/darwin-arm64": {
"version": "0.28.2",
"resolved": "https://registry.npmjs.org/@esbuild/darwin-arm64/-/darwin-arm64-0.28.2.tgz",
"integrity": "sha512-n4KqkOQrraxHJcgjM1RvwbigfQKIKJVpM7xp+KsxiyUSrRdIXnt73VhrPAx0fV44hgfmIVKjxMN9J1t5jySVkw==",
"cpu": [
"arm64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"darwin"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/darwin-x64": {
"version": "0.28.2",
"resolved": "https://registry.npmjs.org/@esbuild/darwin-x64/-/darwin-x64-0.28.2.tgz",
"integrity": "sha512-uq6suIWYP37qzGddBKPw5QEQPi6HiLGsO7UmkpfyaYNQ3D+rN6w6WfwH+nuqcGXWvawGwxOEroO4YGnFh95azw==",
"cpu": [
"x64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"darwin"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/freebsd-arm64": {
"version": "0.28.2",
"resolved": "https://registry.npmjs.org/@esbuild/freebsd-arm64/-/freebsd-arm64-0.28.2.tgz",
"integrity": "sha512-n+I0BTSRIoy+d6RPKnEVwql5UwBJolytvY4mAOIEJorKlqgPII8ix6slVVrfZ5Tnj7glIZvloylbB/EJPMWEXw==",
"cpu": [
"arm64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"freebsd"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/freebsd-x64": {
"version": "0.28.2",
"resolved": "https://registry.npmjs.org/@esbuild/freebsd-x64/-/freebsd-x64-0.28.2.tgz",
"integrity": "sha512-78XJTJkvPs0kz2w61301PJjXl4g7q3JqiYMZ/M/yVI73EHBrCRTgkhu9oqG7vPqq+a/yadEW8aD+agKlk5xrmg==",
"cpu": [
"x64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"freebsd"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/linux-arm": {
"version": "0.28.2",
"resolved": "https://registry.npmjs.org/@esbuild/linux-arm/-/linux-arm-0.28.2.tgz",
"integrity": "sha512-XlDnu2q5yoqems+xay6wSAcg9DDD7K9RLKZEBOMZm3ckNpJBvOX20tSfby8KfrrhINDyv9V2YVZKY/SpoGJI8w==",
"cpu": [
"arm"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"linux"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/linux-arm64": {
"version": "0.28.2",
"resolved": "https://registry.npmjs.org/@esbuild/linux-arm64/-/linux-arm64-0.28.2.tgz",
"integrity": "sha512-pW4AC0P3it8c7do9MVM4p51FzHzdM/TZrerurgRcHJ2WTa1VQ1CIq18xncfpBJw4ojkiZZrKW2yIBWBP92j6Ug==",
"cpu": [
"arm64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"linux"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/linux-ia32": {
"version": "0.28.2",
"resolved": "https://registry.npmjs.org/@esbuild/linux-ia32/-/linux-ia32-0.28.2.tgz",
"integrity": "sha512-CYbnj78HsIeA+DhgUKgFCfvNsTHFhMMrinUrMZpDXJXKN8T3XViTZ/+wtHeVxEWY8ewSzTFN+nRmSwO2tZaLUQ==",
"cpu": [
"ia32"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"linux"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/linux-loong64": {
"version": "0.28.2",
"resolved": "https://registry.npmjs.org/@esbuild/linux-loong64/-/linux-loong64-0.28.2.tgz",
"integrity": "sha512-buwkd8nsph4R+ajRvw0qM5Hja/TXQow3ptzWO2EbG/cqcIkHloRrdlBtQlshyYGTNFvfkfJ5tpPLVkY4DtsPfQ==",
"cpu": [
"loong64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"linux"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/linux-mips64el": {
"version": "0.28.2",
"resolved": "https://registry.npmjs.org/@esbuild/linux-mips64el/-/linux-mips64el-0.28.2.tgz",
"integrity": "sha512-ZVykbDyk7519VwiNb9Lcj9m8XM6v5V9uKPvrEMkkEedVewf+0itkhahp4HDpgERXhwLRpWFypsGbG/J8s0QjJA==",
"cpu": [
"mips64el"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"linux"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/linux-ppc64": {
"version": "0.28.2",
"resolved": "https://registry.npmjs.org/@esbuild/linux-ppc64/-/linux-ppc64-0.28.2.tgz",
"integrity": "sha512-CAXl+Dtd9UUuJd8pKKdwh6MLm3MUMiqMPmhZ3tTSXPqfyQ3vDl6R5hZdZ/kYojK4ofXtdfSv1tFq8XzWx3heNQ==",
"cpu": [
"ppc64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"linux"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/linux-riscv64": {
"version": "0.28.2",
"resolved": "https://registry.npmjs.org/@esbuild/linux-riscv64/-/linux-riscv64-0.28.2.tgz",
"integrity": "sha512-GeXCej4IQtU1B+QlDV8W/RRvbzI3O/Stss+/bCXv4lZls5WGRtu2a+3JkA3i4qIUlMXpcHebWpF8AkJhATowuA==",
"cpu": [
"riscv64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"linux"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/linux-s390x": {
"version": "0.28.2",
"resolved": "https://registry.npmjs.org/@esbuild/linux-s390x/-/linux-s390x-0.28.2.tgz",
"integrity": "sha512-3H1weTYZPxt/WOhByszQZybS9w5lKzUn1FDMsgEChbHWQwHYQQRfBxgCcZvPhjHfKyJjIievvMmEUawJrdY9Dg==",
"cpu": [
"s390x"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"linux"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/linux-x64": {
"version": "0.28.2",
"resolved": "https://registry.npmjs.org/@esbuild/linux-x64/-/linux-x64-0.28.2.tgz",
"integrity": "sha512-4xTZr1FUmSoQW4XIWmit3tzQrUTZM+N3P0XV8xROKYF50XfI7xeO90+1bZvNwxIufQ9hDQVRJH5YhgPVF8A/HQ==",
"cpu": [
"x64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"linux"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/netbsd-arm64": {
"version": "0.28.2",
"resolved": "https://registry.npmjs.org/@esbuild/netbsd-arm64/-/netbsd-arm64-0.28.2.tgz",
"integrity": "sha512-sSATRjPeDBg3pdgHoQfoYBob11Kk1FGa9lui5RIHZCoCkJa9QKlvl3/vKz2usCmYYjs7ymJR/2Nnsqe+Hjt5nw==",
"cpu": [
"arm64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"netbsd"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/netbsd-x64": {
"version": "0.28.2",
"resolved": "https://registry.npmjs.org/@esbuild/netbsd-x64/-/netbsd-x64-0.28.2.tgz",
"integrity": "sha512-lqnzCV+mM0gIADaKihiCg6ifgfU2L3h5E33rNQBN1Y4MaVGnzryzmvvf7UHxprpQdE8hpqLolJ9Rl+SkIRDpyw==",
"cpu": [
"x64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"netbsd"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/openbsd-arm64": {
"version": "0.28.2",
"resolved": "https://registry.npmjs.org/@esbuild/openbsd-arm64/-/openbsd-arm64-0.28.2.tgz",
"integrity": "sha512-AL2qJILH7lNjrDmCQDvdxMfAUIv8KMNZOvrwAQ8i8//ntL9FflhOyMJ8OZSMBb8/AWXe3/5v5S20y3zCoZWKoQ==",
"cpu": [
"arm64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"openbsd"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/openbsd-x64": {
"version": "0.28.2",
"resolved": "https://registry.npmjs.org/@esbuild/openbsd-x64/-/openbsd-x64-0.28.2.tgz",
"integrity": "sha512-QtiuPytchRyC4rwUKhexJdQKvDuZ6hWloi3igqPQNUJCS1/v9EiO3UTOXR6A3FoMo4fnAKbWJdqaIwhOzh8qEw==",
"cpu": [
"x64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"openbsd"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/openharmony-arm64": {
"version": "0.28.2",
"resolved": "https://registry.npmjs.org/@esbuild/openharmony-arm64/-/openharmony-arm64-0.28.2.tgz",
"integrity": "sha512-WkhYDmpTjLvGlScA1rwjRUmhl4k8oXR3cIbtqWmELgU/dFeHHlEllxDvdWcNJV9rbzCexB5vz8gtNewWLgCT7Q==",
"cpu": [
"arm64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"openharmony"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/sunos-x64": {
"version": "0.28.2",
"resolved": "https://registry.npmjs.org/@esbuild/sunos-x64/-/sunos-x64-0.28.2.tgz",
"integrity": "sha512-GPMSkTOtMnv2U2F8gxe4Io6qmVs+YKyp832Etqqxr0hFngmXQ3rzwytelm3GIn7T4VviRUlf3sOgBOiTdvaf7g==",
"cpu": [
"x64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"sunos"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/win32-arm64": {
"version": "0.28.2",
"resolved": "https://registry.npmjs.org/@esbuild/win32-arm64/-/win32-arm64-0.28.2.tgz",
"integrity": "sha512-PIhhEkE9uPBleRBrQEJpUn7MBnibZzbGzYWPmY3x+YoVg/95zbjB4CxPPOQ8l5tYYM4mMaCthF8/1DIfBQQyWQ==",
"cpu": [
"arm64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"win32"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/win32-ia32": {
"version": "0.28.2",
"resolved": "https://registry.npmjs.org/@esbuild/win32-ia32/-/win32-ia32-0.28.2.tgz",
"integrity": "sha512-YmJbfTlvU7Sdn9BB+4PRES4oB6pxgS37MAONj+hBr/cpXS1aBPKXxNnDbu+QCWPj0o9dgyxeq79g6c5P8KeuYA==",
"cpu": [
"ia32"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"win32"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/win32-x64": {
"version": "0.28.2",
"resolved": "https://registry.npmjs.org/@esbuild/win32-x64/-/win32-x64-0.28.2.tgz",
"integrity": "sha512-5ebpxr3nWMzrL/rnUI755Jkuee0bHL/Gq0WTF9lvcpv73wAp5eu8MfBUgWK9bhWvZjj7yX8etf/8tI8Ney695g==",
"cpu": [
"x64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"win32"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@fontsource/vazirmatn": {
"version": "5.3.0",
"resolved": "https://registry.npmjs.org/@fontsource/vazirmatn/-/vazirmatn-5.3.0.tgz",
@@ -613,6 +1057,22 @@
"url": "https://github.com/sponsors/Boshen"
}
},
"node_modules/@playwright/test": {
"version": "1.64.0",
"resolved": "https://registry.npmjs.org/@playwright/test/-/test-1.64.0.tgz",
"integrity": "sha512-oTN9FNYuN6bqQMwiho6jJKLCG2/QOYCixGXuCjRmzOq23eODeukuY2XiAVoVpAECbuezMt1MHQjAiQxK8F+Y+g==",
"dev": true,
"license": "Apache-2.0",
"dependencies": {
"playwright": "1.64.0"
},
"bin": {
"playwright": "cli.js"
},
"engines": {
"node": ">=20"
}
},
"node_modules/@polka/url": {
"version": "1.0.0-next.29",
"resolved": "https://registry.npmjs.org/@polka/url/-/url-1.0.0-next.29.tgz",
@@ -1518,6 +1978,48 @@
"url": "https://github.com/sponsors/antfu"
}
},
"node_modules/esbuild": {
"version": "0.28.2",
"resolved": "https://registry.npmjs.org/esbuild/-/esbuild-0.28.2.tgz",
"integrity": "sha512-HKVLS8dvII+xoKW9kmqxbRKrnWEXfJJr/FZhhJmiqIB0e053QNYFqOBouTMO/k5sID4MvCiUCvv8b9M4h32wIA==",
"dev": true,
"hasInstallScript": true,
"license": "MIT",
"bin": {
"esbuild": "bin/esbuild"
},
"engines": {
"node": ">=18"
},
"optionalDependencies": {
"@esbuild/aix-ppc64": "0.28.2",
"@esbuild/android-arm": "0.28.2",
"@esbuild/android-arm64": "0.28.2",
"@esbuild/android-x64": "0.28.2",
"@esbuild/darwin-arm64": "0.28.2",
"@esbuild/darwin-x64": "0.28.2",
"@esbuild/freebsd-arm64": "0.28.2",
"@esbuild/freebsd-x64": "0.28.2",
"@esbuild/linux-arm": "0.28.2",
"@esbuild/linux-arm64": "0.28.2",
"@esbuild/linux-ia32": "0.28.2",
"@esbuild/linux-loong64": "0.28.2",
"@esbuild/linux-mips64el": "0.28.2",
"@esbuild/linux-ppc64": "0.28.2",
"@esbuild/linux-riscv64": "0.28.2",
"@esbuild/linux-s390x": "0.28.2",
"@esbuild/linux-x64": "0.28.2",
"@esbuild/netbsd-arm64": "0.28.2",
"@esbuild/netbsd-x64": "0.28.2",
"@esbuild/openbsd-arm64": "0.28.2",
"@esbuild/openbsd-x64": "0.28.2",
"@esbuild/openharmony-arm64": "0.28.2",
"@esbuild/sunos-x64": "0.28.2",
"@esbuild/win32-arm64": "0.28.2",
"@esbuild/win32-ia32": "0.28.2",
"@esbuild/win32-x64": "0.28.2"
}
},
"node_modules/escalade": {
"version": "3.2.0",
"resolved": "https://registry.npmjs.org/escalade/-/escalade-3.2.0.tgz",
@@ -2239,6 +2741,35 @@
}
}
},
"node_modules/playwright": {
"version": "1.64.0",
"resolved": "https://registry.npmjs.org/playwright/-/playwright-1.64.0.tgz",
"integrity": "sha512-kVzTnYFYEyQ9RGzBjNCd2+yEqWmVbxl3AHPynv3qQ6JTjv4a+kwRcnqQwIpuP3NnrnIrE/Q6wWAIAvMfIE2/Yg==",
"dev": true,
"license": "Apache-2.0",
"dependencies": {
"playwright-core": "1.64.0"
},
"bin": {
"playwright": "cli.js"
},
"engines": {
"node": ">=20"
}
},
"node_modules/playwright-core": {
"version": "1.64.0",
"resolved": "https://registry.npmjs.org/playwright-core/-/playwright-core-1.64.0.tgz",
"integrity": "sha512-T9r+MZkTECl2+oUcZ26YgZzTrYidTsIhYYkJix+6iDOymOb1FB2RLLSOxRGnZGv5DStt+aduIVbt+E8WygXYpg==",
"dev": true,
"license": "Apache-2.0",
"bin": {
"playwright-core": "cli.js"
},
"engines": {
"node": ">=20"
}
},
"node_modules/postcss": {
"version": "8.5.21",
"resolved": "https://registry.npmjs.org/postcss/-/postcss-8.5.21.tgz",
@@ -2473,6 +3004,25 @@
"license": "0BSD",
"optional": true
},
"node_modules/tsx": {
"version": "4.23.15",
"resolved": "https://registry.npmjs.org/tsx/-/tsx-4.23.15.tgz",
"integrity": "sha512-Yiex1Ovn8z2xPpOWckIiysV1SSyRMY9BkLF++q0yKiDxCqRhosKfMg3janKkiLBwZ5c/YryloKwGZcrEmtwxKw==",
"dev": true,
"license": "MIT",
"dependencies": {
"esbuild": "~0.28.0"
},
"bin": {
"tsx": "dist/cli.mjs"
},
"engines": {
"node": ">=18.0.0"
},
"optionalDependencies": {
"fsevents": "~2.3.3"
}
},
"node_modules/typescript": {
"version": "6.0.3",
"resolved": "https://registry.npmjs.org/typescript/-/typescript-6.0.3.tgz",
+13 -2
View File
@@ -8,7 +8,16 @@
"build": "run-p type-check \"build-only {@}\" --",
"preview": "vite preview",
"build-only": "vite build",
"type-check": "vue-tsc --build"
"type-check": "vue-tsc --build",
"test": "node test/run-all-tests.mjs",
"test:session": "node test/run-session-tests.mjs",
"test:catalog": "node --import tsx --test --test-reporter=spec test/catalog-api.test.ts",
"test:e2e": "npm run e2e:prepare && npm run test:e2e:ci",
"test:e2e:ci": "playwright test -c e2e/playwright.config.ts",
"test:e2e:install": "playwright install chromium",
"e2e:prepare": "node scripts/e2e-prepare.mjs",
"e2e:cleanup": "node scripts/e2e-cleanup.mjs",
"ci:checkout-backend": "node scripts/ci-checkout-backend.mjs"
},
"dependencies": {
"@fontsource/vazirmatn": "^5.2.5",
@@ -25,10 +34,12 @@
"@vitejs/plugin-vue": "^6.0.8",
"@vue/tsconfig": "^0.9.1",
"npm-run-all2": "^9.0.2",
"tsx": "^4.20.5",
"typescript": "~6.0.0",
"vite": "^8.1.5",
"vite-plugin-vue-devtools": "^8.1.5",
"vue-tsc": "^3.3.7"
"vue-tsc": "^3.3.7",
"@playwright/test": "^1.55.1"
},
"engines": {
"node": "^22.18.0 || >=24.12.0"
+127
View File
@@ -0,0 +1,127 @@
/**
* CI: clone backend repo at pinned ref (see e2e/backend.contract.json).
* In CI (CI=true): E2E_BACKEND_REF is required — no fallback to main.
*/
import { readFileSync, existsSync, rmSync } from 'node:fs'
import { dirname, join, resolve } from 'node:path'
import { fileURLToPath } from 'node:url'
import { spawnSync } from 'node:child_process'
const scriptDir = dirname(fileURLToPath(import.meta.url))
const frontendRoot = join(scriptDir, '..')
const contractPath = join(frontendRoot, 'e2e', 'backend.contract.json')
const isCi = process.env.CI === 'true' || process.env.GITEA_ACTIONS === 'true'
if (!existsSync(contractPath)) {
console.error('Missing e2e/backend.contract.json')
process.exit(1)
}
/** @type {{ repositoryUrl: string; checkoutPath: string; localRef?: string; pinnedRef?: string }} */
const contract = JSON.parse(readFileSync(contractPath, 'utf8'))
const envRef = process.env.E2E_BACKEND_REF?.trim()
let ref = envRef
if (isCi && !ref) {
ref = contract.pinnedRef?.trim()
if (!/^[0-9a-f]{40}$/i.test(ref ?? '')) {
console.error(
'E2E backend ref is required in CI. Set E2E_BACKEND_REF or pinnedRef in e2e/backend.contract.json to a full commit SHA. Silent fallback to main is disabled.',
)
process.exit(1)
}
console.log('E2E_BACKEND_REF unset; using committed pinnedRef')
} else if (!isCi && !ref) {
ref = contract.localRef?.trim()
if (!ref) {
console.error(
'Set E2E_BACKEND_REF to a backend commit SHA/tag, or localRef in e2e/backend.contract.json for clone-based local runs.',
)
process.exit(1)
}
}
const repoUrl = process.env.E2E_BACKEND_REPOSITORY_URL?.trim() || contract.repositoryUrl
const checkoutPath = resolve(
frontendRoot,
process.env.E2E_BACKEND_ROOT?.trim() || contract.checkoutPath,
)
const token = process.env.E2E_BACKEND_CHECKOUT_TOKEN?.trim()
let cloneUrl = repoUrl
if (token) {
const u = new URL(repoUrl.replace(/^git\+/, ''))
u.username = token
u.password = 'x-oauth-basic'
cloneUrl = u.toString()
}
if (existsSync(checkoutPath)) {
rmSync(checkoutPath, { recursive: true, force: true })
}
const git = 'git'
const gitEnv = { ...process.env, GIT_TERMINAL_PROMPT: '0' }
const gitOpts = { stdio: 'inherit', env: gitEnv, shell: process.platform === 'win32' }
const isFullSha = /^[0-9a-f]{40}$/i.test(ref)
console.log(`Cloning backend ref=${ref} into ${checkoutPath}`)
let clone
if (isFullSha) {
clone = spawnSync(git, ['clone', '--depth', '1', '--no-checkout', cloneUrl, checkoutPath], gitOpts)
if (clone.status !== 0) {
console.error('Backend clone failed (init).')
process.exit(clone.status ?? 1)
}
const fetch = spawnSync(
git,
['fetch', '--depth', '1', 'origin', ref],
{ ...gitOpts, cwd: checkoutPath },
)
if (fetch.status !== 0) {
console.error(`Backend fetch failed for SHA ${ref}.`)
process.exit(fetch.status ?? 1)
}
const co = spawnSync(git, ['checkout', 'FETCH_HEAD'], { ...gitOpts, cwd: checkoutPath })
if (co.status !== 0) {
console.error('Backend checkout failed.')
process.exit(co.status ?? 1)
}
} else {
clone = spawnSync(
git,
['clone', '--depth', '1', '--branch', ref, cloneUrl, checkoutPath],
gitOpts,
)
if (clone.status !== 0) {
console.error(
'Backend clone failed. For private repos set secret E2E_BACKEND_CHECKOUT_TOKEN (repo read).',
)
process.exit(clone.status ?? 1)
}
}
const head = spawnSync(git, ['rev-parse', 'HEAD'], {
cwd: checkoutPath,
encoding: 'utf8',
shell: process.platform === 'win32',
})
const checkedOutSha = head.stdout?.trim()
if (checkedOutSha) {
console.log(`Backend checkout commit: ${checkedOutSha}`)
if (isFullSha && checkedOutSha.toLowerCase() !== ref.toLowerCase()) {
console.error(
`E2E_BACKEND_REF (${ref}) does not match cloned HEAD (${checkedOutSha}).`,
)
process.exit(1)
}
} else {
console.error('Could not read cloned backend commit (git rev-parse HEAD failed).')
process.exit(1)
}
process.env.E2E_BACKEND_ROOT = checkoutPath
+60
View File
@@ -0,0 +1,60 @@
# Ephemeral trial stack smoke test — does not use production volumes or .env.docker.
param(
[int]$Port = 18080
)
$ErrorActionPreference = 'Stop'
$frontendRoot = Split-Path -Parent $PSScriptRoot
$project = "cgltrial$(Get-Random)"
$secret = ('trial-{0}' -f ('x' * 40))
$cors = "http://127.0.0.1:$Port"
$envFile = Join-Path $env:TEMP "cgl-trial-$project.env"
@"
JWT_SECRET=$secret
CORS_ORIGIN=$cors
VITE_API_URL=/api
FRONTEND_PORT=$Port
"@ | Set-Content -Path $envFile -Encoding utf8
Push-Location $frontendRoot
try {
docker compose -p $project --env-file $envFile config | Out-Null
docker compose -p $project --env-file $envFile build
docker compose -p $project --env-file $envFile up -d
$deadline = (Get-Date).AddMinutes(3)
do {
Start-Sleep -Seconds 3
try {
$h = Invoke-WebRequest -Uri "http://127.0.0.1:$Port/health/ready" -UseBasicParsing
if ($h.StatusCode -eq 200) { break }
} catch { }
} while ((Get-Date) -lt $deadline)
$ready = Invoke-WebRequest -Uri "http://127.0.0.1:$Port/health/ready" -UseBasicParsing
if ($ready.StatusCode -ne 200) { throw 'readiness failed' }
$user = "trial_$([guid]::NewGuid().ToString('N').Substring(0,8))"
$body = @{ username = $user; password = 'pass1234'; name = 'Trial' } | ConvertTo-Json
$reg = Invoke-WebRequest -Uri "http://127.0.0.1:$Port/api/auth/register" -Method POST -Body $body -ContentType 'application/json; charset=utf-8' -UseBasicParsing
$token = ($reg.Content | ConvertFrom-Json).token
$me = Invoke-WebRequest -Uri "http://127.0.0.1:$Port/api/me" -Headers @{ Authorization = "Bearer $token" } -UseBasicParsing
if ($me.StatusCode -ne 200) { throw 'GET /api/me failed' }
$spa = Invoke-WebRequest -Uri "http://127.0.0.1:$Port/map" -UseBasicParsing
if ($spa.Content -notmatch 'html') { throw 'SPA route failed' }
$backendPorts = docker compose -p $project ps --format json | ConvertFrom-Json
foreach ($svc in $backendPorts) {
if ($svc.Service -eq 'backend' -and $svc.Publishers) {
throw 'backend must not publish host ports'
}
}
Write-Host 'docker-trial-smoke: OK'
}
finally {
docker compose -p $project --env-file $envFile down -v --remove-orphans 2>$null
Remove-Item $envFile -Force -ErrorAction SilentlyContinue
Pop-Location
}
+71
View File
@@ -0,0 +1,71 @@
/**
* E2E-only backend: temp SQLite, configurable port/root. Used by Playwright webServer.
*/
import { spawn } from 'node:child_process'
import { existsSync, mkdtempSync, rmSync, mkdirSync, writeFileSync } from 'node:fs'
import { tmpdir } from 'node:os'
import { join, dirname, resolve } from 'node:path'
import { fileURLToPath } from 'node:url'
const scriptDir = dirname(fileURLToPath(import.meta.url))
const frontendRoot = join(scriptDir, '..')
const defaultBackend = join(frontendRoot, '..', 'backend-nest')
const backendRoot = resolve(process.env.E2E_BACKEND_ROOT ?? defaultBackend)
const backendPort = String(process.env.E2E_BACKEND_PORT ?? '3010')
const frontendPort = String(process.env.E2E_FRONTEND_PORT ?? '5190')
const corsOrigin = process.env.E2E_CORS_ORIGIN ?? `http://127.0.0.1:${frontendPort}`
const distMain = join(backendRoot, 'dist', 'main.js')
if (!existsSync(distMain)) {
console.error(`Missing ${distMain}. Run: npm run e2e:prepare (or npm run build in backend).`)
process.exit(1)
}
const runtimeDir = join(frontendRoot, 'e2e', '.runtime')
mkdirSync(runtimeDir, { recursive: true })
const tempDir = mkdtempSync(join(tmpdir(), 'cgl-e2e-'))
const dbPath = join(tempDir, 'app.db')
writeFileSync(
join(runtimeDir, 'state.json'),
JSON.stringify({ tempDir, dbPath, backendPort: Number(backendPort) }),
'utf8',
)
const backend = spawn(process.execPath, ['dist/main.js'], {
cwd: backendRoot,
env: {
...process.env,
PORT: backendPort,
DB_PATH: dbPath,
CORS_ORIGIN: corsOrigin,
JWT_SECRET: process.env.E2E_JWT_SECRET ?? 'e2e-ci-jwt-not-for-production',
NODE_ENV: 'test',
},
stdio: 'inherit',
})
function cleanupTemp() {
try {
backend.kill()
} catch {
// ignore
}
try {
rmSync(tempDir, { recursive: true, force: true })
} catch {
// ignore
}
}
function shutdown(code = 0) {
cleanupTemp()
process.exit(code)
}
process.on('SIGINT', () => shutdown(0))
process.on('SIGTERM', () => shutdown(0))
backend.on('exit', (code, signal) => {
if (signal) shutdown(0)
else process.exit(code ?? 1)
})
+19
View File
@@ -0,0 +1,19 @@
import { readFileSync, rmSync, existsSync } from 'node:fs'
import { join, dirname } from 'node:path'
import { fileURLToPath } from 'node:url'
const frontendRoot = join(dirname(fileURLToPath(import.meta.url)), '..')
const runtimeDir = join(frontendRoot, 'e2e', '.runtime')
const statePath = join(runtimeDir, 'state.json')
if (existsSync(statePath)) {
try {
const { tempDir } = JSON.parse(readFileSync(statePath, 'utf8'))
rmSync(tempDir, { recursive: true, force: true })
} catch {
// ignore
}
}
if (existsSync(runtimeDir)) {
rmSync(runtimeDir, { recursive: true, force: true })
}
+28
View File
@@ -0,0 +1,28 @@
/**
* Build backend for E2E. Path from E2E_BACKEND_ROOT or sibling ../backend-nest.
*/
import { existsSync } from 'node:fs'
import { dirname, join, resolve } from 'node:path'
import { fileURLToPath } from 'node:url'
import { spawnSync } from 'node:child_process'
const scriptDir = dirname(fileURLToPath(import.meta.url))
const frontendRoot = join(scriptDir, '..')
const defaultBackend = join(frontendRoot, '..', 'backend-nest')
const backendRoot = resolve(process.env.E2E_BACKEND_ROOT ?? defaultBackend)
if (!existsSync(join(backendRoot, 'package.json'))) {
console.error(
`E2E backend not found at ${backendRoot}. Set E2E_BACKEND_ROOT or clone per e2e/backend.contract.json.`,
)
process.exit(1)
}
const result = spawnSync('npm', ['run', 'build'], {
cwd: backendRoot,
stdio: 'inherit',
env: process.env,
shell: process.platform === 'win32',
})
process.exit(result.status ?? 1)
+10
View File
@@ -1,9 +1,19 @@
<script setup lang="ts">
import { computed } from 'vue'
import ToastContainer from '@/components/common/ToastContainer.vue'
import BootstrapRecoveryBanner from '@/components/common/BootstrapRecoveryBanner.vue'
import { useAuthStore } from '@/stores/auth'
import { bootstrapFailedRef } from '@/api/bootstrapState'
const authStore = useAuthStore()
const showBootstrapRecovery = computed(
() => authStore.isAuthenticated && bootstrapFailedRef.value,
)
</script>
<template>
<div class="app-shell">
<BootstrapRecoveryBanner v-if="showBootstrapRecovery" />
<RouterView v-slot="{ Component, route }">
<Transition name="page" mode="out-in">
<component :is="Component" :key="route.path" />
+38
View File
@@ -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
}
+15
View File
@@ -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
}
+46
View File
@@ -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
View File
@@ -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'
+31
View File
@@ -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
}
}
+58
View File
@@ -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
View File
@@ -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,
+22
View File
@@ -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
}
}
Binary file not shown.

Before

Width:  |  Height:  |  Size: 880 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 86 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 967 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 62 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 731 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 41 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.0 MiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 74 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 52 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 13 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 497 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 76 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 497 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 76 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 323 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 18 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.1 MiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 133 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 988 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 85 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.1 MiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 127 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 951 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 102 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.0 MiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 102 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 604 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 72 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 270 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 21 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 766 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 114 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 172 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 72 KiB

+33 -27
View File
@@ -1,33 +1,36 @@
import heroExplorer from './hero-explorer.svg'
import treasureChest from './treasure-chest.png'
import professor from './professor.png'
import bankBuilding from './bank-building.png'
import phoneIcon from './phone-icon.png'
import treasureChest from './treasure-chest.webp'
import professor from './professor.webp'
import bankBuilding from './bank-building.webp'
import phoneIcon from './phone-icon.webp'
import shoppingCart from './shopping-cart.svg'
import mapScene from './map-scene.png'
import mapNodeOrb from './map-node-orb.png'
import mapScene from './map-scene.webp'
import mapNodeOrb from './map-node-orb.webp'
import goldBar from './gold-bar.svg'
import goldBarsStack from './gold-bars-stack.png'
import coinLarge from './coin-large.png'
import coinsStack from './coins-stack.png'
import cashBundle from './cash-bundle.png'
import homeHeroBg from './home-hero-bg.png'
import gamepadIcon from './gamepad-icon.png'
import targetIcon from './target-icon.png'
import cartIcon from './cart-icon.png'
import friendsIcon from './friends-icon.png'
import challengeBanner from './challenge-banner.png'
import gameGoldChart from './game-gold-chart.png'
import gameInflation from './game-inflation.png'
import gamePortfolio from './game-portfolio.png'
import gameShopping from './game-shopping.png'
import gamePiggy from './game-piggy.png'
import gameInvestor from './game-investor.png'
import productCastle from './product-castle.png'
import productCrown from './product-crown.png'
import productSuit from './product-suit.png'
import productPet from './product-pet.png'
import productSea from './product-sea.png'
import goldBarsStack from './gold-bars-stack.webp'
import coinLarge from './coin-large.webp'
import coinsStack from './coins-stack.webp'
import cashBundle from './cash-bundle.webp'
import homeHeroBg from './home-hero-bg.webp'
import marketHero from './market-hero.webp'
import walletHero from './wallet-hero.webp'
import gamepadIcon from './gamepad-icon.webp'
import targetIcon from './target-icon.webp'
import cartIcon from './cart-icon.webp'
import friendsIcon from './friends-icon.webp'
import challengeBanner from './challenge-banner.webp'
import nextMissionBanner from './next-mission-banner.webp'
import gameGoldChart from './game-gold-chart.webp'
import gameInflation from './game-inflation.webp'
import gamePortfolio from './game-portfolio.webp'
import gameShopping from './game-shopping.webp'
import gamePiggy from './game-piggy.webp'
import gameInvestor from './game-investor.webp'
import productCastle from './product-castle.webp'
import productCrown from './product-crown.webp'
import productSuit from './product-suit.webp'
import productPet from './product-pet.webp'
import productSea from './product-sea.webp'
import schoolBackpack from './school-backpack.svg'
export const illustrations = {
@@ -45,11 +48,14 @@ export const illustrations = {
coinsStack,
cashBundle,
homeHeroBg,
marketHero,
walletHero,
gamepadIcon,
targetIcon,
cartIcon,
friendsIcon,
challengeBanner,
nextMissionBanner,
gameGoldChart,
gameInflation,
gamePortfolio,
Binary file not shown.

Before

Width:  |  Height:  |  Size: 532 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 43 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 178 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 102 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 46 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 40 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.2 MiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.2 MiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 85 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.1 MiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 84 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 724 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 103 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 853 KiB

Some files were not shown because too many files have changed in this diff Show More