@energy8platform/game-engine 0.10.2 → 0.10.3

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