commit
updates
diff --git a/src/genshin.ts b/src/genshin.ts
index 024cafc..7408082 100644
--- a/src/genshin.ts
+++ b/src/genshin.ts
@@ -21,6 +21,19 @@
* (`showAvatarInfoList`, up to 8) come back — the roster response flags
* this via `partial: true` so callers/UIs can prompt the user to enable it.
*
+ * Persistent ownership ledger (the fourth "tier", and the reason this file
+ * no longer loses data): every character ever seen owned for a UID is
+ * recorded permanently in a NON-expiring KV key (`genshin:owned:<uid>`),
+ * separate from the transient caches above. Ownership is monotonic — once a
+ * character is in the ledger it stays, even after it drops out of Enka
+ * (unpinned from the showcase, "Display all" turned off, profile went
+ * private). Every roster/detail response is the UNION of the live Enka data
+ * and this ledger: live-owned characters are `tracked: true` with a fresh
+ * level; characters known only from the ledger are still `owned: true` but
+ * `tracked: false` with their last-known level. If the live Enka fetch fails
+ * entirely, the ledger alone is served as a `stale: true` response instead of
+ * erroring. This is what stops the API returning partial/no data.
+ *
* Separately: even with "Display all" on, Mihoyo's own API (which Enka
* passes through) only includes full builds (`equipList` — weapon +
* artifacts) for characters currently sitting in the showcase (~8 max).
@@ -60,6 +73,9 @@ const ROSTER_MIN_TTL_SECONDS = 30; // floor under Enka's own ttl, avoids 0/negat
const CATALOG_KEY = "genshin:catalog:v1";
const LOC_KEY = "genshin:loc:v1";
const rawKey = (uid: string) => `genshin:raw:${uid}`;
+/** Persistent per-UID ownership ledger. NO expirationTtl — this key outlives
+ * every cache above and is the source of truth for "has ever been owned". */
+const ledgerKey = (uid: string) => `genshin:owned:${uid}`;
const ELEMENT_NAMES: Record<string, string> = {
Fire: "Pyro",
@@ -81,6 +97,26 @@ const TRAVELER_OVERRIDES: Record<string, { name: string; element: string }> = {
"10000007": { name: "Lumine", element: "All" },
};
+/**
+ * Some characters ship under an internal dev codename that differs from
+ * their public localized name — Enka's catalog can lag behind a reveal (or
+ * never get corrected) and resolve `NameTextMapHash` to the codename
+ * instead. Applied to whatever name the catalog resolves, regardless of
+ * source, so it self-heals once a real `id` override (like
+ * `TRAVELER_OVERRIDES` above) can be added.
+ *
+ * Known case: Sandrone resolves to her Fatui Harbinger codename here.
+ */
+const NAME_ALIASES: Record<string, string> = {
+ Marionette: "Sandrone",
+ MarionetteNew: "Sandrone",
+};
+
+function resolveDisplayName(rawName: string | undefined): string | undefined {
+ if (!rawName) return rawName;
+ return NAME_ALIASES[rawName] ?? rawName;
+}
+
/** appendPropId -> display name, for weapon/artifact stat lines. */
const STAT_NAMES: Record<string, string> = {
FIGHT_PROP_HP: "HP",
@@ -144,14 +180,20 @@ interface RawStat {
appendPropId?: string;
statValue?: number;
}
+/** Artifact main stat has a distinct shape from sub/weapon stats — the id
+ * field is called `mainPropId`, not `appendPropId`. */
+interface RawArtifactMainStat {
+ mainPropId?: string;
+ statValue?: number;
+}
interface RawFlat {
nameTextMapHash?: number | string;
setNameTextMapHash?: number | string;
rankLevel?: number;
icon?: string;
weaponStats?: RawStat[];
- reliquaryMainstat?: RawStat;
- reliquarySubstats?: RawStat[];
+ artifactMainData?: RawArtifactMainStat;
+ reliquarySubStats?: RawStat[];
equipType?: string;
}
interface RawWeaponData {
@@ -333,15 +375,19 @@ async function getUidData(
return { raw, catalog, loc };
}
-function toStat(raw: RawStat | undefined): UnifiedGenshinStat | null {
- if (!raw?.appendPropId) return null;
- const id = raw.appendPropId;
+/** Shared by weapon stats, artifact substats, and (via `statFromId`) the
+ * artifact main stat, which uses a differently-shaped raw field. */
+function statFromId(id: string | undefined, value: number | undefined): UnifiedGenshinStat | null {
+ if (!id) return null;
return {
name: STAT_NAMES[id] ?? id,
- value: raw.statValue ?? 0,
+ value: value ?? 0,
is_percent: PERCENT_STAT_IDS.has(id),
};
}
+function toStat(raw: RawStat | undefined): UnifiedGenshinStat | null {
+ return raw ? statFromId(raw.appendPropId, raw.statValue) : null;
+}
function buildWeapon(equip: RawEquip, loc: RawLoc): UnifiedGenshinWeapon | null {
if (!equip.weapon) return null;
@@ -369,14 +415,134 @@ function buildArtifact(equip: RawEquip, loc: RawLoc): UnifiedGenshinArtifact | n
rarity: equip.flat.rankLevel ?? 1,
// Enka's raw reliquary.level is 1 higher than the in-game "+N" display.
level: Math.max(0, (equip.reliquary.level ?? 1) - 1),
- main_stat: toStat(equip.flat.reliquaryMainstat),
- sub_stats: (equip.flat.reliquarySubstats ?? [])
+ main_stat: statFromId(equip.flat.artifactMainData?.mainPropId, equip.flat.artifactMainData?.statValue),
+ sub_stats: (equip.flat.reliquarySubStats ?? [])
.map((s) => toStat(s))
.filter((s): s is UnifiedGenshinStat => s !== null),
icon_url: equip.flat.icon ? `${ICON_BASE}/${equip.flat.icon}.png` : "",
};
}
+
+// ---- Persistent ownership ledger ----------------------------------------
+//
+// Everything below is the durable, NON-expiring record of what a UID has
+// EVER owned. It's deliberately independent of the Enka/catalog caches above:
+// those answer "what does Enka show right now", this answers "what does this
+// player own, period". The two are unioned when building a response.
+
+/** Don't rewrite the ledger just to bump a `last_seen` more often than this.
+ * Structural changes (a new character, a level-up, a new constellation) still
+ * write immediately; this only throttles no-op "seen again" touches so a
+ * hammered UID doesn't hit KV's per-key write rate limit. */
+const LEDGER_TOUCH_MS = 1000 * 60 * 5;
+
+/** One character's entry in the durable ownership ledger. */
+interface LedgerEntry {
+ /** Highest level ever seen live. */
+ level: number;
+ /** Highest constellation count ever seen live (0 until a detail/constellation
+ * fetch has ever included this character — the roster list alone can't tell). */
+ constellation: number;
+ /** Epoch ms first recorded as owned. */
+ first_seen: number;
+ /** Epoch ms last present in a live Enka response. */
+ last_seen: number;
+}
+
+/** The full durable ledger for one UID. heroId -> entry. */
+interface OwnedLedger {
+ uid: string;
+ updated_at: number;
+ characters: Record<string, LedgerEntry>;
+}
+
+/** One currently-live-owned character, as fed into the ledger. `constellation`
+ * is only known from detail/constellation fetches, not the roster list. */
+interface LiveOwned {
+ id: string;
+ level: number;
+ constellation?: number;
+}
+
+/** Load the durable ledger for a UID, or an empty one if none exists yet. */
+async function loadLedger(env: Env, uid: string): Promise<OwnedLedger> {
+ const stored = (await env.PROFILE_CACHE.get(ledgerKey(uid), "json")) as OwnedLedger | null;
+ if (stored && stored.characters) return stored;
+ return { uid, updated_at: 0, characters: {} };
+}
+
+/** Persist the ledger under its non-expiring key (note: no expirationTtl). */
+async function saveLedger(env: Env, ledger: OwnedLedger, ctx?: ExecutionContext): Promise<void> {
+ const write = env.PROFILE_CACHE.put(ledgerKey(ledger.uid), JSON.stringify(ledger));
+ if (ctx) ctx.waitUntil(write);
+ else await write;
+}
+
+/** Upsert every currently-live-owned character into the ledger. Monotonic:
+ * entries are only ever added or bumped upward, never removed or lowered. In
+ * memory each seen entry's `last_seen` is refreshed to `now`; the boolean
+ * return says whether the change is worth persisting (a new/level-up/const
+ * change, or a `last_seen` that's drifted past LEDGER_TOUCH_MS) so callers can
+ * skip redundant KV writes on plain cache-hit reads. */
+function mergeLedger(ledger: OwnedLedger, live: LiveOwned[], now: number): boolean {
+ let changed = false;
+ for (const c of live) {
+ const existing = ledger.characters[c.id];
+ if (!existing) {
+ ledger.characters[c.id] = {
+ level: c.level,
+ constellation: c.constellation ?? 0,
+ first_seen: now,
+ last_seen: now,
+ };
+ changed = true;
+ continue;
+ }
+ if (c.level > existing.level) {
+ existing.level = c.level;
+ changed = true;
+ }
+ if (c.constellation != null && c.constellation > existing.constellation) {
+ existing.constellation = c.constellation;
+ changed = true;
+ }
+ if (now - existing.last_seen > LEDGER_TOUCH_MS) changed = true;
+ existing.last_seen = now;
+ }
+ if (changed) ledger.updated_at = now;
+ return changed;
+}
+
+/** Build the unified character list as the UNION of the static catalog, the
+ * live-owned levels (empty when serving stale), and the durable ledger.
+ * Ownership = live OR in-ledger; `tracked` = present in the live data. Call
+ * this AFTER mergeLedger so freshly-seen characters already carry a ledger
+ * entry (and thus an accurate `last_seen`). */
+function buildRosterCharacters(
+ catalog: Catalog,
+ ledger: OwnedLedger,
+ liveLevels: Map<string, number>,
+): UnifiedGenshinCharacter[] {
+ const characters = Object.entries(catalog).map(([id, meta]) => {
+ const led = ledger.characters[id];
+ const isLive = liveLevels.has(id);
+ return {
+ id,
+ name: meta.name,
+ element: meta.element,
+ rarity: meta.rarity,
+ icon_url: meta.iconUrl,
+ owned: isLive || !!led,
+ level: isLive ? liveLevels.get(id)! : led ? led.level : null,
+ tracked: isLive,
+ last_seen: led ? led.last_seen : null,
+ };
+ });
+ characters.sort((a, b) => (b.owned === a.owned ? a.name.localeCompare(b.name) : b.owned ? 1 : -1));
+ return characters;
+}
+
/**
* Look up one character's ownership + level, with the same fallback the
* roster builder uses: prefer the full detailed `avatarInfoList` (only
@@ -407,49 +573,79 @@ export async function getGenshinRoster(
ctx?: ExecutionContext,
force = false,
): Promise<UnifiedGenshinRoster> {
- const { raw, catalog } = await getUidData(env, uid, ctx, force);
+ const ledger = await loadLedger(env, uid);
+
+ // Live Enka fetch. If it fails for ANY reason (private profile, unindexed
+ // UID, Enka upstream down) but we've recorded this UID's roster before,
+ // serve the ledger alone rather than erroring — see stale branch below.
+ let raw: EnkaUidResponse;
+ let catalog: Catalog;
+ try {
+ const data = await getUidData(env, uid, ctx, force);
+ raw = data.raw;
+ catalog = data.catalog;
+ } catch (err) {
+ if (Object.keys(ledger.characters).length === 0) throw err; // nothing to fall back to
+ // Catalog is Enka-independent (GitHub + KV); if IT is what failed this
+ // rethrows and the route surfaces the real error.
+ const staleCatalog = await getCatalog(env, ctx);
+ const staleChars = buildRosterCharacters(staleCatalog, ledger, new Map());
+ return {
+ uid,
+ nickname: null,
+ player_level: null,
+ partial: false,
+ stale: true,
+ owned_count: staleChars.filter((c) => c.owned).length,
+ tracked_count: 0, // nothing is live in a stale response
+ total_count: staleChars.length,
+ characters: staleChars,
+ updated_at: ledger.updated_at,
+ };
+ }
// Prefer the full roster (only present if the player enabled "Display all
// your characters"); fall back to the pinned showcase otherwise.
const full = raw.playerInfo.avatarInfoList;
const partial = !full || full.length === 0;
- const owned = new Map<string, number>(); // avatarId -> level
+ const liveLevels = new Map<string, number>(); // avatarId -> level
if (full) {
for (const c of full) {
const level = Number(c.propMap?.["4001"]?.ival ?? 0);
- owned.set(String(c.avatarId), level);
+ liveLevels.set(String(c.avatarId), level);
}
} else {
for (const c of raw.playerInfo.showAvatarInfoList ?? []) {
- owned.set(String(c.avatarId), c.level);
+ liveLevels.set(String(c.avatarId), c.level);
}
}
- const characters: UnifiedGenshinCharacter[] = Object.entries(catalog).map(([id, meta]) => ({
- id,
- name: meta.name,
- element: meta.element,
- rarity: meta.rarity,
- icon_url: meta.iconUrl,
- owned: owned.has(id),
- level: owned.get(id) ?? null,
- }));
- characters.sort((a, b) => (b.owned === a.owned ? a.name.localeCompare(b.name) : b.owned ? 1 : -1));
+ // Record everything seen live into the durable ledger (monotonic), then
+ // build the response as the union of live data + ledger. Only characters
+ // that survive the playable-character catalog filter are fed in.
+ const now = Date.now();
+ const live: LiveOwned[] = [];
+ for (const [id, level] of liveLevels) if (catalog[id]) live.push({ id, level });
+ if (mergeLedger(ledger, live, now)) await saveLedger(env, ledger, ctx);
+
+ const characters = buildRosterCharacters(catalog, ledger, liveLevels);
return {
uid,
nickname: raw.playerInfo.nickname ?? null,
player_level: raw.playerInfo.level ?? null,
partial,
+ stale: false,
// Derived from the filtered `characters` list rather than raw map size —
// Enka's showcase data can include a handful of ids (trial/event NPCs,
// etc.) that don't survive the playable-character catalog filter, which
// would otherwise make this count larger than what's actually visible.
owned_count: characters.filter((c) => c.owned).length,
+ tracked_count: characters.filter((c) => c.tracked).length,
total_count: characters.length,
characters,
- updated_at: Date.now(),
+ updated_at: now,
};
}
@@ -465,7 +661,42 @@ export async function getGenshinCharacterDetail(
ctx?: ExecutionContext,
force = false,
): Promise<UnifiedGenshinCharacterDetail | null> {
- const { raw, catalog, loc } = await getUidData(env, uid, ctx, force);
+ const ledger = await loadLedger(env, uid);
+
+ let raw: EnkaUidResponse;
+ let catalog: Catalog;
+ let loc: RawLoc;
+ try {
+ const data = await getUidData(env, uid, ctx, force);
+ raw = data.raw;
+ catalog = data.catalog;
+ loc = data.loc;
+ } catch (err) {
+ // Enka unavailable. If this character is in the durable ledger, serve it
+ // as owned-but-untracked (last-known level/constellation, no live build).
+ const led = ledger.characters[heroId];
+ const staleCatalog = await getCatalog(env, ctx); // Enka-independent; rethrows if IT failed
+ const meta = staleCatalog[heroId];
+ if (!meta) return null;
+ if (!led) throw err; // real, playable character but nothing owned to fall back to
+ return {
+ id: heroId,
+ name: meta.name,
+ element: meta.element,
+ rarity: meta.rarity,
+ icon_url: meta.iconUrl,
+ owned: true,
+ tracked: false,
+ last_seen: led.last_seen,
+ level: led.level,
+ constellation: led.constellation,
+ friendship: null,
+ weapon: null,
+ artifacts: [],
+ updated_at: ledger.updated_at,
+ };
+ }
+
const meta = catalog[heroId];
if (!meta) return null;
@@ -480,18 +711,54 @@ export async function getGenshinCharacterDetail(
const found = findOwnedAvatar(raw, heroId);
if (!found.owned) {
- return { ...base, owned: false, level: null, constellation: 0, friendship: null, weapon: null, artifacts: [] };
+ // Not in the live data — but if the ledger has it, it's still owned, just
+ // not currently tracked (unpinned / "Display all" off since we last saw it).
+ const led = ledger.characters[heroId];
+ if (led) {
+ return {
+ ...base,
+ owned: true,
+ tracked: false,
+ last_seen: led.last_seen,
+ level: led.level,
+ constellation: led.constellation,
+ friendship: null,
+ weapon: null,
+ artifacts: [],
+ };
+ }
+ return {
+ ...base,
+ owned: false,
+ tracked: false,
+ last_seen: null,
+ level: null,
+ constellation: 0,
+ friendship: null,
+ weapon: null,
+ artifacts: [],
+ };
}
const entry = found.detail;
+ const constellation = entry?.talentIdList?.length ?? 0;
+
+ // Record this live sighting (level + constellation) in the durable ledger.
+ const now = Date.now();
+ if (mergeLedger(ledger, [{ id: heroId, level: found.level, constellation }], now)) {
+ await saveLedger(env, ledger, ctx);
+ }
+
const weaponEquip = entry?.equipList?.find((e) => e.weapon);
const artifactEquips = (entry?.equipList ?? []).filter((e) => e.reliquary);
return {
...base,
owned: true,
+ tracked: true,
+ last_seen: now,
level: found.level,
- constellation: entry?.talentIdList?.length ?? 0,
+ constellation,
friendship: entry?.fetterInfo?.expLevel ?? null,
weapon: weaponEquip ? buildWeapon(weaponEquip, loc) : null,
artifacts: artifactEquips
@@ -523,16 +790,46 @@ export async function getGenshinCharacterConstellations(
ctx?: ExecutionContext,
force = false,
): Promise<UnifiedGenshinCharacterConstellations | null> {
- const { raw, catalog } = await getUidData(env, uid, ctx, force);
+ const ledger = await loadLedger(env, uid);
+
+ let raw: EnkaUidResponse;
+ let catalog: Catalog;
+ try {
+ const data = await getUidData(env, uid, ctx, force);
+ raw = data.raw;
+ catalog = data.catalog;
+ } catch (err) {
+ // Enka down — fall back to the ledger's last-known constellation count.
+ const staleCatalog = await getCatalog(env, ctx);
+ if (!staleCatalog[heroId]) return null;
+ const led = ledger.characters[heroId];
+ if (!led) throw err;
+ // No live talentIdList when stale, so unlocked_talent_ids is empty even
+ // though `constellation` is the last-known count.
+ return { constellation: led.constellation, unlocked_talent_ids: [], friendship: null };
+ }
+
if (!catalog[heroId]) return null;
const found = findOwnedAvatar(raw, heroId);
- if (!found.owned) return { constellation: 0, unlocked_talent_ids: [], friendship: null };
+ if (!found.owned) {
+ // Owned per the ledger but not live — surface the last-known count.
+ const led = ledger.characters[heroId];
+ if (led) return { constellation: led.constellation, unlocked_talent_ids: [], friendship: null };
+ return { constellation: 0, unlocked_talent_ids: [], friendship: null };
+ }
const unlocked = found.detail?.talentIdList ?? [];
+
+ // Keep the ledger's constellation count current from this live sighting.
+ const now = Date.now();
+ if (mergeLedger(ledger, [{ id: heroId, level: found.level, constellation: unlocked.length }], now)) {
+ await saveLedger(env, ledger, ctx);
+ }
+
return {
constellation: unlocked.length,
unlocked_talent_ids: unlocked,
friendship: found.detail?.fetterInfo?.expLevel ?? null,
};
-}
+}
\ No newline at end of file
diff --git a/src/types.ts b/src/types.ts
index 24a5887..b97a7ab 100644
--- a/src/types.ts
+++ b/src/types.ts
@@ -557,6 +557,18 @@ export interface UnifiedGenshinCharacter {
owned: boolean;
/** Character level, or null if not owned. */
level: number | null;
+ /** True when this character is present in the CURRENT live Enka response
+ * (pinned showcase, or full roster with "Display all" on). False when the
+ * character is only known from the persistent ownership ledger — i.e. it
+ * was seen owned before but has since dropped out of Enka (unpinned from
+ * the showcase, "Display all" turned off, or the profile went private).
+ * Such a character is still `owned: true`; it just isn't being tracked
+ * live anymore, so `level` is the last value we ever saw. Always false
+ * when `owned` is false. */
+ tracked: boolean;
+ /** Epoch ms of the last time this character was seen in a live Enka
+ * response. null if never seen live (i.e. not owned). */
+ last_seen: number | null;
}
export interface UnifiedGenshinRoster {
@@ -568,7 +580,16 @@ export interface UnifiedGenshinRoster {
* your characters" on their in-game Character Showcase. `owned`/`level`
* below are then only accurate for the characters they've pinned. */
partial: boolean;
+ /** True when this whole response was served from the persistent ownership
+ * ledger because the live Enka fetch failed (profile private, UID
+ * unindexed, or Enka upstream down). Every character is then `tracked:
+ * false` and levels are last-known. When false, the ledger was merged with
+ * fresh live data as normal. */
+ stale: boolean;
owned_count: number;
+ /** Of the owned characters, how many are currently tracked live (present in
+ * the Enka response). `owned_count - tracked_count` = owned-but-untracked. */
+ tracked_count: number;
total_count: number;
characters: UnifiedGenshinCharacter[];
updated_at: number;