@invonetwork/web-sdk 3.27.0 → 3.29.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.
@@ -1,8 +1,9 @@
1
- import { InvoServer } from './server.cjs';
1
+ import { I as InvoServer, a as InvoEnvironment } from './server-UZ38eD2p.cjs';
2
+ export { D as DEMO_KEY_PREFIX, E as EnvironmentUnknownError, P as PRODUCTION_BASE_URL, S as SANDBOX_BASE_URL, b as baseUrlForKey, i as isDemoKey, r as resolveEnvironment, v as verifyInvoSignature } from './server-UZ38eD2p.cjs';
2
3
  import { G as GameCurrencyKind, a as GamePurchaseStatus, b as GameEconomyConfig } from './types-CoW9LopI.cjs';
3
4
  export { c as GameCatalog, d as GameCatalogItem, e as GameCheckout, f as GameCurrencyBalance, g as GameErrorBody, h as GameItemPurchase, i as GamePlayer, j as GamePremiumPack, k as GamePurchase, l as GameSession, m as GameWallet } from './types-CoW9LopI.cjs';
4
5
  export { I as InvoError } from './types-_lIm74kd.cjs';
5
- export { S as SDK_VERSION } from './version-BXFwI0-s.cjs';
6
+ export { S as SDK_VERSION } from './version-xyYQO5hp.cjs';
6
7
 
7
8
  interface StoredPlayer {
8
9
  id: string;
@@ -108,6 +109,12 @@ interface InvoGameServerOptions {
108
109
  now?: () => Date;
109
110
  /** Structured log sink. Never receives secrets, tokens or full phone numbers. */
110
111
  log?: (level: GameServerLogLevel, message: string, fields?: Record<string, unknown>) => void;
112
+ /**
113
+ * Set when `invo` uses the public demo key (3.29.0): sign-ins are mapped to the demo
114
+ * sandbox's player email format for this project and given a fictional phone, so no real
115
+ * address or number ever reaches INVO. {@link invoGameServerFromEnv} sets it for you.
116
+ */
117
+ demoProjectId?: string;
111
118
  }
112
119
  interface InvoGameServer {
113
120
  readonly basePath: string;
@@ -135,11 +142,23 @@ interface InvoGameServerFromEnvOptions {
135
142
  basePath?: string;
136
143
  log?: InvoGameServerOptions["log"];
137
144
  /**
138
- * A stable id for this copy of the game (e.g. one per Replit fork), sent to INVO's sandbox
139
- * as the `X-Invo-Project-Id` header so sandbox activity can be told apart per project and
140
- * carried over when the project goes live. Not sent in production. Not a secret.
145
+ * A stable id for this copy of the game (e.g. one per Replit fork): `proj_` + a 26-character
146
+ * uppercase ULID (see {@link newProjectId}). Sent to INVO as the `X-Invo-Project-Id` header on
147
+ * every call, so sandbox activity is told apart per project, and so the first live call after
148
+ * go-live links the project to your INVO account. Required with the public demo key. Not a
149
+ * secret. `INVO_PROJECT_ID` in `env` is used when this is not given.
141
150
  */
142
151
  projectId?: string;
152
+ /**
153
+ * The webhook signing secret, when it does not come from `INVO_WEBHOOK_SECRET` (3.29.0):
154
+ * for example the one {@link registerProject} stored for a template fork.
155
+ */
156
+ webhookSecret?: string | string[];
157
+ /**
158
+ * Public demo key only: where the fork's project id, webhook secret and registration token
159
+ * are kept. Default `.invo/project.json`. Keep it out of version control.
160
+ */
161
+ projectFile?: string;
143
162
  /** Override `fetch` for the calls to INVO (tests, proxies). */
144
163
  fetch?: typeof fetch;
145
164
  }
@@ -148,7 +167,10 @@ interface InvoGameServerSetup {
148
167
  server: InvoGameServer;
149
168
  /** Names of required environment variables that are not set. Empty when ready. */
150
169
  missing: string[];
170
+ /** True once the key is known to be a sandbox key. False while a live key is being looked up. */
151
171
  sandbox: boolean;
172
+ /** `"sandbox"`, `"production"`, or `"resolving"` while a key's environment is being looked up. */
173
+ environment: InvoEnvironment | "resolving";
152
174
  }
153
175
  /**
154
176
  * Build the game server from environment variables (Replit Secrets, `.env`, your host's
@@ -156,13 +178,18 @@ interface InvoGameServerSetup {
156
178
  * `503 INVO_SETUP_REQUIRED` naming what to add, `/health` and `/catalog` keep working, and the
157
179
  * game itself stays playable.
158
180
  *
159
- * - `INVO_GAME_SECRET` (required): the game secret for this environment, from the INVO console
181
+ * - `INVO_GAME_SECRET` (required): your INVO key. The environment follows the key (3.28.0): the
182
+ * public demo key (`ivsdk_demo_...`) is the sandbox; any other key is looked up once with
183
+ * `GET /api/sdk/key-environment`. Going live is swapping this key, nothing else.
160
184
  * - `INVO_WEBHOOK_SECRET` (required): the webhook signing secret; several, comma-separated, while rotating
161
- * - `INVO_ENV`: `sandbox` (default) or `production`
185
+ * - `INVO_PROJECT_ID`: this copy's project id, when `projectId` is not passed
186
+ * - `INVO_ENV`: `sandbox` or `production`, only to override the key-based choice
162
187
  * - `INVO_BASE_URL`: override the API base (rarely needed)
163
188
  * - `PUBLIC_URL`: the game's public origin, for checkout return links
164
189
  */
165
190
  declare function invoGameServerFromEnv(options: InvoGameServerFromEnvOptions): InvoGameServerSetup;
191
+ /** A new template project id: `proj_` + a 26-character uppercase Crockford ULID. */
192
+ declare function newProjectId(now?: number): string;
166
193
  /** The parts of Node's `IncomingMessage` the adapter reads. */
167
194
  interface NodeRequestLike {
168
195
  method?: string;
@@ -182,4 +209,58 @@ interface NodeResponseLike {
182
209
  */
183
210
  declare function toNodeListener(server: InvoGameServer, fallback?: (req: NodeRequestLike, res: NodeResponseLike) => unknown): (req: NodeRequestLike, res: NodeResponseLike) => Promise<void>;
184
211
 
185
- export { type FileGameStoreOptions, GameCurrencyKind, GameEconomyConfig, GamePurchaseStatus, GameServerError, type GameServerLogLevel, type GameStore, type GameStoreState, type InvoGameServer, type InvoGameServerFromEnvOptions, type InvoGameServerOptions, type InvoGameServerSetup, InvoServer, type LedgerEntry, type NodeRequestLike, type NodeResponseLike, type StoredIdempotentResult, type StoredPlayer, type StoredPurchase, type StoredSession, createFileGameStore, createInvoGameServer, createMemoryGameStore, emptyGameState, invoGameServerFromEnv, playerIdFor, toNodeListener, validateEconomy };
212
+ declare const DEMO_EMAIL_DOMAIN = "demo.invo.network";
213
+ declare const DEFAULT_PROJECT_FILE = ".invo/project.json";
214
+ /** What the project file holds. Secrets: keep the file out of version control. */
215
+ interface DemoProjectFile {
216
+ projectId: string;
217
+ /** The public host the project was registered from (remix detection). */
218
+ host?: string;
219
+ webhookUrl?: string;
220
+ webhookSecret?: string;
221
+ registrationToken?: string;
222
+ }
223
+ declare function isValidProjectId(value: unknown): value is string;
224
+ /**
225
+ * The demo-sandbox email for a player, deterministic per (email, project):
226
+ * `<local part, cleaned>-<8 hex of sha256(email)>+<project ulid lowercase>@demo.invo.network`.
227
+ */
228
+ declare function toDemoEmail(email: string, projectId: string): string;
229
+ /** The fictional phone INVO's demo sandbox accepts for a player: `+1202555 01XX`. */
230
+ declare function demoPhoneFor(email: string): string;
231
+ /**
232
+ * This fork's project, from `INVO_PROJECT_ID`, else the project file, else a new id written to
233
+ * the file. When `publicUrl`'s host differs from the host the file was registered from, the file
234
+ * was copied by a remix: a fresh project id replaces it.
235
+ */
236
+ declare function loadProject(opts?: {
237
+ file?: string;
238
+ publicUrl?: string;
239
+ projectId?: string;
240
+ }): DemoProjectFile;
241
+ interface RegisterProjectOptions {
242
+ /** The public demo key (`ivsdk_demo_...`). */
243
+ gameSecret: string;
244
+ /** This fork's public webhook URL, e.g. `https://my-game.replit.app/api/invo/webhook`. */
245
+ webhookUrl: string;
246
+ file?: string;
247
+ projectId?: string;
248
+ baseUrl?: string;
249
+ fetch?: typeof fetch;
250
+ }
251
+ interface RegisteredProject {
252
+ projectId: string;
253
+ /** The signing secret to verify INVO webhooks with, or null if INVO never returned one. */
254
+ webhookSecret: string | null;
255
+ /** True when this call created the registration (a new fork). */
256
+ created: boolean;
257
+ }
258
+ /**
259
+ * Register this fork with the demo sandbox (call on every server start). The first call
260
+ * stores the webhook signing secret and the registration token in the project file; later
261
+ * calls change nothing unless the webhook URL moved. A `409 PROJECT_REGISTERED` (a remix that
262
+ * copied another fork's project id) gets a fresh project id, once.
263
+ */
264
+ declare function registerProject(opts: RegisterProjectOptions): Promise<RegisteredProject>;
265
+
266
+ export { DEFAULT_PROJECT_FILE, DEMO_EMAIL_DOMAIN, type DemoProjectFile, type FileGameStoreOptions, GameCurrencyKind, GameEconomyConfig, GamePurchaseStatus, GameServerError, type GameServerLogLevel, type GameStore, type GameStoreState, InvoEnvironment, type InvoGameServer, type InvoGameServerFromEnvOptions, type InvoGameServerOptions, type InvoGameServerSetup, InvoServer, type LedgerEntry, type NodeRequestLike, type NodeResponseLike, type RegisterProjectOptions, type RegisteredProject, type StoredIdempotentResult, type StoredPlayer, type StoredPurchase, type StoredSession, createFileGameStore, createInvoGameServer, createMemoryGameStore, demoPhoneFor, emptyGameState, invoGameServerFromEnv, isValidProjectId, loadProject, newProjectId, playerIdFor, registerProject, toDemoEmail, toNodeListener, validateEconomy };
@@ -1,8 +1,9 @@
1
- import { InvoServer } from './server.js';
1
+ import { I as InvoServer, a as InvoEnvironment } from './server-Dnx5jxS4.js';
2
+ export { D as DEMO_KEY_PREFIX, E as EnvironmentUnknownError, P as PRODUCTION_BASE_URL, S as SANDBOX_BASE_URL, b as baseUrlForKey, i as isDemoKey, r as resolveEnvironment, v as verifyInvoSignature } from './server-Dnx5jxS4.js';
2
3
  import { G as GameCurrencyKind, a as GamePurchaseStatus, b as GameEconomyConfig } from './types-CoW9LopI.js';
3
4
  export { c as GameCatalog, d as GameCatalogItem, e as GameCheckout, f as GameCurrencyBalance, g as GameErrorBody, h as GameItemPurchase, i as GamePlayer, j as GamePremiumPack, k as GamePurchase, l as GameSession, m as GameWallet } from './types-CoW9LopI.js';
4
5
  export { I as InvoError } from './types-_lIm74kd.js';
5
- export { S as SDK_VERSION } from './version-BXFwI0-s.js';
6
+ export { S as SDK_VERSION } from './version-xyYQO5hp.js';
6
7
 
7
8
  interface StoredPlayer {
8
9
  id: string;
@@ -108,6 +109,12 @@ interface InvoGameServerOptions {
108
109
  now?: () => Date;
109
110
  /** Structured log sink. Never receives secrets, tokens or full phone numbers. */
110
111
  log?: (level: GameServerLogLevel, message: string, fields?: Record<string, unknown>) => void;
112
+ /**
113
+ * Set when `invo` uses the public demo key (3.29.0): sign-ins are mapped to the demo
114
+ * sandbox's player email format for this project and given a fictional phone, so no real
115
+ * address or number ever reaches INVO. {@link invoGameServerFromEnv} sets it for you.
116
+ */
117
+ demoProjectId?: string;
111
118
  }
112
119
  interface InvoGameServer {
113
120
  readonly basePath: string;
@@ -135,11 +142,23 @@ interface InvoGameServerFromEnvOptions {
135
142
  basePath?: string;
136
143
  log?: InvoGameServerOptions["log"];
137
144
  /**
138
- * A stable id for this copy of the game (e.g. one per Replit fork), sent to INVO's sandbox
139
- * as the `X-Invo-Project-Id` header so sandbox activity can be told apart per project and
140
- * carried over when the project goes live. Not sent in production. Not a secret.
145
+ * A stable id for this copy of the game (e.g. one per Replit fork): `proj_` + a 26-character
146
+ * uppercase ULID (see {@link newProjectId}). Sent to INVO as the `X-Invo-Project-Id` header on
147
+ * every call, so sandbox activity is told apart per project, and so the first live call after
148
+ * go-live links the project to your INVO account. Required with the public demo key. Not a
149
+ * secret. `INVO_PROJECT_ID` in `env` is used when this is not given.
141
150
  */
142
151
  projectId?: string;
152
+ /**
153
+ * The webhook signing secret, when it does not come from `INVO_WEBHOOK_SECRET` (3.29.0):
154
+ * for example the one {@link registerProject} stored for a template fork.
155
+ */
156
+ webhookSecret?: string | string[];
157
+ /**
158
+ * Public demo key only: where the fork's project id, webhook secret and registration token
159
+ * are kept. Default `.invo/project.json`. Keep it out of version control.
160
+ */
161
+ projectFile?: string;
143
162
  /** Override `fetch` for the calls to INVO (tests, proxies). */
144
163
  fetch?: typeof fetch;
145
164
  }
@@ -148,7 +167,10 @@ interface InvoGameServerSetup {
148
167
  server: InvoGameServer;
149
168
  /** Names of required environment variables that are not set. Empty when ready. */
150
169
  missing: string[];
170
+ /** True once the key is known to be a sandbox key. False while a live key is being looked up. */
151
171
  sandbox: boolean;
172
+ /** `"sandbox"`, `"production"`, or `"resolving"` while a key's environment is being looked up. */
173
+ environment: InvoEnvironment | "resolving";
152
174
  }
153
175
  /**
154
176
  * Build the game server from environment variables (Replit Secrets, `.env`, your host's
@@ -156,13 +178,18 @@ interface InvoGameServerSetup {
156
178
  * `503 INVO_SETUP_REQUIRED` naming what to add, `/health` and `/catalog` keep working, and the
157
179
  * game itself stays playable.
158
180
  *
159
- * - `INVO_GAME_SECRET` (required): the game secret for this environment, from the INVO console
181
+ * - `INVO_GAME_SECRET` (required): your INVO key. The environment follows the key (3.28.0): the
182
+ * public demo key (`ivsdk_demo_...`) is the sandbox; any other key is looked up once with
183
+ * `GET /api/sdk/key-environment`. Going live is swapping this key, nothing else.
160
184
  * - `INVO_WEBHOOK_SECRET` (required): the webhook signing secret; several, comma-separated, while rotating
161
- * - `INVO_ENV`: `sandbox` (default) or `production`
185
+ * - `INVO_PROJECT_ID`: this copy's project id, when `projectId` is not passed
186
+ * - `INVO_ENV`: `sandbox` or `production`, only to override the key-based choice
162
187
  * - `INVO_BASE_URL`: override the API base (rarely needed)
163
188
  * - `PUBLIC_URL`: the game's public origin, for checkout return links
164
189
  */
165
190
  declare function invoGameServerFromEnv(options: InvoGameServerFromEnvOptions): InvoGameServerSetup;
191
+ /** A new template project id: `proj_` + a 26-character uppercase Crockford ULID. */
192
+ declare function newProjectId(now?: number): string;
166
193
  /** The parts of Node's `IncomingMessage` the adapter reads. */
167
194
  interface NodeRequestLike {
168
195
  method?: string;
@@ -182,4 +209,58 @@ interface NodeResponseLike {
182
209
  */
183
210
  declare function toNodeListener(server: InvoGameServer, fallback?: (req: NodeRequestLike, res: NodeResponseLike) => unknown): (req: NodeRequestLike, res: NodeResponseLike) => Promise<void>;
184
211
 
185
- export { type FileGameStoreOptions, GameCurrencyKind, GameEconomyConfig, GamePurchaseStatus, GameServerError, type GameServerLogLevel, type GameStore, type GameStoreState, type InvoGameServer, type InvoGameServerFromEnvOptions, type InvoGameServerOptions, type InvoGameServerSetup, InvoServer, type LedgerEntry, type NodeRequestLike, type NodeResponseLike, type StoredIdempotentResult, type StoredPlayer, type StoredPurchase, type StoredSession, createFileGameStore, createInvoGameServer, createMemoryGameStore, emptyGameState, invoGameServerFromEnv, playerIdFor, toNodeListener, validateEconomy };
212
+ declare const DEMO_EMAIL_DOMAIN = "demo.invo.network";
213
+ declare const DEFAULT_PROJECT_FILE = ".invo/project.json";
214
+ /** What the project file holds. Secrets: keep the file out of version control. */
215
+ interface DemoProjectFile {
216
+ projectId: string;
217
+ /** The public host the project was registered from (remix detection). */
218
+ host?: string;
219
+ webhookUrl?: string;
220
+ webhookSecret?: string;
221
+ registrationToken?: string;
222
+ }
223
+ declare function isValidProjectId(value: unknown): value is string;
224
+ /**
225
+ * The demo-sandbox email for a player, deterministic per (email, project):
226
+ * `<local part, cleaned>-<8 hex of sha256(email)>+<project ulid lowercase>@demo.invo.network`.
227
+ */
228
+ declare function toDemoEmail(email: string, projectId: string): string;
229
+ /** The fictional phone INVO's demo sandbox accepts for a player: `+1202555 01XX`. */
230
+ declare function demoPhoneFor(email: string): string;
231
+ /**
232
+ * This fork's project, from `INVO_PROJECT_ID`, else the project file, else a new id written to
233
+ * the file. When `publicUrl`'s host differs from the host the file was registered from, the file
234
+ * was copied by a remix: a fresh project id replaces it.
235
+ */
236
+ declare function loadProject(opts?: {
237
+ file?: string;
238
+ publicUrl?: string;
239
+ projectId?: string;
240
+ }): DemoProjectFile;
241
+ interface RegisterProjectOptions {
242
+ /** The public demo key (`ivsdk_demo_...`). */
243
+ gameSecret: string;
244
+ /** This fork's public webhook URL, e.g. `https://my-game.replit.app/api/invo/webhook`. */
245
+ webhookUrl: string;
246
+ file?: string;
247
+ projectId?: string;
248
+ baseUrl?: string;
249
+ fetch?: typeof fetch;
250
+ }
251
+ interface RegisteredProject {
252
+ projectId: string;
253
+ /** The signing secret to verify INVO webhooks with, or null if INVO never returned one. */
254
+ webhookSecret: string | null;
255
+ /** True when this call created the registration (a new fork). */
256
+ created: boolean;
257
+ }
258
+ /**
259
+ * Register this fork with the demo sandbox (call on every server start). The first call
260
+ * stores the webhook signing secret and the registration token in the project file; later
261
+ * calls change nothing unless the webhook URL moved. A `409 PROJECT_REGISTERED` (a remix that
262
+ * copied another fork's project id) gets a fresh project id, once.
263
+ */
264
+ declare function registerProject(opts: RegisterProjectOptions): Promise<RegisteredProject>;
265
+
266
+ export { DEFAULT_PROJECT_FILE, DEMO_EMAIL_DOMAIN, type DemoProjectFile, type FileGameStoreOptions, GameCurrencyKind, GameEconomyConfig, GamePurchaseStatus, GameServerError, type GameServerLogLevel, type GameStore, type GameStoreState, InvoEnvironment, type InvoGameServer, type InvoGameServerFromEnvOptions, type InvoGameServerOptions, type InvoGameServerSetup, InvoServer, type LedgerEntry, type NodeRequestLike, type NodeResponseLike, type RegisterProjectOptions, type RegisteredProject, type StoredIdempotentResult, type StoredPlayer, type StoredPurchase, type StoredSession, createFileGameStore, createInvoGameServer, createMemoryGameStore, demoPhoneFor, emptyGameState, invoGameServerFromEnv, isValidProjectId, loadProject, newProjectId, playerIdFor, registerProject, toDemoEmail, toNodeListener, validateEconomy };
@@ -1,13 +1,129 @@
1
- import { InvoServer, verifyWebhook } from './chunk-2DYTV74W.js';
2
- export { InvoServer } from './chunk-2DYTV74W.js';
1
+ import { isDemoKey, SANDBOX_BASE_URL, PRODUCTION_BASE_URL, InvoServer, resolveEnvironment, verifyWebhook } from './chunk-FJR44FKW.js';
2
+ export { DEMO_KEY_PREFIX, EnvironmentUnknownError, InvoServer, PRODUCTION_BASE_URL, SANDBOX_BASE_URL, baseUrlForKey, isDemoKey, resolveEnvironment, verifyInvoSignature } from './chunk-FJR44FKW.js';
3
3
  import './chunk-6CN236QH.js';
4
- export { SDK_VERSION } from './chunk-3YDO7GSH.js';
4
+ export { SDK_VERSION } from './chunk-KZJABBVT.js';
5
5
  import { InvoError } from './chunk-VP3OK4J4.js';
6
6
  export { InvoError } from './chunk-VP3OK4J4.js';
7
7
  import { createHash, randomBytes } from 'crypto';
8
- import { promises } from 'fs';
8
+ import { promises, readFileSync, mkdirSync, writeFileSync } from 'fs';
9
9
  import * as path from 'path';
10
+ import { dirname } from 'path';
10
11
 
12
+ var DEMO_EMAIL_DOMAIN = "demo.invo.network";
13
+ var DEFAULT_PROJECT_FILE = ".invo/project.json";
14
+ var PROJECT_ID = /^proj_[0-9A-HJKMNP-TV-Z]{26}$/;
15
+ function newDemoProjectId(now = Date.now()) {
16
+ const A = "0123456789ABCDEFGHJKMNPQRSTVWXYZ";
17
+ let t = now;
18
+ let time = "";
19
+ for (let i = 0; i < 10; i++) {
20
+ time = A[t % 32] + time;
21
+ t = Math.floor(t / 32);
22
+ }
23
+ const bytes = randomBytes(16);
24
+ let rand = "";
25
+ for (let i = 0; i < 16; i++) rand += A[bytes[i] % 32];
26
+ return "proj_" + time + rand;
27
+ }
28
+ function isValidProjectId(value) {
29
+ return typeof value === "string" && PROJECT_ID.test(value);
30
+ }
31
+ function toDemoEmail(email, projectId) {
32
+ if (!isValidProjectId(projectId)) throw new Error("A valid template project id is required.");
33
+ const lower = email.trim().toLowerCase();
34
+ if (lower.endsWith("@" + DEMO_EMAIL_DOMAIN)) return lower;
35
+ const local = (lower.split("@")[0] ?? "player").replace(/[^a-z0-9._-]/g, "").slice(0, 24) || "player";
36
+ const tag = createHash("sha256").update(lower).digest("hex").slice(0, 8);
37
+ return `${local}-${tag}+${projectId.slice(5).toLowerCase()}@${DEMO_EMAIL_DOMAIN}`;
38
+ }
39
+ function demoPhoneFor(email) {
40
+ const n = BigInt("0x" + createHash("sha256").update(email.trim().toLowerCase()).digest("hex")) % BigInt(100);
41
+ return "+120255501" + n.toString().padStart(2, "0");
42
+ }
43
+ function hostOf(url) {
44
+ if (!url) return void 0;
45
+ try {
46
+ return new URL(url).host.toLowerCase();
47
+ } catch {
48
+ return void 0;
49
+ }
50
+ }
51
+ function readFile(file) {
52
+ try {
53
+ const data = JSON.parse(readFileSync(file, "utf8"));
54
+ return isValidProjectId(data.projectId) ? data : null;
55
+ } catch {
56
+ return null;
57
+ }
58
+ }
59
+ function writeFile(file, data) {
60
+ mkdirSync(dirname(file), { recursive: true });
61
+ writeFileSync(file, JSON.stringify(data, null, 2) + "\n", { encoding: "utf8", mode: 384 });
62
+ }
63
+ function loadProject(opts = {}) {
64
+ const file = opts.file ?? DEFAULT_PROJECT_FILE;
65
+ if (opts.projectId) {
66
+ if (!isValidProjectId(opts.projectId)) throw new Error('INVO_PROJECT_ID must be "proj_" + a 26-character ULID.');
67
+ const saved2 = readFile(file);
68
+ return saved2 && saved2.projectId === opts.projectId ? saved2 : { projectId: opts.projectId };
69
+ }
70
+ const host = hostOf(opts.publicUrl);
71
+ const saved = readFile(file);
72
+ if (saved && (!host || !saved.host || saved.host === host)) return saved;
73
+ const fresh = { projectId: newDemoProjectId(), host };
74
+ try {
75
+ writeFile(file, fresh);
76
+ } catch {
77
+ }
78
+ return fresh;
79
+ }
80
+ async function registerProject(opts) {
81
+ if (!isDemoKey(opts.gameSecret)) throw new Error("registerProject is for the public demo key only.");
82
+ const file = opts.file ?? DEFAULT_PROJECT_FILE;
83
+ const fetchImpl = opts.fetch ?? ((input, init) => fetch(input, init));
84
+ const base = (opts.baseUrl ?? SANDBOX_BASE_URL).replace(/\/+$/, "");
85
+ let project = loadProject({ file, publicUrl: opts.webhookUrl, projectId: opts.projectId });
86
+ for (let attempt = 0; attempt < 2; attempt++) {
87
+ const res = await fetchImpl(base + "/api/demo/projects/register", {
88
+ method: "POST",
89
+ redirect: "error",
90
+ headers: {
91
+ "Content-Type": "application/json",
92
+ Accept: "application/json",
93
+ "X-Game-Secret-Key": opts.gameSecret,
94
+ "X-Invo-Project-Id": project.projectId,
95
+ "X-Invo-Project-Host": hostOf(opts.webhookUrl) ?? ""
96
+ },
97
+ body: JSON.stringify({ webhook_url: opts.webhookUrl, registration_token: project.registrationToken })
98
+ });
99
+ const body = await res.json().catch(() => ({}));
100
+ if (res.status === 409 && body.error_code === "PROJECT_REGISTERED" && attempt === 0 && !opts.projectId) {
101
+ project = { projectId: newDemoProjectId(), host: hostOf(opts.webhookUrl) };
102
+ continue;
103
+ }
104
+ if (!res.ok) throw new Error(`INVO demo registration failed (${res.status} ${body.error_code ?? ""}): ${body.error ?? ""}`.trim());
105
+ const created = res.status === 201;
106
+ if (created) {
107
+ project = {
108
+ projectId: project.projectId,
109
+ host: hostOf(opts.webhookUrl),
110
+ webhookUrl: opts.webhookUrl,
111
+ webhookSecret: body.webhook?.signing_secret ?? project.webhookSecret,
112
+ registrationToken: body.registration_token ?? project.registrationToken
113
+ };
114
+ } else {
115
+ project = { ...project, host: project.host ?? hostOf(opts.webhookUrl), webhookUrl: opts.webhookUrl };
116
+ }
117
+ try {
118
+ writeFile(file, project);
119
+ } catch {
120
+ }
121
+ return { projectId: project.projectId, webhookSecret: project.webhookSecret ?? null, created };
122
+ }
123
+ throw new Error("INVO demo registration failed.");
124
+ }
125
+
126
+ // src/game/server.ts
11
127
  var MAX_BODY_BYTES = 1e6;
12
128
  var EMAIL = /^[^\s@]{1,64}@[^\s@]{1,255}\.[^\s@]{2,63}$/;
13
129
  var E164 = /^\+[1-9]\d{6,14}$/;
@@ -199,9 +315,12 @@ function createInvoGameServer(options) {
199
315
  const name = (rawName || email.split("@")[0] || "Player").slice(0, 64);
200
316
  const id = playerIdFor(email);
201
317
  const known = await store.read((s) => s.players[id] ?? null);
202
- const phoneForInvo = phone ?? known?.phone ?? void 0;
318
+ const demoPid = options.demoProjectId;
319
+ const invoEmail = demoPid ? toDemoEmail(email, demoPid) : email;
320
+ const phoneForInvo = demoPid ? demoPhoneFor(invoEmail) : phone ?? known?.phone ?? void 0;
321
+ const storedPhone = demoPid ? null : phone;
203
322
  try {
204
- await invo.mintPlayerToken({ playerEmail: email, playerPhone: phoneForInvo, playerName: name });
323
+ await invo.mintPlayerToken({ playerEmail: invoEmail, playerPhone: phoneForInvo, playerName: name });
205
324
  } catch (err) {
206
325
  if (err instanceof InvoError && err.status === 404) {
207
326
  throw new GameServerError(400, "PHONE_REQUIRED", "First sign-in needs a phone number so INVO can create your account.");
@@ -213,7 +332,7 @@ function createInvoGameServer(options) {
213
332
  const expiresAt = new Date(now().getTime() + sessionTtlMs).toISOString();
214
333
  const player = await store.transact((s) => {
215
334
  const existing = s.players[id];
216
- const record = existing ? { ...existing, name, phone: phone ?? existing.phone } : { id, email, phone, name, createdAt: iso() };
335
+ const record = existing ? { ...existing, email: invoEmail, name, phone: storedPhone ?? existing.phone } : { id, email: invoEmail, phone: storedPhone, name, createdAt: iso() };
217
336
  s.players[id] = record;
218
337
  if (soft.starting > 0) {
219
338
  addLedger(s, { playerId: id, currency: "soft", amount: soft.starting, reason: "starting balance", ref: `start:${id}`, at: iso() });
@@ -548,31 +667,72 @@ function createInvoGameServer(options) {
548
667
  function invoGameServerFromEnv(options) {
549
668
  validateEconomy(options.economy);
550
669
  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());
670
+ const secret = env["INVO_GAME_SECRET"]?.trim() ?? "";
671
+ const forced = env["INVO_ENV"]?.trim().toLowerCase();
672
+ const known = forced ? forced === "production" ? "production" : "sandbox" : env["INVO_BASE_URL"] || !secret || isDemoKey(secret) ? "sandbox" : null;
673
+ const state = { environment: known };
674
+ const sandboxNow = () => state.environment === "sandbox";
675
+ const envNow = () => state.environment ?? "resolving";
676
+ const demo = isDemoKey(secret);
677
+ const demoProject = demo ? loadProject({ file: options.projectFile ?? DEFAULT_PROJECT_FILE, publicUrl: env["PUBLIC_URL"], projectId: (options.projectId ?? env["INVO_PROJECT_ID"])?.trim() || void 0 }) : null;
678
+ const webhookSecrets = (() => {
679
+ const raw = options.webhookSecret ?? env["INVO_WEBHOOK_SECRET"] ?? demoProject?.webhookSecret ?? "";
680
+ return (Array.isArray(raw) ? raw : raw.split(",")).map((s) => s.trim()).filter(Boolean);
681
+ })();
682
+ const missing = [
683
+ ...secret ? [] : ["INVO_GAME_SECRET"],
684
+ ...webhookSecrets.length ? [] : ["INVO_WEBHOOK_SECRET"]
685
+ ];
554
686
  if (missing.length) {
555
- return { server: setupRequiredServer(options.economy, missing, sandbox, options.basePath), missing, sandbox };
687
+ return { server: setupRequiredServer(options.economy, missing, sandboxNow(), options.basePath), missing, sandbox: sandboxNow(), environment: envNow() };
556
688
  }
557
689
  const baseFetch = options.fetch ?? ((input, init) => fetch(input, init));
558
- const projectId = sandbox ? options.projectId?.trim() : void 0;
559
- const invoFetch = projectId ? (input, init) => {
690
+ const projectId = demoProject?.projectId ?? ((options.projectId ?? env["INVO_PROJECT_ID"])?.trim() || void 0);
691
+ const explicitBase = env["INVO_BASE_URL"] || (forced ? state.environment === "production" ? PRODUCTION_BASE_URL : SANDBOX_BASE_URL : "");
692
+ const resolveNow = () => resolveEnvironment(secret, { fetch: baseFetch }).then((e) => {
693
+ state.environment = e;
694
+ return e;
695
+ });
696
+ if (!explicitBase && !known) resolveNow().catch(() => void 0);
697
+ const invoFetch = async (input, init) => {
698
+ let url = typeof input === "string" ? input : input instanceof URL ? input.href : input.url;
699
+ if (!explicitBase) {
700
+ const e = known ?? state.environment ?? await resolveNow();
701
+ if (e === "sandbox" && url.startsWith(PRODUCTION_BASE_URL + "/")) url = SANDBOX_BASE_URL + url.slice(PRODUCTION_BASE_URL.length);
702
+ }
560
703
  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({
704
+ if (projectId) headers.set("X-Invo-Project-Id", projectId);
705
+ return baseFetch(url, { ...init, headers });
706
+ };
707
+ const invo = new InvoServer({ gameSecret: secret, baseUrl: explicitBase || PRODUCTION_BASE_URL, fetch: invoFetch });
708
+ const serverOptions = {
566
709
  invo,
567
- webhookSecret: env["INVO_WEBHOOK_SECRET"].split(",").map((s) => s.trim()).filter(Boolean),
710
+ webhookSecret: webhookSecrets,
711
+ demoProjectId: demo ? projectId : void 0,
568
712
  economy: options.economy,
569
713
  store: options.store,
570
- sandbox,
714
+ get sandbox() {
715
+ return sandboxNow();
716
+ },
571
717
  basePath: options.basePath,
572
718
  publicUrl: env["PUBLIC_URL"] || void 0,
573
719
  log: options.log
574
- });
575
- return { server, missing, sandbox };
720
+ };
721
+ const server = createInvoGameServer(serverOptions);
722
+ return { server, missing, sandbox: sandboxNow(), environment: envNow() };
723
+ }
724
+ function newProjectId(now = Date.now()) {
725
+ const A = "0123456789ABCDEFGHJKMNPQRSTVWXYZ";
726
+ let t = now;
727
+ let time = "";
728
+ for (let i = 0; i < 10; i++) {
729
+ time = A[t % 32] + time;
730
+ t = Math.floor(t / 32);
731
+ }
732
+ const bytes = randomBytes(16);
733
+ let rand = "";
734
+ for (let i = 0; i < 16; i++) rand += A[bytes[i] % 32];
735
+ return "proj_" + time + rand;
576
736
  }
577
737
  function setupRequiredServer(economy, missing, sandbox, basePathOpt) {
578
738
  const basePath = (basePathOpt ?? "/api/invo").replace(/\/+$/, "");
@@ -711,6 +871,6 @@ function createFileGameStore(options) {
711
871
  };
712
872
  }
713
873
 
714
- export { GameServerError, createFileGameStore, createInvoGameServer, createMemoryGameStore, emptyGameState, invoGameServerFromEnv, playerIdFor, toNodeListener, validateEconomy };
874
+ export { DEFAULT_PROJECT_FILE, DEMO_EMAIL_DOMAIN, GameServerError, createFileGameStore, createInvoGameServer, createMemoryGameStore, demoPhoneFor, emptyGameState, invoGameServerFromEnv, isValidProjectId, loadProject, newProjectId, playerIdFor, registerProject, toDemoEmail, toNodeListener, validateEconomy };
715
875
  //# sourceMappingURL=game-server.js.map
716
876
  //# sourceMappingURL=game-server.js.map
package/dist/game.cjs CHANGED
@@ -2162,7 +2162,7 @@ function mountInvoUI(container, economy, options = {}) {
2162
2162
  }
2163
2163
 
2164
2164
  // src/version.ts
2165
- var SDK_VERSION = "3.27.0";
2165
+ var SDK_VERSION = "3.29.0";
2166
2166
 
2167
2167
  exports.InvoGameEconomy = InvoGameEconomy;
2168
2168
  exports.InvoGameError = InvoGameError;
package/dist/game.d.cts CHANGED
@@ -1,6 +1,6 @@
1
1
  import { i as GamePlayer, m as GameWallet, c as GameCatalog, k as GamePurchase, h as GameItemPurchase, d as GameCatalogItem, f as GameCurrencyBalance } from './types-CoW9LopI.cjs';
2
2
  export { e as GameCheckout, G as GameCurrencyKind, b as GameEconomyConfig, g as GameErrorBody, j as GamePremiumPack, a as GamePurchaseStatus, l as GameSession } from './types-CoW9LopI.cjs';
3
- export { S as SDK_VERSION } from './version-BXFwI0-s.cjs';
3
+ export { S as SDK_VERSION } from './version-xyYQO5hp.cjs';
4
4
 
5
5
  /**
6
6
  * INVO game economy client (3.27.0), the browser half. It talks ONLY to your game server
package/dist/game.d.ts CHANGED
@@ -1,6 +1,6 @@
1
1
  import { i as GamePlayer, m as GameWallet, c as GameCatalog, k as GamePurchase, h as GameItemPurchase, d as GameCatalogItem, f as GameCurrencyBalance } from './types-CoW9LopI.js';
2
2
  export { e as GameCheckout, G as GameCurrencyKind, b as GameEconomyConfig, g as GameErrorBody, j as GamePremiumPack, a as GamePurchaseStatus, l as GameSession } from './types-CoW9LopI.js';
3
- export { S as SDK_VERSION } from './version-BXFwI0-s.js';
3
+ export { S as SDK_VERSION } from './version-xyYQO5hp.js';
4
4
 
5
5
  /**
6
6
  * INVO game economy client (3.27.0), the browser half. It talks ONLY to your game server
package/dist/game.js CHANGED
@@ -1,4 +1,4 @@
1
- export { SDK_VERSION } from './chunk-3YDO7GSH.js';
1
+ export { SDK_VERSION } from './chunk-KZJABBVT.js';
2
2
  import { newEventId } from './chunk-VP3OK4J4.js';
3
3
 
4
4
  // src/game/client.ts