BlueGit

timfa questward

Files

questward / server / src / persistence / stateDb.js

stateDb.js

stateDb.js 58.1 KiB Download Raw
1import { openDatabase } from "./database.js";
2import { emptyEquipment, emptySlots, insertStack, insertStackGrowable, normalizeVault, normalizeInventorySlots, publicSlots, migrateBagCoins, migrateInheritanceCoins } from "../../../shared/items/inventory.js";
3import { attachOrigins, godsOrigin } from "../../../shared/items/origin.js";
4import { itemDefinition, ItemId } from "../../../shared/definitions/items.js";
5import { buildStarterBagContents } from "../../../shared/items/starterLoadout.js";
6import { normalizePlayerSkills, defaultPlayerSkills, storedSkillXp } from "../../../shared/skills/state.js";
7import { normalizePlayerSpells, defaultPlayerSpells, storedPlayerSpells } from "../../../shared/spells/state.js";
8import { decayKillCounter } from "../../../shared/combat/skull.js";
9import {
10 applyBountyDailyDecay,
11 bountyDecayDayKey,
12 bountyDecayDaysBetween
13} from "../../../shared/bounty/pricing.js";
14
15const STATE_SCHEMA = `
16CREATE TABLE IF NOT EXISTS accounts (
17 account_id INTEGER PRIMARY KEY AUTOINCREMENT,
18 auth_subject TEXT NOT NULL UNIQUE,
19 email TEXT,
20 is_admin INTEGER NOT NULL DEFAULT 0
21);
22
23CREATE TABLE IF NOT EXISTS surname_claims (
24 surname_normalized TEXT PRIMARY KEY,
25 account_id INTEGER NOT NULL
26);
27
28CREATE TABLE IF NOT EXISTS characters (
29 character_id INTEGER PRIMARY KEY AUTOINCREMENT,
30 account_id INTEGER NOT NULL,
31 first_name TEXT NOT NULL,
32 last_name TEXT NOT NULL,
33 first_normalized TEXT NOT NULL,
34 last_normalized TEXT NOT NULL,
35 sex TEXT NOT NULL,
36 tile_x INTEGER NOT NULL DEFAULT 8,
37 tile_y INTEGER NOT NULL DEFAULT 8,
38 gait TEXT NOT NULL DEFAULT 'walk',
39 is_dead INTEGER NOT NULL DEFAULT 0,
40 deletion_scheduled_at INTEGER,
41 hair_style TEXT,
42 hair_hue REAL NOT NULL DEFAULT 30,
43 hair_saturation REAL NOT NULL DEFAULT 0.55,
44 hair_darkness REAL NOT NULL DEFAULT 0.45
45);
46CREATE TABLE IF NOT EXISTS friend_requests (
47 request_id INTEGER PRIMARY KEY AUTOINCREMENT,
48 from_character_id INTEGER NOT NULL,
49 to_character_id INTEGER NOT NULL,
50 created_at INTEGER NOT NULL,
51 UNIQUE (from_character_id, to_character_id)
52);
53
54CREATE TABLE IF NOT EXISTS friendships (
55 character_id_a INTEGER NOT NULL,
56 character_id_b INTEGER NOT NULL,
57 created_at INTEGER NOT NULL,
58 PRIMARY KEY (character_id_a, character_id_b)
59);
60
61CREATE TABLE IF NOT EXISTS persistent_entities (
62 entity_id INTEGER PRIMARY KEY,
63 tile_x INTEGER NOT NULL,
64 tile_y INTEGER NOT NULL,
65 components_blob TEXT NOT NULL
66);
67
68CREATE TABLE IF NOT EXISTS character_bags (
69 character_id INTEGER PRIMARY KEY,
70 inventory_blob TEXT NOT NULL,
71 equipment_blob TEXT NOT NULL,
72 currency INTEGER NOT NULL DEFAULT 0,
73 vault_blob TEXT NOT NULL,
74 vault_currency INTEGER NOT NULL DEFAULT 0,
75 skills_blob TEXT NOT NULL DEFAULT '{}'
76);
77
78CREATE TABLE IF NOT EXISTS account_inheritance (
79 account_id INTEGER PRIMARY KEY,
80 slots_blob TEXT NOT NULL,
81 currency INTEGER NOT NULL DEFAULT 0
82);
83
84CREATE TABLE IF NOT EXISTS ground_items (
85 ground_item_id INTEGER PRIMARY KEY,
86 tile_x INTEGER NOT NULL,
87 tile_y INTEGER NOT NULL,
88 stack_blob TEXT NOT NULL,
89 dropped_at INTEGER NOT NULL,
90 expires_at INTEGER NOT NULL,
91 source TEXT NOT NULL,
92 dropped_by_character_id INTEGER
93);
94
95CREATE TABLE IF NOT EXISTS courier_transits (
96 courier_id INTEGER PRIMARY KEY AUTOINCREMENT,
97 sender_character_id INTEGER NOT NULL,
98 destination_kind TEXT NOT NULL,
99 destination_character_id INTEGER,
100 cargo_blob TEXT NOT NULL,
101 origin_x REAL NOT NULL,
102 origin_y REAL NOT NULL,
103 dest_x REAL NOT NULL,
104 dest_y REAL NOT NULL,
105 traveled REAL NOT NULL DEFAULT 0,
106 status TEXT NOT NULL,
107 entity_id INTEGER,
108 updated_at INTEGER NOT NULL,
109 created_at INTEGER NOT NULL
110);
111
112CREATE TABLE IF NOT EXISTS market_orders (
113 order_id INTEGER PRIMARY KEY AUTOINCREMENT,
114 character_id INTEGER NOT NULL,
115 side TEXT NOT NULL,
116 item_id INTEGER NOT NULL,
117 quantity INTEGER NOT NULL,
118 limit_unit_price INTEGER NOT NULL,
119 escrow_coins INTEGER NOT NULL DEFAULT 0,
120 escrow_stack_blob TEXT,
121 listing_key TEXT,
122 created_at INTEGER NOT NULL,
123 status TEXT NOT NULL
124);
125
126CREATE TABLE IF NOT EXISTS market_trades (
127 trade_id INTEGER PRIMARY KEY AUTOINCREMENT,
128 buy_order_id INTEGER NOT NULL,
129 sell_order_id INTEGER NOT NULL,
130 item_id INTEGER NOT NULL,
131 quantity INTEGER NOT NULL,
132 unit_price INTEGER NOT NULL,
133 buyer_character_id INTEGER NOT NULL,
134 seller_character_id INTEGER NOT NULL,
135 created_at INTEGER NOT NULL
136);
137
138CREATE TABLE IF NOT EXISTS item_last_sales (
139 item_id INTEGER PRIMARY KEY,
140 last_trade_price INTEGER NOT NULL,
141 last_trade_at INTEGER NOT NULL,
142 price_from INTEGER NOT NULL
143);
144
145CREATE TABLE IF NOT EXISTS bank_rest_notices (
146 notice_id INTEGER PRIMARY KEY AUTOINCREMENT,
147 character_id INTEGER NOT NULL,
148 item_id INTEGER NOT NULL,
149 item_name TEXT NOT NULL,
150 quantity INTEGER NOT NULL,
151 source_name TEXT NOT NULL,
152 created_at INTEGER NOT NULL
153);
154
155CREATE TABLE IF NOT EXISTS held_courier_deliveries (
156 hold_id INTEGER PRIMARY KEY AUTOINCREMENT,
157 character_id INTEGER NOT NULL,
158 sender_character_id INTEGER NOT NULL,
159 origin_tile_x INTEGER NOT NULL,
160 origin_tile_y INTEGER NOT NULL,
161 destination_kind TEXT NOT NULL,
162 destination_character_id INTEGER,
163 vault_character_id INTEGER,
164 cargo_blob TEXT NOT NULL,
165 created_at INTEGER NOT NULL
166);
167
168CREATE TABLE IF NOT EXISTS character_bounties (
169 character_id INTEGER PRIMARY KEY,
170 amount INTEGER NOT NULL DEFAULT 0,
171 last_decay_day TEXT
172);
173
174CREATE TABLE IF NOT EXISTS character_quest_state (
175 character_id INTEGER NOT NULL,
176 quest_id TEXT NOT NULL,
177 state_value TEXT NOT NULL,
178 progress_blob TEXT NOT NULL DEFAULT '{}',
179 started_at INTEGER,
180 completed_at INTEGER,
181 PRIMARY KEY (character_id, quest_id)
182);
183
184CREATE TABLE IF NOT EXISTS character_dialogue_heard (
185 character_id INTEGER NOT NULL,
186 dialogue_id TEXT NOT NULL,
187 step_id TEXT NOT NULL,
188 heard_at INTEGER NOT NULL,
189 PRIMARY KEY (character_id, dialogue_id, step_id)
190);
191
192CREATE TABLE IF NOT EXISTS character_quest_journal (
193 entry_id INTEGER PRIMARY KEY AUTOINCREMENT,
194 character_id INTEGER NOT NULL,
195 quest_id TEXT NOT NULL,
196 step_id TEXT NOT NULL,
197 text TEXT NOT NULL,
198 written_at INTEGER NOT NULL
199);
200
201CREATE TABLE IF NOT EXISTS character_dialogue_triggers (
202 character_id INTEGER NOT NULL,
203 dialogue_id TEXT NOT NULL,
204 trigger_id TEXT NOT NULL,
205 latched_at INTEGER NOT NULL,
206 PRIMARY KEY (character_id, dialogue_id, trigger_id)
207);
208
209CREATE TABLE IF NOT EXISTS character_visited_dimensions (
210 character_id INTEGER NOT NULL,
211 dimension_id TEXT NOT NULL,
212 first_visited_at INTEGER NOT NULL,
213 PRIMARY KEY (character_id, dimension_id)
214);
215`;
216
217export class StateDatabase
218{
219 constructor(filePath)
220 {
221 this.db = openDatabase(filePath);
222 this.db.exec(STATE_SCHEMA);
223 this.#migrateSchema();
224 }
225
226 #migrateSchema ()
227 {
228 const bagColumns = this.db.prepare("PRAGMA table_info(character_bags)").all();
229 if (!bagColumns.some((column) => column.name === "skills_blob"))
230 {
231 this.db.exec("ALTER TABLE character_bags ADD COLUMN skills_blob TEXT NOT NULL DEFAULT '{}'");
232 }
233 const characterColumns = this.db.prepare("PRAGMA table_info(characters)").all();
234 if (!characterColumns.some((column) => column.name === "is_dead"))
235 { this.db.exec("ALTER TABLE characters ADD COLUMN is_dead INTEGER NOT NULL DEFAULT 0"); }
236 if (!characterColumns.some((column) => column.name === "hair_style"))
237 {
238 this.db.exec("ALTER TABLE characters ADD COLUMN hair_style TEXT");
239 this.db.exec("ALTER TABLE characters ADD COLUMN hair_hue REAL NOT NULL DEFAULT 30");
240 this.db.exec("ALTER TABLE characters ADD COLUMN hair_saturation REAL NOT NULL DEFAULT 0.55");
241 this.db.exec("ALTER TABLE characters ADD COLUMN hair_darkness REAL NOT NULL DEFAULT 0.45");
242 }
243 if (!characterColumns.some((column) => column.name === "dimension_id"))
244 { this.db.exec("ALTER TABLE characters ADD COLUMN dimension_id TEXT NOT NULL DEFAULT 'overworld'"); }
245 this.db.exec(`
246 CREATE TABLE IF NOT EXISTS character_visited_dimensions (
247 character_id INTEGER NOT NULL,
248 dimension_id TEXT NOT NULL,
249 first_visited_at INTEGER NOT NULL,
250 PRIMARY KEY (character_id, dimension_id)
251 )
252 `);
253 const courierColumns = this.db.prepare("PRAGMA table_info(courier_transits)").all();
254 if (!courierColumns.some((column) => column.name === "vault_character_id"))
255 { this.db.exec("ALTER TABLE courier_transits ADD COLUMN vault_character_id INTEGER"); }
256 if (!bagColumns.some((column) => column.name === "spells_blob"))
257 {
258 this.db.exec("ALTER TABLE character_bags ADD COLUMN spells_blob TEXT NOT NULL DEFAULT '{}'");
259 }
260 if (!characterColumns.some((column) => column.name === "health_current"))
261 { this.db.exec("ALTER TABLE characters ADD COLUMN health_current INTEGER"); }
262 const accountColumns = this.db.prepare("PRAGMA table_info(accounts)").all();
263 if (!accountColumns.some((column) => column.name === "username"))
264 { this.db.exec("ALTER TABLE accounts ADD COLUMN username TEXT"); }
265 if (!characterColumns.some((column) => column.name === "kill_counter"))
266 { this.db.exec("ALTER TABLE characters ADD COLUMN kill_counter REAL NOT NULL DEFAULT 0"); }
267 if (!characterColumns.some((column) => column.name === "kill_counter_at"))
268 { this.db.exec("ALTER TABLE characters ADD COLUMN kill_counter_at INTEGER"); }
269 if (!characterColumns.some((column) => column.name === "cowardice_forgiven_hour"))
270 { this.db.exec("ALTER TABLE characters ADD COLUMN cowardice_forgiven_hour INTEGER"); }
271 if (!characterColumns.some((column) => column.name === "respawn_altar_x"))
272 {
273 this.db.exec("ALTER TABLE characters ADD COLUMN respawn_altar_x INTEGER");
274 this.db.exec("ALTER TABLE characters ADD COLUMN respawn_altar_y INTEGER");
275 this.db.exec("ALTER TABLE characters ADD COLUMN respawn_altar_dimension_id TEXT");
276 }
277 const marketColumns = this.db.prepare("PRAGMA table_info(market_orders)").all();
278 if (!marketColumns.some((column) => column.name === "listing_key"))
279 { this.db.exec("ALTER TABLE market_orders ADD COLUMN listing_key TEXT"); }
280 const bountyColumns = this.db.prepare("PRAGMA table_info(character_bounties)").all();
281 if (!bountyColumns.some((column) => column.name === "last_decay_day"))
282 { this.db.exec("ALTER TABLE character_bounties ADD COLUMN last_decay_day TEXT"); }
283 this.db.exec(`
284 CREATE TABLE IF NOT EXISTS account_friend_requests (
285 request_id INTEGER PRIMARY KEY AUTOINCREMENT,
286 from_account_id INTEGER NOT NULL,
287 to_account_id INTEGER NOT NULL,
288 created_at INTEGER NOT NULL,
289 UNIQUE (from_account_id, to_account_id)
290 )
291 `);
292 this.db.exec(`
293 CREATE TABLE IF NOT EXISTS account_friendships (
294 account_id_a INTEGER NOT NULL,
295 account_id_b INTEGER NOT NULL,
296 created_at INTEGER NOT NULL,
297 PRIMARY KEY (account_id_a, account_id_b)
298 )
299 `);
300 this.#migrateCharacterFriendsToAccounts();
301 this.db.exec(`
302 CREATE TABLE IF NOT EXISTS auth_sessions (
303 session_id TEXT PRIMARY KEY,
304 auth_subject TEXT NOT NULL,
305 username TEXT,
306 email TEXT,
307 access_token TEXT,
308 expires_at INTEGER NOT NULL
309 )
310 `);
311 this.db.exec(`
312 CREATE INDEX IF NOT EXISTS auth_sessions_subject ON auth_sessions(auth_subject)
313 `);
314 this.#grantLanternsToExistingCharacters();
315 }
316
317 /** One-time: lift legacy character friendships / requests to account scope. */
318 #migrateCharacterFriendsToAccounts ()
319 {
320 const legacyFriends = this.db.prepare("SELECT character_id_a, character_id_b, created_at FROM friendships").all();
321 const insertFriend = this.db.prepare(`
322 INSERT OR IGNORE INTO account_friendships (account_id_a, account_id_b, created_at)
323 VALUES (?, ?, ?)
324 `);
325 for (const row of legacyFriends)
326 {
327 const a = this.getCharacter(row.character_id_a);
328 const b = this.getCharacter(row.character_id_b);
329 if (!a || !b || a.account_id === b.account_id)
330 { continue; }
331 const [idA, idB] = pairIds(a.account_id, b.account_id);
332 insertFriend.run(idA, idB, row.created_at | 0 || Date.now());
333 }
334 const legacyRequests = this.db.prepare(`
335 SELECT from_character_id, to_character_id, created_at FROM friend_requests
336 `).all();
337 const insertReq = this.db.prepare(`
338 INSERT OR IGNORE INTO account_friend_requests (from_account_id, to_account_id, created_at)
339 VALUES (?, ?, ?)
340 `);
341 for (const row of legacyRequests)
342 {
343 const from = this.getCharacter(row.from_character_id);
344 const to = this.getCharacter(row.to_character_id);
345 if (!from || !to || from.account_id === to.account_id)
346 { continue; }
347 insertReq.run(from.account_id, to.account_id, row.created_at | 0 || Date.now());
348 }
349 if (legacyFriends.length || legacyRequests.length)
350 {
351 this.db.exec("DELETE FROM friendships");
352 this.db.exec("DELETE FROM friend_requests");
353 }
354 }
355
356 createAuthSession ({ sessionId, authSubject, username = null, email = null, accessToken = null, expiresAtMs })
357 {
358 this.db.prepare(`
359 INSERT INTO auth_sessions (session_id, auth_subject, username, email, access_token, expires_at)
360 VALUES (?, ?, ?, ?, ?, ?)
361 `).run(sessionId, authSubject, username, email, accessToken, expiresAtMs);
362 }
363
364 getAuthSession (sessionId)
365 {
366 return this.db.prepare(`
367 SELECT session_id, auth_subject, username, email, access_token, expires_at
368 FROM auth_sessions
369 WHERE session_id = ?
370 `).get(sessionId) ?? null;
371 }
372
373 deleteAuthSession (sessionId)
374 {
375 if (!sessionId)
376 { return; }
377 this.db.prepare("DELETE FROM auth_sessions WHERE session_id = ?").run(sessionId);
378 }
379
380 #grantLanternsToExistingCharacters ()
381 {
382 const def = itemDefinition(ItemId.lantern);
383 if (!def)
384 { return; }
385 const rows = this.db.prepare("SELECT character_id, inventory_blob, equipment_blob FROM character_bags").all();
386 const update = this.db.prepare(`
387 UPDATE character_bags
388 SET inventory_blob = ?, equipment_blob = ?
389 WHERE character_id = ?
390 `);
391 for (const row of rows)
392 {
393 const inventory = JSON.parse(row.inventory_blob || "[]");
394 const equipment = JSON.parse(row.equipment_blob || "{}");
395 if (bagContainsItem(inventory, equipment, ItemId.lantern))
396 { continue; }
397 if (!equipment.slots?.offhand)
398 {
399 equipment.slots = equipment.slots ?? {};
400 equipment.slots.offhand = attachOrigins({
401 itemId: ItemId.lantern,
402 quantity: 1,
403 origins: [{ origin: godsOrigin(), quantity: 1 }]
404 });
405 }
406 else
407 {
408 const result = insertStack(inventory, attachOrigins({
409 itemId: ItemId.lantern,
410 quantity: 1,
411 origins: [{ origin: godsOrigin(), quantity: 1 }]
412 }), def);
413 if (!result.ok)
414 { continue; }
415 inventory.splice(0, inventory.length, ...result.slots);
416 }
417 update.run(JSON.stringify(inventory), JSON.stringify(equipment), row.character_id);
418 }
419 }
420
421 getAccountBySubject (authSubject)
422 {
423 return this.db.prepare("SELECT * FROM accounts WHERE auth_subject = ?").get(authSubject) ?? null;
424 }
425
426 countAccounts ()
427 {
428 return this.db.prepare("SELECT COUNT(*) AS count FROM accounts").get().count;
429 }
430
431 countGameAdmins ()
432 {
433 return this.db.prepare("SELECT COUNT(*) AS count FROM accounts WHERE is_admin = 1").get().count;
434 }
435
436 findAccountByUsername (username)
437 {
438 const normalized = String(username ?? "").trim().toLowerCase();
439 if (!normalized)
440 { return null; }
441 return this.db.prepare(`
442 SELECT * FROM accounts
443 WHERE lower(username) = ?
444 ORDER BY account_id ASC
445 LIMIT 1
446 `).get(normalized) ?? null;
447 }
448
449 listGameAdmins ()
450 {
451 return this.db.prepare(`
452 SELECT account_id, auth_subject, username, email, is_admin
453 FROM accounts
454 WHERE is_admin = 1
455 ORDER BY account_id ASC
456 `).all();
457 }
458
459 #syncAccountProfile (accountId, { email, username })
460 {
461 const fields = [];
462 const values = [];
463 if (email != null)
464 {
465 fields.push("email = ?");
466 values.push(email);
467 }
468 if (username != null)
469 {
470 fields.push("username = ?");
471 values.push(username);
472 }
473 if (!fields.length)
474 { return; }
475 values.push(accountId);
476 this.db.prepare(`UPDATE accounts SET ${fields.join(", ")} WHERE account_id = ?`).run(...values);
477 }
478
479 resolveAccountFromAuth ({ authSubject, email = null, username = null })
480 {
481 const existing = this.getAccountBySubject(authSubject);
482 if (existing)
483 {
484 this.#syncAccountProfile(existing.account_id, { email, username });
485 return this.getAccountBySubject(authSubject);
486 }
487 const isFirstAccount = this.countAccounts() === 0;
488 return this.createAccount(authSubject, isFirstAccount, email, username);
489 }
490
491 setGameAdmin (authSubject, isAdmin)
492 {
493 const account = this.getAccountBySubject(authSubject);
494 if (!account)
495 {
496 const error = new Error("Account not found.");
497 error.userFacing = true;
498 throw error;
499 }
500 if (!isAdmin && account.is_admin && this.countGameAdmins() <= 1)
501 {
502 const error = new Error("Cannot remove the last game admin.");
503 error.userFacing = true;
504 throw error;
505 }
506 this.db.prepare("UPDATE accounts SET is_admin = ? WHERE auth_subject = ?").run(isAdmin ? 1 : 0, authSubject);
507 return this.getAccountBySubject(authSubject);
508 }
509
510 grantGameAdminByUsername (username)
511 {
512 const account = this.findAccountByUsername(username);
513 if (!account)
514 {
515 const error = new Error("No account with that username has signed in yet.");
516 error.userFacing = true;
517 throw error;
518 }
519 return this.setGameAdmin(account.auth_subject, true);
520 }
521
522 createAccount (authSubject, isAdmin, email = null, username = null)
523 {
524 this.db.prepare(`
525 INSERT INTO accounts (auth_subject, email, username, is_admin)
526 VALUES (?, ?, ?, ?)
527 `).run(
528 authSubject,
529 email,
530 username,
531 isAdmin ? 1 : 0
532 );
533 return this.getAccountBySubject(authSubject);
534 }
535
536 ensureAccount (authSubject, isAdmin, email = null, username = null)
537 {
538 const existing = this.getAccountBySubject(authSubject);
539 if (existing)
540 {
541 this.#syncAccountProfile(existing.account_id, { email, username });
542 return existing;
543 }
544
545 return this.createAccount(authSubject, isAdmin, email, username);
546 }
547
548 listCharacters (accountId)
549 {
550 return this.db.prepare(`
551 SELECT * FROM characters
552 WHERE account_id = ?
553 ORDER BY character_id ASC
554 `).all(accountId);
555 }
556
557 getCharacter (characterId)
558 {
559 return this.db.prepare("SELECT * FROM characters WHERE character_id = ?").get(characterId) ?? null;
560 }
561
562 /** All character ids (for world-settings fan-out such as initial quests). */
563 listAllCharacterIds ()
564 {
565 return this.db.prepare("SELECT character_id FROM characters").all()
566 .map((row) => row.character_id | 0)
567 .filter((id) => id > 0);
568 }
569
570 findSurnameClaim (surnameNormalized)
571 {
572 return this.db.prepare("SELECT * FROM surname_claims WHERE surname_normalized = ?").get(surnameNormalized) ?? null;
573 }
574
575 createCharacter (accountId, firstName, lastName, sex, tileX, tileY, hair = null, starterSettings = null, creationClothing = null)
576 {
577 const firstNormalized = normalizeName(firstName);
578 const lastNormalized = normalizeName(lastName);
579 const hairStyle = hair?.style ?? null;
580 const hairHue = Number(hair?.hue) || 30;
581 const hairSaturation = Number(hair?.saturation);
582 const hairDarkness = Number(hair?.darkness);
583 this.db.exec("BEGIN");
584 try
585 {
586 this.db.prepare(`
587 INSERT INTO characters (
588 account_id, first_name, last_name, first_normalized, last_normalized, sex, tile_x, tile_y,
589 dimension_id, hair_style, hair_hue, hair_saturation, hair_darkness
590 ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, 'overworld', ?, ?, ?, ?)
591 `).run(
592 accountId,
593 firstName,
594 lastName,
595 firstNormalized,
596 lastNormalized,
597 sex,
598 tileX,
599 tileY,
600 hairStyle,
601 hairHue,
602 Number.isFinite(hairSaturation) ? hairSaturation : 0.55,
603 Number.isFinite(hairDarkness) ? hairDarkness : 0.45
604 );
605 const characterId = Number(this.db.prepare("SELECT last_insert_rowid() AS id").get().id);
606
607 const claim = this.findSurnameClaim(lastNormalized);
608 if (!claim)
609 {
610 this.db.prepare("INSERT INTO surname_claims (surname_normalized, account_id) VALUES (?, ?)").run(
611 lastNormalized,
612 accountId
613 );
614 }
615
616 this.db.exec("COMMIT");
617 this.#ensureBag(characterId, starterSettings, creationClothing);
618 return this.getCharacter(characterId);
619 }
620 catch (error)
621 {
622 this.db.exec("ROLLBACK");
623 throw error;
624 }
625 }
626
627 updateCharacterHair (characterId, { style, hue, saturation, darkness })
628 {
629 this.db.prepare(`
630 UPDATE characters
631 SET hair_style = ?, hair_hue = ?, hair_saturation = ?, hair_darkness = ?
632 WHERE character_id = ?
633 `).run(
634 style ?? null,
635 Number(hue) || 30,
636 Number.isFinite(Number(saturation)) ? Number(saturation) : 0.55,
637 Number.isFinite(Number(darkness)) ? Number(darkness) : 0.45,
638 characterId | 0
639 );
640 return this.getCharacter(characterId);
641 }
642
643 scheduleDeletion (characterId, at)
644 {
645 this.db.prepare("UPDATE characters SET deletion_scheduled_at = ? WHERE character_id = ?").run(at, characterId);
646 }
647
648 cancelDeletion (characterId)
649 {
650 this.db.prepare("UPDATE characters SET deletion_scheduled_at = NULL WHERE character_id = ?").run(characterId);
651 }
652
653 deleteCharacter (characterId)
654 {
655 const character = this.getCharacter(characterId);
656 if (!character)
657 { return; }
658
659 this.db.exec("BEGIN");
660 try
661 {
662 this.#moveGoodsToInheritance(character);
663 this.db.prepare("DELETE FROM character_bags WHERE character_id = ?").run(characterId);
664 this.db.prepare("DELETE FROM characters WHERE character_id = ?").run(characterId);
665 this.db.prepare("DELETE FROM character_bounties WHERE character_id = ?").run(characterId);
666 // Account friendships persist; only clear legacy character rows if any remain.
667 this.db.prepare("DELETE FROM friend_requests WHERE from_character_id = ? OR to_character_id = ?").run(
668 characterId,
669 characterId
670 );
671 this.db.prepare("DELETE FROM friendships WHERE character_id_a = ? OR character_id_b = ?").run(
672 characterId,
673 characterId
674 );
675 const remaining = this.db.prepare(`
676 SELECT COUNT(*) AS count FROM characters
677 WHERE account_id = ? AND last_normalized = ?
678 `).get(character.account_id, character.last_normalized);
679 if (!remaining.count)
680 {
681 this.db.prepare("DELETE FROM surname_claims WHERE surname_normalized = ? AND account_id = ?").run(
682 character.last_normalized,
683 character.account_id
684 );
685 }
686 this.db.exec("COMMIT");
687 }
688 catch (error)
689 {
690 this.db.exec("ROLLBACK");
691 throw error;
692 }
693 }
694
695 saveCharacterPosition (characterId, tileX, tileY, gait, dimensionId = "overworld")
696 {
697 this.db.prepare(`
698 UPDATE characters SET tile_x = ?, tile_y = ?, gait = ?, dimension_id = ?
699 WHERE character_id = ?
700 `).run(
701 tileX,
702 tileY,
703 gait,
704 String(dimensionId ?? "overworld"),
705 characterId
706 );
707 }
708
709 getCharacterRespawnAltar (characterId)
710 {
711 const row = this.db.prepare(`
712 SELECT respawn_altar_x, respawn_altar_y, respawn_altar_dimension_id
713 FROM characters WHERE character_id = ?
714 `).get(characterId | 0);
715 if (!row || row.respawn_altar_x == null || row.respawn_altar_y == null)
716 { return null; }
717 return {
718 tileX: row.respawn_altar_x | 0,
719 tileY: row.respawn_altar_y | 0,
720 dimensionId: String(row.respawn_altar_dimension_id ?? "overworld")
721 };
722 }
723
724 setCharacterRespawnAltar (characterId, tileX, tileY, dimensionId = "overworld")
725 {
726 this.db.prepare(`
727 UPDATE characters
728 SET respawn_altar_x = ?, respawn_altar_y = ?, respawn_altar_dimension_id = ?
729 WHERE character_id = ?
730 `).run(tileX | 0, tileY | 0, String(dimensionId ?? "overworld"), characterId | 0);
731 }
732
733 markDimensionVisited (characterId, dimensionId, now = Date.now())
734 {
735 const dim = String(dimensionId ?? "overworld");
736 this.db.prepare(`
737 INSERT INTO character_visited_dimensions (character_id, dimension_id, first_visited_at)
738 VALUES (?, ?, ?)
739 ON CONFLICT(character_id, dimension_id) DO NOTHING
740 `).run(characterId | 0, dim, now);
741 }
742
743 hasVisitedDimension (characterId, dimensionId)
744 {
745 const row = this.db.prepare(`
746 SELECT 1 AS ok FROM character_visited_dimensions
747 WHERE character_id = ? AND dimension_id = ?
748 `).get(characterId | 0, String(dimensionId ?? "overworld"));
749 return !!row;
750 }
751
752 listVisitedDimensions (characterId)
753 {
754 return this.db.prepare(`
755 SELECT dimension_id, first_visited_at
756 FROM character_visited_dimensions
757 WHERE character_id = ?
758 ORDER BY first_visited_at ASC
759 `).all(characterId | 0).map((row) => ({
760 dimensionId: row.dimension_id,
761 firstVisitedAt: row.first_visited_at
762 }));
763 }
764
765 saveCharacterHealth (characterId, current)
766 {
767 this.db.prepare("UPDATE characters SET health_current = ? WHERE character_id = ?").run(
768 Math.max(0, current | 0),
769 characterId
770 );
771 }
772
773 setCharacterDead (characterId, isDead)
774 {
775 this.db.prepare("UPDATE characters SET is_dead = ? WHERE character_id = ?").run(
776 isDead ? 1 : 0,
777 characterId
778 );
779 }
780
781 listDueDeletions (now)
782 {
783 return this.db.prepare(`
784 SELECT * FROM characters
785 WHERE deletion_scheduled_at IS NOT NULL AND deletion_scheduled_at <= ?
786 `).all(now);
787 }
788
789 getCharacterByName (firstName, lastName)
790 {
791 return this.db.prepare(`
792 SELECT * FROM characters
793 WHERE first_normalized = ? AND last_normalized = ?
794 `).get(normalizeName(firstName), normalizeName(lastName)) ?? null;
795 }
796
797 /**
798 * Admin gift search: match first name, last name, "first last", or account username.
799 * @param {string} query
800 * @param {number} [limit]
801 */
802 searchCharactersForGift (query, limit = 40)
803 {
804 const raw = String(query ?? "").trim();
805 if (!raw)
806 { return []; }
807 const cap = Math.min(100, Math.max(1, limit | 0 || 40));
808 const needle = `%${normalizeName(raw).replace(/%/g, "")}%`;
809 const parts = raw.split(/\s+/u).filter(Boolean);
810 const firstPart = parts[0] ? normalizeName(parts[0]) : "";
811 const lastPart = parts.length >= 2 ? normalizeName(parts.slice(1).join(" ")) : "";
812
813 if (parts.length >= 2 && firstPart && lastPart)
814 {
815 return this.db.prepare(`
816 SELECT
817 c.character_id,
818 c.first_name,
819 c.last_name,
820 c.account_id,
821 a.username AS account_username
822 FROM characters c
823 LEFT JOIN accounts a ON a.account_id = c.account_id
824 WHERE (c.first_normalized = ? AND c.last_normalized = ?)
825 OR c.first_normalized LIKE ?
826 OR c.last_normalized LIKE ?
827 OR lower(COALESCE(a.username, '')) LIKE ?
828 OR (c.first_normalized || ' ' || c.last_normalized) LIKE ?
829 ORDER BY c.last_normalized ASC, c.first_normalized ASC, c.character_id ASC
830 LIMIT ?
831 `).all(firstPart, lastPart, needle, needle, needle, needle, cap);
832 }
833
834 return this.db.prepare(`
835 SELECT
836 c.character_id,
837 c.first_name,
838 c.last_name,
839 c.account_id,
840 a.username AS account_username
841 FROM characters c
842 LEFT JOIN accounts a ON a.account_id = c.account_id
843 WHERE c.first_normalized LIKE ?
844 OR c.last_normalized LIKE ?
845 OR lower(COALESCE(a.username, '')) LIKE ?
846 OR (c.first_normalized || ' ' || c.last_normalized) LIKE ?
847 ORDER BY c.last_normalized ASC, c.first_normalized ASC, c.character_id ASC
848 LIMIT ?
849 `).all(needle, needle, needle, needle, cap);
850 }
851
852 getCharacterBounty (characterId, now = Date.now())
853 {
854 return this.applyCharacterBountyDecay(characterId, now);
855 }
856
857 /**
858 * Daily −1 bounty decay (lazy). First touch after migration stamps today without retroactive decay.
859 * Never moves `last_decay_day` backward (simulation clocks in tests can be epoch-relative).
860 */
861 applyCharacterBountyDecay (characterId, now = Date.now())
862 {
863 const id = characterId | 0;
864 const row = this.db.prepare(`
865 SELECT amount, last_decay_day FROM character_bounties WHERE character_id = ?
866 `).get(id);
867 if (!row)
868 { return 0; }
869 const day = bountyDecayDayKey(now);
870 let amount = Math.max(0, row.amount | 0);
871 const last = row.last_decay_day ? String(row.last_decay_day) : "";
872 if (!last)
873 {
874 this.db.prepare(`
875 UPDATE character_bounties SET last_decay_day = ? WHERE character_id = ?
876 `).run(day, id);
877 return amount;
878 }
879 if (last === day)
880 { return amount; }
881 const days = bountyDecayDaysBetween(last, day);
882 if (days <= 0)
883 {
884 // `now` is on/before the stamped day (clock skew / harness) — leave the stamp alone.
885 return amount;
886 }
887 amount = applyBountyDailyDecay(amount, days);
888 this.db.prepare(`
889 UPDATE character_bounties SET amount = ?, last_decay_day = ? WHERE character_id = ?
890 `).run(amount, day, id);
891 return amount;
892 }
893
894 /** Add coins to a bounty; returns the new total. */
895 addCharacterBounty (characterId, amount, now = Date.now())
896 {
897 const id = characterId | 0;
898 const add = Math.max(0, amount | 0);
899 if (add <= 0)
900 { return this.getCharacterBounty(id, now); }
901 const day = bountyDecayDayKey(now);
902 this.applyCharacterBountyDecay(id, now);
903 this.db.prepare(`
904 INSERT INTO character_bounties (character_id, amount, last_decay_day) VALUES (?, ?, ?)
905 ON CONFLICT(character_id) DO UPDATE SET amount = amount + excluded.amount
906 `).run(id, add, day);
907 return this.getCharacterBounty(id, now);
908 }
909
910 /** Reduce bounty by up to `amount`; returns the new total. */
911 reduceCharacterBounty (characterId, amount, now = Date.now())
912 {
913 const id = characterId | 0;
914 const cut = Math.max(0, amount | 0);
915 const current = this.getCharacterBounty(id, now);
916 if (cut <= 0)
917 { return current; }
918 const next = Math.max(0, current - cut);
919 const day = bountyDecayDayKey(now);
920 this.db.prepare(`
921 INSERT INTO character_bounties (character_id, amount, last_decay_day) VALUES (?, ?, ?)
922 ON CONFLICT(character_id) DO UPDATE SET amount = excluded.amount
923 `).run(id, next, day);
924 return next;
925 }
926
927 /** Zero out and return the previous bounty amount. */
928 takeCharacterBounty (characterId, now = Date.now())
929 {
930 const id = characterId | 0;
931 const amount = this.getCharacterBounty(id, now);
932 if (amount <= 0)
933 { return 0; }
934 const day = bountyDecayDayKey(now);
935 this.db.prepare(`
936 INSERT INTO character_bounties (character_id, amount, last_decay_day) VALUES (?, 0, ?)
937 ON CONFLICT(character_id) DO UPDATE SET amount = 0
938 `).run(id, day);
939 return amount;
940 }
941
942 getQuestState (characterId, questId)
943 {
944 const row = this.db.prepare(`
945 SELECT state_value, progress_blob, started_at, completed_at
946 FROM character_quest_state
947 WHERE character_id = ? AND quest_id = ?
948 `).get(characterId | 0, String(questId));
949 if (!row)
950 { return { state: "not-started", progress: {}, startedAt: null, completedAt: null }; }
951 const progress = JSON.parse(row.progress_blob || "{}");
952 let state = row.state_value;
953 if (state !== "not-started" && state !== "completed")
954 { state = Number(state) | 0; }
955 return {
956 state,
957 progress,
958 startedAt: row.started_at ?? null,
959 completedAt: row.completed_at ?? null
960 };
961 }
962
963 listQuestStates (characterId)
964 {
965 return this.db.prepare(`
966 SELECT quest_id, state_value, progress_blob, started_at, completed_at
967 FROM character_quest_state
968 WHERE character_id = ?
969 `).all(characterId | 0).map((row) =>
970 {
971 let state = row.state_value;
972 if (state !== "not-started" && state !== "completed")
973 { state = Number(state) | 0; }
974 return {
975 questId: row.quest_id,
976 state,
977 progress: JSON.parse(row.progress_blob || "{}"),
978 startedAt: row.started_at ?? null,
979 completedAt: row.completed_at ?? null
980 };
981 });
982 }
983
984 saveQuestState (characterId, questId, state, progress = {}, startedAt = null, completedAt = null)
985 {
986 const stateValue = state === "not-started" || state === "completed" ? state : String(state | 0);
987 this.db.prepare(`
988 INSERT INTO character_quest_state
989 (character_id, quest_id, state_value, progress_blob, started_at, completed_at)
990 VALUES (?, ?, ?, ?, ?, ?)
991 ON CONFLICT(character_id, quest_id) DO UPDATE SET
992 state_value = excluded.state_value,
993 progress_blob = excluded.progress_blob,
994 started_at = excluded.started_at,
995 completed_at = excluded.completed_at
996 `).run(
997 characterId | 0,
998 String(questId),
999 stateValue,
1000 JSON.stringify(progress ?? {}),
1001 startedAt,
1002 completedAt
1003 );
1004 }
1005
1006 isDialogueHeard (characterId, dialogueId, stepId)
1007 {
1008 const row = this.db.prepare(`
1009 SELECT 1 FROM character_dialogue_heard
1010 WHERE character_id = ? AND dialogue_id = ? AND step_id = ?
1011 `).get(characterId | 0, String(dialogueId), String(stepId));
1012 return !!row;
1013 }
1014
1015 markDialogueHeard (characterId, dialogueId, stepId)
1016 {
1017 this.db.prepare(`
1018 INSERT OR IGNORE INTO character_dialogue_heard
1019 (character_id, dialogue_id, step_id, heard_at)
1020 VALUES (?, ?, ?, ?)
1021 `).run(characterId | 0, String(dialogueId), String(stepId), Date.now());
1022 }
1023
1024 listDialogueHeard (characterId)
1025 {
1026 return this.db.prepare(`
1027 SELECT dialogue_id, step_id, heard_at
1028 FROM character_dialogue_heard
1029 WHERE character_id = ?
1030 `).all(characterId | 0);
1031 }
1032
1033 isDialogueTriggerLatched (characterId, dialogueId, triggerId)
1034 {
1035 const row = this.db.prepare(`
1036 SELECT 1 FROM character_dialogue_triggers
1037 WHERE character_id = ? AND dialogue_id = ? AND trigger_id = ?
1038 `).get(characterId | 0, String(dialogueId), String(triggerId));
1039 return !!row;
1040 }
1041
1042 latchDialogueTrigger (characterId, dialogueId, triggerId)
1043 {
1044 this.db.prepare(`
1045 INSERT OR IGNORE INTO character_dialogue_triggers
1046 (character_id, dialogue_id, trigger_id, latched_at)
1047 VALUES (?, ?, ?, ?)
1048 `).run(characterId | 0, String(dialogueId), String(triggerId), Date.now());
1049 }
1050
1051 listDialogueTriggers (characterId)
1052 {
1053 return this.db.prepare(`
1054 SELECT dialogue_id, trigger_id, latched_at
1055 FROM character_dialogue_triggers
1056 WHERE character_id = ?
1057 `).all(characterId | 0);
1058 }
1059
1060 appendQuestJournal (characterId, questId, stepId, text)
1061 {
1062 const trimmed = String(text ?? "").trim();
1063 if (!trimmed)
1064 { return null; }
1065 const writtenAt = Date.now();
1066 const result = this.db.prepare(`
1067 INSERT INTO character_quest_journal
1068 (character_id, quest_id, step_id, text, written_at)
1069 VALUES (?, ?, ?, ?, ?)
1070 `).run(characterId | 0, String(questId), String(stepId), trimmed, writtenAt);
1071 return {
1072 entryId: Number(result.lastInsertRowid),
1073 questId: String(questId),
1074 stepId: String(stepId),
1075 text: trimmed,
1076 writtenAt
1077 };
1078 }
1079
1080 listQuestJournal (characterId, questId = null)
1081 {
1082 if (questId)
1083 {
1084 return this.db.prepare(`
1085 SELECT entry_id, quest_id, step_id, text, written_at
1086 FROM character_quest_journal
1087 WHERE character_id = ? AND quest_id = ?
1088 ORDER BY written_at ASC, entry_id ASC
1089 `).all(characterId | 0, String(questId));
1090 }
1091 return this.db.prepare(`
1092 SELECT entry_id, quest_id, step_id, text, written_at
1093 FROM character_quest_journal
1094 WHERE character_id = ?
1095 ORDER BY written_at ASC, entry_id ASC
1096 `).all(characterId | 0);
1097 }
1098
1099 listFriendRecords (characterId)
1100 {
1101 return this.listAccountFriendRecords(this.accountIdOfCharacter(characterId));
1102 }
1103
1104 accountIdOfCharacter (characterId)
1105 {
1106 const row = this.getCharacter(characterId);
1107 return row?.account_id | 0;
1108 }
1109
1110 getAccount (accountId)
1111 {
1112 return this.db.prepare(`
1113 SELECT account_id, auth_subject, username, email, is_admin
1114 FROM accounts WHERE account_id = ?
1115 `).get(accountId | 0) ?? null;
1116 }
1117
1118 accountDisplayName (accountId)
1119 {
1120 const row = this.getAccount(accountId);
1121 if (!row)
1122 { return "Unknown"; }
1123 const name = String(row.username ?? "").trim();
1124 return name || `Account ${row.account_id}`;
1125 }
1126
1127 listAccountFriendRecords (accountId)
1128 {
1129 const id = accountId | 0;
1130 if (!id)
1131 { return []; }
1132 return this.db.prepare(`
1133 SELECT
1134 CASE WHEN account_id_a = ? THEN account_id_b ELSE account_id_a END AS account_id,
1135 created_at
1136 FROM account_friendships
1137 WHERE account_id_a = ? OR account_id_b = ?
1138 ORDER BY created_at ASC
1139 `).all(id, id, id);
1140 }
1141
1142 areAccountFriends (accountId, otherAccountId)
1143 {
1144 const aId = accountId | 0;
1145 const bId = otherAccountId | 0;
1146 if (!aId || !bId)
1147 { return false; }
1148 if (aId === bId)
1149 { return true; }
1150 const [a, b] = pairIds(aId, bId);
1151 return !!this.db.prepare(`
1152 SELECT 1 FROM account_friendships WHERE account_id_a = ? AND account_id_b = ?
1153 `).get(a, b);
1154 }
1155
1156 areFriends (characterId, otherId)
1157 {
1158 const left = this.getCharacter(characterId);
1159 const right = this.getCharacter(otherId);
1160 if (!left || !right)
1161 { return false; }
1162 return this.areAccountFriends(left.account_id, right.account_id);
1163 }
1164
1165 insertAccountFriendship (accountId, otherId)
1166 {
1167 const [a, b] = pairIds(accountId, otherId);
1168 this.db.prepare(`
1169 INSERT OR IGNORE INTO account_friendships (account_id_a, account_id_b, created_at)
1170 VALUES (?, ?, ?)
1171 `).run(a, b, Date.now());
1172 }
1173
1174 insertFriendship (characterId, otherId)
1175 {
1176 const left = this.getCharacter(characterId);
1177 const right = this.getCharacter(otherId);
1178 if (!left || !right)
1179 { return; }
1180 this.insertAccountFriendship(left.account_id, right.account_id);
1181 }
1182
1183 deleteAccountFriendship (accountId, otherId)
1184 {
1185 const [a, b] = pairIds(accountId, otherId);
1186 this.db.prepare(`
1187 DELETE FROM account_friendships WHERE account_id_a = ? AND account_id_b = ?
1188 `).run(a, b);
1189 }
1190
1191 deleteFriendship (characterId, otherId)
1192 {
1193 const left = this.getCharacter(characterId);
1194 const right = this.getCharacter(otherId);
1195 if (!left || !right)
1196 { return; }
1197 this.deleteAccountFriendship(left.account_id, right.account_id);
1198 }
1199
1200 listIncomingAccountRequests (accountId)
1201 {
1202 return this.db.prepare(`
1203 SELECT request_id, from_account_id, to_account_id, created_at
1204 FROM account_friend_requests
1205 WHERE to_account_id = ?
1206 ORDER BY created_at ASC
1207 `).all(accountId | 0);
1208 }
1209
1210 listOutgoingAccountRequests (accountId)
1211 {
1212 return this.db.prepare(`
1213 SELECT request_id, from_account_id, to_account_id, created_at
1214 FROM account_friend_requests
1215 WHERE from_account_id = ?
1216 ORDER BY created_at ASC
1217 `).all(accountId | 0);
1218 }
1219
1220 listIncomingRequests (characterId)
1221 {
1222 return this.listIncomingAccountRequests(this.accountIdOfCharacter(characterId));
1223 }
1224
1225 listOutgoingRequests (characterId)
1226 {
1227 return this.listOutgoingAccountRequests(this.accountIdOfCharacter(characterId));
1228 }
1229
1230 getAccountFriendRequest (fromAccountId, toAccountId)
1231 {
1232 return this.db.prepare(`
1233 SELECT * FROM account_friend_requests
1234 WHERE from_account_id = ? AND to_account_id = ?
1235 `).get(fromAccountId | 0, toAccountId | 0) ?? null;
1236 }
1237
1238 getFriendRequest (fromId, toId)
1239 {
1240 const from = this.getCharacter(fromId);
1241 const to = this.getCharacter(toId);
1242 if (!from || !to)
1243 { return null; }
1244 return this.getAccountFriendRequest(from.account_id, to.account_id);
1245 }
1246
1247 insertAccountFriendRequest (fromAccountId, toAccountId)
1248 {
1249 this.db.prepare(`
1250 INSERT INTO account_friend_requests (from_account_id, to_account_id, created_at)
1251 VALUES (?, ?, ?)
1252 `).run(fromAccountId | 0, toAccountId | 0, Date.now());
1253 }
1254
1255 insertFriendRequest (fromId, toId)
1256 {
1257 const from = this.getCharacter(fromId);
1258 const to = this.getCharacter(toId);
1259 if (!from || !to)
1260 { return; }
1261 this.insertAccountFriendRequest(from.account_id, to.account_id);
1262 }
1263
1264 deleteAccountFriendRequest (fromAccountId, toAccountId)
1265 {
1266 this.db.prepare(`
1267 DELETE FROM account_friend_requests
1268 WHERE from_account_id = ? AND to_account_id = ?
1269 `).run(fromAccountId | 0, toAccountId | 0);
1270 }
1271
1272 deleteFriendRequest (fromId, toId)
1273 {
1274 const from = this.getCharacter(fromId);
1275 const to = this.getCharacter(toId);
1276 if (!from || !to)
1277 { return; }
1278 this.deleteAccountFriendRequest(from.account_id, to.account_id);
1279 }
1280
1281 /** Decayed kill counter at `now` (does not write). */
1282 peekKillCounter (characterId, now = Date.now())
1283 {
1284 const row = this.getCharacter(characterId);
1285 if (!row)
1286 { return 0; }
1287 const current = Math.max(0, Number(row.kill_counter) || 0);
1288 const at = row.kill_counter_at | 0;
1289 if (!(current > 0) || !at || now <= at)
1290 { return current; }
1291 return decayKillCounter(current, now - at).killCounter;
1292 }
1293
1294 getKillCounterState (characterId)
1295 {
1296 const row = this.getCharacter(characterId);
1297 if (!row)
1298 { return { killCounter: 0, updatedAt: Date.now() }; }
1299 return {
1300 killCounter: Math.max(0, Number(row.kill_counter) || 0),
1301 updatedAt: row.kill_counter_at | 0 || Date.now()
1302 };
1303 }
1304
1305 setKillCounter (characterId, killCounter, updatedAt = Date.now())
1306 {
1307 const value = Math.max(0, Number(killCounter) || 0);
1308 this.db.prepare(`
1309 UPDATE characters SET kill_counter = ?, kill_counter_at = ? WHERE character_id = ?
1310 `).run(value, updatedAt | 0, characterId | 0);
1311 return value;
1312 }
1313
1314 addKillCounter (characterId, amount, now = Date.now())
1315 {
1316 const state = this.getKillCounterState(characterId);
1317 const decayed = decayKillCounter(state.killCounter, Math.max(0, now - (state.updatedAt | 0)));
1318 const next = decayed.killCounter + Math.max(0, Number(amount) || 0);
1319 return this.setKillCounter(characterId, next, now);
1320 }
1321
1322 getCowardiceForgivenHour (characterId)
1323 {
1324 const row = this.getCharacter(characterId);
1325 if (!row || row.cowardice_forgiven_hour == null)
1326 { return null; }
1327 return row.cowardice_forgiven_hour | 0;
1328 }
1329
1330 setCowardiceForgivenHour (characterId, hourKey)
1331 {
1332 this.db.prepare(`
1333 UPDATE characters SET cowardice_forgiven_hour = ? WHERE character_id = ?
1334 `).run(hourKey | 0, characterId | 0);
1335 }
1336
1337 listPersistentInRegion (minX, minY, maxX, maxY)
1338 {
1339 return this.db.prepare(`
1340 SELECT entity_id, tile_x, tile_y, components_blob
1341 FROM persistent_entities
1342 WHERE tile_x >= ? AND tile_x <= ? AND tile_y >= ? AND tile_y <= ?
1343 `).all(minX, maxX, minY, maxY);
1344 }
1345
1346 replacePersistentInRegion (minX, minY, maxX, maxY, entities)
1347 {
1348 this.db.exec("BEGIN");
1349 try
1350 {
1351 this.db.prepare(`
1352 DELETE FROM persistent_entities
1353 WHERE tile_x >= ? AND tile_x <= ? AND tile_y >= ? AND tile_y <= ?
1354 `).run(minX, maxX, minY, maxY);
1355 const insert = this.db.prepare(`
1356 INSERT INTO persistent_entities (entity_id, tile_x, tile_y, components_blob)
1357 VALUES (?, ?, ?, ?)
1358 `);
1359 for (const entity of entities)
1360 {
1361 insert.run(
1362 entity.entityId,
1363 entity.tileX,
1364 entity.tileY,
1365 JSON.stringify(entity.payload?.components ?? entity.components)
1366 );
1367 }
1368 this.db.exec("COMMIT");
1369 }
1370 catch (error)
1371 {
1372 this.db.exec("ROLLBACK");
1373 throw error;
1374 }
1375 }
1376
1377 #ensureBag (characterId, starterSettings = null, creationClothing = null)
1378 {
1379 const existing = this.db.prepare("SELECT * FROM character_bags WHERE character_id = ?").get(characterId);
1380 if (existing)
1381 { return parseBag(existing, characterId); }
1382 const contents = buildStarterBagContents(starterSettings, creationClothing);
1383 this.db.prepare(`
1384 INSERT INTO character_bags (
1385 character_id, inventory_blob, equipment_blob, currency, vault_blob, vault_currency, skills_blob
1386 ) VALUES (?, ?, ?, 0, ?, 0, ?)
1387 `).run(
1388 characterId,
1389 JSON.stringify(contents.slots),
1390 JSON.stringify(contents.equipment),
1391 JSON.stringify({ slots: [], reserved: [] }),
1392 JSON.stringify(storedSkillXp(defaultPlayerSkills()))
1393 );
1394 return this.getBag(characterId);
1395 }
1396
1397 getBag (characterId)
1398 {
1399 const row = this.db.prepare("SELECT * FROM character_bags WHERE character_id = ?").get(characterId);
1400 if (row)
1401 { return parseBag(row, characterId); }
1402 if (this.getCharacter(characterId))
1403 { return this.#ensureBag(characterId); }
1404 return null;
1405 }
1406
1407 saveBag (characterId, bag)
1408 {
1409 this.#ensureBag(characterId);
1410 const migrated = migrateBagCoins(bag);
1411 const vault = normalizeVault(
1412 migrated.vaultReserved != null
1413 ? { slots: migrated.vault, reserved: migrated.vaultReserved }
1414 : migrated.vault
1415 );
1416 this.db.prepare(`
1417 UPDATE character_bags
1418 SET inventory_blob = ?, equipment_blob = ?, currency = 0, vault_blob = ?, vault_currency = 0
1419 WHERE character_id = ?
1420 `).run(
1421 JSON.stringify(normalizeInventorySlots(migrated.inventory ?? emptySlots())),
1422 JSON.stringify(migrated.equipment ?? emptyEquipment()),
1423 JSON.stringify({ slots: vault.slots, reserved: vault.reserved }),
1424 characterId
1425 );
1426 }
1427
1428 getSkills (characterId)
1429 {
1430 const row = this.db.prepare("SELECT skills_blob FROM character_bags WHERE character_id = ?").get(characterId);
1431 if (row)
1432 {
1433 const parsed = JSON.parse(row.skills_blob || "{}");
1434 const skills = normalizePlayerSkills(parsed);
1435 // Persist floors (Health ≥ 5, others ≥ 1) for legacy under-leveled rows.
1436 if (this.#skillsBlobNeedsRewrite(parsed, skills))
1437 { this.saveSkills(characterId, skills); }
1438 return skills;
1439 }
1440 if (this.getCharacter(characterId))
1441 {
1442 this.#ensureBag(characterId);
1443 return this.getSkills(characterId);
1444 }
1445 return null;
1446 }
1447
1448 /** True when stored blob is below the default minimum levels and must be rewritten. */
1449 #skillsBlobNeedsRewrite (parsed, normalized)
1450 {
1451 const raw = parsed?.xp && typeof parsed.xp === "object" ? parsed.xp : parsed;
1452 if (!raw || typeof raw !== "object")
1453 { return true; }
1454 for (const skillId of Object.keys(normalized.xp))
1455 {
1456 const stored = Math.max(0, Math.floor(Number(raw[skillId]) || 0));
1457 if (stored < normalized.xp[skillId])
1458 { return true; }
1459 }
1460 return false;
1461 }
1462
1463 saveSkills (characterId, skills)
1464 {
1465 this.#ensureBag(characterId);
1466 const xp = storedSkillXp(skills?.xp ? skills : { xp: skills });
1467 this.db.prepare("UPDATE character_bags SET skills_blob = ? WHERE character_id = ?").run(
1468 JSON.stringify({ xp }),
1469 characterId
1470 );
1471 }
1472
1473 getSpells (characterId)
1474 {
1475 const row = this.db.prepare("SELECT spells_blob FROM character_bags WHERE character_id = ?").get(characterId);
1476 if (row)
1477 {
1478 return normalizePlayerSpells(JSON.parse(row.spells_blob || "{}"));
1479 }
1480 if (this.getCharacter(characterId))
1481 {
1482 this.#ensureBag(characterId);
1483 return this.getSpells(characterId);
1484 }
1485 return null;
1486 }
1487
1488 saveSpells (characterId, spells)
1489 {
1490 this.#ensureBag(characterId);
1491 this.db.prepare("UPDATE character_bags SET spells_blob = ? WHERE character_id = ?").run(
1492 JSON.stringify(storedPlayerSpells(spells)),
1493 characterId
1494 );
1495 }
1496 getInheritance (accountId)
1497 {
1498 const row = this.db.prepare("SELECT * FROM account_inheritance WHERE account_id = ?").get(accountId);
1499 if (!row)
1500 { return { accountId, slots: emptySlots() }; }
1501 return migrateInheritanceCoins({
1502 accountId,
1503 slots: JSON.parse(row.slots_blob),
1504 currency: row.currency
1505 });
1506 }
1507
1508 saveInheritance (accountId, inheritance)
1509 {
1510 const migrated = migrateInheritanceCoins(inheritance);
1511 this.db.prepare(`
1512 INSERT INTO account_inheritance (account_id, slots_blob, currency)
1513 VALUES (?, ?, 0)
1514 ON CONFLICT(account_id) DO UPDATE SET slots_blob = excluded.slots_blob, currency = 0
1515 `).run(accountId, JSON.stringify(migrated.slots ?? emptySlots()));
1516 }
1517
1518 #moveGoodsToInheritance (character)
1519 {
1520 const bag = this.getBag(character.character_id) ?? {
1521 inventory: emptySlots(),
1522 equipment: emptyEquipment(),
1523 vault: [],
1524 vaultReserved: []
1525 };
1526 const inheritance = this.getInheritance(character.account_id);
1527 const vault = normalizeVault(
1528 bag.vaultReserved != null
1529 ? { slots: bag.vault, reserved: bag.vaultReserved }
1530 : bag.vault
1531 );
1532 // Void outstanding cheques issued by this character: reservations return to available vault.
1533 for (const reserved of vault.reserved ?? [])
1534 {
1535 const stack = {
1536 itemId: reserved.itemId,
1537 quantity: reserved.quantity,
1538 origin: reserved.origin ?? null,
1539 instance: reserved.instance ?? null
1540 };
1541 const def = itemDefinition(stack.itemId);
1542 if (!def)
1543 { continue; }
1544 const restored = insertStackGrowable(vault.slots, stack, def);
1545 vault.slots = restored.slots;
1546 }
1547 vault.reserved = [];
1548 const incoming = [
1549 ...(bag.inventory ?? []),
1550 ...Object.values(bag.equipment?.slots ?? {}),
1551 ...(vault.slots ?? [])
1552 ].filter(Boolean);
1553 let slots = inheritance.slots ?? emptySlots();
1554 for (const stack of incoming)
1555 {
1556 const def = itemDefinition(stack.itemId);
1557 if (!def)
1558 { continue; }
1559 const result = insertStack(slots, stack, def);
1560 if (result.ok)
1561 { slots = result.slots; }
1562 else
1563 {
1564 const extra = result.slots;
1565 for (const leftover of extra)
1566 {
1567 if (leftover)
1568 { slots.push(leftover); }
1569 }
1570 slots.push({ ...stack, quantity: result.remainder });
1571 }
1572 }
1573 this.saveInheritance(character.account_id, {
1574 slots: publicSlots(slots)
1575 });
1576 }
1577
1578 nextGroundItemId ()
1579 {
1580 const row = this.db.prepare("SELECT MAX(ground_item_id) AS id FROM ground_items").get();
1581 return (row?.id ?? 0) + 1;
1582 }
1583
1584 listGroundItemsInRegion (minX, minY, maxX, maxY)
1585 {
1586 return this.db.prepare(`
1587 SELECT * FROM ground_items
1588 WHERE tile_x >= ? AND tile_x <= ? AND tile_y >= ? AND tile_y <= ?
1589 `).all(minX, maxX, minY, maxY).map(parseGroundItem);
1590 }
1591
1592 upsertGroundItem (item)
1593 {
1594 this.db.prepare(`
1595 INSERT INTO ground_items (
1596 ground_item_id, tile_x, tile_y, stack_blob, dropped_at, expires_at, source, dropped_by_character_id
1597 ) VALUES (?, ?, ?, ?, ?, ?, ?, ?)
1598 ON CONFLICT(ground_item_id) DO UPDATE SET
1599 tile_x = excluded.tile_x,
1600 tile_y = excluded.tile_y,
1601 stack_blob = excluded.stack_blob,
1602 dropped_at = excluded.dropped_at,
1603 expires_at = excluded.expires_at,
1604 source = excluded.source,
1605 dropped_by_character_id = excluded.dropped_by_character_id
1606 `).run(
1607 item.groundItemId,
1608 item.tileX,
1609 item.tileY,
1610 JSON.stringify(item.stack),
1611 item.droppedAt,
1612 item.expiresAt,
1613 item.source,
1614 item.droppedByCharacterId ?? null
1615 );
1616 }
1617
1618 deleteGroundItem (groundItemId)
1619 {
1620 this.db.prepare("DELETE FROM ground_items WHERE ground_item_id = ?").run(groundItemId);
1621 }
1622
1623 insertCourierTransit (transit)
1624 {
1625 const now = transit.updatedAt ?? Date.now();
1626 const result = this.db.prepare(`
1627 INSERT INTO courier_transits (
1628 sender_character_id, destination_kind, destination_character_id, cargo_blob,
1629 origin_x, origin_y, dest_x, dest_y, traveled, status, entity_id, updated_at, created_at,
1630 vault_character_id
1631 ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
1632 `).run(
1633 transit.senderCharacterId,
1634 transit.destinationKind,
1635 transit.destinationCharacterId ?? null,
1636 JSON.stringify(transit.cargo),
1637 transit.originX,
1638 transit.originY,
1639 transit.destX,
1640 transit.destY,
1641 transit.traveled ?? 0,
1642 transit.status ?? "in_transit",
1643 transit.entityId ?? null,
1644 now,
1645 transit.createdAt ?? now,
1646 transit.vaultCharacterId ?? null
1647 );
1648 return this.getCourierTransit(Number(result.lastInsertRowid));
1649 }
1650
1651 getCourierTransit (courierId)
1652 {
1653 const row = this.db.prepare("SELECT * FROM courier_transits WHERE courier_id = ?").get(courierId);
1654 return row ? parseCourierTransit(row) : null;
1655 }
1656
1657 listActiveCourierTransits ()
1658 {
1659 return this.db.prepare(`
1660 SELECT * FROM courier_transits WHERE status = 'in_transit' ORDER BY courier_id ASC
1661 `).all().map(parseCourierTransit);
1662 }
1663
1664 updateCourierTransit (transit)
1665 {
1666 this.db.prepare(`
1667 UPDATE courier_transits
1668 SET traveled = ?, status = ?, entity_id = ?, updated_at = ?,
1669 origin_x = ?, origin_y = ?, dest_x = ?, dest_y = ?,
1670 destination_kind = ?, destination_character_id = ?, vault_character_id = ?
1671 WHERE courier_id = ?
1672 `).run(
1673 transit.traveled ?? 0,
1674 transit.status,
1675 transit.entityId ?? null,
1676 transit.updatedAt ?? Date.now(),
1677 transit.originX,
1678 transit.originY,
1679 transit.destX,
1680 transit.destY,
1681 transit.destinationKind,
1682 transit.destinationCharacterId ?? null,
1683 transit.vaultCharacterId ?? null,
1684 transit.courierId
1685 );
1686 }
1687
1688 appendBankRestNotice (characterId, entry)
1689 {
1690 const qty = Math.max(1, entry.quantity | 0);
1691 this.db.prepare(`
1692 INSERT INTO bank_rest_notices (character_id, item_id, item_name, quantity, source_name, created_at)
1693 VALUES (?, ?, ?, ?, ?, ?)
1694 `).run(
1695 characterId,
1696 entry.itemId | 0,
1697 String(entry.itemName ?? "Item"),
1698 qty,
1699 String(entry.sourceName ?? "unknown source"),
1700 entry.createdAt ?? Date.now()
1701 );
1702 }
1703
1704 listBankRestNotices (characterId)
1705 {
1706 return this.db.prepare(`
1707 SELECT * FROM bank_rest_notices WHERE character_id = ? ORDER BY notice_id ASC
1708 `).all(characterId).map((row) => ({
1709 noticeId: row.notice_id,
1710 characterId: row.character_id,
1711 itemId: row.item_id,
1712 itemName: row.item_name,
1713 quantity: row.quantity,
1714 sourceName: row.source_name,
1715 createdAt: row.created_at
1716 }));
1717 }
1718
1719 clearBankRestNotices (characterId)
1720 {
1721 this.db.prepare("DELETE FROM bank_rest_notices WHERE character_id = ?").run(characterId);
1722 }
1723
1724 insertHeldCourierDelivery (delivery)
1725 {
1726 const now = delivery.createdAt ?? Date.now();
1727 const result = this.db.prepare(`
1728 INSERT INTO held_courier_deliveries (
1729 character_id, sender_character_id, origin_tile_x, origin_tile_y,
1730 destination_kind, destination_character_id, vault_character_id, cargo_blob, created_at
1731 ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
1732 `).run(
1733 delivery.characterId,
1734 delivery.senderCharacterId,
1735 delivery.originTileX | 0,
1736 delivery.originTileY | 0,
1737 delivery.destinationKind,
1738 delivery.destinationCharacterId ?? null,
1739 delivery.vaultCharacterId ?? null,
1740 JSON.stringify(delivery.cargo),
1741 now
1742 );
1743 return Number(result.lastInsertRowid);
1744 }
1745
1746 listHeldCourierDeliveries (characterId)
1747 {
1748 return this.db.prepare(`
1749 SELECT * FROM held_courier_deliveries WHERE character_id = ? ORDER BY hold_id ASC
1750 `).all(characterId).map(parseHeldCourierDelivery);
1751 }
1752
1753 deleteHeldCourierDelivery (holdId)
1754 {
1755 this.db.prepare("DELETE FROM held_courier_deliveries WHERE hold_id = ?").run(holdId);
1756 }
1757
1758 insertMarketOrder (order)
1759 {
1760 const result = this.db.prepare(`
1761 INSERT INTO market_orders (
1762 character_id, side, item_id, quantity, limit_unit_price,
1763 escrow_coins, escrow_stack_blob, listing_key, created_at, status
1764 ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
1765 `).run(
1766 order.characterId,
1767 order.side,
1768 order.itemId | 0,
1769 order.quantity | 0,
1770 order.limitUnitPrice | 0,
1771 order.escrowCoins | 0 || 0,
1772 order.escrowStack ? JSON.stringify(order.escrowStack) : null,
1773 order.listingKey ?? null,
1774 order.createdAt ?? Date.now(),
1775 order.status ?? "open"
1776 );
1777 return this.getMarketOrder(Number(result.lastInsertRowid));
1778 }
1779
1780 getMarketOrder (orderId)
1781 {
1782 const row = this.db.prepare("SELECT * FROM market_orders WHERE order_id = ?").get(orderId);
1783 return row ? parseMarketOrder(row) : null;
1784 }
1785
1786 updateMarketOrder (order)
1787 {
1788 this.db.prepare(`
1789 UPDATE market_orders
1790 SET quantity = ?, escrow_coins = ?, escrow_stack_blob = ?, status = ?
1791 WHERE order_id = ?
1792 `).run(
1793 order.quantity | 0,
1794 order.escrowCoins | 0 || 0,
1795 order.escrowStack ? JSON.stringify(order.escrowStack) : null,
1796 order.status,
1797 order.orderId
1798 );
1799 return this.getMarketOrder(order.orderId);
1800 }
1801
1802 listOpenMarketOrdersForCharacter (characterId)
1803 {
1804 return this.db.prepare(`
1805 SELECT * FROM market_orders
1806 WHERE character_id = ? AND status = 'open'
1807 ORDER BY created_at ASC, order_id ASC
1808 `).all(characterId).map(parseMarketOrder);
1809 }
1810
1811 listOpenBuyOrdersForItem (itemId, listingKey = null)
1812 {
1813 if (listingKey)
1814 {
1815 return this.db.prepare(`
1816 SELECT * FROM market_orders
1817 WHERE status = 'open' AND side = 'buy' AND item_id = ? AND listing_key = ?
1818 ORDER BY limit_unit_price DESC, created_at ASC, order_id ASC
1819 `).all(itemId | 0, listingKey).map(parseMarketOrder);
1820 }
1821 return this.db.prepare(`
1822 SELECT * FROM market_orders
1823 WHERE status = 'open' AND side = 'buy' AND item_id = ?
1824 AND (listing_key IS NULL OR listing_key = '')
1825 ORDER BY limit_unit_price DESC, created_at ASC, order_id ASC
1826 `).all(itemId | 0).map(parseMarketOrder);
1827 }
1828
1829 listOpenSellOrdersForItem (itemId, listingKey = null)
1830 {
1831 if (listingKey)
1832 {
1833 return this.db.prepare(`
1834 SELECT * FROM market_orders
1835 WHERE status = 'open' AND side = 'sell' AND item_id = ? AND listing_key = ?
1836 ORDER BY limit_unit_price ASC, created_at ASC, order_id ASC
1837 `).all(itemId | 0, listingKey).map(parseMarketOrder);
1838 }
1839 return this.db.prepare(`
1840 SELECT * FROM market_orders
1841 WHERE status = 'open' AND side = 'sell' AND item_id = ?
1842 AND (listing_key IS NULL OR listing_key = '')
1843 ORDER BY limit_unit_price ASC, created_at ASC, order_id ASC
1844 `).all(itemId | 0).map(parseMarketOrder);
1845 }
1846
1847 listExpiredMarketOrders (createdBefore)
1848 {
1849 return this.db.prepare(`
1850 SELECT * FROM market_orders
1851 WHERE status = 'open' AND created_at < ?
1852 ORDER BY created_at ASC, order_id ASC
1853 `).all(createdBefore).map(parseMarketOrder);
1854 }
1855
1856 insertMarketTrade (trade)
1857 {
1858 const result = this.db.prepare(`
1859 INSERT INTO market_trades (
1860 buy_order_id, sell_order_id, item_id, quantity, unit_price,
1861 buyer_character_id, seller_character_id, created_at
1862 ) VALUES (?, ?, ?, ?, ?, ?, ?, ?)
1863 `).run(
1864 trade.buyOrderId,
1865 trade.sellOrderId,
1866 trade.itemId | 0,
1867 trade.quantity | 0,
1868 trade.unitPrice | 0,
1869 trade.buyerCharacterId,
1870 trade.sellerCharacterId,
1871 trade.createdAt ?? Date.now()
1872 );
1873 return Number(result.lastInsertRowid);
1874 }
1875
1876 upsertItemLastSale (sale)
1877 {
1878 this.db.prepare(`
1879 INSERT INTO item_last_sales (item_id, last_trade_price, last_trade_at, price_from)
1880 VALUES (?, ?, ?, ?)
1881 ON CONFLICT(item_id) DO UPDATE SET
1882 last_trade_price = excluded.last_trade_price,
1883 last_trade_at = excluded.last_trade_at,
1884 price_from = excluded.price_from
1885 `).run(
1886 sale.itemId | 0,
1887 sale.lastTradePrice | 0,
1888 sale.lastTradeAt,
1889 Math.round(Number(sale.priceFrom) || 0)
1890 );
1891 }
1892
1893 listItemLastSales ()
1894 {
1895 return this.db.prepare("SELECT * FROM item_last_sales").all().map((row) => ({
1896 itemId: row.item_id,
1897 lastTradePrice: row.last_trade_price,
1898 lastTradeAt: row.last_trade_at,
1899 priceFrom: row.price_from
1900 }));
1901 }
1902
1903 close ()
1904 {
1905 this.db.close();
1906 }
1907}
1908
1909export function normalizeName (value)
1910{
1911 return String(value ?? "").trim().toLocaleLowerCase();
1912}
1913
1914function pairIds (left, right)
1915{
1916 return left < right ? [left, right] : [right, left];
1917}
1918
1919function parseGroundItem (row)
1920{
1921 return {
1922 groundItemId: row.ground_item_id,
1923 tileX: row.tile_x,
1924 tileY: row.tile_y,
1925 stack: JSON.parse(row.stack_blob),
1926 droppedAt: row.dropped_at,
1927 expiresAt: row.expires_at,
1928 source: row.source,
1929 droppedByCharacterId: row.dropped_by_character_id
1930 };
1931}
1932
1933function parseMarketOrder (row)
1934{
1935 return {
1936 orderId: row.order_id,
1937 characterId: row.character_id,
1938 side: row.side,
1939 itemId: row.item_id,
1940 quantity: row.quantity,
1941 limitUnitPrice: row.limit_unit_price,
1942 escrowCoins: row.escrow_coins | 0,
1943 escrowStack: row.escrow_stack_blob ? JSON.parse(row.escrow_stack_blob) : null,
1944 listingKey: row.listing_key ?? null,
1945 createdAt: row.created_at,
1946 status: row.status
1947 };
1948}
1949
1950function bagContainsItem (inventory, equipment, itemId)
1951{
1952 for (const stack of inventory ?? [])
1953 {
1954 if (stack?.itemId === itemId)
1955 { return true; }
1956 }
1957 for (const stack of Object.values(equipment?.slots ?? {}))
1958 {
1959 if (stack?.itemId === itemId)
1960 { return true; }
1961 }
1962 return false;
1963}
1964
1965function parseBag (row, characterId)
1966{
1967 const vault = normalizeVault(JSON.parse(row.vault_blob));
1968 return migrateBagCoins({
1969 characterId,
1970 inventory: normalizeInventorySlots(JSON.parse(row.inventory_blob)),
1971 equipment: JSON.parse(row.equipment_blob),
1972 currency: row.currency,
1973 vault: vault.slots,
1974 vaultReserved: vault.reserved,
1975 vaultCurrency: row.vault_currency
1976 });
1977}
1978
1979function parseCourierTransit (row)
1980{
1981 return {
1982 courierId: row.courier_id,
1983 senderCharacterId: row.sender_character_id,
1984 destinationKind: row.destination_kind,
1985 destinationCharacterId: row.destination_character_id,
1986 vaultCharacterId: row.vault_character_id ?? null,
1987 cargo: JSON.parse(row.cargo_blob),
1988 originX: row.origin_x,
1989 originY: row.origin_y,
1990 destX: row.dest_x,
1991 destY: row.dest_y,
1992 traveled: row.traveled,
1993 status: row.status,
1994 entityId: row.entity_id,
1995 updatedAt: row.updated_at,
1996 createdAt: row.created_at
1997 };
1998}
1999
2000function parseHeldCourierDelivery (row)
2001{
2002 return {
2003 holdId: row.hold_id,
2004 characterId: row.character_id,
2005 senderCharacterId: row.sender_character_id,
2006 originTileX: row.origin_tile_x,
2007 originTileY: row.origin_tile_y,
2008 destinationKind: row.destination_kind,
2009 destinationCharacterId: row.destination_character_id,
2010 vaultCharacterId: row.vault_character_id,
2011 cargo: JSON.parse(row.cargo_blob),
2012 createdAt: row.created_at
2013 };
2014}