@energy8platform/game-engine 0.9.2 → 0.10.1

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.
@@ -0,0 +1,1000 @@
1
+ 'use strict';
2
+
3
+ const fengari$1 = require('fengari');
4
+ const { lua: lua$1, lauxlib: lauxlib$1 } = fengari$1;
5
+ const { to_luastring: to_luastring$1, to_jsstring: to_jsstring$1 } = fengari$1;
6
+ /**
7
+ * Seeded xoshiro128** PRNG for deterministic simulation/replay.
8
+ * Period: 2^128 - 1
9
+ */
10
+ function createSeededRng(seed) {
11
+ let s0 = (seed >>> 0) | 1;
12
+ let s1 = (seed * 1103515245 + 12345) >>> 0;
13
+ let s2 = (seed * 6364136223846793005 + 1442695040888963407) >>> 0;
14
+ let s3 = (seed * 1442695040888963407 + 6364136223846793005) >>> 0;
15
+ return () => {
16
+ const result = (((s1 * 5) << 7) * 9) >>> 0;
17
+ const t = s1 << 9;
18
+ s2 ^= s0;
19
+ s3 ^= s1;
20
+ s1 ^= s2;
21
+ s0 ^= s3;
22
+ s2 ^= t;
23
+ s3 = ((s3 << 11) | (s3 >>> 21)) >>> 0;
24
+ return result / 4294967296;
25
+ };
26
+ }
27
+ /**
28
+ * Implements and registers all platform `engine.*` functions into a Lua state.
29
+ */
30
+ class LuaEngineAPI {
31
+ rng;
32
+ logger;
33
+ gameDefinition;
34
+ constructor(gameDefinition, rng, logger) {
35
+ this.gameDefinition = gameDefinition;
36
+ this.rng = rng ?? Math.random;
37
+ this.logger = logger ?? ((level, msg) => {
38
+ const fn = level === 'error' ? console.error
39
+ : level === 'warn' ? console.warn
40
+ : level === 'debug' ? console.debug
41
+ : console.log;
42
+ fn(`[Lua:${level}] ${msg}`);
43
+ });
44
+ }
45
+ /** Register `engine` global table on the Lua state */
46
+ register(L) {
47
+ // Create the `engine` table
48
+ lua$1.lua_newtable(L);
49
+ this.registerFunction(L, 'random', (LS) => {
50
+ const min = lauxlib$1.luaL_checkinteger(LS, 1);
51
+ const max = lauxlib$1.luaL_checkinteger(LS, 2);
52
+ const result = this.random(Number(min), Number(max));
53
+ lua$1.lua_pushinteger(LS, result);
54
+ return 1;
55
+ });
56
+ this.registerFunction(L, 'random_float', (LS) => {
57
+ lua$1.lua_pushnumber(LS, this.randomFloat());
58
+ return 1;
59
+ });
60
+ this.registerFunction(L, 'random_weighted', (LS) => {
61
+ lauxlib$1.luaL_checktype(LS, 1, lua$1.LUA_TTABLE);
62
+ const weights = [];
63
+ const len = lua$1.lua_rawlen(LS, 1);
64
+ for (let i = 1; i <= len; i++) {
65
+ lua$1.lua_rawgeti(LS, 1, i);
66
+ weights.push(lua$1.lua_tonumber(LS, -1));
67
+ lua$1.lua_pop(LS, 1);
68
+ }
69
+ const result = this.randomWeighted(weights);
70
+ lua$1.lua_pushinteger(LS, result);
71
+ return 1;
72
+ });
73
+ this.registerFunction(L, 'shuffle', (LS) => {
74
+ lauxlib$1.luaL_checktype(LS, 1, lua$1.LUA_TTABLE);
75
+ const arr = [];
76
+ const len = lua$1.lua_rawlen(LS, 1);
77
+ for (let i = 1; i <= len; i++) {
78
+ lua$1.lua_rawgeti(LS, 1, i);
79
+ arr.push(luaToJS(LS, -1));
80
+ lua$1.lua_pop(LS, 1);
81
+ }
82
+ const shuffled = this.shuffle(arr);
83
+ pushJSArray(LS, shuffled);
84
+ return 1;
85
+ });
86
+ this.registerFunction(L, 'log', (LS) => {
87
+ const level = to_jsstring$1(lauxlib$1.luaL_checkstring(LS, 1));
88
+ const msg = to_jsstring$1(lauxlib$1.luaL_checkstring(LS, 2));
89
+ this.logger(level, msg);
90
+ return 0;
91
+ });
92
+ this.registerFunction(L, 'get_config', (LS) => {
93
+ const config = this.getConfig();
94
+ pushJSObject(LS, config);
95
+ return 1;
96
+ });
97
+ // Set the table as global `engine`
98
+ lua$1.lua_setglobal(L, to_luastring$1('engine'));
99
+ }
100
+ // ─── engine.* implementations ─────────────────────────
101
+ random(min, max) {
102
+ return Math.floor(this.rng() * (max - min + 1)) + min;
103
+ }
104
+ randomFloat() {
105
+ return this.rng();
106
+ }
107
+ randomWeighted(weights) {
108
+ const totalWeight = weights.reduce((a, b) => a + b, 0);
109
+ let roll = this.rng() * totalWeight;
110
+ for (let i = 0; i < weights.length; i++) {
111
+ roll -= weights[i];
112
+ if (roll < 0)
113
+ return i + 1; // 1-based index
114
+ }
115
+ return weights.length; // fallback to last
116
+ }
117
+ shuffle(arr) {
118
+ const copy = [...arr];
119
+ for (let i = copy.length - 1; i > 0; i--) {
120
+ const j = Math.floor(this.rng() * (i + 1));
121
+ [copy[i], copy[j]] = [copy[j], copy[i]];
122
+ }
123
+ return copy;
124
+ }
125
+ getConfig() {
126
+ const def = this.gameDefinition;
127
+ let betLevels = [];
128
+ if (Array.isArray(def.bet_levels)) {
129
+ betLevels = def.bet_levels;
130
+ }
131
+ else if (def.bet_levels && 'levels' in def.bet_levels && def.bet_levels.levels) {
132
+ betLevels = def.bet_levels.levels;
133
+ }
134
+ return {
135
+ id: def.id,
136
+ type: def.type,
137
+ bet_levels: betLevels,
138
+ };
139
+ }
140
+ // ─── Helpers ──────────────────────────────────────────
141
+ registerFunction(L, name, fn) {
142
+ lua$1.lua_pushcfunction(L, fn);
143
+ lua$1.lua_setfield(L, -2, to_luastring$1(name));
144
+ }
145
+ }
146
+ // ─── Lua ↔ JS marshalling ───────────────────────────────
147
+ /** Read a Lua value at the given stack index and return its JS equivalent */
148
+ function luaToJS(L, idx) {
149
+ const type = lua$1.lua_type(L, idx);
150
+ switch (type) {
151
+ case lua$1.LUA_TNIL:
152
+ return null;
153
+ case lua$1.LUA_TBOOLEAN:
154
+ return lua$1.lua_toboolean(L, idx);
155
+ case lua$1.LUA_TNUMBER:
156
+ if (lua$1.lua_isinteger(L, idx)) {
157
+ return Number(lua$1.lua_tointeger(L, idx));
158
+ }
159
+ return lua$1.lua_tonumber(L, idx);
160
+ case lua$1.LUA_TSTRING:
161
+ return to_jsstring$1(lua$1.lua_tostring(L, idx));
162
+ case lua$1.LUA_TTABLE:
163
+ return luaTableToJS(L, idx);
164
+ default:
165
+ return null;
166
+ }
167
+ }
168
+ /** Convert a Lua table to a JS object or array */
169
+ function luaTableToJS(L, idx) {
170
+ // Normalize index to absolute
171
+ if (idx < 0)
172
+ idx = lua$1.lua_gettop(L) + idx + 1;
173
+ // Check if it's an array (sequential integer keys starting at 1)
174
+ const len = lua$1.lua_rawlen(L, idx);
175
+ if (len > 0) {
176
+ // Verify it's a pure array by checking key 1 exists
177
+ lua$1.lua_rawgeti(L, idx, 1);
178
+ const hasFirst = lua$1.lua_type(L, -1) !== lua$1.LUA_TNIL;
179
+ lua$1.lua_pop(L, 1);
180
+ if (hasFirst) {
181
+ // Check if there are also string keys (mixed table)
182
+ let hasStringKeys = false;
183
+ lua$1.lua_pushnil(L);
184
+ while (lua$1.lua_next(L, idx) !== 0) {
185
+ lua$1.lua_pop(L, 1); // pop value
186
+ if (lua$1.lua_type(L, -1) === lua$1.LUA_TSTRING) {
187
+ hasStringKeys = true;
188
+ lua$1.lua_pop(L, 1); // pop key
189
+ break;
190
+ }
191
+ }
192
+ if (!hasStringKeys) {
193
+ // Pure array
194
+ const arr = [];
195
+ for (let i = 1; i <= len; i++) {
196
+ lua$1.lua_rawgeti(L, idx, i);
197
+ arr.push(luaToJS(L, -1));
198
+ lua$1.lua_pop(L, 1);
199
+ }
200
+ return arr;
201
+ }
202
+ }
203
+ }
204
+ // Object (or mixed table)
205
+ const obj = {};
206
+ lua$1.lua_pushnil(L);
207
+ while (lua$1.lua_next(L, idx) !== 0) {
208
+ const keyType = lua$1.lua_type(L, -2);
209
+ let key;
210
+ if (keyType === lua$1.LUA_TSTRING) {
211
+ key = to_jsstring$1(lua$1.lua_tostring(L, -2));
212
+ }
213
+ else if (keyType === lua$1.LUA_TNUMBER) {
214
+ key = String(lua$1.lua_tonumber(L, -2));
215
+ }
216
+ else {
217
+ lua$1.lua_pop(L, 1);
218
+ continue;
219
+ }
220
+ obj[key] = luaToJS(L, -1);
221
+ lua$1.lua_pop(L, 1);
222
+ }
223
+ return obj;
224
+ }
225
+ /** Push a JS value onto the Lua stack */
226
+ function pushJSValue(L, value) {
227
+ if (value === null || value === undefined) {
228
+ lua$1.lua_pushnil(L);
229
+ }
230
+ else if (typeof value === 'boolean') {
231
+ lua$1.lua_pushboolean(L, value ? 1 : 0);
232
+ }
233
+ else if (typeof value === 'number') {
234
+ if (Number.isInteger(value)) {
235
+ lua$1.lua_pushinteger(L, value);
236
+ }
237
+ else {
238
+ lua$1.lua_pushnumber(L, value);
239
+ }
240
+ }
241
+ else if (typeof value === 'string') {
242
+ lua$1.lua_pushstring(L, to_luastring$1(value));
243
+ }
244
+ else if (Array.isArray(value)) {
245
+ pushJSArray(L, value);
246
+ }
247
+ else if (typeof value === 'object') {
248
+ pushJSObject(L, value);
249
+ }
250
+ else {
251
+ lua$1.lua_pushnil(L);
252
+ }
253
+ }
254
+ /** Push a JS array as a Lua table (1-based) */
255
+ function pushJSArray(L, arr) {
256
+ lua$1.lua_createtable(L, arr.length, 0);
257
+ for (let i = 0; i < arr.length; i++) {
258
+ pushJSValue(L, arr[i]);
259
+ lua$1.lua_rawseti(L, -2, i + 1);
260
+ }
261
+ }
262
+ /** Push a JS object as a Lua table */
263
+ function pushJSObject(L, obj) {
264
+ const keys = Object.keys(obj);
265
+ lua$1.lua_createtable(L, 0, keys.length);
266
+ for (const key of keys) {
267
+ pushJSValue(L, obj[key]);
268
+ lua$1.lua_setfield(L, -2, to_luastring$1(key));
269
+ }
270
+ }
271
+
272
+ /**
273
+ * Replicates the platform's action dispatch and transition evaluation.
274
+ * Routes play requests to the correct action, evaluates transition conditions
275
+ * against current variables to determine next actions and session operations.
276
+ */
277
+ class ActionRouter {
278
+ actions;
279
+ constructor(gameDefinition) {
280
+ this.actions = gameDefinition.actions;
281
+ }
282
+ /** Look up action by name and validate prerequisites */
283
+ resolveAction(actionName, hasSession) {
284
+ const action = this.actions[actionName];
285
+ if (!action) {
286
+ throw new Error(`Unknown action: "${actionName}". Available: ${Object.keys(this.actions).join(', ')}`);
287
+ }
288
+ if (action.requires_session && !hasSession) {
289
+ throw new Error(`Action "${actionName}" requires an active session`);
290
+ }
291
+ return action;
292
+ }
293
+ /** Evaluate transitions in order, return the first matching rule */
294
+ evaluateTransitions(action, variables) {
295
+ for (const rule of action.transitions) {
296
+ if (evaluateCondition(rule.condition, variables)) {
297
+ return { rule, nextActions: rule.next_actions };
298
+ }
299
+ }
300
+ throw new Error(`No matching transition for action with stage "${action.stage}". ` +
301
+ `Variables: ${JSON.stringify(variables)}`);
302
+ }
303
+ }
304
+ // ─── Condition Evaluator ────────────────────────────────
305
+ /**
306
+ * Evaluates a transition condition expression against variables.
307
+ *
308
+ * Supports:
309
+ * - "always" → true
310
+ * - Simple comparisons: "var > 0", "var == 1", "var >= 10", "var != 0", "var < 5", "var <= 3"
311
+ * - Logical connectives: "expr && expr", "expr || expr"
312
+ *
313
+ * This covers all patterns used by the platform's govaluate conditions.
314
+ */
315
+ function evaluateCondition(condition, variables) {
316
+ const trimmed = condition.trim();
317
+ if (trimmed === 'always')
318
+ return true;
319
+ // Handle || (OR) — lowest precedence
320
+ if (trimmed.includes('||')) {
321
+ const parts = splitOnOperator(trimmed, '||');
322
+ return parts.some(part => evaluateCondition(part, variables));
323
+ }
324
+ // Handle && (AND)
325
+ if (trimmed.includes('&&')) {
326
+ const parts = splitOnOperator(trimmed, '&&');
327
+ return parts.every(part => evaluateCondition(part, variables));
328
+ }
329
+ // Single comparison: "variable op value"
330
+ return evaluateComparison(trimmed, variables);
331
+ }
332
+ function splitOnOperator(expr, operator) {
333
+ const parts = [];
334
+ let depth = 0;
335
+ let current = '';
336
+ for (let i = 0; i < expr.length; i++) {
337
+ if (expr[i] === '(')
338
+ depth++;
339
+ else if (expr[i] === ')')
340
+ depth--;
341
+ if (depth === 0 && expr.substring(i, i + operator.length) === operator) {
342
+ parts.push(current);
343
+ current = '';
344
+ i += operator.length - 1;
345
+ }
346
+ else {
347
+ current += expr[i];
348
+ }
349
+ }
350
+ parts.push(current);
351
+ return parts;
352
+ }
353
+ function evaluateComparison(expr, variables) {
354
+ // Match: variable_name operator value
355
+ const match = expr.trim().match(/^\s*([a-zA-Z_][a-zA-Z0-9_]*)\s*(>=|<=|!=|==|>|<)\s*(-?\d+(?:\.\d+)?)\s*$/);
356
+ if (!match) {
357
+ throw new Error(`Cannot parse condition: "${expr}"`);
358
+ }
359
+ const [, varName, op, valueStr] = match;
360
+ const left = variables[varName] ?? 0;
361
+ const right = parseFloat(valueStr);
362
+ switch (op) {
363
+ case '>': return left > right;
364
+ case '>=': return left >= right;
365
+ case '<': return left < right;
366
+ case '<=': return left <= right;
367
+ case '==': return left === right;
368
+ case '!=': return left !== right;
369
+ default: return false;
370
+ }
371
+ }
372
+
373
+ /**
374
+ * Manages session lifecycle: creation, spin counting, retriggers, and completion.
375
+ * Handles both slot sessions (fixed spin count) and table game sessions (unlimited).
376
+ * Also manages _persist_ data roundtrip between Lua calls.
377
+ */
378
+ class SessionManager {
379
+ session = null;
380
+ get isActive() {
381
+ return this.session !== null && !this.session.completed;
382
+ }
383
+ get current() {
384
+ if (!this.session)
385
+ return null;
386
+ return this.toSessionData();
387
+ }
388
+ get sessionTotalWin() {
389
+ return this.session?.totalWin ?? 0;
390
+ }
391
+ /** Create a new session from a transition rule */
392
+ createSession(rule, variables, bet) {
393
+ let spinsRemaining = -1; // unlimited by default
394
+ if (rule.session_config?.total_spins_var) {
395
+ const varName = rule.session_config.total_spins_var;
396
+ spinsRemaining = variables[varName] ?? -1;
397
+ }
398
+ const persistentVars = {};
399
+ if (rule.session_config?.persistent_vars) {
400
+ for (const varName of rule.session_config.persistent_vars) {
401
+ persistentVars[varName] = variables[varName] ?? 0;
402
+ }
403
+ }
404
+ this.session = {
405
+ spinsRemaining,
406
+ spinsPlayed: 0,
407
+ totalWin: 0,
408
+ completed: false,
409
+ maxWinReached: false,
410
+ bet,
411
+ persistentVars,
412
+ persistentData: {},
413
+ };
414
+ return this.toSessionData();
415
+ }
416
+ /** Update session after a spin: decrement counter, accumulate win, handle retrigger */
417
+ updateSession(rule, variables, spinWin) {
418
+ if (!this.session)
419
+ throw new Error('No active session');
420
+ // Accumulate win
421
+ this.session.totalWin += spinWin;
422
+ this.session.spinsPlayed++;
423
+ // Decrement spins (only for non-unlimited sessions)
424
+ if (this.session.spinsRemaining > 0) {
425
+ this.session.spinsRemaining--;
426
+ }
427
+ // Handle retrigger (add_spins_var)
428
+ if (rule.add_spins_var) {
429
+ const extraSpins = variables[rule.add_spins_var] ?? 0;
430
+ if (extraSpins > 0 && this.session.spinsRemaining >= 0) {
431
+ this.session.spinsRemaining += extraSpins;
432
+ }
433
+ }
434
+ // Update persistent vars
435
+ if (this.session.persistentVars) {
436
+ for (const key of Object.keys(this.session.persistentVars)) {
437
+ if (key in variables) {
438
+ this.session.persistentVars[key] = variables[key];
439
+ }
440
+ }
441
+ }
442
+ // Auto-complete if spins exhausted
443
+ if (this.session.spinsRemaining === 0) {
444
+ this.session.completed = true;
445
+ }
446
+ return this.toSessionData();
447
+ }
448
+ /** Complete the session, return accumulated totalWin */
449
+ completeSession() {
450
+ if (!this.session)
451
+ throw new Error('No active session to complete');
452
+ this.session.completed = true;
453
+ const totalWin = this.session.totalWin;
454
+ const session = this.toSessionData();
455
+ return { totalWin, session };
456
+ }
457
+ /** Mark max win reached — stops the session */
458
+ markMaxWinReached() {
459
+ if (this.session) {
460
+ this.session.maxWinReached = true;
461
+ this.session.completed = true;
462
+ }
463
+ }
464
+ /** Store _persist_* data extracted from Lua result */
465
+ storePersistData(data) {
466
+ if (!this.session)
467
+ return;
468
+ for (const key of Object.keys(data)) {
469
+ if (key.startsWith('_persist_')) {
470
+ const cleanKey = key.slice('_persist_'.length);
471
+ this.session.persistentData[cleanKey] = data[key];
472
+ }
473
+ }
474
+ }
475
+ /** Get _ps_* params to inject into next execute() call */
476
+ getPersistentParams() {
477
+ if (!this.session)
478
+ return {};
479
+ const params = {};
480
+ // Session persistent vars (float64)
481
+ for (const [key, value] of Object.entries(this.session.persistentVars)) {
482
+ params[key] = value;
483
+ }
484
+ // _persist_ complex data → _ps_*
485
+ for (const [key, value] of Object.entries(this.session.persistentData)) {
486
+ params[`_ps_${key}`] = value;
487
+ }
488
+ return params;
489
+ }
490
+ /** Reset all session state */
491
+ reset() {
492
+ this.session = null;
493
+ }
494
+ toSessionData() {
495
+ if (!this.session)
496
+ throw new Error('No session');
497
+ return {
498
+ spinsRemaining: this.session.spinsRemaining,
499
+ spinsPlayed: this.session.spinsPlayed,
500
+ totalWin: Math.round(this.session.totalWin * 100) / 100,
501
+ completed: this.session.completed,
502
+ maxWinReached: this.session.maxWinReached,
503
+ betAmount: this.session.bet,
504
+ };
505
+ }
506
+ }
507
+
508
+ /**
509
+ * Manages cross-spin persistent state — variables that survive between base game spins.
510
+ * Separate from session-scoped persistence (handled by SessionManager).
511
+ *
512
+ * Handles two mechanisms:
513
+ * 1. Numeric vars declared in `persistent_state.vars` — stored in state.variables
514
+ * 2. Complex data with `_persist_game_*` prefix — stored separately, injected as `_ps_*`
515
+ */
516
+ class PersistentState {
517
+ config;
518
+ vars = {};
519
+ gameData = {};
520
+ constructor(config) {
521
+ this.config = config;
522
+ }
523
+ /** Load persistent vars into variables map before execute() */
524
+ loadIntoVariables(variables) {
525
+ if (!this.config)
526
+ return;
527
+ for (const varName of this.config.vars) {
528
+ if (varName in this.vars) {
529
+ variables[varName] = this.vars[varName];
530
+ }
531
+ }
532
+ }
533
+ /** Save persistent vars from variables map after execute() */
534
+ saveFromVariables(variables) {
535
+ if (!this.config)
536
+ return;
537
+ for (const varName of this.config.vars) {
538
+ if (varName in variables) {
539
+ this.vars[varName] = variables[varName];
540
+ }
541
+ }
542
+ }
543
+ /** Extract _persist_game_* keys from Lua return data, store them */
544
+ storeGameData(data) {
545
+ for (const key of Object.keys(data)) {
546
+ if (key.startsWith('_persist_game_')) {
547
+ const cleanKey = key.slice('_persist_game_'.length);
548
+ this.gameData[cleanKey] = data[key];
549
+ delete data[key]; // remove from client data
550
+ }
551
+ }
552
+ }
553
+ /** Get _ps_* params for next execute() call */
554
+ getGameDataParams() {
555
+ const params = {};
556
+ for (const [key, value] of Object.entries(this.gameData)) {
557
+ params[`_ps_${key}`] = value;
558
+ }
559
+ return params;
560
+ }
561
+ /** Get exposed vars for client data.persistent_state */
562
+ getExposedVars() {
563
+ if (!this.config?.exposed_vars?.length)
564
+ return undefined;
565
+ const exposed = {};
566
+ for (const varName of this.config.exposed_vars) {
567
+ if (varName in this.vars) {
568
+ exposed[varName] = this.vars[varName];
569
+ }
570
+ }
571
+ return exposed;
572
+ }
573
+ /** Reset all state */
574
+ reset() {
575
+ this.vars = {};
576
+ this.gameData = {};
577
+ }
578
+ }
579
+
580
+ const fengari = require('fengari');
581
+ const { lua, lauxlib, lualib } = fengari;
582
+ const { to_luastring, to_jsstring } = fengari;
583
+ /**
584
+ * Runs Lua game scripts locally, replicating the platform's server-side execution.
585
+ *
586
+ * Implements the full lifecycle: action routing → state assembly → Lua execute() →
587
+ * result extraction → transition evaluation → session management.
588
+ *
589
+ * @example
590
+ * ```ts
591
+ * const engine = new LuaEngine({
592
+ * script: luaSource,
593
+ * gameDefinition: { id: 'my-slot', type: 'SLOT', actions: { ... } },
594
+ * });
595
+ *
596
+ * const result = engine.execute({ action: 'spin', bet: 1.0 });
597
+ * // result.data.matrix, result.totalWin, result.nextActions, etc.
598
+ * ```
599
+ */
600
+ class LuaEngine {
601
+ L;
602
+ api;
603
+ actionRouter;
604
+ sessionManager;
605
+ persistentState;
606
+ gameDefinition;
607
+ variables = {};
608
+ constructor(config) {
609
+ this.gameDefinition = config.gameDefinition;
610
+ // Set up RNG
611
+ const rng = config.seed !== undefined
612
+ ? createSeededRng(config.seed)
613
+ : undefined;
614
+ // Initialize sub-managers
615
+ this.api = new LuaEngineAPI(config.gameDefinition, rng, config.logger);
616
+ this.actionRouter = new ActionRouter(config.gameDefinition);
617
+ this.sessionManager = new SessionManager();
618
+ this.persistentState = new PersistentState(config.gameDefinition.persistent_state);
619
+ // Create Lua state and load standard libraries
620
+ this.L = lauxlib.luaL_newstate();
621
+ lualib.luaL_openlibs(this.L);
622
+ // Register engine.* API
623
+ this.api.register(this.L);
624
+ // Load and compile the script
625
+ this.loadScript(config.script);
626
+ }
627
+ /** Current session data (if any) */
628
+ get session() {
629
+ return this.sessionManager.current;
630
+ }
631
+ /** Current persistent state values */
632
+ get persistentVars() {
633
+ return { ...this.variables };
634
+ }
635
+ /**
636
+ * Execute a play action — the main entry point.
637
+ * This is what DevBridge calls on each PLAY_REQUEST.
638
+ */
639
+ execute(params) {
640
+ const { action: actionName, bet, params: clientParams } = params;
641
+ // 1. Resolve the action definition
642
+ const action = this.actionRouter.resolveAction(actionName, this.sessionManager.isActive);
643
+ // 2. Build state.variables
644
+ const stateVars = { ...this.variables, bet };
645
+ // Load cross-spin persistent state
646
+ this.persistentState.loadIntoVariables(stateVars);
647
+ // Load session persistent vars
648
+ if (this.sessionManager.isActive) {
649
+ const sessionParams = this.sessionManager.getPersistentParams();
650
+ for (const [k, v] of Object.entries(sessionParams)) {
651
+ if (typeof v === 'number') {
652
+ stateVars[k] = v;
653
+ }
654
+ }
655
+ }
656
+ // 3. Build state.params
657
+ const stateParams = { ...clientParams };
658
+ stateParams._action = actionName;
659
+ // Inject session _ps_* persistent data
660
+ if (this.sessionManager.isActive) {
661
+ const sessionParams = this.sessionManager.getPersistentParams();
662
+ for (const [k, v] of Object.entries(sessionParams)) {
663
+ if (typeof v !== 'number') {
664
+ stateParams[k] = v;
665
+ }
666
+ }
667
+ }
668
+ // Inject cross-spin _ps_* game data
669
+ const gameDataParams = this.persistentState.getGameDataParams();
670
+ Object.assign(stateParams, gameDataParams);
671
+ // Handle buy bonus
672
+ if (action.buy_bonus_mode && this.gameDefinition.buy_bonus) {
673
+ const mode = this.gameDefinition.buy_bonus.modes[action.buy_bonus_mode];
674
+ if (mode) {
675
+ stateParams.buy_bonus = true;
676
+ stateParams.buy_bonus_mode = action.buy_bonus_mode;
677
+ stateParams.forced_scatter_count = this.pickFromDistribution(mode.scatter_distribution);
678
+ }
679
+ }
680
+ // Handle ante bet
681
+ if (clientParams?.ante_bet && this.gameDefinition.ante_bet) {
682
+ stateParams.ante_bet = true;
683
+ }
684
+ // 4. Build the state table and call Lua execute()
685
+ const luaResult = this.callLuaExecute(action.stage, stateParams, stateVars);
686
+ // 5. Extract special fields from Lua result
687
+ const totalWinMultiplier = typeof luaResult.total_win === 'number' ? luaResult.total_win : 0;
688
+ const resultVariables = (luaResult.variables ?? {});
689
+ const totalWin = Math.round(totalWinMultiplier * bet * 100) / 100;
690
+ // Merge result variables into engine variables
691
+ Object.assign(stateVars, resultVariables);
692
+ this.variables = { ...stateVars };
693
+ delete this.variables.bet; // bet is per-spin, not persistent
694
+ // Build client data (everything except special keys)
695
+ const data = {};
696
+ for (const [key, value] of Object.entries(luaResult)) {
697
+ if (key !== 'total_win' && key !== 'variables') {
698
+ data[key] = value;
699
+ }
700
+ }
701
+ // 6. Apply max win cap
702
+ let cappedWin = totalWin;
703
+ if (this.gameDefinition.max_win) {
704
+ const cap = this.calculateMaxWinCap(bet);
705
+ if (cap !== undefined && totalWin > cap) {
706
+ cappedWin = cap;
707
+ this.variables.max_win_reached = 1;
708
+ data.max_win_reached = true;
709
+ this.sessionManager.markMaxWinReached();
710
+ }
711
+ }
712
+ // 7. Handle _persist_* and _persist_game_* keys
713
+ this.sessionManager.storePersistData(data);
714
+ this.persistentState.storeGameData(data);
715
+ // Save cross-spin persistent state
716
+ this.persistentState.saveFromVariables(this.variables);
717
+ // Add exposed persistent vars to client data
718
+ const exposedVars = this.persistentState.getExposedVars();
719
+ if (exposedVars) {
720
+ data.persistent_state = exposedVars;
721
+ }
722
+ // Remove _persist_* keys from client data
723
+ for (const key of Object.keys(data)) {
724
+ if (key.startsWith('_persist_')) {
725
+ delete data[key];
726
+ }
727
+ }
728
+ // 8. Evaluate transitions
729
+ const { rule, nextActions } = this.actionRouter.evaluateTransitions(action, this.variables);
730
+ let creditDeferred = action.credit === 'defer' || rule.credit_override === 'defer';
731
+ let session = this.sessionManager.current;
732
+ // Handle session creation
733
+ if (rule.creates_session && !this.sessionManager.isActive) {
734
+ session = this.sessionManager.createSession(rule, this.variables, bet);
735
+ creditDeferred = true;
736
+ }
737
+ // Handle session update
738
+ else if (this.sessionManager.isActive) {
739
+ session = this.sessionManager.updateSession(rule, this.variables, cappedWin);
740
+ // Handle session completion
741
+ if (rule.complete_session || session?.completed) {
742
+ const completed = this.sessionManager.completeSession();
743
+ session = completed.session;
744
+ creditDeferred = false;
745
+ }
746
+ }
747
+ return {
748
+ totalWin: cappedWin,
749
+ data,
750
+ nextActions,
751
+ session,
752
+ variables: { ...this.variables },
753
+ creditDeferred,
754
+ };
755
+ }
756
+ /** Reset all state (sessions, persistent vars, variables) */
757
+ reset() {
758
+ this.variables = {};
759
+ this.sessionManager.reset();
760
+ this.persistentState.reset();
761
+ }
762
+ /** Destroy the Lua VM */
763
+ destroy() {
764
+ if (this.L) {
765
+ lua.lua_close(this.L);
766
+ this.L = null;
767
+ }
768
+ }
769
+ // ─── Private ──────────────────────────────────────────
770
+ loadScript(source) {
771
+ const status = lauxlib.luaL_dostring(this.L, to_luastring(source));
772
+ if (status !== lua.LUA_OK) {
773
+ const err = to_jsstring(lua.lua_tostring(this.L, -1));
774
+ lua.lua_pop(this.L, 1);
775
+ throw new Error(`Failed to load Lua script: ${err}`);
776
+ }
777
+ // Verify that execute() function exists
778
+ lua.lua_getglobal(this.L, to_luastring('execute'));
779
+ if (lua.lua_type(this.L, -1) !== lua.LUA_TFUNCTION) {
780
+ lua.lua_pop(this.L, 1);
781
+ throw new Error('Lua script must define a global `execute(state)` function');
782
+ }
783
+ lua.lua_pop(this.L, 1);
784
+ }
785
+ callLuaExecute(stage, params, variables) {
786
+ // Push the execute function
787
+ lua.lua_getglobal(this.L, to_luastring('execute'));
788
+ // Build and push the state table
789
+ lua.lua_createtable(this.L, 0, 3);
790
+ // state.stage
791
+ lua.lua_pushstring(this.L, to_luastring(stage));
792
+ lua.lua_setfield(this.L, -2, to_luastring('stage'));
793
+ // state.params
794
+ pushJSValue(this.L, params);
795
+ lua.lua_setfield(this.L, -2, to_luastring('params'));
796
+ // state.variables
797
+ pushJSValue(this.L, variables);
798
+ lua.lua_setfield(this.L, -2, to_luastring('variables'));
799
+ // Call execute(state) → 1 result
800
+ const status = lua.lua_pcall(this.L, 1, 1, 0);
801
+ if (status !== lua.LUA_OK) {
802
+ const err = to_jsstring(lua.lua_tostring(this.L, -1));
803
+ lua.lua_pop(this.L, 1);
804
+ throw new Error(`Lua execute() failed: ${err}`);
805
+ }
806
+ // Marshal result table to JS
807
+ const result = luaToJS(this.L, -1);
808
+ lua.lua_pop(this.L, 1);
809
+ if (!result || typeof result !== 'object' || Array.isArray(result)) {
810
+ throw new Error('Lua execute() must return a table');
811
+ }
812
+ return result;
813
+ }
814
+ calculateMaxWinCap(bet) {
815
+ const mw = this.gameDefinition.max_win;
816
+ if (!mw)
817
+ return undefined;
818
+ const caps = [];
819
+ if (mw.multiplier !== undefined)
820
+ caps.push(bet * mw.multiplier);
821
+ if (mw.fixed !== undefined)
822
+ caps.push(mw.fixed);
823
+ return caps.length > 0 ? Math.min(...caps) : undefined;
824
+ }
825
+ pickFromDistribution(distribution) {
826
+ const entries = Object.entries(distribution);
827
+ const totalWeight = entries.reduce((sum, [, w]) => sum + w, 0);
828
+ let roll = this.api.randomFloat() * totalWeight;
829
+ for (const [value, weight] of entries) {
830
+ roll -= weight;
831
+ if (roll < 0)
832
+ return parseInt(value, 10);
833
+ }
834
+ return parseInt(entries[entries.length - 1][0], 10);
835
+ }
836
+ }
837
+
838
+ /**
839
+ * Runs N iterations of a Lua game script and collects RTP statistics.
840
+ * Supports regular spins, buy bonus, and ante bet simulation.
841
+ *
842
+ * @example
843
+ * ```ts
844
+ * const runner = new SimulationRunner({
845
+ * script: luaSource,
846
+ * gameDefinition,
847
+ * iterations: 1_000_000,
848
+ * bet: 1.0,
849
+ * seed: 42,
850
+ * onProgress: (done, total) => console.log(`${done}/${total}`),
851
+ * });
852
+ *
853
+ * const result = runner.run();
854
+ * console.log(`RTP: ${result.totalRtp.toFixed(2)}%`);
855
+ * ```
856
+ */
857
+ class SimulationRunner {
858
+ config;
859
+ constructor(config) {
860
+ this.config = config;
861
+ }
862
+ run() {
863
+ const { script, gameDefinition, iterations, bet, seed, action: startAction = 'spin', params, progressInterval = 100_000, onProgress, } = this.config;
864
+ const engine = new LuaEngine({
865
+ script,
866
+ gameDefinition,
867
+ seed,
868
+ logger: () => { }, // suppress Lua logs during simulation
869
+ });
870
+ const spinCost = this.calculateSpinCost(startAction, bet, gameDefinition, params);
871
+ let totalWagered = 0;
872
+ let totalWon = 0;
873
+ let baseGameWin = 0;
874
+ let bonusWin = 0;
875
+ let hits = 0;
876
+ let maxWinMultiplier = 0;
877
+ let maxWinHits = 0;
878
+ let bonusTriggered = 0;
879
+ let bonusSpinsPlayed = 0;
880
+ const startTime = Date.now();
881
+ try {
882
+ for (let i = 0; i < iterations; i++) {
883
+ totalWagered += spinCost;
884
+ let roundWin = 0;
885
+ // Execute the starting action
886
+ const result = engine.execute({
887
+ action: startAction,
888
+ bet,
889
+ params,
890
+ });
891
+ const baseWin = result.totalWin;
892
+ roundWin += baseWin;
893
+ // If a bonus session was created, play through it
894
+ if (result.session && !result.session.completed) {
895
+ bonusTriggered++;
896
+ // Find the bonus action from nextActions (different from startAction)
897
+ const bonusAction = result.nextActions.find(a => a !== startAction)
898
+ ?? result.nextActions[0];
899
+ // Play bonus spins until session completes
900
+ let bonusSessionWin = 0;
901
+ let safetyLimit = 10_000;
902
+ let lastResult = result;
903
+ while (lastResult.session && !lastResult.session.completed && safetyLimit-- > 0) {
904
+ lastResult = engine.execute({
905
+ action: bonusAction,
906
+ bet,
907
+ });
908
+ bonusSessionWin += lastResult.totalWin;
909
+ bonusSpinsPlayed++;
910
+ }
911
+ bonusWin += bonusSessionWin;
912
+ roundWin += bonusSessionWin;
913
+ }
914
+ baseGameWin += baseWin;
915
+ totalWon += roundWin;
916
+ if (roundWin > 0)
917
+ hits++;
918
+ const roundMultiplier = roundWin / bet;
919
+ if (roundMultiplier > maxWinMultiplier) {
920
+ maxWinMultiplier = roundMultiplier;
921
+ }
922
+ if (result.variables?.max_win_reached === 1) {
923
+ maxWinHits++;
924
+ }
925
+ // Progress reporting
926
+ if (onProgress && (i + 1) % progressInterval === 0) {
927
+ onProgress(i + 1, iterations);
928
+ }
929
+ }
930
+ }
931
+ finally {
932
+ engine.destroy();
933
+ }
934
+ const durationMs = Date.now() - startTime;
935
+ return {
936
+ gameId: gameDefinition.id,
937
+ action: startAction,
938
+ iterations,
939
+ durationMs,
940
+ totalRtp: totalWagered > 0 ? (totalWon / totalWagered) * 100 : 0,
941
+ baseGameRtp: totalWagered > 0 ? (baseGameWin / totalWagered) * 100 : 0,
942
+ bonusRtp: totalWagered > 0 ? (bonusWin / totalWagered) * 100 : 0,
943
+ hitFrequency: iterations > 0 ? (hits / iterations) * 100 : 0,
944
+ maxWin: Math.round(maxWinMultiplier * 100) / 100,
945
+ maxWinHits,
946
+ bonusTriggered,
947
+ bonusSpinsPlayed,
948
+ };
949
+ }
950
+ /** Calculate the real cost of one spin (accounting for buy bonus / ante bet) */
951
+ calculateSpinCost(action, bet, gameDefinition, params) {
952
+ // Check if this is a buy bonus action
953
+ const actionDef = gameDefinition.actions[action];
954
+ if (actionDef?.buy_bonus_mode && gameDefinition.buy_bonus) {
955
+ const mode = gameDefinition.buy_bonus.modes[actionDef.buy_bonus_mode];
956
+ if (mode) {
957
+ return bet * mode.cost_multiplier;
958
+ }
959
+ }
960
+ // Check ante bet
961
+ if (params?.ante_bet && gameDefinition.ante_bet) {
962
+ return bet * gameDefinition.ante_bet.cost_multiplier;
963
+ }
964
+ return bet;
965
+ }
966
+ }
967
+ /** Format a SimulationResult for console output */
968
+ function formatSimulationResult(result) {
969
+ const lines = [
970
+ '',
971
+ '--- Simulation Results ---',
972
+ `Game: ${result.gameId}`,
973
+ `Action: ${result.action}`,
974
+ `Iterations: ${result.iterations.toLocaleString()}`,
975
+ `Duration: ${(result.durationMs / 1000).toFixed(1)}s`,
976
+ `Total RTP: ${result.totalRtp.toFixed(2)}%`,
977
+ `Base Game RTP: ${result.baseGameRtp.toFixed(2)}%`,
978
+ `Bonus RTP: ${result.bonusRtp.toFixed(2)}%`,
979
+ `Hit Frequency: ${result.hitFrequency.toFixed(2)}%`,
980
+ `Max Win: ${result.maxWin.toFixed(2)}x`,
981
+ `Max Win Hits: ${result.maxWinHits} (rounds capped by max_win)`,
982
+ ];
983
+ if (result.bonusTriggered > 0) {
984
+ const frequency = Math.round(result.iterations / result.bonusTriggered);
985
+ lines.push(`Bonus Triggered: ${result.bonusTriggered.toLocaleString()} (1 in ${frequency} spins)`);
986
+ lines.push(`Bonus Spins Played: ${result.bonusSpinsPlayed.toLocaleString()}`);
987
+ }
988
+ return lines.join('\n');
989
+ }
990
+
991
+ exports.ActionRouter = ActionRouter;
992
+ exports.LuaEngine = LuaEngine;
993
+ exports.LuaEngineAPI = LuaEngineAPI;
994
+ exports.PersistentState = PersistentState;
995
+ exports.SessionManager = SessionManager;
996
+ exports.SimulationRunner = SimulationRunner;
997
+ exports.createSeededRng = createSeededRng;
998
+ exports.evaluateCondition = evaluateCondition;
999
+ exports.formatSimulationResult = formatSimulationResult;
1000
+ //# sourceMappingURL=lua.cjs.js.map