nomadro/apps/minigame-cocos/assets/scripts/sim/SaveSystem.ts
Eric 58a845db32 Add WeChat minigame triple-engine scaffold with Godot Chiang Mai plaza SoT.
Unity and Cocos stay as parallel schemes; apps/minigame ships the Godot 4.7 WeChat pack for DevTools.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-11-06 20:17:14 +08:00

77 lines
1.9 KiB
TypeScript

/**
* Local save — WeChat Storage when present, else browser/localStorage.
* Field shape inspired by KenneyNL/Starter-Kit-City-Builder map.structures + cash
* (MIT, stars>1000) — see docs/OSS_RESEARCH.md.
*/
import type { SaveBlob } from '../core/types'
export const SAVE_KEY = 'nomadro_cocos_nomad_v1'
type StorageLike = {
getItem(key: string): string | null
setItem(key: string, value: string): void
removeItem?(key: string): void
}
function resolveStorage(): StorageLike | null {
const g = globalThis as {
wx?: {
getStorageSync?: (k: string) => unknown
setStorageSync?: (k: string, v: unknown) => void
removeStorageSync?: (k: string) => void
}
localStorage?: StorageLike
}
if (g.wx?.getStorageSync && g.wx?.setStorageSync) {
return {
getItem(key) {
try {
const v = g.wx!.getStorageSync!(key)
if (v == null || v === '') return null
return typeof v === 'string' ? v : JSON.stringify(v)
} catch {
return null
}
},
setItem(key, value) {
g.wx!.setStorageSync!(key, value)
},
removeItem(key) {
g.wx!.removeStorageSync?.(key)
},
}
}
if (g.localStorage) return g.localStorage
return null
}
export function saveBlob(blob: SaveBlob): boolean {
const store = resolveStorage()
if (!store) return false
try {
store.setItem(SAVE_KEY, JSON.stringify(blob))
return true
} catch {
return false
}
}
export function loadBlob(): SaveBlob | null {
const store = resolveStorage()
if (!store) return null
try {
const raw = store.getItem(SAVE_KEY)
if (!raw) return null
const data = JSON.parse(raw) as SaveBlob
if (!data || data.version !== 1 || !data.stats) return null
return data
} catch {
return null
}
}
export function clearSave(): void {
resolveStorage()?.removeItem?.(SAVE_KEY)
}