generated from nhcarrigan/template
feat: error handling, logging, analytics, OG tags, and sticky sidebar (#44)
## Summary
- Add comprehensive try/catch error handling across all API routes, middleware, and the Hono global error handler, piping every unhandled error to the `@nhcarrigan/logger` service to prevent silent crashes and unhandled Promise rejections
- Add a `logError` utility on the frontend that forwards errors through the overridden `console.error` to the backend telemetry endpoint; apply it to every silent `catch {}` block in the game context, sound, notification, and clipboard utilities, and wrap the React tree in an `ErrorBoundary`
- Add Plausible analytics, Open Graph + Twitter Card meta tags, Tree-Nation widget, and Google Ads to `index.html`
- Make the game sidebar sticky with a `--resource-bar-height` CSS custom property offset so it stays viewport-height without overlapping the resource bar; reset sticky behaviour in the mobile responsive override
## Test plan
- [ ] Lint passes: `pnpm lint`
- [ ] Build passes: `pnpm build`
- [ ] Verify errors thrown in API routes appear in the logger service rather than crashing the process
- [ ] Verify frontend errors appear in the `/api/fe/error` backend log
- [ ] Verify Open Graph tags render correctly when sharing the URL
- [ ] Verify Plausible analytics fires on page load
- [ ] Verify Tree-Nation badge renders in the sidebar
- [ ] Verify sidebar stays fixed while the main content scrolls on desktop
- [ ] Verify mobile layout is unaffected
✨ This issue was created with help from Hikari~ 🌸
Reviewed-on: #44
Co-authored-by: Hikari <hikari@nhcarrigan.com>
Co-committed-by: Hikari <hikari@nhcarrigan.com>
This commit was merged in pull request #44.
This commit is contained in:
+192
-163
@@ -6,11 +6,13 @@
|
||||
*/
|
||||
/* eslint-disable max-lines-per-function -- Route handlers require many steps */
|
||||
/* eslint-disable max-statements -- Route handlers require many statements */
|
||||
/* eslint-disable complexity -- Route handlers have inherent complexity */
|
||||
import { Hono } from "hono";
|
||||
import { defaultPrestigeUpgrades } from "../data/prestigeUpgrades.js";
|
||||
import { prisma } from "../db/client.js";
|
||||
import { authMiddleware } from "../middleware/auth.js";
|
||||
import { updateChallengeProgress } from "../services/dailyChallenges.js";
|
||||
import { logger } from "../services/logger.js";
|
||||
import {
|
||||
buildPostPrestigeState,
|
||||
computeRunestoneMultipliers,
|
||||
@@ -25,190 +27,217 @@ const prestigeRouter = new Hono<HonoEnvironment>();
|
||||
prestigeRouter.use("*", authMiddleware);
|
||||
|
||||
prestigeRouter.post("/", async(context) => {
|
||||
const discordId = context.get("discordId");
|
||||
try {
|
||||
const discordId = context.get("discordId");
|
||||
|
||||
const record = await prisma.gameState.findUnique({ where: { discordId } });
|
||||
const record = await prisma.gameState.findUnique({ where: { discordId } });
|
||||
|
||||
if (!record) {
|
||||
return context.json({ error: "No save found" }, 404);
|
||||
}
|
||||
if (!record) {
|
||||
return context.json({ error: "No save found" }, 404);
|
||||
}
|
||||
|
||||
/* eslint-disable-next-line @typescript-eslint/consistent-type-assertions -- Prisma returns JsonValue */
|
||||
const state = record.state as unknown as GameState;
|
||||
/* eslint-disable-next-line @typescript-eslint/consistent-type-assertions -- Prisma returns JsonValue */
|
||||
const state = record.state as unknown as GameState;
|
||||
|
||||
if (!isEligibleForPrestige(state)) {
|
||||
return context.json(
|
||||
{
|
||||
error: "Not eligible for prestige — collect 1,000,000 total gold first",
|
||||
if (!isEligibleForPrestige(state)) {
|
||||
return context.json(
|
||||
{
|
||||
// eslint-disable-next-line stylistic/max-len -- Error message cannot be shortened
|
||||
error: "Not eligible for prestige — collect 1,000,000 total gold first",
|
||||
},
|
||||
400,
|
||||
);
|
||||
}
|
||||
|
||||
// Update daily prestige challenge progress before resetting the run
|
||||
let updatedDailyChallenges = state.dailyChallenges;
|
||||
let challengeCrystals = 0;
|
||||
if (updatedDailyChallenges) {
|
||||
const result = updateChallengeProgress(
|
||||
updatedDailyChallenges,
|
||||
"prestige",
|
||||
1,
|
||||
);
|
||||
updatedDailyChallenges = result.updatedChallenges;
|
||||
challengeCrystals = result.crystalsAwarded;
|
||||
}
|
||||
|
||||
const {
|
||||
milestoneRunestones,
|
||||
prestigeData,
|
||||
prestigeState,
|
||||
runestonesEarned,
|
||||
} = buildPostPrestigeState(state, state.player.characterName);
|
||||
|
||||
// Preserve daily challenges across the prestige reset and apply any crystal rewards
|
||||
const finalState: GameState = {
|
||||
...prestigeState,
|
||||
...updatedDailyChallenges === undefined
|
||||
? {}
|
||||
: { dailyChallenges: updatedDailyChallenges },
|
||||
resources: {
|
||||
...prestigeState.resources,
|
||||
crystals: prestigeState.resources.crystals + challengeCrystals,
|
||||
},
|
||||
400,
|
||||
);
|
||||
}
|
||||
};
|
||||
|
||||
// Update daily prestige challenge progress before resetting the run
|
||||
let updatedDailyChallenges = state.dailyChallenges;
|
||||
let challengeCrystals = 0;
|
||||
if (updatedDailyChallenges) {
|
||||
const result = updateChallengeProgress(
|
||||
updatedDailyChallenges,
|
||||
// Capture current-run stats to accumulate into lifetime totals before resetting
|
||||
// eslint-disable-next-line capitalized-comments -- v8 ignore
|
||||
/* v8 ignore next 10 -- @preserve */
|
||||
const runBossesDefeated = state.bosses.filter((boss) => {
|
||||
return boss.status === "defeated";
|
||||
}).length;
|
||||
const runQuestsCompleted = state.quests.filter((quest) => {
|
||||
return quest.status === "completed";
|
||||
}).length;
|
||||
let runAdventurersRecruited = 0;
|
||||
for (const adventurer of state.adventurers) {
|
||||
runAdventurersRecruited = runAdventurersRecruited + adventurer.count;
|
||||
}
|
||||
|
||||
// eslint-disable-next-line capitalized-comments -- v8 ignore
|
||||
/* v8 ignore next 3 -- @preserve */
|
||||
const runAchievementsUnlocked = state.achievements.filter((achievement) => {
|
||||
return achievement.unlockedAt !== null;
|
||||
}).length;
|
||||
|
||||
const now = Date.now();
|
||||
await prisma.gameState.update({
|
||||
/* eslint-disable-next-line @typescript-eslint/consistent-type-assertions -- Prisma requires object */
|
||||
data: { state: finalState as object, updatedAt: now },
|
||||
where: { discordId },
|
||||
});
|
||||
|
||||
await prisma.player.update({
|
||||
data: {
|
||||
characterName: state.player.characterName,
|
||||
|
||||
lastSavedAt: now,
|
||||
|
||||
lifetimeAchievementsUnlocked: { increment: runAchievementsUnlocked },
|
||||
|
||||
lifetimeAdventurersRecruited: { increment: runAdventurersRecruited },
|
||||
|
||||
lifetimeBossesDefeated: { increment: runBossesDefeated },
|
||||
|
||||
lifetimeClicks: { increment: state.player.totalClicks },
|
||||
|
||||
// Accumulate into lifetime totals — never reset
|
||||
lifetimeGoldEarned: { increment: state.player.totalGoldEarned },
|
||||
|
||||
lifetimeQuestsCompleted: { increment: runQuestsCompleted },
|
||||
|
||||
totalClicks: 0,
|
||||
// Reset current-run counters
|
||||
totalGoldEarned: 0,
|
||||
},
|
||||
where: { discordId },
|
||||
});
|
||||
|
||||
const prestigeCount = prestigeData.count;
|
||||
void logger.metric("prestige", 1, { discordId, prestigeCount });
|
||||
void postMilestoneWebhook(discordId, "prestige", {
|
||||
// eslint-disable-next-line capitalized-comments -- v8 ignore
|
||||
/* v8 ignore next -- @preserve */
|
||||
apotheosis: prestigeState.apotheosis?.count ?? 0,
|
||||
|
||||
prestige: prestigeData.count,
|
||||
|
||||
// eslint-disable-next-line capitalized-comments -- v8 ignore
|
||||
/* v8 ignore next 2 -- @preserve */
|
||||
transcendence: prestigeState.transcendence?.count ?? 0,
|
||||
});
|
||||
|
||||
return context.json({
|
||||
milestoneRunestones: milestoneRunestones,
|
||||
newPrestigeCount: prestigeData.count, // eslint-disable-line unicorn/no-keyword-prefix -- API response field name required by client
|
||||
runestones: runestonesEarned,
|
||||
});
|
||||
} catch (error) {
|
||||
void logger.error(
|
||||
"prestige",
|
||||
1,
|
||||
error instanceof Error
|
||||
? error
|
||||
: new Error(String(error)),
|
||||
);
|
||||
updatedDailyChallenges = result.updatedChallenges;
|
||||
challengeCrystals = result.crystalsAwarded;
|
||||
return context.json({ error: "Internal server error" }, 500);
|
||||
}
|
||||
|
||||
const {
|
||||
milestoneRunestones,
|
||||
prestigeData,
|
||||
prestigeState,
|
||||
runestonesEarned,
|
||||
} = buildPostPrestigeState(state, state.player.characterName);
|
||||
|
||||
// Preserve daily challenges across the prestige reset and apply any crystal rewards
|
||||
const finalState: GameState = {
|
||||
...prestigeState,
|
||||
...updatedDailyChallenges === undefined
|
||||
? {}
|
||||
: { dailyChallenges: updatedDailyChallenges },
|
||||
resources: {
|
||||
...prestigeState.resources,
|
||||
crystals: prestigeState.resources.crystals + challengeCrystals,
|
||||
},
|
||||
};
|
||||
|
||||
// Capture current-run stats to accumulate into lifetime totals before resetting
|
||||
// eslint-disable-next-line capitalized-comments -- v8 ignore
|
||||
/* v8 ignore next 10 -- @preserve */
|
||||
const runBossesDefeated = state.bosses.filter((boss) => {
|
||||
return boss.status === "defeated";
|
||||
}).length;
|
||||
const runQuestsCompleted = state.quests.filter((quest) => {
|
||||
return quest.status === "completed";
|
||||
}).length;
|
||||
let runAdventurersRecruited = 0;
|
||||
for (const adventurer of state.adventurers) {
|
||||
runAdventurersRecruited = runAdventurersRecruited + adventurer.count;
|
||||
}
|
||||
|
||||
// eslint-disable-next-line capitalized-comments -- v8 ignore
|
||||
/* v8 ignore next 3 -- @preserve */
|
||||
const runAchievementsUnlocked = state.achievements.filter((achievement) => {
|
||||
return achievement.unlockedAt !== null;
|
||||
}).length;
|
||||
|
||||
const now = Date.now();
|
||||
await prisma.gameState.update({
|
||||
/* eslint-disable-next-line @typescript-eslint/consistent-type-assertions -- Prisma requires object */
|
||||
data: { state: finalState as object, updatedAt: now },
|
||||
where: { discordId },
|
||||
});
|
||||
|
||||
await prisma.player.update({
|
||||
data: {
|
||||
characterName: state.player.characterName,
|
||||
|
||||
lastSavedAt: now,
|
||||
|
||||
lifetimeAchievementsUnlocked: { increment: runAchievementsUnlocked },
|
||||
|
||||
lifetimeAdventurersRecruited: { increment: runAdventurersRecruited },
|
||||
|
||||
lifetimeBossesDefeated: { increment: runBossesDefeated },
|
||||
|
||||
lifetimeClicks: { increment: state.player.totalClicks },
|
||||
|
||||
// Accumulate into lifetime totals — never reset
|
||||
lifetimeGoldEarned: { increment: state.player.totalGoldEarned },
|
||||
|
||||
lifetimeQuestsCompleted: { increment: runQuestsCompleted },
|
||||
|
||||
totalClicks: 0,
|
||||
// Reset current-run counters
|
||||
totalGoldEarned: 0,
|
||||
},
|
||||
where: { discordId },
|
||||
});
|
||||
|
||||
void postMilestoneWebhook(discordId, "prestige", {
|
||||
// eslint-disable-next-line capitalized-comments -- v8 ignore
|
||||
/* v8 ignore next -- @preserve */
|
||||
apotheosis: prestigeState.apotheosis?.count ?? 0,
|
||||
|
||||
prestige: prestigeData.count,
|
||||
|
||||
// eslint-disable-next-line capitalized-comments -- v8 ignore
|
||||
/* v8 ignore next 2 -- @preserve */
|
||||
transcendence: prestigeState.transcendence?.count ?? 0,
|
||||
});
|
||||
|
||||
return context.json({
|
||||
milestoneRunestones: milestoneRunestones,
|
||||
newPrestigeCount: prestigeData.count, // eslint-disable-line unicorn/no-keyword-prefix -- API response field name required by client
|
||||
runestones: runestonesEarned,
|
||||
});
|
||||
});
|
||||
|
||||
prestigeRouter.post("/buy-upgrade", async(context) => {
|
||||
const discordId = context.get("discordId");
|
||||
const body = await context.req.json<BuyPrestigeUpgradeRequest>();
|
||||
try {
|
||||
const discordId = context.get("discordId");
|
||||
const body = await context.req.json<BuyPrestigeUpgradeRequest>();
|
||||
|
||||
const { upgradeId } = body;
|
||||
// eslint-disable-next-line @typescript-eslint/strict-boolean-expressions -- Runtime body validation
|
||||
if (!upgradeId) {
|
||||
return context.json({ error: "upgradeId is required" }, 400);
|
||||
}
|
||||
const { upgradeId } = body;
|
||||
// eslint-disable-next-line @typescript-eslint/strict-boolean-expressions -- Runtime body validation
|
||||
if (!upgradeId) {
|
||||
return context.json({ error: "upgradeId is required" }, 400);
|
||||
}
|
||||
|
||||
const upgrade = defaultPrestigeUpgrades.find((prestigeUpgrade) => {
|
||||
return prestigeUpgrade.id === upgradeId;
|
||||
});
|
||||
if (!upgrade) {
|
||||
return context.json({ error: "Unknown prestige upgrade" }, 404);
|
||||
}
|
||||
const upgrade = defaultPrestigeUpgrades.find((prestigeUpgrade) => {
|
||||
return prestigeUpgrade.id === upgradeId;
|
||||
});
|
||||
if (!upgrade) {
|
||||
return context.json({ error: "Unknown prestige upgrade" }, 404);
|
||||
}
|
||||
|
||||
const record = await prisma.gameState.findUnique({ where: { discordId } });
|
||||
if (!record) {
|
||||
return context.json({ error: "No save found" }, 404);
|
||||
}
|
||||
const record = await prisma.gameState.findUnique({ where: { discordId } });
|
||||
if (!record) {
|
||||
return context.json({ error: "No save found" }, 404);
|
||||
}
|
||||
|
||||
/* eslint-disable-next-line @typescript-eslint/consistent-type-assertions -- Prisma returns JsonValue */
|
||||
const state = record.state as unknown as GameState;
|
||||
const { purchasedUpgradeIds, runestones } = state.prestige;
|
||||
/* eslint-disable-next-line @typescript-eslint/consistent-type-assertions -- Prisma returns JsonValue */
|
||||
const state = record.state as unknown as GameState;
|
||||
const { purchasedUpgradeIds, runestones } = state.prestige;
|
||||
|
||||
if (purchasedUpgradeIds.includes(upgradeId)) {
|
||||
return context.json({ error: "Upgrade already purchased" }, 400);
|
||||
}
|
||||
if (purchasedUpgradeIds.includes(upgradeId)) {
|
||||
return context.json({ error: "Upgrade already purchased" }, 400);
|
||||
}
|
||||
|
||||
if (runestones < upgrade.runestonesCost) {
|
||||
return context.json({ error: "Not enough runestones" }, 400);
|
||||
}
|
||||
if (runestones < upgrade.runestonesCost) {
|
||||
return context.json({ error: "Not enough runestones" }, 400);
|
||||
}
|
||||
|
||||
const updatedRunestones = runestones - upgrade.runestonesCost;
|
||||
const updatedPurchasedUpgradeIds = [ ...purchasedUpgradeIds, upgradeId ];
|
||||
const updatedRunestones = runestones - upgrade.runestonesCost;
|
||||
const updatedPurchasedUpgradeIds = [ ...purchasedUpgradeIds, upgradeId ];
|
||||
|
||||
const updatedState: GameState = {
|
||||
...state,
|
||||
prestige: {
|
||||
...state.prestige,
|
||||
const updatedState: GameState = {
|
||||
...state,
|
||||
prestige: {
|
||||
...state.prestige,
|
||||
purchasedUpgradeIds: updatedPurchasedUpgradeIds,
|
||||
runestones: updatedRunestones,
|
||||
...computeRunestoneMultipliers(updatedPurchasedUpgradeIds),
|
||||
},
|
||||
};
|
||||
|
||||
await prisma.gameState.update({
|
||||
/* eslint-disable-next-line @typescript-eslint/consistent-type-assertions -- Prisma requires object */
|
||||
data: { state: updatedState as object, updatedAt: Date.now() },
|
||||
where: { discordId },
|
||||
});
|
||||
|
||||
const multipliers = computeRunestoneMultipliers(updatedPurchasedUpgradeIds);
|
||||
|
||||
void logger.metric("prestige_upgrade_purchased", 1, {
|
||||
discordId,
|
||||
upgradeId,
|
||||
});
|
||||
return context.json({
|
||||
purchasedUpgradeIds: updatedPurchasedUpgradeIds,
|
||||
runestones: updatedRunestones,
|
||||
...computeRunestoneMultipliers(updatedPurchasedUpgradeIds),
|
||||
},
|
||||
};
|
||||
|
||||
await prisma.gameState.update({
|
||||
/* eslint-disable-next-line @typescript-eslint/consistent-type-assertions -- Prisma requires object */
|
||||
data: { state: updatedState as object, updatedAt: Date.now() },
|
||||
where: { discordId },
|
||||
});
|
||||
|
||||
const multipliers = computeRunestoneMultipliers(updatedPurchasedUpgradeIds);
|
||||
|
||||
return context.json({
|
||||
purchasedUpgradeIds: updatedPurchasedUpgradeIds,
|
||||
runestonesRemaining: updatedRunestones,
|
||||
...multipliers,
|
||||
});
|
||||
runestonesRemaining: updatedRunestones,
|
||||
...multipliers,
|
||||
});
|
||||
} catch (error) {
|
||||
void logger.error(
|
||||
"prestige_buy_upgrade",
|
||||
error instanceof Error
|
||||
? error
|
||||
: new Error(String(error)),
|
||||
);
|
||||
return context.json({ error: "Internal server error" }, 500);
|
||||
}
|
||||
});
|
||||
|
||||
export { prestigeRouter };
|
||||
|
||||
Reference in New Issue
Block a user