M1 기반: 모노레포, 공통 엔진, 공용 프로토콜, 오목 엔진, 서버 골격
- packages/engine: 시드 RNG(sfc32), GameDefinition 타입, 무작위 대국·정보 유출 테스트 도구 - packages/shared: WS 프로토콜 스키마, 닉네임·방 코드 규칙, 게임 카탈로그 - packages/games/omok: 한국식·렌주·자유룰, 재귀 금수 판정, 무르기·무승부·시계 (테스트 27개) - apps/server: SQLite 스키마, 게스트·디스코드 로그인, 세션, 방 관리(저장·복구·타이머·재접속), WS 게이트웨이, HTTP API Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
8
packages/shared/package.json
Normal file
8
packages/shared/package.json
Normal file
@@ -0,0 +1,8 @@
|
||||
{
|
||||
"name": "@bg/shared",
|
||||
"version": "0.0.0",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"exports": { ".": "./src/index.ts" },
|
||||
"dependencies": { "zod": "4.6.5" }
|
||||
}
|
||||
17
packages/shared/src/catalog.ts
Normal file
17
packages/shared/src/catalog.ts
Normal file
@@ -0,0 +1,17 @@
|
||||
/** Game catalog metadata shared by server and web (docs/games/README.md). */
|
||||
export interface CatalogEntry {
|
||||
id: string;
|
||||
nameKo: string;
|
||||
minPlayers: number;
|
||||
maxPlayers: number;
|
||||
minutes: string;
|
||||
level: '쉬움' | '보통' | '어려움';
|
||||
blurb: string;
|
||||
available: boolean;
|
||||
}
|
||||
|
||||
export const CATALOG: CatalogEntry[] = [
|
||||
{ id: 'omok', nameKo: '오목', minPlayers: 2, maxPlayers: 2, minutes: '5~15', level: '쉬움', blurb: '먼저 다섯 개를 한 줄로!', available: true },
|
||||
];
|
||||
|
||||
export const catalogById = (id: string): CatalogEntry | undefined => CATALOG.find((g) => g.id === id);
|
||||
4
packages/shared/src/index.ts
Normal file
4
packages/shared/src/index.ts
Normal file
@@ -0,0 +1,4 @@
|
||||
export * from './protocol';
|
||||
export * from './nickname';
|
||||
export * from './room-code';
|
||||
export * from './catalog';
|
||||
48
packages/shared/src/nickname.ts
Normal file
48
packages/shared/src/nickname.ts
Normal file
@@ -0,0 +1,48 @@
|
||||
/** Nickname rules, docs/05-accounts-auth.md §2. Shared by server validation and client form. */
|
||||
export const NICK_MIN = 2;
|
||||
export const NICK_MAX = 12;
|
||||
|
||||
const ALLOWED = /^[0-9A-Za-z가-힣ㄱ-ㅎㅏ-ㅣ _.\-]+$/;
|
||||
|
||||
// Minimal built-in list; the server may extend it. Matching ignores spaces and punctuation.
|
||||
const BANNED = ['시발', '씨발', '병신', '좆', '개새끼', '느금', '니애미', 'fuck', 'shit', 'bitch'];
|
||||
|
||||
export function normalizeNickname(raw: string): string {
|
||||
return raw.normalize('NFC').trim().replace(/\s+/g, ' ');
|
||||
}
|
||||
|
||||
export function containsProfanity(text: string): boolean {
|
||||
const squashed = text.normalize('NFC').toLowerCase().replace(/[\s_.\-*0-9]/g, '');
|
||||
return BANNED.some((w) => squashed.includes(w));
|
||||
}
|
||||
|
||||
export function maskProfanity(text: string): string {
|
||||
let out = text;
|
||||
for (const w of BANNED) {
|
||||
out = out.replace(new RegExp(w.split('').map(escapeRe).join('[\\s_.\\-*]*'), 'gi'), (m) => '*'.repeat(m.length));
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
function escapeRe(s: string): string {
|
||||
return s.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
|
||||
}
|
||||
|
||||
/** Returns a Korean error message, or null when valid. Input must already be normalized. */
|
||||
export function nicknameError(nick: string): string | null {
|
||||
const len = [...nick].length;
|
||||
if (len < NICK_MIN) return `닉네임은 ${NICK_MIN}글자 이상이어야 해요.`;
|
||||
if (len > NICK_MAX) return `닉네임은 ${NICK_MAX}글자까지 쓸 수 있어요.`;
|
||||
if (!ALLOWED.test(nick)) return '한글, 영어, 숫자와 _ - . 만 쓸 수 있어요.';
|
||||
if (containsProfanity(nick)) return '다른 닉네임을 써 주세요.';
|
||||
return null;
|
||||
}
|
||||
|
||||
const ADJ = ['용감한', '느긋한', '반짝이는', '씩씩한', '졸린', '신나는', '똑똑한', '배고픈', '귀여운', '날쌘', '든든한', '행복한'];
|
||||
const NOUN = ['호랑이', '고양이', '거북이', '다람쥐', '부엉이', '펭귄', '판다', '토끼', '여우', '돌고래', '곰돌이', '참새'];
|
||||
|
||||
export function suggestNickname(rand: () => number = Math.random): string {
|
||||
const a = ADJ[Math.floor(rand() * ADJ.length)]!;
|
||||
const n = NOUN[Math.floor(rand() * NOUN.length)]!;
|
||||
return `${a} ${n}`;
|
||||
}
|
||||
117
packages/shared/src/protocol.ts
Normal file
117
packages/shared/src/protocol.ts
Normal file
@@ -0,0 +1,117 @@
|
||||
/** WebSocket protocol, docs/03-realtime-protocol.md. */
|
||||
import { z } from 'zod';
|
||||
|
||||
export const PROTOCOL = 1;
|
||||
export const MAX_CLIENT_MESSAGE_BYTES = 16 * 1024;
|
||||
export const CHAT_MAX = 200;
|
||||
|
||||
const code = z.string().regex(/^\d{6}$/);
|
||||
const userId = z.string().min(1).max(64);
|
||||
|
||||
export const ClientMessage = z.discriminatedUnion('t', [
|
||||
z.object({ t: z.literal('join'), code, as: z.enum(['player', 'spectator']).default('player') }),
|
||||
z.object({ t: z.literal('leave') }),
|
||||
z.object({ t: z.literal('seat'), seat: z.number().int().min(0).max(31).optional() }),
|
||||
z.object({ t: z.literal('unseat') }),
|
||||
z.object({ t: z.literal('ready'), ready: z.boolean() }),
|
||||
z.object({
|
||||
t: z.literal('config'),
|
||||
gameId: z.string().max(40).optional(),
|
||||
options: z.unknown().optional(),
|
||||
maxPlayers: z.number().int().min(1).max(32).optional(),
|
||||
visibility: z.enum(['private', 'public']).optional(),
|
||||
turnSeconds: z.number().int().min(5).max(600).nullable().optional(),
|
||||
allowSpectators: z.boolean().optional(),
|
||||
chatEnabled: z.boolean().optional(),
|
||||
chatFilter: z.boolean().optional(),
|
||||
}),
|
||||
z.object({ t: z.literal('start') }),
|
||||
z.object({ t: z.literal('kick'), userId }),
|
||||
z.object({ t: z.literal('host'), userId }),
|
||||
z.object({ t: z.literal('act'), cs: z.number().int().min(1), a: z.unknown() }),
|
||||
z.object({ t: z.literal('chat'), text: z.string().min(1).max(CHAT_MAX) }),
|
||||
z.object({ t: z.literal('emote'), id: z.string().max(20) }),
|
||||
z.object({ t: z.literal('rematch') }),
|
||||
z.object({ t: z.literal('sync') }),
|
||||
z.object({ t: z.literal('ping'), ts: z.number() }),
|
||||
]);
|
||||
export type ClientMessage = z.infer<typeof ClientMessage>;
|
||||
|
||||
export const EMOTES = ['thumbs', 'laugh', 'wow', 'sad', 'clap', 'nice', 'hurry', 'gg'] as const;
|
||||
export const EMOTE_LABEL: Record<(typeof EMOTES)[number], string> = {
|
||||
thumbs: '👍',
|
||||
laugh: '😂',
|
||||
wow: '😮',
|
||||
sad: '😢',
|
||||
clap: '👏',
|
||||
nice: '잘했어요!',
|
||||
hurry: '조금만 서둘러 주세요',
|
||||
gg: '좋은 게임이었어요',
|
||||
};
|
||||
|
||||
export interface PublicUser {
|
||||
id: string;
|
||||
nickname: string;
|
||||
avatar: string | null;
|
||||
kind: 'guest' | 'member';
|
||||
}
|
||||
|
||||
export interface SeatView {
|
||||
user: PublicUser;
|
||||
ready: boolean;
|
||||
connected: boolean;
|
||||
away: boolean;
|
||||
}
|
||||
|
||||
export type RoomStatus = 'lobby' | 'playing' | 'finished' | 'paused' | 'broken';
|
||||
|
||||
export interface RoomView {
|
||||
code: string;
|
||||
hostId: string;
|
||||
gameId: string;
|
||||
options: unknown;
|
||||
maxPlayers: number;
|
||||
minPlayers: number;
|
||||
visibility: 'private' | 'public';
|
||||
turnSeconds: number | null;
|
||||
allowSpectators: boolean;
|
||||
chatEnabled: boolean;
|
||||
chatFilter: boolean;
|
||||
seats: (SeatView | null)[];
|
||||
spectators: PublicUser[];
|
||||
status: RoomStatus;
|
||||
gameNo: number;
|
||||
rematchVotes: string[];
|
||||
sessionStats: Record<string, { played: number; wins: number }>;
|
||||
seedHash: string | null;
|
||||
/** Seed revealed after the game for fairness check. */
|
||||
lastSeed: string | null;
|
||||
}
|
||||
|
||||
export interface GameResultView {
|
||||
ranking: string[][];
|
||||
scores?: Record<string, number>;
|
||||
summary: string;
|
||||
reason: string;
|
||||
}
|
||||
|
||||
export type ServerMessage =
|
||||
| { t: 'welcome'; me: PublicUser; serverTime: number; protocol: number; activeRoom: string | null }
|
||||
| { t: 'room'; seq: number; room: RoomView }
|
||||
| {
|
||||
t: 'state';
|
||||
seq: number;
|
||||
view: unknown;
|
||||
events: unknown[];
|
||||
active: string[];
|
||||
deadline: number | null;
|
||||
cs?: number;
|
||||
}
|
||||
| { t: 'reject'; cs: number; reason: string }
|
||||
| { t: 'chat'; from: PublicUser | null; text: string; at: number; channel?: string }
|
||||
| { t: 'emote'; from: string; id: string }
|
||||
| { t: 'result'; seq: number; result: GameResultView }
|
||||
| { t: 'notice'; code: string; message: string }
|
||||
| { t: 'error'; code: string; message: string }
|
||||
| { t: 'pong'; ts: number; serverTime: number }
|
||||
| { t: 'bye'; reason: 'restart' | 'replaced' | 'kicked' | 'closed' };
|
||||
20
packages/shared/src/room-code.ts
Normal file
20
packages/shared/src/room-code.ts
Normal file
@@ -0,0 +1,20 @@
|
||||
/** 6-digit numeric room codes, docs/06-lobby-rooms.md §3. */
|
||||
export function normalizeRoomCode(input: string): string | null {
|
||||
const m = input.match(/\/r\/(\d{6})\b/);
|
||||
if (m) return m[1]!;
|
||||
const digits = input.replace(/[\s\-]/g, '');
|
||||
return /^\d{6}$/.test(digits) ? digits : null;
|
||||
}
|
||||
|
||||
export function isAllowedRoomCode(code: string): boolean {
|
||||
if (!/^\d{6}$/.test(code)) return false;
|
||||
if (/^(\d)\1{5}$/.test(code)) return false; // 000000, 111111, ...
|
||||
const asc = '0123456789';
|
||||
const desc = '9876543210';
|
||||
if (asc.includes(code) || desc.includes(code)) return false; // 123456, 654321
|
||||
return true;
|
||||
}
|
||||
|
||||
export function formatRoomCode(code: string): string {
|
||||
return `${code.slice(0, 3)} ${code.slice(3)}`;
|
||||
}
|
||||
5
packages/shared/tsconfig.json
Normal file
5
packages/shared/tsconfig.json
Normal file
@@ -0,0 +1,5 @@
|
||||
{
|
||||
"extends": "../../tsconfig.base.json",
|
||||
"compilerOptions": { "outDir": "dist", "rootDir": "src", "lib": ["ES2023", "DOM"] },
|
||||
"include": ["src"]
|
||||
}
|
||||
Reference in New Issue
Block a user