mirror of
https://github.com/Such-Software/wownerogue.git
synced 2026-12-02 11:54:04 +01:00
feat: add tavern render kit and character entitlements
This commit is contained in:
@@ -0,0 +1,35 @@
|
||||
const Appearance = require('../src/multiplayer/appearance');
|
||||
|
||||
describe('appearance catalog normalization', () => {
|
||||
test('normalizes character tint and equipment slots', () => {
|
||||
expect(Appearance.normalizeAppearance({
|
||||
avatar: 'char-ranger',
|
||||
tint: 'moss',
|
||||
equipment: { body: 'mail', head: 'helm', shield: 'bad', weapon: 'bow' }
|
||||
})).toEqual({
|
||||
avatar: 'char-ranger',
|
||||
tint: 'moss',
|
||||
equipment: { body: 'mail', head: 'helm', shield: 'none', weapon: 'bow' }
|
||||
});
|
||||
});
|
||||
|
||||
test('strips character-only fields from color and premium skin avatars', () => {
|
||||
expect(Appearance.normalizeAppearance({
|
||||
avatar: 'monero-knight',
|
||||
tint: 'teal',
|
||||
equipment: { body: 'mail' }
|
||||
})).toEqual({
|
||||
avatar: 'monero-knight',
|
||||
tint: 'none',
|
||||
equipment: { body: 'none', head: 'none', shield: 'none', weapon: 'none' }
|
||||
});
|
||||
});
|
||||
|
||||
test('falls back unknown avatars to default', () => {
|
||||
expect(Appearance.normalizeAppearance('rainbow')).toEqual({
|
||||
avatar: 'default',
|
||||
tint: 'none',
|
||||
equipment: { body: 'none', head: 'none', shield: 'none', weapon: 'none' }
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,67 @@
|
||||
const SocketChatProvider = require('../src/network/chat/SocketChatProvider');
|
||||
|
||||
function makeFakeIo() {
|
||||
const io = {
|
||||
emitted: [], // { channel|null, event, payload }
|
||||
to(channel) {
|
||||
return { emit: (event, payload) => io.emitted.push({ channel, event, payload }) };
|
||||
},
|
||||
emit(event, payload) { io.emitted.push({ channel: null, event, payload }); }
|
||||
};
|
||||
return io;
|
||||
}
|
||||
|
||||
describe('SocketChatProvider', () => {
|
||||
test('global publish persists via history and broadcasts via broadcastManager', async () => {
|
||||
const io = makeFakeIo();
|
||||
const saved = [];
|
||||
const broadcast = [];
|
||||
const history = { saveMessage: (m) => { saved.push(m); return Promise.resolve(); } };
|
||||
const broadcastManager = {
|
||||
broadcastChatMessage: (username, text, ts, socketId) => broadcast.push({ username, text, ts, socketId })
|
||||
};
|
||||
const provider = new SocketChatProvider({ io, broadcastManager, historyManager: history });
|
||||
|
||||
await provider.publish({ scope: 'global', username: 'abc123', text: 'hi', ts: 42, socketId: 'sock', userId: 7 });
|
||||
|
||||
expect(saved).toHaveLength(1);
|
||||
expect(saved[0]).toMatchObject({ socketId: 'sock', username: 'abc123', message: 'hi', userId: 7 });
|
||||
expect(broadcast).toHaveLength(1);
|
||||
expect(broadcast[0]).toEqual({ username: 'abc123', text: 'hi', ts: 42, socketId: 'sock' });
|
||||
});
|
||||
|
||||
test('global publish falls back to io.emit when no broadcastManager is given', async () => {
|
||||
const io = makeFakeIo();
|
||||
const provider = new SocketChatProvider({ io });
|
||||
await provider.publish({ scope: 'global', username: 'x', text: 'yo', ts: 1 });
|
||||
const ev = io.emitted.find(e => e.event === 'chat_broadcast' && e.channel === null);
|
||||
expect(ev).toBeTruthy();
|
||||
expect(ev.payload).toMatchObject({ username: 'x', message: 'yo', timestamp: 1 });
|
||||
});
|
||||
|
||||
test('room-scoped publish delivers only to that room and tags the scope', async () => {
|
||||
const io = makeFakeIo();
|
||||
const provider = new SocketChatProvider({ io });
|
||||
await provider.publish({ scope: 'tavern:main', username: 'bob', text: 'hey', ts: 5 });
|
||||
const ev = io.emitted.find(e => e.event === 'chat_broadcast');
|
||||
expect(ev.channel).toBe('tavern:main');
|
||||
expect(ev.payload).toMatchObject({ username: 'bob', message: 'hey', timestamp: 5, scope: 'tavern:main' });
|
||||
});
|
||||
|
||||
test('getHistory: global reads the history manager; room scopes are ephemeral', async () => {
|
||||
const io = makeFakeIo();
|
||||
const history = { getRecentMessages: (n) => Promise.resolve([{ message: 'old', n }]) };
|
||||
const provider = new SocketChatProvider({ io, historyManager: history });
|
||||
await expect(provider.getHistory({ scope: 'global', limit: 10 })).resolves.toEqual([{ message: 'old', n: 10 }]);
|
||||
await expect(provider.getHistory({ scope: 'tavern:main' })).resolves.toEqual([]);
|
||||
});
|
||||
|
||||
test('an injected history manager is not shut down by the provider (caller owns it)', async () => {
|
||||
const io = makeFakeIo();
|
||||
let shut = false;
|
||||
const history = { shutdown: () => { shut = true; } };
|
||||
const provider = new SocketChatProvider({ io, historyManager: history });
|
||||
await provider.shutdown();
|
||||
expect(shut).toBe(false);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,48 @@
|
||||
const Appearance = require('../src/multiplayer/appearance');
|
||||
const Entitlements = require('../src/multiplayer/entitlements');
|
||||
|
||||
describe('cosmetic entitlements', () => {
|
||||
test('free users cannot select premium generated skins or 3D avatars', () => {
|
||||
const entitlements = Entitlements.snapshotForUser({ credits: 0, total_credits_purchased: 0 });
|
||||
|
||||
expect(Entitlements.canUsePack(entitlements, 'generated-skins')).toBe(false);
|
||||
expect(Entitlements.canUsePack(entitlements, 'kenney-3d-characters')).toBe(false);
|
||||
expect(Entitlements.normalizeAppearance({ avatar: 'monero-knight' }, entitlements).avatar).toBe('default');
|
||||
expect(Entitlements.normalizeAppearance({ avatar: 'kenney-survivor-male' }, entitlements).avatar).toBe('default');
|
||||
});
|
||||
|
||||
test('any credits purchase unlocks the preview premium packs', () => {
|
||||
const entitlements = Entitlements.snapshotForUser({ credits: 7, total_credits_purchased: 10 });
|
||||
|
||||
expect(entitlements.premium).toBe(true);
|
||||
expect(entitlements.level).toBe('credits');
|
||||
expect(entitlements.packs['generated-skins']).toBe(true);
|
||||
expect(entitlements.packs['iso-dungeon']).toBe(true);
|
||||
expect(entitlements.packs['kenney-3d-characters']).toBe(true);
|
||||
expect(Entitlements.normalizeAppearance({ avatar: 'monero-knight' }, entitlements).avatar).toBe('monero-knight');
|
||||
});
|
||||
|
||||
test('explicit pack grants can unlock one pack without unlocking all packs', () => {
|
||||
const entitlements = Entitlements.snapshotForUser(
|
||||
{ credits: 0, total_credits_purchased: 0 },
|
||||
[{ pack_id: 'generated-skins' }]
|
||||
);
|
||||
|
||||
expect(entitlements.premium).toBe(true);
|
||||
expect(entitlements.packs['generated-skins']).toBe(true);
|
||||
expect(entitlements.packs['kenney-3d-characters']).toBe(false);
|
||||
expect(Entitlements.normalizeAppearance({ avatar: 'monero-knight' }, entitlements).avatar).toBe('monero-knight');
|
||||
expect(Entitlements.normalizeAppearance({ avatar: 'kenney-survivor-male' }, entitlements).avatar).toBe('default');
|
||||
});
|
||||
|
||||
test('appearance catalog reports all premium avatar ids, including 3D models', () => {
|
||||
expect(Appearance.premiumAvatarIds()).toEqual(expect.arrayContaining([
|
||||
'monero-knight',
|
||||
'wownero-rogue',
|
||||
'cypher-operative',
|
||||
'kenney-survivor-male',
|
||||
'kenney-survivor-female'
|
||||
]));
|
||||
expect(Appearance.avatarPack('kenney-survivor-male')).toBe('kenney-3d-characters');
|
||||
});
|
||||
});
|
||||
@@ -199,6 +199,64 @@ describe('GameModeManager', () => {
|
||||
expect(result.creditsAdded).toBe(15); // 10 + 5 bonus
|
||||
});
|
||||
|
||||
test('applies bundled pack grants from package info', async () => {
|
||||
mockDb.query.mockResolvedValueOnce({
|
||||
rows: [{ user_id: 1, description: '', status: 'pending', payment_type: 'credits_package' }]
|
||||
});
|
||||
|
||||
mockClient.query
|
||||
.mockResolvedValueOnce({ rows: [{ id: 123 }] }) // UPDATE payments
|
||||
.mockResolvedValueOnce({ rows: [{ id: 1, credits: 15, total_credits_purchased: 15, premium_level: 'supporter' }] }) // UPDATE users
|
||||
.mockResolvedValueOnce({ rows: [] }) // INSERT credit_transactions
|
||||
.mockResolvedValueOnce({ rows: [] }) // INSERT pack entitlement
|
||||
.mockResolvedValueOnce({ rows: [{ pack_id: 'kenney-3d-characters' }] }); // SELECT active grants
|
||||
|
||||
const result = await gmm.processCreditsPackageConfirmation('socket1', 123, {
|
||||
id: 'bundle',
|
||||
credits: 10,
|
||||
grants: {
|
||||
credits: 15,
|
||||
packs: ['kenney-3d-characters'],
|
||||
premiumLevel: 'supporter'
|
||||
}
|
||||
});
|
||||
|
||||
expect(result.success).toBe(true);
|
||||
expect(result.creditsAdded).toBe(15);
|
||||
expect(result.grantsApplied.packs.map(p => p.id)).toEqual(['kenney-3d-characters']);
|
||||
expect(result.entitlements.packs['kenney-3d-characters']).toBe(true);
|
||||
|
||||
const entitlementInsert = mockClient.query.mock.calls.find(([sql]) => /INSERT INTO user_pack_entitlements/i.test(sql));
|
||||
expect(entitlementInsert).toBeDefined();
|
||||
expect(entitlementInsert[1][1]).toBe('kenney-3d-characters');
|
||||
});
|
||||
|
||||
test('applies standalone cosmetic pack product without granting credits', async () => {
|
||||
mockDb.query.mockResolvedValueOnce({
|
||||
rows: [{
|
||||
user_id: 1,
|
||||
description: '3D pack',
|
||||
status: 'pending',
|
||||
payment_type: 'cosmetic_pack',
|
||||
product_id: 'pack_3d',
|
||||
product_grants: { credits: 0, packs: [{ id: 'kenney-3d-characters' }], premiumLevel: null }
|
||||
}]
|
||||
});
|
||||
|
||||
mockClient.query
|
||||
.mockResolvedValueOnce({ rows: [{ id: 456 }] }) // UPDATE payments
|
||||
.mockResolvedValueOnce({ rows: [{ id: 1, credits: 0, total_credits_purchased: 0, premium_level: 'free' }] }) // UPDATE users
|
||||
.mockResolvedValueOnce({ rows: [] }) // INSERT pack entitlement
|
||||
.mockResolvedValueOnce({ rows: [{ pack_id: 'kenney-3d-characters' }] }); // SELECT active grants
|
||||
|
||||
const result = await gmm.processProductPaymentConfirmation('socket1', 456, null, 1000);
|
||||
|
||||
expect(result.success).toBe(true);
|
||||
expect(result.creditsAdded).toBe(0);
|
||||
expect(result.entitlements.packs['kenney-3d-characters']).toBe(true);
|
||||
expect(mockClient.query.mock.calls.some(([sql]) => /INSERT INTO credit_transactions/i.test(sql))).toBe(false);
|
||||
});
|
||||
|
||||
test('falls back to default credits when package info missing and no description', async () => {
|
||||
// Step 1: db.query — SELECT payment lookup with no credits in description
|
||||
mockDb.query.mockResolvedValueOnce({
|
||||
|
||||
@@ -0,0 +1,98 @@
|
||||
const IdentityService = require('../src/network/identityService');
|
||||
|
||||
function makeSocket(id = 'sockA') {
|
||||
return { id, emit: jest.fn() };
|
||||
}
|
||||
|
||||
function makeDb({ user, grants = [] } = {}) {
|
||||
const state = {
|
||||
user: {
|
||||
id: 1,
|
||||
socket_id: 'sockA',
|
||||
credits: 0,
|
||||
total_credits_purchased: 0,
|
||||
premium_level: 'free',
|
||||
appearance: {
|
||||
avatar: 'char-ranger',
|
||||
tint: 'teal',
|
||||
equipment: { body: 'mail', head: 'hood', shield: 'round', weapon: 'bow' }
|
||||
},
|
||||
...user
|
||||
},
|
||||
grants
|
||||
};
|
||||
const db = {
|
||||
state,
|
||||
query: jest.fn(async (text, params = []) => {
|
||||
if (/SELECT pack_id/i.test(text)) return { rows: state.grants };
|
||||
if (/UPDATE users[\s\S]*SET appearance/i.test(text)) {
|
||||
state.user = { ...state.user, appearance: JSON.parse(params[0]) };
|
||||
return { rows: [state.user] };
|
||||
}
|
||||
return { rows: [] };
|
||||
})
|
||||
};
|
||||
return db;
|
||||
}
|
||||
|
||||
describe('IdentityService', () => {
|
||||
test('loads stored appearance and entitlements for a socket user', async () => {
|
||||
const db = makeDb({ user: { total_credits_purchased: 5, credits: 2 } });
|
||||
const sessionManager = { sessions: new Map([['sockA', db.state.user]]) };
|
||||
const gameModeManager = { getOrCreateUser: jest.fn(async () => db.state.user), db };
|
||||
const svc = new IdentityService({ db, gameModeManager, sessionManager });
|
||||
|
||||
const snapshot = await svc.identityForSocket(makeSocket());
|
||||
|
||||
expect(snapshot.appearance).toEqual(db.state.user.appearance);
|
||||
expect(snapshot.entitlements.premium).toBe(true);
|
||||
expect(snapshot.entitlements.packs['iso-dungeon']).toBe(true);
|
||||
});
|
||||
|
||||
test('saves normalized appearance and refreshes the session cache', async () => {
|
||||
const db = makeDb({ user: { total_credits_purchased: 0 } });
|
||||
const sessionManager = { sessions: new Map([['sockA', db.state.user]]) };
|
||||
const gameModeManager = { getOrCreateUser: jest.fn(async () => db.state.user), db };
|
||||
const svc = new IdentityService({ db, gameModeManager, sessionManager });
|
||||
|
||||
const snapshot = await svc.saveAppearanceForSocket(makeSocket(), {
|
||||
avatar: 'char-ranger',
|
||||
tint: 'bad',
|
||||
equipment: { body: 'mail', head: 'bad', shield: 'round', weapon: 'laser' }
|
||||
});
|
||||
|
||||
expect(snapshot.appearance).toEqual({
|
||||
avatar: 'char-ranger',
|
||||
tint: 'none',
|
||||
equipment: { body: 'mail', head: 'none', shield: 'round', weapon: 'none' }
|
||||
});
|
||||
expect(db.state.user.appearance).toEqual(snapshot.appearance);
|
||||
expect(sessionManager.sessions.get('sockA').appearance).toEqual(snapshot.appearance);
|
||||
});
|
||||
|
||||
test('falls back unauthorized premium appearance before saving', async () => {
|
||||
const db = makeDb({ user: { total_credits_purchased: 0 } });
|
||||
const gameModeManager = { getOrCreateUser: jest.fn(async () => db.state.user), db };
|
||||
const svc = new IdentityService({ db, gameModeManager });
|
||||
|
||||
const snapshot = await svc.saveAppearanceForSocket(makeSocket(), { avatar: 'monero-knight' });
|
||||
|
||||
expect(snapshot.appearance.avatar).toBe('default');
|
||||
expect(db.state.user.appearance.avatar).toBe('default');
|
||||
});
|
||||
|
||||
test('allows an explicitly granted pack appearance', async () => {
|
||||
const db = makeDb({
|
||||
user: { total_credits_purchased: 0 },
|
||||
grants: [{ pack_id: 'generated-skins' }]
|
||||
});
|
||||
const gameModeManager = { getOrCreateUser: jest.fn(async () => db.state.user), db };
|
||||
const svc = new IdentityService({ db, gameModeManager });
|
||||
|
||||
const snapshot = await svc.saveAppearanceForSocket(makeSocket(), { avatar: 'monero-knight' });
|
||||
|
||||
expect(snapshot.appearance.avatar).toBe('monero-knight');
|
||||
expect(snapshot.entitlements.packs['generated-skins']).toBe(true);
|
||||
expect(snapshot.entitlements.packs['kenney-3d-characters']).toBe(false);
|
||||
});
|
||||
});
|
||||
@@ -485,6 +485,49 @@ describe('Payment & Payout Comprehensive Tests', () => {
|
||||
expect(result.package).toBeDefined();
|
||||
});
|
||||
|
||||
test('creates cosmetic_pack payment request with durable product grants', async () => {
|
||||
const user = { id: 1, credits: 0 };
|
||||
gmm.configSnapshot.products = {
|
||||
cosmetic: [{
|
||||
id: 'pack_3d',
|
||||
label: '3D Character Pack',
|
||||
price: 250000000000n,
|
||||
grants: { packs: ['kenney-3d-characters'] }
|
||||
}]
|
||||
};
|
||||
|
||||
mockDb.query.mockResolvedValueOnce({ rows: [user] }); // getOrCreateUser
|
||||
mockDb.query.mockResolvedValueOnce({ rows: [] }); // update last_active
|
||||
mockDb.query.mockResolvedValueOnce({ rows: [] }); // no existing payment
|
||||
mockDb.query.mockResolvedValueOnce({ rows: [] }); // expire stale payments
|
||||
|
||||
mockWalletService.createPaymentRequest.mockResolvedValueOnce({
|
||||
address: 'wow1packpayment',
|
||||
expiresAt: new Date()
|
||||
});
|
||||
|
||||
mockDb.query.mockResolvedValueOnce({
|
||||
rows: [{ id: 1001, expires_at: new Date() }]
|
||||
}); // INSERT payment
|
||||
|
||||
const result = await gmm.createPaymentRequest('socket1', 'cosmetic_pack', { productId: 'pack_3d' });
|
||||
|
||||
expect(result.address).toBe('wow1packpayment');
|
||||
expect(result.paymentType).toBe('cosmetic_pack');
|
||||
expect(result.productId).toBe('pack_3d');
|
||||
expect(result.grants.packs).toEqual(['kenney-3d-characters']);
|
||||
expect(mockWalletService.createPaymentRequest).toHaveBeenCalledWith(
|
||||
250000000000,
|
||||
expect.stringContaining('3D Character Pack'),
|
||||
1,
|
||||
'socket1'
|
||||
);
|
||||
|
||||
const insertCall = mockDb.query.mock.calls.find(([sql]) => /INSERT INTO payments/i.test(sql));
|
||||
expect(insertCall[1][8]).toBe('pack_3d');
|
||||
expect(JSON.parse(insertCall[1][9]).packs[0].id).toBe('kenney-3d-characters');
|
||||
});
|
||||
|
||||
test('reuses existing pending payment request', async () => {
|
||||
const user = { id: 1, credits: 0 };
|
||||
gmm.singleGamePrice = 100000000000;
|
||||
|
||||
@@ -0,0 +1,43 @@
|
||||
const ProductGrants = require('../src/payments/productGrants');
|
||||
|
||||
describe('product grants', () => {
|
||||
test('derives credit grants from credit package fields when grants are absent', () => {
|
||||
const grants = ProductGrants.normalizeProductGrants({ id: 'small', credits: 10, bonus: 2 });
|
||||
|
||||
expect(grants).toMatchObject({
|
||||
credits: 12,
|
||||
packs: [],
|
||||
premiumLevel: null
|
||||
});
|
||||
});
|
||||
|
||||
test('normalizes bundled pack grants and premium tier', () => {
|
||||
const grants = ProductGrants.normalizeProductGrants({
|
||||
id: 'bundle',
|
||||
credits: 10,
|
||||
grants: {
|
||||
credits: 15,
|
||||
packs: ['generated-skins', { id: 'kenney-3d-characters' }, 'bad-pack'],
|
||||
premiumLevel: 'Supporter'
|
||||
}
|
||||
});
|
||||
|
||||
expect(grants.credits).toBe(15);
|
||||
expect(grants.packs.map(p => p.id)).toEqual(['generated-skins', 'kenney-3d-characters']);
|
||||
expect(grants.premiumLevel).toBe('supporter');
|
||||
});
|
||||
|
||||
test('public summaries omit internal source/expiry fields', () => {
|
||||
const summary = ProductGrants.publicGrantSummary({
|
||||
credits: 0,
|
||||
packs: [{ id: 'iso-dungeon', source: 'operator', expiresAt: '2030-01-01' }],
|
||||
premiumLevel: null
|
||||
});
|
||||
|
||||
expect(summary).toEqual({
|
||||
credits: 0,
|
||||
packs: ['iso-dungeon'],
|
||||
premiumLevel: null
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,38 @@
|
||||
const scene = require('../html/js/render/sceneModel');
|
||||
|
||||
describe('sceneFromTavern (render kit adapter)', () => {
|
||||
test('maps layout chars to tile kinds and occupants to entities', () => {
|
||||
const appearance = {
|
||||
avatar: 'char-ranger',
|
||||
tint: 'teal',
|
||||
equipment: { body: 'mail', head: 'hood', shield: 'round', weapon: 'bow' }
|
||||
};
|
||||
const state = {
|
||||
cols: 3, rows: 2,
|
||||
layout: ['#=@', 'o..'],
|
||||
occupants: [{ id: 'a', x: 2, y: 0, avatar: 'green', appearance, facing: 'left', name: 'Al' }]
|
||||
};
|
||||
const s = scene.sceneFromTavern(state, 'a');
|
||||
expect(s.cols).toBe(3);
|
||||
expect(s.rows).toBe(2);
|
||||
expect(s.grid[0]).toEqual(['wall', 'bar', 'floor']); // '@' is walkable floor
|
||||
expect(s.grid[1]).toEqual(['table', 'floor', 'floor']);
|
||||
expect(s.entities).toHaveLength(1);
|
||||
expect(s.entities[0]).toMatchObject({ id: 'a', x: 2, y: 0, kind: 'avatar', avatar: 'char-ranger', appearance, facing: 'left', label: 'Al', you: true });
|
||||
expect(s.entities[0].color).toBe(scene.AVATAR_COLORS.default);
|
||||
});
|
||||
|
||||
test('you-flag is false for other occupants and unknown avatars fall back to default', () => {
|
||||
const s = scene.sceneFromTavern(
|
||||
{ cols: 1, rows: 1, layout: ['.'], occupants: [{ id: 'b', x: 0, y: 0, avatar: 'zzz' }] },
|
||||
'a'
|
||||
);
|
||||
expect(s.entities[0].you).toBe(false);
|
||||
expect(s.entities[0].color).toBe(scene.AVATAR_COLORS.default);
|
||||
});
|
||||
|
||||
test('unknown / out-of-legend characters are treated as walls (solid)', () => {
|
||||
const s = scene.sceneFromTavern({ cols: 2, rows: 1, layout: ['?~'], occupants: [] });
|
||||
expect(s.grid[0]).toEqual(['wall', 'wall']);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,228 @@
|
||||
// TavernManager tests. The manager owns transport + the server tick; we drive it with a
|
||||
// fake Socket.IO io/socket so no real server or network is involved.
|
||||
|
||||
function makeFakeIo() {
|
||||
const io = {
|
||||
emitted: [], // { channel, event, payload }
|
||||
sockets: { sockets: new Map() },
|
||||
to(channel) {
|
||||
return { emit: (event, payload) => io.emitted.push({ channel, event, payload }) };
|
||||
}
|
||||
};
|
||||
return io;
|
||||
}
|
||||
|
||||
function makeFakeSocket(id, io) {
|
||||
const socket = {
|
||||
id,
|
||||
joined: new Set(),
|
||||
emitted: [], // { event, payload }
|
||||
join(ch) { this.joined.add(ch); },
|
||||
leave(ch) { this.joined.delete(ch); },
|
||||
emit(event, payload) { this.emitted.push({ event, payload }); }
|
||||
};
|
||||
if (io) io.sockets.sockets.set(id, socket);
|
||||
return socket;
|
||||
}
|
||||
|
||||
function loadManager() {
|
||||
// enabled is read from env in the constructor.
|
||||
jest.resetModules();
|
||||
return require('../src/network/tavernManager');
|
||||
}
|
||||
|
||||
describe('TavernManager', () => {
|
||||
const prev = process.env.TAVERN_ENABLED;
|
||||
afterAll(() => { process.env.TAVERN_ENABLED = prev; });
|
||||
|
||||
test('is inert and refuses joins when TAVERN_ENABLED is not set', async () => {
|
||||
delete process.env.TAVERN_ENABLED;
|
||||
const TavernManager = loadManager();
|
||||
const io = makeFakeIo();
|
||||
const mgr = new TavernManager({ io });
|
||||
mgr.initialize(); // must not start a timer
|
||||
expect(mgr._tickInterval).toBeNull();
|
||||
|
||||
const s = makeFakeSocket('a', io);
|
||||
const res = await mgr.join(s, { name: 'Alice' });
|
||||
expect(res.success).toBe(false);
|
||||
expect(s.emitted.some(e => e.event === 'tavern_error')).toBe(true);
|
||||
expect(mgr.room.size).toBe(0);
|
||||
});
|
||||
|
||||
describe('when enabled', () => {
|
||||
let TavernManager;
|
||||
beforeAll(() => { process.env.TAVERN_ENABLED = 'true'; });
|
||||
beforeEach(() => { TavernManager = loadManager(); });
|
||||
|
||||
test('join adds an occupant and sends full state (with the map) to the joiner', async () => {
|
||||
const io = makeFakeIo();
|
||||
const mgr = new TavernManager({ io });
|
||||
const s = makeFakeSocket('a', io);
|
||||
|
||||
const res = await mgr.join(s, { name: 'Alice', avatar: 'green' });
|
||||
expect(res.success).toBe(true);
|
||||
expect(mgr.room.size).toBe(1);
|
||||
expect(s.joined.has(mgr.channel)).toBe(true);
|
||||
|
||||
const joined = s.emitted.find(e => e.event === 'tavern_joined');
|
||||
expect(joined).toBeTruthy();
|
||||
expect(joined.payload.you).toBe('a');
|
||||
expect(Array.isArray(joined.payload.state.layout)).toBe(true);
|
||||
expect(joined.payload.state.occupants.map(o => o.id)).toEqual(['a']);
|
||||
});
|
||||
|
||||
test('join preserves structured character appearance', async () => {
|
||||
const io = makeFakeIo();
|
||||
const mgr = new TavernManager({ io });
|
||||
const s = makeFakeSocket('a', io);
|
||||
const appearance = {
|
||||
avatar: 'char-ranger',
|
||||
tint: 'teal',
|
||||
equipment: { body: 'mail', head: 'hood', shield: 'round', weapon: 'bow' }
|
||||
};
|
||||
|
||||
await mgr.join(s, { name: 'Alice', avatar: 'green', appearance });
|
||||
const occ = mgr.room.getOccupant('a');
|
||||
expect(occ.avatar).toBe('char-ranger');
|
||||
expect(occ.appearance).toEqual(appearance);
|
||||
|
||||
const joined = s.emitted.find(e => e.event === 'tavern_joined');
|
||||
expect(joined.payload.state.occupants[0].appearance).toEqual(appearance);
|
||||
});
|
||||
|
||||
test('appearance is normalized and names are sanitized', async () => {
|
||||
const io = makeFakeIo();
|
||||
const mgr = new TavernManager({ io });
|
||||
const s = makeFakeSocket('a', io);
|
||||
await mgr.join(s, {
|
||||
name: ' <b>Ann</b> ',
|
||||
avatar: 'rainbow',
|
||||
appearance: {
|
||||
avatar: 'char-ranger',
|
||||
tint: 'bad',
|
||||
equipment: { body: 'mail', head: 'bad', shield: 'round', weapon: 'laser' }
|
||||
}
|
||||
});
|
||||
const occ = mgr.room.getOccupant('a');
|
||||
expect(occ.avatar).toBe('char-ranger');
|
||||
expect(occ.appearance).toEqual({
|
||||
avatar: 'char-ranger',
|
||||
tint: 'none',
|
||||
equipment: { body: 'mail', head: 'none', shield: 'round', weapon: 'none' }
|
||||
});
|
||||
expect(occ.name).not.toMatch(/[<>]/);
|
||||
expect(occ.name.length).toBeLessThanOrEqual(16);
|
||||
});
|
||||
|
||||
test('premium avatars require a premium entitlement', async () => {
|
||||
const io = makeFakeIo();
|
||||
const mgr = new TavernManager({ io });
|
||||
const s = makeFakeSocket('a', io);
|
||||
await mgr.join(s, { appearance: { avatar: 'monero-knight' } });
|
||||
expect(mgr.room.getOccupant('a').avatar).toBe('default');
|
||||
|
||||
const paid = new TavernManager({
|
||||
io,
|
||||
entitlementProvider: async () => ({ premium: true, totalCreditsPurchased: 10 })
|
||||
});
|
||||
const s2 = makeFakeSocket('b', io);
|
||||
await paid.join(s2, { appearance: { avatar: 'monero-knight' } });
|
||||
expect(paid.room.getOccupant('b').avatar).toBe('monero-knight');
|
||||
});
|
||||
|
||||
test('move is server-authoritative and honours the flood cooldown', async () => {
|
||||
const io = makeFakeIo();
|
||||
const mgr = new TavernManager({ io });
|
||||
const s = makeFakeSocket('a', io);
|
||||
await mgr.join(s, {});
|
||||
const occ = mgr.room.getOccupant('a');
|
||||
const startX = occ.x;
|
||||
|
||||
mgr.move(s, { dir: 'right' });
|
||||
expect(occ.x).toBe(startX + 1);
|
||||
|
||||
// Immediate second move is dropped by the cooldown.
|
||||
mgr.move(s, { dir: 'right' });
|
||||
expect(occ.x).toBe(startX + 1);
|
||||
});
|
||||
|
||||
test('the tick broadcasts a snapshot to the room when occupied', async () => {
|
||||
const io = makeFakeIo();
|
||||
const mgr = new TavernManager({ io });
|
||||
const s = makeFakeSocket('a', io);
|
||||
await mgr.join(s, {});
|
||||
io.emitted.length = 0;
|
||||
|
||||
mgr._tick();
|
||||
const update = io.emitted.find(e => e.event === 'tavern_update' && e.channel === mgr.channel);
|
||||
expect(update).toBeTruthy();
|
||||
expect(update.payload.occupants.map(o => o.id)).toEqual(['a']);
|
||||
});
|
||||
|
||||
test('disconnect removes the occupant', async () => {
|
||||
const io = makeFakeIo();
|
||||
const mgr = new TavernManager({ io });
|
||||
const s = makeFakeSocket('a', io);
|
||||
await mgr.join(s, {});
|
||||
expect(mgr.room.size).toBe(1);
|
||||
|
||||
mgr.handleDisconnect('a', s);
|
||||
expect(mgr.room.size).toBe(0);
|
||||
expect(s.joined.has(mgr.channel)).toBe(false);
|
||||
});
|
||||
|
||||
test('chat from an occupant is delivered to the tavern room, HTML-escaped', async () => {
|
||||
const io = makeFakeIo();
|
||||
const mgr = new TavernManager({ io });
|
||||
const s = makeFakeSocket('a', io);
|
||||
await mgr.join(s, { name: 'Alice' });
|
||||
io.emitted.length = 0;
|
||||
|
||||
mgr.chat(s, { text: 'hi <b>there</b>' });
|
||||
const ev = io.emitted.find(e => e.event === 'chat_broadcast' && e.channel === mgr.channel);
|
||||
expect(ev).toBeTruthy();
|
||||
expect(ev.payload.username).toBe('Alice');
|
||||
expect(ev.payload.message).toBe('hi <b>there</b>');
|
||||
expect(ev.payload.scope).toBe(mgr.channel);
|
||||
});
|
||||
|
||||
test('chat honours the flood cooldown', async () => {
|
||||
const io = makeFakeIo();
|
||||
const mgr = new TavernManager({ io });
|
||||
const s = makeFakeSocket('a', io);
|
||||
await mgr.join(s, {});
|
||||
io.emitted.length = 0;
|
||||
mgr.chat(s, { text: 'one' });
|
||||
s.emitted.length = 0;
|
||||
mgr.chat(s, { text: 'two' }); // immediate second is dropped
|
||||
const msgs = io.emitted.filter(e => e.event === 'chat_broadcast');
|
||||
expect(msgs).toHaveLength(1);
|
||||
expect(msgs[0].payload.message).toBe('one');
|
||||
// The sender is told, rather than the message vanishing silently.
|
||||
expect(s.emitted.some(e => e.event === 'tavern_notice')).toBe(true);
|
||||
});
|
||||
|
||||
test('non-occupants and empty messages cannot chat', async () => {
|
||||
const io = makeFakeIo();
|
||||
const mgr = new TavernManager({ io });
|
||||
const outsider = makeFakeSocket('z', io);
|
||||
mgr.chat(outsider, { text: 'sneaky' }); // never joined -> ignored
|
||||
|
||||
const s = makeFakeSocket('a', io);
|
||||
await mgr.join(s, {});
|
||||
io.emitted.length = 0;
|
||||
mgr.chat(s, { text: ' ' }); // whitespace only -> ignored
|
||||
expect(io.emitted.filter(e => e.event === 'chat_broadcast')).toHaveLength(0);
|
||||
});
|
||||
|
||||
test('shutdown clears the tick timer', () => {
|
||||
const io = makeFakeIo();
|
||||
const mgr = new TavernManager({ io });
|
||||
mgr.initialize();
|
||||
expect(mgr._tickInterval).not.toBeNull();
|
||||
mgr.shutdown();
|
||||
expect(mgr._tickInterval).toBeNull();
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,86 @@
|
||||
const Room = require('../src/multiplayer/Room');
|
||||
const Occupant = require('../src/multiplayer/Occupant');
|
||||
|
||||
describe('Room — shared real-time engine (Tavern instance)', () => {
|
||||
test('builds a rectangular walkable map with at least one spawn', () => {
|
||||
const room = new Room({ id: 'test-room', type: 'tavern' });
|
||||
expect(room.rows).toBeGreaterThan(0);
|
||||
expect(room.cols).toBeGreaterThan(0);
|
||||
expect(room.spawns.length).toBeGreaterThan(0);
|
||||
// Border is solid; a spawn tile is walkable.
|
||||
expect(room.isWalkable(0, 0)).toBe(false);
|
||||
const s = room.spawns[0];
|
||||
expect(room.isWalkable(s.x, s.y)).toBe(true);
|
||||
});
|
||||
|
||||
test('occupants join at a spawn and appear in the snapshot', () => {
|
||||
const room = new Room({ id: 'r' });
|
||||
const a = room.addOccupant('alice', { name: 'Alice', avatar: 'default' });
|
||||
room.addOccupant('bob', { name: 'Bob' });
|
||||
expect(a).toBeInstanceOf(Occupant);
|
||||
expect(room.size).toBe(2);
|
||||
const ids = room.snapshot().occupants.map(o => o.id).sort();
|
||||
expect(ids).toEqual(['alice', 'bob']);
|
||||
});
|
||||
|
||||
test('server-authoritative movement: a valid step moves and sets facing', () => {
|
||||
const room = new Room({ id: 'r' });
|
||||
const occ = room.addOccupant('alice');
|
||||
const startX = occ.x;
|
||||
const res = room.moveOccupant('alice', 1, 0); // step right (spawn has open floor right)
|
||||
expect(res.moved).toBe(true);
|
||||
expect(occ.x).toBe(startX + 1);
|
||||
expect(occ.facing).toBe('right');
|
||||
});
|
||||
|
||||
test('rejects diagonal, multi-tile and no-op requests', () => {
|
||||
const room = new Room({ id: 'r' });
|
||||
room.addOccupant('alice');
|
||||
expect(room.moveOccupant('alice', 1, 1).moved).toBe(false); // diagonal
|
||||
expect(room.moveOccupant('alice', 0, 0).moved).toBe(false); // no-op
|
||||
expect(room.moveOccupant('ghost', 1, 0).moved).toBe(false); // not in room
|
||||
});
|
||||
|
||||
test('cannot walk through walls or off the map', () => {
|
||||
const room = new Room({ id: 'r' });
|
||||
const occ = room.addOccupant('alice');
|
||||
for (let i = 0; i < 40; i++) room.moveOccupant('alice', -1, 0); // slam left
|
||||
expect(occ.x).toBeGreaterThanOrEqual(0);
|
||||
expect(room.isWalkable(occ.x, occ.y)).toBe(true); // still on floor
|
||||
expect(room.isWalkable(occ.x - 1, occ.y)).toBe(false); // wall to the left
|
||||
});
|
||||
|
||||
test('match rooms (solidOccupants) block stepping onto another occupant', () => {
|
||||
const match = new Room({ id: 'm', solidOccupants: true });
|
||||
const p = match.addOccupant('p'); // spawn A
|
||||
const q = match.addOccupant('q'); // spawn B, adjacent to A
|
||||
expect(Math.abs(p.x - q.x) + Math.abs(p.y - q.y)).toBe(1);
|
||||
const res = match.moveOccupant('q', Math.sign(p.x - q.x), Math.sign(p.y - q.y));
|
||||
expect(res.moved).toBe(false);
|
||||
expect(res.reason).toBe('occupied');
|
||||
});
|
||||
|
||||
test('tavern rooms let occupants share a tile (open doorways, no blocking griefing)', () => {
|
||||
const tavern = new Room({ id: 't', solidOccupants: false });
|
||||
const p = tavern.addOccupant('p');
|
||||
const q = tavern.addOccupant('q');
|
||||
const res = tavern.moveOccupant('q', Math.sign(p.x - q.x), Math.sign(p.y - q.y));
|
||||
expect(res.moved).toBe(true);
|
||||
expect(tavern.isOccupied(p.x, p.y)).toBe(true); // both share the tile, allowed
|
||||
});
|
||||
|
||||
test('tick is a heartbeat that increments and never throws', () => {
|
||||
const room = new Room({ id: 'r' });
|
||||
for (let i = 0; i < 5; i++) room.tick();
|
||||
expect(room.tickCount).toBe(5);
|
||||
expect(room.snapshot().tick).toBe(5);
|
||||
});
|
||||
|
||||
test('removeOccupant clears them from the snapshot', () => {
|
||||
const room = new Room({ id: 'r' });
|
||||
room.addOccupant('alice');
|
||||
expect(room.removeOccupant('alice')).toBe(true);
|
||||
expect(room.size).toBe(0);
|
||||
expect(room.snapshot().occupants).toEqual([]);
|
||||
});
|
||||
});
|
||||
Reference in New Issue
Block a user