@invonetwork/web-sdk 3.26.0 → 3.27.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +1369 -1350
- package/README.md +119 -1
- package/dist/chunk-2DYTV74W.js +3681 -0
- package/dist/chunk-3YDO7GSH.js +6 -0
- package/dist/chunk-6CN236QH.js +473 -0
- package/dist/{chunk-7BYAUHTA.js → chunk-VP3OK4J4.js} +56 -459
- package/dist/game-server.cjs +5933 -0
- package/dist/game-server.d.cts +185 -0
- package/dist/game-server.d.ts +185 -0
- package/dist/game-server.js +716 -0
- package/dist/game.cjs +2172 -0
- package/dist/game.d.cts +197 -0
- package/dist/game.d.ts +197 -0
- package/dist/game.js +1034 -0
- package/dist/index.cjs +87 -0
- package/dist/index.d.cts +19 -3
- package/dist/index.d.ts +19 -3
- package/dist/index.js +26 -2
- package/dist/server.cjs +98 -1
- package/dist/server.d.cts +28 -10
- package/dist/server.d.ts +28 -10
- package/dist/server.js +4 -3649
- package/dist/types-CoW9LopI.d.cts +143 -0
- package/dist/types-CoW9LopI.d.ts +143 -0
- package/dist/{types-Cjd4SAR8.d.cts → types-_lIm74kd.d.cts} +40 -1
- package/dist/{types-Cjd4SAR8.d.ts → types-_lIm74kd.d.ts} +40 -1
- package/dist/version-BXFwI0-s.d.cts +8 -0
- package/dist/version-BXFwI0-s.d.ts +8 -0
- package/package.json +91 -77
|
@@ -0,0 +1,716 @@
|
|
|
1
|
+
import { InvoServer, verifyWebhook } from './chunk-2DYTV74W.js';
|
|
2
|
+
export { InvoServer } from './chunk-2DYTV74W.js';
|
|
3
|
+
import './chunk-6CN236QH.js';
|
|
4
|
+
export { SDK_VERSION } from './chunk-3YDO7GSH.js';
|
|
5
|
+
import { InvoError } from './chunk-VP3OK4J4.js';
|
|
6
|
+
export { InvoError } from './chunk-VP3OK4J4.js';
|
|
7
|
+
import { createHash, randomBytes } from 'crypto';
|
|
8
|
+
import { promises } from 'fs';
|
|
9
|
+
import * as path from 'path';
|
|
10
|
+
|
|
11
|
+
var MAX_BODY_BYTES = 1e6;
|
|
12
|
+
var EMAIL = /^[^\s@]{1,64}@[^\s@]{1,255}\.[^\s@]{2,63}$/;
|
|
13
|
+
var E164 = /^\+[1-9]\d{6,14}$/;
|
|
14
|
+
var REQUEST_ID = /^[A-Za-z0-9_-]{8,64}$/;
|
|
15
|
+
var ITEM_ID = /^[A-Za-z0-9._-]{1,64}$/;
|
|
16
|
+
var USD = /^\d{1,6}(\.\d{1,2})?$/;
|
|
17
|
+
var GameServerError = class extends Error {
|
|
18
|
+
constructor(status, code, message, requestId) {
|
|
19
|
+
super(message);
|
|
20
|
+
this.name = "GameServerError";
|
|
21
|
+
this.status = status;
|
|
22
|
+
this.code = code;
|
|
23
|
+
this.requestId = requestId;
|
|
24
|
+
}
|
|
25
|
+
};
|
|
26
|
+
function validateEconomy(economy) {
|
|
27
|
+
const problems = [];
|
|
28
|
+
if (!economy?.premium?.name) problems.push("premium.name is required");
|
|
29
|
+
if (!economy?.soft?.name) problems.push("soft.name is required");
|
|
30
|
+
const ids = /* @__PURE__ */ new Set();
|
|
31
|
+
for (const item of economy?.items ?? []) {
|
|
32
|
+
if (!ITEM_ID.test(item.id)) problems.push(`item id "${item.id}" must match ${ITEM_ID}`);
|
|
33
|
+
if (ids.has(item.id)) problems.push(`item id "${item.id}" is used twice`);
|
|
34
|
+
ids.add(item.id);
|
|
35
|
+
if (!item.name) problems.push(`item "${item.id}" needs a name`);
|
|
36
|
+
if (item.currency !== "premium" && item.currency !== "soft") problems.push(`item "${item.id}" currency must be premium or soft`);
|
|
37
|
+
if (!Number.isInteger(item.price) || item.price < 1 || item.price > 999999) problems.push(`item "${item.id}" price must be a whole number 1..999999`);
|
|
38
|
+
if (item.maxOwned !== void 0 && (!Number.isInteger(item.maxOwned) || item.maxOwned < 1 || item.maxOwned > 1e3)) {
|
|
39
|
+
problems.push(`item "${item.id}" maxOwned must be a whole number 1..1000`);
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
const packIds = /* @__PURE__ */ new Set();
|
|
43
|
+
for (const pack of economy?.premium?.packs ?? []) {
|
|
44
|
+
if (!ITEM_ID.test(pack.id)) problems.push(`pack id "${pack.id}" must match ${ITEM_ID}`);
|
|
45
|
+
if (packIds.has(pack.id)) problems.push(`pack id "${pack.id}" is used twice`);
|
|
46
|
+
packIds.add(pack.id);
|
|
47
|
+
if (!USD.test(pack.usdAmount) || Number(pack.usdAmount) <= 0) problems.push(`pack "${pack.id}" usdAmount must be a decimal string like "4.99"`);
|
|
48
|
+
}
|
|
49
|
+
if (problems.length) throw new Error(`Invalid game economy config:
|
|
50
|
+
- ${problems.join("\n- ")}`);
|
|
51
|
+
}
|
|
52
|
+
function playerIdFor(email) {
|
|
53
|
+
return "p_" + createHash("sha256").update(email.trim().toLowerCase()).digest("hex").slice(0, 24);
|
|
54
|
+
}
|
|
55
|
+
function maskPhone(phone) {
|
|
56
|
+
if (!phone) return null;
|
|
57
|
+
return "\u2022\u2022\u2022" + phone.slice(-4);
|
|
58
|
+
}
|
|
59
|
+
function json(status, body, extra = {}) {
|
|
60
|
+
return new Response(JSON.stringify(body), {
|
|
61
|
+
status,
|
|
62
|
+
headers: { "content-type": "application/json; charset=utf-8", "cache-control": "no-store", ...extra }
|
|
63
|
+
});
|
|
64
|
+
}
|
|
65
|
+
function errorResponse(err) {
|
|
66
|
+
const body = { error: { code: err.code, message: err.message } };
|
|
67
|
+
if (err.requestId) body.error.requestId = err.requestId;
|
|
68
|
+
return json(err.status, body);
|
|
69
|
+
}
|
|
70
|
+
function fromInvoError(err) {
|
|
71
|
+
const status = err.status >= 400 && err.status < 500 ? err.status : 502;
|
|
72
|
+
return new GameServerError(status, err.code || "INVO_ERROR", err.message, err.requestId);
|
|
73
|
+
}
|
|
74
|
+
async function readJson(request) {
|
|
75
|
+
const text = await readText(request);
|
|
76
|
+
if (!text) return {};
|
|
77
|
+
try {
|
|
78
|
+
const parsed = JSON.parse(text);
|
|
79
|
+
if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) throw new Error("not an object");
|
|
80
|
+
return parsed;
|
|
81
|
+
} catch {
|
|
82
|
+
throw new GameServerError(400, "INVALID_JSON", "The request body must be a JSON object.");
|
|
83
|
+
}
|
|
84
|
+
}
|
|
85
|
+
async function readText(request) {
|
|
86
|
+
const declared = Number(request.headers.get("content-length") ?? "0");
|
|
87
|
+
if (declared > MAX_BODY_BYTES) throw new GameServerError(413, "BODY_TOO_LARGE", "Request body is too large.");
|
|
88
|
+
const text = await request.text();
|
|
89
|
+
if (text.length > MAX_BODY_BYTES) throw new GameServerError(413, "BODY_TOO_LARGE", "Request body is too large.");
|
|
90
|
+
return text;
|
|
91
|
+
}
|
|
92
|
+
function softBalance(state, playerId) {
|
|
93
|
+
let sum = 0;
|
|
94
|
+
for (const e of state.ledger) if (e.playerId === playerId && e.currency === "soft") sum += e.amount;
|
|
95
|
+
return sum;
|
|
96
|
+
}
|
|
97
|
+
function addLedger(state, entry) {
|
|
98
|
+
if (state.ledgerRefs[entry.ref]) return null;
|
|
99
|
+
const full = { id: "le_" + randomBytes(9).toString("hex"), ...entry };
|
|
100
|
+
state.ledger.push(full);
|
|
101
|
+
state.ledgerRefs[entry.ref] = full.id;
|
|
102
|
+
return full;
|
|
103
|
+
}
|
|
104
|
+
function grant(state, playerId, itemId, quantity) {
|
|
105
|
+
var _a;
|
|
106
|
+
const inv = (_a = state.inventory)[playerId] ?? (_a[playerId] = {});
|
|
107
|
+
inv[itemId] = (inv[itemId] ?? 0) + quantity;
|
|
108
|
+
}
|
|
109
|
+
function toNumber(v) {
|
|
110
|
+
if (typeof v === "number" && Number.isFinite(v)) return v;
|
|
111
|
+
if (typeof v === "string" && v.trim() && Number.isFinite(Number(v))) return Number(v);
|
|
112
|
+
return null;
|
|
113
|
+
}
|
|
114
|
+
function createInvoGameServer(options) {
|
|
115
|
+
validateEconomy(options.economy);
|
|
116
|
+
const { invo, store, economy } = options;
|
|
117
|
+
const basePath = (options.basePath ?? "/api/invo").replace(/\/+$/, "");
|
|
118
|
+
const sessionTtlMs = options.sessionTtlMs ?? 7 * 24 * 60 * 60 * 1e3;
|
|
119
|
+
const now = options.now ?? (() => /* @__PURE__ */ new Date());
|
|
120
|
+
const log = options.log ?? (() => void 0);
|
|
121
|
+
const secrets = Array.isArray(options.webhookSecret) ? options.webhookSecret : [options.webhookSecret];
|
|
122
|
+
if (!secrets.length || secrets.some((s) => !s)) throw new Error("createInvoGameServer requires a webhookSecret.");
|
|
123
|
+
const itemsById = new Map(economy.items.map((i) => [i.id, i]));
|
|
124
|
+
const packsById = new Map(economy.premium.packs.map((p) => [p.id, p]));
|
|
125
|
+
const soft = {
|
|
126
|
+
starting: economy.soft.startingBalance ?? 0,
|
|
127
|
+
maxPerRequest: economy.soft.maxEarnPerRequest ?? 1e3,
|
|
128
|
+
maxPerMinute: economy.soft.maxEarnPerMinute ?? 1e4
|
|
129
|
+
};
|
|
130
|
+
const iso = () => now().toISOString();
|
|
131
|
+
function toPlayer(p) {
|
|
132
|
+
return { id: p.id, email: p.email, name: p.name, phoneMasked: maskPhone(p.phone) };
|
|
133
|
+
}
|
|
134
|
+
async function sessionPlayer(request) {
|
|
135
|
+
const header = request.headers.get("authorization") ?? "";
|
|
136
|
+
const token = header.startsWith("Bearer ") ? header.slice(7).trim() : "";
|
|
137
|
+
if (!token) throw new GameServerError(401, "SESSION_REQUIRED", "Sign in first.");
|
|
138
|
+
const found = await store.read((s) => {
|
|
139
|
+
const session = s.sessions[token];
|
|
140
|
+
if (!session) return null;
|
|
141
|
+
return { session, player: s.players[session.playerId] };
|
|
142
|
+
});
|
|
143
|
+
if (!found || !found.player) throw new GameServerError(401, "SESSION_INVALID", "Your session ended. Sign in again.");
|
|
144
|
+
if (Date.parse(found.session.expiresAt) <= now().getTime()) {
|
|
145
|
+
await store.transact((s) => void delete s.sessions[token]);
|
|
146
|
+
throw new GameServerError(401, "SESSION_EXPIRED", "Your session expired. Sign in again.");
|
|
147
|
+
}
|
|
148
|
+
return { player: found.player, token };
|
|
149
|
+
}
|
|
150
|
+
async function readWallet(player, premiumHint) {
|
|
151
|
+
let premium = premiumHint ?? null;
|
|
152
|
+
if (premium === null) {
|
|
153
|
+
try {
|
|
154
|
+
const res = await invo.getPlayerBalance({ playerEmail: player.email });
|
|
155
|
+
const want = economy.premium.name.toLowerCase();
|
|
156
|
+
const row = res.balances.find((b) => b.currencyName.toLowerCase() === want) ?? res.balances[0];
|
|
157
|
+
premium = row ? toNumber(row.availableBalance) ?? 0 : 0;
|
|
158
|
+
} catch (err) {
|
|
159
|
+
if (err instanceof InvoError && err.status === 404) premium = 0;
|
|
160
|
+
else log("warn", "premium balance unavailable", { playerId: player.id, code: err.code });
|
|
161
|
+
}
|
|
162
|
+
}
|
|
163
|
+
const { softBal, inventory } = await store.read((s) => ({
|
|
164
|
+
softBal: softBalance(s, player.id),
|
|
165
|
+
inventory: { ...s.inventory[player.id] ?? {} }
|
|
166
|
+
}));
|
|
167
|
+
return {
|
|
168
|
+
premium: { kind: "premium", name: economy.premium.name, balance: premium },
|
|
169
|
+
soft: { kind: "soft", name: economy.soft.name, balance: softBal },
|
|
170
|
+
inventory,
|
|
171
|
+
asOf: iso()
|
|
172
|
+
};
|
|
173
|
+
}
|
|
174
|
+
function originFor(request) {
|
|
175
|
+
if (options.publicUrl) return options.publicUrl.replace(/\/+$/, "");
|
|
176
|
+
const proto = request.headers.get("x-forwarded-proto")?.split(",")[0]?.trim();
|
|
177
|
+
const host = request.headers.get("x-forwarded-host")?.split(",")[0]?.trim() ?? request.headers.get("host");
|
|
178
|
+
if (host) return `${proto || new URL(request.url).protocol.replace(":", "")}://${host}`;
|
|
179
|
+
return new URL(request.url).origin;
|
|
180
|
+
}
|
|
181
|
+
async function catalog() {
|
|
182
|
+
const body = {
|
|
183
|
+
premium: { name: economy.premium.name, packs: economy.premium.packs },
|
|
184
|
+
soft: { name: economy.soft.name },
|
|
185
|
+
items: economy.items,
|
|
186
|
+
sandbox: options.sandbox
|
|
187
|
+
};
|
|
188
|
+
return json(200, body);
|
|
189
|
+
}
|
|
190
|
+
async function signIn(request) {
|
|
191
|
+
const body = await readJson(request);
|
|
192
|
+
const email = typeof body["email"] === "string" ? body["email"].trim().toLowerCase() : "";
|
|
193
|
+
const phone = typeof body["phone"] === "string" && body["phone"].trim() ? body["phone"].replace(/[\s()-]/g, "") : null;
|
|
194
|
+
const rawName = typeof body["name"] === "string" ? body["name"].trim() : "";
|
|
195
|
+
if (!EMAIL.test(email)) throw new GameServerError(400, "INVALID_EMAIL", "Enter a valid email address.");
|
|
196
|
+
if (phone !== null && !E164.test(phone)) {
|
|
197
|
+
throw new GameServerError(400, "INVALID_PHONE", "Enter the phone number in international format, e.g. +15555550111.");
|
|
198
|
+
}
|
|
199
|
+
const name = (rawName || email.split("@")[0] || "Player").slice(0, 64);
|
|
200
|
+
const id = playerIdFor(email);
|
|
201
|
+
const known = await store.read((s) => s.players[id] ?? null);
|
|
202
|
+
const phoneForInvo = phone ?? known?.phone ?? void 0;
|
|
203
|
+
try {
|
|
204
|
+
await invo.mintPlayerToken({ playerEmail: email, playerPhone: phoneForInvo, playerName: name });
|
|
205
|
+
} catch (err) {
|
|
206
|
+
if (err instanceof InvoError && err.status === 404) {
|
|
207
|
+
throw new GameServerError(400, "PHONE_REQUIRED", "First sign-in needs a phone number so INVO can create your account.");
|
|
208
|
+
}
|
|
209
|
+
if (err instanceof InvoError) throw fromInvoError(err);
|
|
210
|
+
throw err;
|
|
211
|
+
}
|
|
212
|
+
const token = randomBytes(32).toString("base64url");
|
|
213
|
+
const expiresAt = new Date(now().getTime() + sessionTtlMs).toISOString();
|
|
214
|
+
const player = await store.transact((s) => {
|
|
215
|
+
const existing = s.players[id];
|
|
216
|
+
const record = existing ? { ...existing, name, phone: phone ?? existing.phone } : { id, email, phone, name, createdAt: iso() };
|
|
217
|
+
s.players[id] = record;
|
|
218
|
+
if (soft.starting > 0) {
|
|
219
|
+
addLedger(s, { playerId: id, currency: "soft", amount: soft.starting, reason: "starting balance", ref: `start:${id}`, at: iso() });
|
|
220
|
+
}
|
|
221
|
+
for (const [t, sess] of Object.entries(s.sessions)) {
|
|
222
|
+
if (sess.playerId === id && Date.parse(sess.expiresAt) <= now().getTime()) delete s.sessions[t];
|
|
223
|
+
}
|
|
224
|
+
s.sessions[token] = { playerId: id, expiresAt };
|
|
225
|
+
return record;
|
|
226
|
+
});
|
|
227
|
+
log("info", "player signed in", { playerId: id });
|
|
228
|
+
const session = { sessionToken: token, expiresAt, player: toPlayer(player), wallet: await readWallet(player) };
|
|
229
|
+
return json(200, session);
|
|
230
|
+
}
|
|
231
|
+
async function signOut(request) {
|
|
232
|
+
const { token } = await sessionPlayer(request);
|
|
233
|
+
await store.transact((s) => void delete s.sessions[token]);
|
|
234
|
+
return json(200, { ok: true });
|
|
235
|
+
}
|
|
236
|
+
async function checkout(request) {
|
|
237
|
+
const { player, token } = await sessionPlayer(request);
|
|
238
|
+
const body = await readJson(request);
|
|
239
|
+
const pack = packsById.get(String(body["packId"] ?? ""));
|
|
240
|
+
if (!pack) throw new GameServerError(404, "PACK_NOT_FOUND", "That pack is not for sale.");
|
|
241
|
+
const purchaseRef = "pr_" + randomBytes(12).toString("hex");
|
|
242
|
+
const origin = originFor(request);
|
|
243
|
+
let session;
|
|
244
|
+
try {
|
|
245
|
+
session = await invo.createCheckout({
|
|
246
|
+
playerEmail: player.email,
|
|
247
|
+
usdAmount: pack.usdAmount,
|
|
248
|
+
successUrl: `${origin}/?invo_purchase=${purchaseRef}&invo_status=success`,
|
|
249
|
+
cancelUrl: `${origin}/?invo_purchase=${purchaseRef}&invo_status=cancel`,
|
|
250
|
+
// Echoed on the signed purchase.completed webhook: that is how the credit finds this purchase.
|
|
251
|
+
metadata: { purchase_ref: purchaseRef, pack_id: pack.id, player_id: player.id }
|
|
252
|
+
});
|
|
253
|
+
} catch (err) {
|
|
254
|
+
if (err instanceof InvoError) throw fromInvoError(err);
|
|
255
|
+
throw err;
|
|
256
|
+
}
|
|
257
|
+
const stamp = iso();
|
|
258
|
+
await store.transact((s) => {
|
|
259
|
+
s.purchases[purchaseRef] = {
|
|
260
|
+
purchaseRef,
|
|
261
|
+
playerId: player.id,
|
|
262
|
+
packId: pack.id,
|
|
263
|
+
sessionId: session.sessionId,
|
|
264
|
+
status: "pending",
|
|
265
|
+
credited: null,
|
|
266
|
+
orderId: null,
|
|
267
|
+
createdAt: stamp,
|
|
268
|
+
updatedAt: stamp
|
|
269
|
+
};
|
|
270
|
+
});
|
|
271
|
+
log("info", "checkout created", { playerId: player.id, packId: pack.id, purchaseRef });
|
|
272
|
+
const out = { purchaseRef, checkoutUrl: session.checkoutUrl, expiresAt: session.expiresAt };
|
|
273
|
+
return json(200, out);
|
|
274
|
+
}
|
|
275
|
+
async function purchaseStatus(request, ref) {
|
|
276
|
+
const { player } = await sessionPlayer(request);
|
|
277
|
+
const p = await store.read((s) => s.purchases[ref] ?? null);
|
|
278
|
+
if (!p || p.playerId !== player.id) throw new GameServerError(404, "PURCHASE_NOT_FOUND", "No such purchase.");
|
|
279
|
+
const out = {
|
|
280
|
+
purchaseRef: p.purchaseRef,
|
|
281
|
+
packId: p.packId,
|
|
282
|
+
status: p.status,
|
|
283
|
+
credited: p.credited,
|
|
284
|
+
createdAt: p.createdAt,
|
|
285
|
+
updatedAt: p.updatedAt
|
|
286
|
+
};
|
|
287
|
+
return json(200, out);
|
|
288
|
+
}
|
|
289
|
+
async function webhook(request) {
|
|
290
|
+
const raw = await readText(request);
|
|
291
|
+
let event;
|
|
292
|
+
try {
|
|
293
|
+
event = verifyWebhook(raw, request.headers.get("x-invo-signature"), secrets);
|
|
294
|
+
} catch (err) {
|
|
295
|
+
const code = err instanceof InvoError && err.code || "WEBHOOK_MALFORMED";
|
|
296
|
+
log("warn", "webhook refused", { code });
|
|
297
|
+
throw new GameServerError(400, code, "Webhook verification failed.");
|
|
298
|
+
}
|
|
299
|
+
const key = String(event.idempotency_key || request.headers.get("x-invo-idempotency-key") || event.event_id || "");
|
|
300
|
+
if (!key) throw new GameServerError(400, "WEBHOOK_MALFORMED", "Webhook has no idempotency key.");
|
|
301
|
+
const data = event.data ?? {};
|
|
302
|
+
const at = iso();
|
|
303
|
+
const outcome = await store.transact((s) => {
|
|
304
|
+
if (s.webhooks[key]) return "duplicate";
|
|
305
|
+
s.webhooks[key] = at;
|
|
306
|
+
const email = typeof data["player_email"] === "string" ? data["player_email"].toLowerCase() : "";
|
|
307
|
+
const playerId = email ? playerIdFor(email) : "";
|
|
308
|
+
const metadata = data["metadata"] ?? {};
|
|
309
|
+
const purchaseRef = typeof metadata["purchase_ref"] === "string" ? metadata["purchase_ref"] : "";
|
|
310
|
+
const purchase = purchaseRef ? s.purchases[purchaseRef] : void 0;
|
|
311
|
+
const orderId = String(data["order_id"] ?? data["transaction_id"] ?? "");
|
|
312
|
+
switch (event.event_type) {
|
|
313
|
+
case "purchase.completed": {
|
|
314
|
+
if (metadata["source"] === "subscription_renewal") return "ignored";
|
|
315
|
+
const amount = toNumber(data["currency_amount"]) ?? 0;
|
|
316
|
+
const owner = purchase?.playerId ?? playerId;
|
|
317
|
+
if (owner) {
|
|
318
|
+
addLedger(s, { playerId: owner, currency: "premium", amount, reason: "premium purchase (INVO)", ref: `order:${orderId}`, at });
|
|
319
|
+
}
|
|
320
|
+
if (purchase && purchase.status === "pending") {
|
|
321
|
+
purchase.status = "credited";
|
|
322
|
+
purchase.credited = amount;
|
|
323
|
+
purchase.orderId = orderId || null;
|
|
324
|
+
purchase.updatedAt = at;
|
|
325
|
+
}
|
|
326
|
+
return "credited";
|
|
327
|
+
}
|
|
328
|
+
case "purchase.failed": {
|
|
329
|
+
if (purchase && purchase.status === "pending") {
|
|
330
|
+
purchase.status = "failed";
|
|
331
|
+
purchase.updatedAt = at;
|
|
332
|
+
}
|
|
333
|
+
return "failed";
|
|
334
|
+
}
|
|
335
|
+
case "purchase.refunded":
|
|
336
|
+
case "purchase.disputed": {
|
|
337
|
+
if (event.event_type === "purchase.disputed" && data["dispute_status"] !== "lost") return "ignored";
|
|
338
|
+
const target = Object.values(s.purchases).find((p) => p.orderId && p.orderId === orderId);
|
|
339
|
+
if (target) {
|
|
340
|
+
target.status = "refunded";
|
|
341
|
+
target.updatedAt = at;
|
|
342
|
+
const credited = target.credited ?? 0;
|
|
343
|
+
addLedger(s, { playerId: target.playerId, currency: "premium", amount: -credited, reason: `premium ${event.event_type}`, ref: `refund:${orderId}`, at });
|
|
344
|
+
}
|
|
345
|
+
return "refunded";
|
|
346
|
+
}
|
|
347
|
+
case "item.purchased": {
|
|
348
|
+
const txId = String(data["transaction_id"] ?? "");
|
|
349
|
+
const itemId = String(data["item_id"] ?? "");
|
|
350
|
+
const item = itemsById.get(itemId);
|
|
351
|
+
if (!txId || !playerId || !item || s.ledgerRefs[`item:${txId}`]) return "noop";
|
|
352
|
+
const qty = Math.max(1, Math.trunc(toNumber(data["item_quantity"]) ?? 1));
|
|
353
|
+
const owned = s.inventory[playerId]?.[itemId] ?? 0;
|
|
354
|
+
const granted = Math.min(qty, Math.max(0, (item.maxOwned ?? 1) - owned));
|
|
355
|
+
if (granted > 0) grant(s, playerId, itemId, granted);
|
|
356
|
+
addLedger(s, { playerId, currency: "premium", amount: -(toNumber(data["total_price"]) ?? item.price * qty), reason: `item ${itemId} (webhook)`, ref: `item:${txId}`, at });
|
|
357
|
+
return "granted";
|
|
358
|
+
}
|
|
359
|
+
default:
|
|
360
|
+
return "ignored";
|
|
361
|
+
}
|
|
362
|
+
});
|
|
363
|
+
log("info", "webhook processed", { type: event.event_type, outcome });
|
|
364
|
+
return json(200, { ok: true, outcome });
|
|
365
|
+
}
|
|
366
|
+
async function buyItem(request, itemId) {
|
|
367
|
+
const { player } = await sessionPlayer(request);
|
|
368
|
+
const item = itemsById.get(itemId);
|
|
369
|
+
if (!item) throw new GameServerError(404, "ITEM_NOT_FOUND", "That item is not in the shop.");
|
|
370
|
+
const body = await readJson(request);
|
|
371
|
+
const clientRequestId = String(body["clientRequestId"] ?? "");
|
|
372
|
+
if (!REQUEST_ID.test(clientRequestId)) {
|
|
373
|
+
throw new GameServerError(400, "INVALID_REQUEST_ID", "clientRequestId must be 8-64 letters, digits, - or _.");
|
|
374
|
+
}
|
|
375
|
+
const quantity = body["quantity"] === void 0 ? 1 : Number(body["quantity"]);
|
|
376
|
+
const maxOwned = item.maxOwned ?? 1;
|
|
377
|
+
if (!Number.isInteger(quantity) || quantity < 1 || quantity > maxOwned) {
|
|
378
|
+
throw new GameServerError(400, "INVALID_QUANTITY", `quantity must be a whole number 1..${maxOwned}.`);
|
|
379
|
+
}
|
|
380
|
+
const idemKey = `${player.id}:${clientRequestId}`;
|
|
381
|
+
const total = item.price * quantity;
|
|
382
|
+
const replay = await store.read((s) => s.idempotency[idemKey] ?? null);
|
|
383
|
+
if (replay) {
|
|
384
|
+
const prior2 = replay.result;
|
|
385
|
+
return json(200, { ...prior2, replayed: true, wallet: await readWallet(player) });
|
|
386
|
+
}
|
|
387
|
+
const owned = await store.read((s) => s.inventory[player.id]?.[item.id] ?? 0);
|
|
388
|
+
if (owned + quantity > maxOwned) {
|
|
389
|
+
throw new GameServerError(409, maxOwned === 1 ? "ALREADY_OWNED" : "MAX_OWNED", maxOwned === 1 ? `You already own ${item.name}.` : `You can own at most ${maxOwned} ${item.name}.`);
|
|
390
|
+
}
|
|
391
|
+
if (item.currency === "soft") {
|
|
392
|
+
const result = await store.transact((s) => {
|
|
393
|
+
const again = s.idempotency[idemKey];
|
|
394
|
+
if (again) return { replayed: true, prior: again.result };
|
|
395
|
+
if ((s.inventory[player.id]?.[item.id] ?? 0) + quantity > maxOwned) {
|
|
396
|
+
throw new GameServerError(409, "ALREADY_OWNED", `You already own ${item.name}.`);
|
|
397
|
+
}
|
|
398
|
+
const balance = softBalance(s, player.id);
|
|
399
|
+
if (balance < total) {
|
|
400
|
+
throw new GameServerError(400, "INSUFFICIENT_BALANCE", `Not enough ${economy.soft.name}: ${total} needed, ${balance} held.`);
|
|
401
|
+
}
|
|
402
|
+
const entry = addLedger(s, { playerId: player.id, currency: "soft", amount: -total, reason: `item ${item.id} x${quantity}`, ref: `buy:${idemKey}`, at: iso() });
|
|
403
|
+
grant(s, player.id, item.id, quantity);
|
|
404
|
+
const prior2 = { itemId: item.id, quantity, currency: "soft", transactionId: entry?.id ?? `buy:${idemKey}` };
|
|
405
|
+
s.idempotency[idemKey] = { at: iso(), result: prior2 };
|
|
406
|
+
return { replayed: false, prior: prior2 };
|
|
407
|
+
});
|
|
408
|
+
log("info", "item bought", { playerId: player.id, itemId: item.id, currency: "soft", replayed: result.replayed });
|
|
409
|
+
return json(200, { ...result.prior, replayed: result.replayed, wallet: await readWallet(player) });
|
|
410
|
+
}
|
|
411
|
+
let invoResult;
|
|
412
|
+
try {
|
|
413
|
+
invoResult = await invo.purchaseItem({
|
|
414
|
+
// Scoped to the player so two players can never collide on INVO's per-game key.
|
|
415
|
+
clientRequestId: `${player.id.slice(2, 14)}_${clientRequestId}`,
|
|
416
|
+
playerEmail: player.email,
|
|
417
|
+
playerName: player.name,
|
|
418
|
+
playerPhone: player.phone ?? void 0,
|
|
419
|
+
itemId: item.id,
|
|
420
|
+
itemName: item.name,
|
|
421
|
+
itemQuantity: quantity,
|
|
422
|
+
unitPrice: item.price.toFixed(2),
|
|
423
|
+
totalPrice: total.toFixed(2),
|
|
424
|
+
itemCategory: item.category,
|
|
425
|
+
itemDescription: item.description
|
|
426
|
+
});
|
|
427
|
+
} catch (err) {
|
|
428
|
+
if (err instanceof InvoError && err.isInsufficientBalance) {
|
|
429
|
+
throw new GameServerError(400, "INSUFFICIENT_BALANCE", `Not enough ${economy.premium.name} for ${item.name}.`, err.requestId);
|
|
430
|
+
}
|
|
431
|
+
if (err instanceof InvoError && err.isDuplicateRequest) {
|
|
432
|
+
throw new GameServerError(409, "PURCHASE_IN_PROGRESS", "This purchase is already being processed. Your item will arrive shortly.", err.requestId);
|
|
433
|
+
}
|
|
434
|
+
if (err instanceof InvoError) throw fromInvoError(err);
|
|
435
|
+
throw err;
|
|
436
|
+
}
|
|
437
|
+
const prior = { itemId: item.id, quantity, currency: "premium", transactionId: invoResult.transactionId };
|
|
438
|
+
await store.transact((s) => {
|
|
439
|
+
if (s.idempotency[idemKey]) return;
|
|
440
|
+
if (!s.ledgerRefs[`item:${invoResult.transactionId}`]) grant(s, player.id, item.id, quantity);
|
|
441
|
+
addLedger(s, { playerId: player.id, currency: "premium", amount: -total, reason: `item ${item.id} x${quantity}`, ref: `item:${invoResult.transactionId}`, at: iso() });
|
|
442
|
+
s.idempotency[idemKey] = { at: iso(), result: prior };
|
|
443
|
+
});
|
|
444
|
+
log("info", "item bought", { playerId: player.id, itemId: item.id, currency: "premium", transactionId: invoResult.transactionId });
|
|
445
|
+
return json(200, { ...prior, replayed: false, wallet: await readWallet(player, toNumber(invoResult.newBalance)) });
|
|
446
|
+
}
|
|
447
|
+
async function earn(request) {
|
|
448
|
+
const { player } = await sessionPlayer(request);
|
|
449
|
+
const body = await readJson(request);
|
|
450
|
+
const amount = Number(body["amount"]);
|
|
451
|
+
const eventId = String(body["eventId"] ?? "");
|
|
452
|
+
const reason = typeof body["reason"] === "string" ? body["reason"].slice(0, 80) : "earned in play";
|
|
453
|
+
if (!REQUEST_ID.test(eventId)) throw new GameServerError(400, "INVALID_EVENT_ID", "eventId must be 8-64 letters, digits, - or _.");
|
|
454
|
+
if (!Number.isInteger(amount) || amount < 1 || amount > soft.maxPerRequest) {
|
|
455
|
+
throw new GameServerError(400, "INVALID_AMOUNT", `amount must be a whole number 1..${soft.maxPerRequest}.`);
|
|
456
|
+
}
|
|
457
|
+
const ref = `earn:${player.id}:${eventId}`;
|
|
458
|
+
const result = await store.transact((s) => {
|
|
459
|
+
if (s.ledgerRefs[ref]) return { replayed: true, balance: softBalance(s, player.id) };
|
|
460
|
+
const cutoff = now().getTime() - 6e4;
|
|
461
|
+
let lastMinute = 0;
|
|
462
|
+
for (const e of s.ledger) {
|
|
463
|
+
if (e.playerId === player.id && e.currency === "soft" && e.amount > 0 && e.ref.startsWith("earn:") && Date.parse(e.at) > cutoff) lastMinute += e.amount;
|
|
464
|
+
}
|
|
465
|
+
if (lastMinute + amount > soft.maxPerMinute) {
|
|
466
|
+
throw new GameServerError(429, "EARN_RATE_LIMITED", `Earning is limited to ${soft.maxPerMinute} ${economy.soft.name} a minute.`);
|
|
467
|
+
}
|
|
468
|
+
addLedger(s, { playerId: player.id, currency: "soft", amount, reason, ref, at: iso() });
|
|
469
|
+
return { replayed: false, balance: softBalance(s, player.id) };
|
|
470
|
+
});
|
|
471
|
+
return json(200, { soft: { kind: "soft", name: economy.soft.name, balance: result.balance }, replayed: result.replayed });
|
|
472
|
+
}
|
|
473
|
+
async function events(request) {
|
|
474
|
+
const { player } = await sessionPlayer(request);
|
|
475
|
+
const body = await readJson(request);
|
|
476
|
+
try {
|
|
477
|
+
const res = await invo.reportGameEvent({
|
|
478
|
+
playerEmail: player.email,
|
|
479
|
+
eventType: String(body["eventType"] ?? ""),
|
|
480
|
+
eventId: typeof body["eventId"] === "string" ? body["eventId"] : void 0,
|
|
481
|
+
payload: body["payload"] && typeof body["payload"] === "object" ? body["payload"] : {}
|
|
482
|
+
});
|
|
483
|
+
return json(202, { accepted: res.accepted, eventId: res.eventId });
|
|
484
|
+
} catch (err) {
|
|
485
|
+
if (err instanceof InvoError) throw fromInvoError(err);
|
|
486
|
+
throw err;
|
|
487
|
+
}
|
|
488
|
+
}
|
|
489
|
+
async function rewards(request) {
|
|
490
|
+
const { player } = await sessionPlayer(request);
|
|
491
|
+
try {
|
|
492
|
+
const res = await invo.getPlayerRewards(player.email);
|
|
493
|
+
return json(200, {
|
|
494
|
+
available: true,
|
|
495
|
+
cards: res.cards.map((c) => ({
|
|
496
|
+
programId: c.programId,
|
|
497
|
+
title: c.title,
|
|
498
|
+
description: c.description,
|
|
499
|
+
status: c.status,
|
|
500
|
+
stepsComplete: c.stepsComplete,
|
|
501
|
+
stepsRequired: c.stepsRequired,
|
|
502
|
+
steps: c.steps.map((st) => ({ label: st.label, state: st.state, progress: st.progress }))
|
|
503
|
+
}))
|
|
504
|
+
});
|
|
505
|
+
} catch (err) {
|
|
506
|
+
if (err instanceof InvoError && (err.status === 404 || err.code === "NO_TENANT" || err.status === 409)) {
|
|
507
|
+
return json(200, { available: false, cards: [] });
|
|
508
|
+
}
|
|
509
|
+
if (err instanceof InvoError) throw fromInvoError(err);
|
|
510
|
+
throw err;
|
|
511
|
+
}
|
|
512
|
+
}
|
|
513
|
+
async function route(request, sub, method) {
|
|
514
|
+
if (method === "GET" && sub === "/health") return json(200, { ok: true, setupRequired: false, sandbox: options.sandbox });
|
|
515
|
+
if (method === "GET" && sub === "/catalog") return catalog();
|
|
516
|
+
if (method === "POST" && sub === "/session") return signIn(request);
|
|
517
|
+
if (method === "POST" && sub === "/session/end") return signOut(request);
|
|
518
|
+
if (method === "GET" && sub === "/wallet") {
|
|
519
|
+
const { player } = await sessionPlayer(request);
|
|
520
|
+
return json(200, await readWallet(player));
|
|
521
|
+
}
|
|
522
|
+
if (method === "POST" && sub === "/checkout") return checkout(request);
|
|
523
|
+
if (method === "GET" && sub.startsWith("/purchases/")) return purchaseStatus(request, decodeURIComponent(sub.slice("/purchases/".length)));
|
|
524
|
+
if (method === "POST" && sub === "/webhook") return webhook(request);
|
|
525
|
+
const buy = /^\/items\/([^/]+)\/buy$/.exec(sub);
|
|
526
|
+
if (method === "POST" && buy) return buyItem(request, decodeURIComponent(buy[1]));
|
|
527
|
+
if (method === "POST" && sub === "/earn") return earn(request);
|
|
528
|
+
if (method === "POST" && sub === "/events") return events(request);
|
|
529
|
+
if (method === "GET" && sub === "/rewards") return rewards(request);
|
|
530
|
+
return json(404, { error: { code: "NOT_FOUND", message: "No such route." } });
|
|
531
|
+
}
|
|
532
|
+
return {
|
|
533
|
+
basePath,
|
|
534
|
+
async handle(request) {
|
|
535
|
+
const url = new URL(request.url);
|
|
536
|
+
if (url.pathname !== basePath && !url.pathname.startsWith(basePath + "/")) return null;
|
|
537
|
+
const sub = url.pathname.slice(basePath.length) || "/";
|
|
538
|
+
try {
|
|
539
|
+
return await route(request, sub, request.method.toUpperCase());
|
|
540
|
+
} catch (err) {
|
|
541
|
+
if (err instanceof GameServerError) return errorResponse(err);
|
|
542
|
+
log("error", "unhandled game-server error", { path: sub, message: err?.message });
|
|
543
|
+
return errorResponse(new GameServerError(500, "INTERNAL", "Something went wrong. Try again."));
|
|
544
|
+
}
|
|
545
|
+
}
|
|
546
|
+
};
|
|
547
|
+
}
|
|
548
|
+
function invoGameServerFromEnv(options) {
|
|
549
|
+
validateEconomy(options.economy);
|
|
550
|
+
const env = options.env;
|
|
551
|
+
const sandbox = (env["INVO_ENV"] ?? "sandbox").toLowerCase() !== "production";
|
|
552
|
+
const baseUrl = env["INVO_BASE_URL"] || (sandbox ? "https://sandbox.invo.network/sandbox" : "https://invo.network");
|
|
553
|
+
const missing = ["INVO_GAME_SECRET", "INVO_WEBHOOK_SECRET"].filter((k) => !env[k]?.trim());
|
|
554
|
+
if (missing.length) {
|
|
555
|
+
return { server: setupRequiredServer(options.economy, missing, sandbox, options.basePath), missing, sandbox };
|
|
556
|
+
}
|
|
557
|
+
const baseFetch = options.fetch ?? ((input, init) => fetch(input, init));
|
|
558
|
+
const projectId = sandbox ? options.projectId?.trim() : void 0;
|
|
559
|
+
const invoFetch = projectId ? (input, init) => {
|
|
560
|
+
const headers = new Headers(init?.headers);
|
|
561
|
+
headers.set("X-Invo-Project-Id", projectId);
|
|
562
|
+
return baseFetch(input, { ...init, headers });
|
|
563
|
+
} : baseFetch;
|
|
564
|
+
const invo = new InvoServer({ gameSecret: env["INVO_GAME_SECRET"].trim(), baseUrl, fetch: invoFetch });
|
|
565
|
+
const server = createInvoGameServer({
|
|
566
|
+
invo,
|
|
567
|
+
webhookSecret: env["INVO_WEBHOOK_SECRET"].split(",").map((s) => s.trim()).filter(Boolean),
|
|
568
|
+
economy: options.economy,
|
|
569
|
+
store: options.store,
|
|
570
|
+
sandbox,
|
|
571
|
+
basePath: options.basePath,
|
|
572
|
+
publicUrl: env["PUBLIC_URL"] || void 0,
|
|
573
|
+
log: options.log
|
|
574
|
+
});
|
|
575
|
+
return { server, missing, sandbox };
|
|
576
|
+
}
|
|
577
|
+
function setupRequiredServer(economy, missing, sandbox, basePathOpt) {
|
|
578
|
+
const basePath = (basePathOpt ?? "/api/invo").replace(/\/+$/, "");
|
|
579
|
+
const message = `Add ${missing.join(" and ")} to your environment (on Replit: Tools \u2192 Secrets), then restart.`;
|
|
580
|
+
return {
|
|
581
|
+
basePath,
|
|
582
|
+
async handle(request) {
|
|
583
|
+
const url = new URL(request.url);
|
|
584
|
+
if (url.pathname !== basePath && !url.pathname.startsWith(basePath + "/")) return null;
|
|
585
|
+
const sub = url.pathname.slice(basePath.length) || "/";
|
|
586
|
+
if (request.method === "GET" && sub === "/health") return json(200, { ok: true, setupRequired: true, missing, sandbox });
|
|
587
|
+
if (request.method === "GET" && sub === "/catalog") {
|
|
588
|
+
const body = { premium: { name: economy.premium.name, packs: economy.premium.packs }, soft: { name: economy.soft.name }, items: economy.items, sandbox };
|
|
589
|
+
return json(200, body);
|
|
590
|
+
}
|
|
591
|
+
return json(503, { error: { code: "INVO_SETUP_REQUIRED", message } });
|
|
592
|
+
}
|
|
593
|
+
};
|
|
594
|
+
}
|
|
595
|
+
function toNodeListener(server, fallback) {
|
|
596
|
+
return async (req, res) => {
|
|
597
|
+
const pathOnly = (req.url ?? "/").split("?")[0] ?? "/";
|
|
598
|
+
if (pathOnly !== server.basePath && !pathOnly.startsWith(server.basePath + "/")) {
|
|
599
|
+
if (fallback) {
|
|
600
|
+
await fallback(req, res);
|
|
601
|
+
} else {
|
|
602
|
+
res.statusCode = 404;
|
|
603
|
+
res.end("Not found");
|
|
604
|
+
}
|
|
605
|
+
return;
|
|
606
|
+
}
|
|
607
|
+
const headers = new Headers();
|
|
608
|
+
for (const [k, v] of Object.entries(req.headers)) {
|
|
609
|
+
if (v === void 0) continue;
|
|
610
|
+
if (Array.isArray(v)) v.forEach((x) => headers.append(k, x));
|
|
611
|
+
else headers.set(k, v);
|
|
612
|
+
}
|
|
613
|
+
const method = (req.method ?? "GET").toUpperCase();
|
|
614
|
+
let body;
|
|
615
|
+
if (method !== "GET" && method !== "HEAD") {
|
|
616
|
+
const chunks = [];
|
|
617
|
+
let size = 0;
|
|
618
|
+
for await (const chunk of req) {
|
|
619
|
+
const bytes = typeof chunk === "string" ? new TextEncoder().encode(chunk) : chunk;
|
|
620
|
+
size += bytes.length;
|
|
621
|
+
if (size > MAX_BODY_BYTES) {
|
|
622
|
+
res.statusCode = 413;
|
|
623
|
+
res.end(JSON.stringify({ error: { code: "BODY_TOO_LARGE", message: "Request body is too large." } }));
|
|
624
|
+
return;
|
|
625
|
+
}
|
|
626
|
+
chunks.push(bytes);
|
|
627
|
+
}
|
|
628
|
+
body = new Uint8Array(size);
|
|
629
|
+
let offset = 0;
|
|
630
|
+
for (const c of chunks) {
|
|
631
|
+
body.set(c, offset);
|
|
632
|
+
offset += c.length;
|
|
633
|
+
}
|
|
634
|
+
}
|
|
635
|
+
const host = headers.get("host") ?? "localhost";
|
|
636
|
+
const request = new Request(`http://${host}${req.url ?? "/"}`, { method, headers, body });
|
|
637
|
+
const response = await server.handle(request) ?? json(404, { error: { code: "NOT_FOUND", message: "No such route." } });
|
|
638
|
+
res.statusCode = response.status;
|
|
639
|
+
response.headers.forEach((value, name) => res.setHeader(name, value));
|
|
640
|
+
res.end(new Uint8Array(await response.arrayBuffer()));
|
|
641
|
+
};
|
|
642
|
+
}
|
|
643
|
+
function emptyGameState() {
|
|
644
|
+
return {
|
|
645
|
+
version: 1,
|
|
646
|
+
players: {},
|
|
647
|
+
sessions: {},
|
|
648
|
+
ledger: [],
|
|
649
|
+
ledgerRefs: {},
|
|
650
|
+
purchases: {},
|
|
651
|
+
idempotency: {},
|
|
652
|
+
inventory: {},
|
|
653
|
+
webhooks: {}
|
|
654
|
+
};
|
|
655
|
+
}
|
|
656
|
+
function clone(v) {
|
|
657
|
+
return JSON.parse(JSON.stringify(v));
|
|
658
|
+
}
|
|
659
|
+
function serial() {
|
|
660
|
+
let tail = Promise.resolve();
|
|
661
|
+
return (job) => {
|
|
662
|
+
const run = tail.then(job, job);
|
|
663
|
+
tail = run.catch(() => void 0);
|
|
664
|
+
return run;
|
|
665
|
+
};
|
|
666
|
+
}
|
|
667
|
+
function createMemoryGameStore(initial) {
|
|
668
|
+
let state = initial ? clone(initial) : emptyGameState();
|
|
669
|
+
const queue = serial();
|
|
670
|
+
return {
|
|
671
|
+
read: (fn) => queue(async () => fn(state)),
|
|
672
|
+
transact: (fn) => queue(async () => {
|
|
673
|
+
const draft = clone(state);
|
|
674
|
+
const out = fn(draft);
|
|
675
|
+
state = draft;
|
|
676
|
+
return out;
|
|
677
|
+
})
|
|
678
|
+
};
|
|
679
|
+
}
|
|
680
|
+
function createFileGameStore(options) {
|
|
681
|
+
const file = path.resolve(options.file);
|
|
682
|
+
const queue = serial();
|
|
683
|
+
let cache;
|
|
684
|
+
async function load() {
|
|
685
|
+
if (cache) return cache;
|
|
686
|
+
try {
|
|
687
|
+
const text = await promises.readFile(file, "utf8");
|
|
688
|
+
const parsed = JSON.parse(text);
|
|
689
|
+
cache = { ...emptyGameState(), ...parsed, version: 1 };
|
|
690
|
+
} catch (err) {
|
|
691
|
+
if (err.code !== "ENOENT") throw err;
|
|
692
|
+
cache = emptyGameState();
|
|
693
|
+
}
|
|
694
|
+
return cache;
|
|
695
|
+
}
|
|
696
|
+
async function save(state) {
|
|
697
|
+
await promises.mkdir(path.dirname(file), { recursive: true });
|
|
698
|
+
const tmp = `${file}.${Date.now()}.${Math.random().toString(36).slice(2)}.tmp`;
|
|
699
|
+
await promises.writeFile(tmp, JSON.stringify(state), "utf8");
|
|
700
|
+
await promises.rename(tmp, file);
|
|
701
|
+
}
|
|
702
|
+
return {
|
|
703
|
+
read: (fn) => queue(async () => fn(await load())),
|
|
704
|
+
transact: (fn) => queue(async () => {
|
|
705
|
+
const draft = clone(await load());
|
|
706
|
+
const out = fn(draft);
|
|
707
|
+
await save(draft);
|
|
708
|
+
cache = draft;
|
|
709
|
+
return out;
|
|
710
|
+
})
|
|
711
|
+
};
|
|
712
|
+
}
|
|
713
|
+
|
|
714
|
+
export { GameServerError, createFileGameStore, createInvoGameServer, createMemoryGameStore, emptyGameState, invoGameServerFromEnv, playerIdFor, toNodeListener, validateEconomy };
|
|
715
|
+
//# sourceMappingURL=game-server.js.map
|
|
716
|
+
//# sourceMappingURL=game-server.js.map
|