@getenginex/sdk-igaming 0.0.0-stage → 0.5.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.
@@ -0,0 +1,734 @@
1
+ import { fail, ok } from '@getenginex/sdk/testing';
2
+
3
+ // src/testing/bonus.ts
4
+ var uuid = (n) => `c0000000-0000-4000-8000-${String(n).padStart(12, "0")}`;
5
+ var WINDOW = { starts_at: "2026-09-01T03:00:00Z", ends_at: "2027-01-01T03:00:00Z" };
6
+ var brl = (minor) => ({ amount: String(minor), currency: "BRL" });
7
+ var TERMS_DIGEST = "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855";
8
+ function offer(n, fields, texts) {
9
+ const [displayName, description] = texts;
10
+ return {
11
+ campaign_id: uuid(n),
12
+ campaign_version_id: uuid(100 + n),
13
+ publication_id: uuid(200 + n),
14
+ product_scope: "PRODUCT_SCOPE_CASINO",
15
+ timezone: "America/Sao_Paulo",
16
+ enrollment_window: WINDOW,
17
+ qualification_window: WINDOW,
18
+ publication_starts_at: WINDOW.starts_at,
19
+ publication_ends_at: WINDOW.ends_at,
20
+ ...fields,
21
+ content: {
22
+ default_locale: "pt-BR",
23
+ supported_locales: ["pt-BR"],
24
+ localized_content: [
25
+ {
26
+ locale: "pt-BR",
27
+ display_name: displayName,
28
+ description,
29
+ terms: `Termos de "${displayName}": v\xE1lido uma vez por jogador.`,
30
+ terms_revision: "v1"
31
+ }
32
+ ]
33
+ }
34
+ };
35
+ }
36
+ var WELCOME = offer(
37
+ 1,
38
+ {
39
+ claim_window: WINDOW,
40
+ entry_policy: { code: "ENTRY_POLICY_CODE_OPT_IN", version: 1 },
41
+ reward_claim_policy: { code: "REWARD_CLAIM_POLICY_CODE_PLAYER_CLAIM", version: 1 },
42
+ qualification: { version: 1, immediate: {} },
43
+ reward: {
44
+ reward_key: "welcome-credit",
45
+ reward_kind: "REWARD_KIND_BALANCE_CREDIT",
46
+ reward_kind_version: 1,
47
+ execution_profile_code: "EXECUTION_PROFILE_CODE_ENGINE_MANAGED_BALANCE",
48
+ execution_profile_version: 1,
49
+ balance_credit: {
50
+ fixed_amount: { amount: brl(5e3) },
51
+ balance_class: "BALANCE_CLASS_RESTRICTED",
52
+ proceeds_class: "PROCEEDS_CLASS_RESTRICTED_UNTIL_WAGERING_COMPLETION",
53
+ validity: { duration_from_grant: { duration: "604800s" } }
54
+ },
55
+ wagering_policy: {
56
+ version: 1,
57
+ multiplier: {
58
+ requirement_basis: "REQUIREMENT_BASIS_GRANTED_BALANCE",
59
+ multiplier: { decimal: "30" },
60
+ contribution_rates: [{ casino: { category_codes: ["slots"] }, rate: { basis_points: 1e4 } }],
61
+ rounding: "ROUNDING_MODE_HALF_UP"
62
+ }
63
+ },
64
+ stacking_policy: { version: 1, exclusive_in_group: { stacking_group_key: "welcome" } }
65
+ }
66
+ },
67
+ ["B\xF4nus de boas-vindas", "R$ 50 em b\xF4nus para jogar slots, com rollover de 30x."]
68
+ );
69
+ var FREE_SPINS = offer(
70
+ 2,
71
+ {
72
+ entry_policy: { code: "ENTRY_POLICY_CODE_AUTOMATIC", version: 1 },
73
+ reward_claim_policy: { code: "REWARD_CLAIM_POLICY_CODE_AUTOMATIC", version: 1 },
74
+ qualification: {
75
+ version: 1,
76
+ activity_aggregate: {
77
+ basis: "BASIS_SETTLED_STAKE",
78
+ product_scope: "PRODUCT_SCOPE_CASINO",
79
+ currency: "BRL",
80
+ window: "604800s",
81
+ timezone: "America/Sao_Paulo",
82
+ casino: { category_codes: ["slots"] }
83
+ }
84
+ },
85
+ reward: {
86
+ reward_key: "weekly-spins",
87
+ reward_kind: "REWARD_KIND_CASINO_FREE_SPINS",
88
+ reward_kind_version: 1,
89
+ execution_profile_code: "EXECUTION_PROFILE_CODE_PROVIDER_ENTITLEMENT",
90
+ execution_profile_version: 1,
91
+ casino_free_spins: {
92
+ provider_code: "pragmatic-play",
93
+ casino_scope: { game_ids: ["mock-game-1"] },
94
+ quantity: 50,
95
+ denomination: brl(20),
96
+ currency: "BRL",
97
+ grant_window: WINDOW,
98
+ proceeds_class: "PROCEEDS_CLASS_REAL"
99
+ },
100
+ wagering_policy: { version: 1, none: {} }
101
+ }
102
+ },
103
+ ["50 giros gr\xE1tis", "Aposte R$ 100 em slots na semana e ganhe 50 giros no Gates of Olympus."]
104
+ );
105
+ var PROMO = offer(
106
+ 3,
107
+ {
108
+ entry_policy: { code: "ENTRY_POLICY_CODE_PROMO_CODE", version: 1 },
109
+ reward_claim_policy: { code: "REWARD_CLAIM_POLICY_CODE_AUTOMATIC", version: 1 },
110
+ qualification: {
111
+ version: 1,
112
+ deposit_settled: {
113
+ currency: "BRL",
114
+ eligible_method_codes: ["pix"],
115
+ first_deposit_policy: "FIRST_DEPOSIT_POLICY_REQUIRED",
116
+ minimum_settled_net_amount: brl(2e3),
117
+ amount_basis: "DEPOSIT_AMOUNT_BASIS_SETTLED_NET_DEPOSIT"
118
+ }
119
+ },
120
+ reward: {
121
+ reward_key: "first-deposit",
122
+ reward_kind: "REWARD_KIND_BALANCE_CREDIT",
123
+ reward_kind_version: 1,
124
+ execution_profile_code: "EXECUTION_PROFILE_CODE_ENGINE_MANAGED_BALANCE",
125
+ execution_profile_version: 1,
126
+ balance_credit: {
127
+ percent_of_source_amount: {
128
+ percentage: { basis_points: 1e4 },
129
+ rounding: "ROUNDING_MODE_FLOOR",
130
+ maximum_reward: brl(5e4)
131
+ },
132
+ balance_class: "BALANCE_CLASS_RESTRICTED",
133
+ proceeds_class: "PROCEEDS_CLASS_RESTRICTED_UNTIL_WAGERING_COMPLETION",
134
+ validity: { no_expiry: {} }
135
+ },
136
+ wagering_policy: {
137
+ version: 1,
138
+ multiplier: {
139
+ requirement_basis: "REQUIREMENT_BASIS_GRANTED_BALANCE",
140
+ multiplier: { decimal: "20" },
141
+ rounding: "ROUNDING_MODE_HALF_UP"
142
+ }
143
+ },
144
+ stacking_policy: { version: 1, exclusive_in_group: { stacking_group_key: "welcome" } }
145
+ }
146
+ },
147
+ ["Primeiro dep\xF3sito em dobro", "100% do primeiro dep\xF3sito PIX (m\xEDnimo R$ 20) at\xE9 R$ 500."]
148
+ );
149
+ var OFFERS = [WELCOME, FREE_SPINS, PROMO];
150
+ var CATALOG = [WELCOME, FREE_SPINS];
151
+ var PROMO_CODES = { BEMVINDO: PROMO };
152
+ var UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
153
+ var NIL = "00000000-0000-0000-0000-000000000000";
154
+ function bodyOf(req) {
155
+ return typeof req.body === "object" && req.body !== null ? req.body : {};
156
+ }
157
+ function badId(req, param) {
158
+ const value = req.params?.[param] ?? "";
159
+ return UUID.test(value) && value !== NIL ? void 0 : fail(400, "INVALID_ARGUMENT", `${param} must be a valid non-zero UUID`);
160
+ }
161
+ function cursorPage(req, key, items) {
162
+ const q = req.url.searchParams;
163
+ let size = 20;
164
+ if (q.has("page_size")) {
165
+ size = Number(q.get("page_size"));
166
+ if (!Number.isInteger(size) || size <= 0)
167
+ return fail(400, "INVALID_ARGUMENT", "page_size must be a positive integer");
168
+ }
169
+ let start = 0;
170
+ if (q.has("cursor")) {
171
+ const match = /^mock-cursor-(\d+)$/.exec(q.get("cursor") ?? "");
172
+ if (!match) return fail(400, "INVALID_ARGUMENT", "invalid cursor");
173
+ start = Number(match[1]);
174
+ }
175
+ const page = items.slice(start, start + size);
176
+ const data = {};
177
+ if (page.length > 0) data[key] = page;
178
+ if (start + size < items.length) data.next_cursor = `mock-cursor-${start + size}`;
179
+ return ok(data);
180
+ }
181
+ function localized(o, locale) {
182
+ const content = o.content;
183
+ return content.localized_content.find((c) => c.locale === locale) ?? content.localized_content.find((c) => c.locale === content.default_locale);
184
+ }
185
+ function createBonusRoutes() {
186
+ const now = () => (/* @__PURE__ */ new Date()).toISOString();
187
+ let seq = 0;
188
+ const participations = [
189
+ participation(uuid(900), FREE_SPINS, { completed: { completed_at: "2026-09-20T15:00:00Z" } })
190
+ ];
191
+ const replays = /* @__PURE__ */ new Map();
192
+ const redeemed = /* @__PURE__ */ new Map();
193
+ function participation(id, o, state, termsAcceptance) {
194
+ const snapshot = { reward: o.reward, content: o.content };
195
+ if (termsAcceptance) snapshot.terms_acceptance = termsAcceptance;
196
+ return {
197
+ id,
198
+ campaign_id: o.campaign_id,
199
+ campaign_version_id: o.campaign_version_id,
200
+ reward_key: o.reward.reward_key,
201
+ qualification_snapshot: o.qualification,
202
+ ...state,
203
+ snapshot
204
+ };
205
+ }
206
+ function acceptance(body) {
207
+ const t = body.terms_acceptance;
208
+ if (typeof t !== "object" || t === null) return void 0;
209
+ const { locale, terms_revision } = t;
210
+ return { locale, terms_revision, terms_digest_sha256_hex: TERMS_DIGEST, accepted_at: now() };
211
+ }
212
+ const idempotent = (route, handler) => async (req) => {
213
+ const key = req.headers.get("idempotency-key") ?? "";
214
+ if (key === "" || key !== key.trim()) {
215
+ return fail(400, "INVALID_ARGUMENT", "Idempotency-Key must be normalized and non-empty");
216
+ }
217
+ const id = `${route} ${req.url.pathname} ${key}`;
218
+ const payload = JSON.stringify(req.body ?? null);
219
+ const hit = replays.get(id);
220
+ if (hit && hit.payload !== payload)
221
+ return fail(422, "PAYLOAD_MISMATCH", "payload does not match original request");
222
+ if (hit) return new Response(hit.text, { status: hit.status, headers: { "content-type": "application/json" } });
223
+ const res = await handler(req);
224
+ if (res.status < 500 && res.status !== 429) {
225
+ replays.set(id, { payload, status: res.status, text: await res.clone().text() });
226
+ }
227
+ return res;
228
+ };
229
+ const created = (p) => ok({ participation: p }, void 0, 201);
230
+ const notFound = (what) => fail(404, "BONUS_NOT_FOUND", `${what} not found`);
231
+ const notEligible = (message) => fail(500, "BONUS_NOT_ELIGIBLE", message);
232
+ const joined = (o) => participations.some((p) => p.campaign_id === o.campaign_id);
233
+ const add = (p) => {
234
+ participations.unshift(p);
235
+ return p;
236
+ };
237
+ const nextId = () => uuid(1e3 + ++seq);
238
+ return {
239
+ "GET /api/v1/bonus-campaigns/public-offers": (req) => cursorPage(req, "offers", CATALOG),
240
+ "GET /api/v1/bonus-campaigns/offers": (req) => cursorPage(req, "offers", CATALOG),
241
+ "GET /api/v1/bonus-campaigns/offers/:campaignId": (req) => {
242
+ const bad = badId(req, "campaignId");
243
+ if (bad) return bad;
244
+ const o = CATALOG.find((x) => x.campaign_id === req.params?.campaignId);
245
+ return o ? ok({ offer: o }) : notFound("campaign offer");
246
+ },
247
+ "POST /api/v1/bonus-campaigns/offers/:campaignId/opt-in": idempotent("opt-in", (req) => {
248
+ const bad = badId(req, "campaignId");
249
+ if (bad) return bad;
250
+ const body = bodyOf(req);
251
+ if (req.body === void 0) return fail(400, "INVALID_ARGUMENT", "request body is required");
252
+ const o = OFFERS.find((x) => x.campaign_id === req.params?.campaignId);
253
+ if (!o) return notFound("campaign offer");
254
+ if (o.entry_policy.code !== "ENTRY_POLICY_CODE_OPT_IN")
255
+ return notEligible("campaign does not accept opt-in");
256
+ if (body.campaign_version_id !== o.campaign_version_id) {
257
+ return fail(422, "FAILED_PRECONDITION", "campaign version is not the published one");
258
+ }
259
+ if (joined(o)) return fail(409, "ALREADY_EXISTS", "player already participates in this campaign");
260
+ return created(add(participation(nextId(), o, { qualified: { qualified_at: now() } }, acceptance(body))));
261
+ }),
262
+ "POST /api/v1/bonus-campaigns/participations/:participationId/claim": idempotent("claim", (req) => {
263
+ const bad = badId(req, "participationId");
264
+ if (bad) return bad;
265
+ const p = participations.find((x) => x.id === req.params?.participationId);
266
+ if (!p) return notFound("participation");
267
+ if (p.completed) return fail(409, "BONUS_ALREADY_CLAIMED", "reward already claimed");
268
+ const o = OFFERS.find((x) => x.campaign_id === p.campaign_id);
269
+ if (o.reward_claim_policy.code !== "REWARD_CLAIM_POLICY_CODE_PLAYER_CLAIM" || !p.qualified) {
270
+ return notEligible("participation is not claimable");
271
+ }
272
+ delete p.qualified;
273
+ p.completed = { completed_at: now() };
274
+ return ok({ participation: p });
275
+ }),
276
+ "POST /api/v1/bonus-campaigns/promo-codes/resolve": (req) => {
277
+ const { plaintext, locale } = bodyOf(req);
278
+ if (typeof plaintext !== "string" || plaintext.trim() === "") {
279
+ return fail(400, "INVALID_ARGUMENT", "invalid typed campaign request");
280
+ }
281
+ const o = PROMO_CODES[plaintext.trim().toUpperCase()];
282
+ if (!o) return notFound("promo code");
283
+ return ok({ offer: o, localized_content: localized(o, typeof locale === "string" ? locale : "") });
284
+ },
285
+ // Sem o middleware de idempotência do transporte (o corpo tem um segredo): o handler só exige o
286
+ // header e repassa a chave ao serviço de bônus, que faz a idempotência do comando — aqui, a mesma
287
+ // chave devolve a participação criada por ela.
288
+ "POST /api/v1/bonus-campaigns/promo-codes/redeem": (req) => {
289
+ const key = req.headers.get("idempotency-key") ?? "";
290
+ if (key === "" || key !== key.trim()) {
291
+ return fail(400, "INVALID_ARGUMENT", "Idempotency-Key must be normalized and non-empty");
292
+ }
293
+ const body = bodyOf(req);
294
+ const plaintext = typeof body.plaintext === "string" ? body.plaintext.trim().toUpperCase() : "";
295
+ if (plaintext === "") return fail(400, "INVALID_ARGUMENT", "invalid typed campaign request");
296
+ const o = PROMO_CODES[plaintext];
297
+ if (!o) return notFound("promo code");
298
+ const previous = participations.find((p2) => p2.id === redeemed.get(key));
299
+ if (previous) return created(previous);
300
+ if (joined(o)) return fail(409, "BONUS_ALREADY_CLAIMED", "promo code already redeemed");
301
+ const p = add(participation(nextId(), o, { enrolled: {} }, acceptance(body)));
302
+ redeemed.set(key, String(p.id));
303
+ return created(p);
304
+ },
305
+ "GET /api/v1/bonus-campaigns/participations": (req) => cursorPage(req, "participations", participations),
306
+ "GET /api/v1/bonus-campaigns/participations/:participationId": (req) => {
307
+ const bad = badId(req, "participationId");
308
+ if (bad) return bad;
309
+ const p = participations.find((x) => x.id === req.params?.participationId);
310
+ return p ? ok({ participation: p }) : notFound("participation");
311
+ }
312
+ };
313
+ }
314
+ var PROVIDERS = [
315
+ ["pragmatic-play", "Pragmatic Play"],
316
+ ["evolution", "Evolution"],
317
+ ["spribe", "Spribe"]
318
+ ];
319
+ var CATEGORIES = [
320
+ ["slots", "Slots", "slot-machine", 1],
321
+ ["live", "Ao vivo", "live", 2],
322
+ ["crash", "Crash", "rocket", 3]
323
+ ];
324
+ var GAMES = [
325
+ ["Gates of Olympus", "pragmatic-play", "slots", "slot", false, true, false, true, 96.5, "high"],
326
+ ["Sweet Bonanza", "pragmatic-play", "slots", "slot", false, true, false, true, 96.48, "medium"],
327
+ ["Sugar Rush 1000", "pragmatic-play", "slots", "slot", true, false, false, true, 96.53, "high"],
328
+ ["Lightning Roulette", "evolution", "live", "roulette", false, true, true, false, 97.3, "low"],
329
+ ["Crazy Time", "evolution", "live", "game_show", true, false, true, false, 96.08, "high"],
330
+ ["Blackjack Classic", "evolution", "live", "blackjack", false, false, true, false, 99.29, "low"],
331
+ ["Aviator", "spribe", "crash", "crash", false, true, false, true, 97, "medium"]
332
+ ].map(([name, provider, category, type, isNew, popular, live, demo, rtp, volatility], i) => ({
333
+ id: `mock-game-${i + 1}`,
334
+ name,
335
+ provider,
336
+ category,
337
+ type,
338
+ thumbnail: `https://cdn.mock.local/games/mock-game-${i + 1}.webp`,
339
+ is_new: isNew,
340
+ is_popular: popular,
341
+ is_live: live,
342
+ demo_available: demo,
343
+ rtp,
344
+ volatility,
345
+ priority: i + 1
346
+ }));
347
+ var HISTORY = [
348
+ ["mock-game-1", "mock-round-1", "win", 7e3, "2026-09-02T12:01:00Z"],
349
+ ["mock-game-1", "mock-round-1", "bet", 2e3, "2026-09-02T12:00:00Z"],
350
+ ["mock-game-7", "mock-round-0", "bet", 1e3, "2026-09-01T20:00:00Z"]
351
+ ].map(([gameId, roundId, type, amount, createdAt], i) => ({
352
+ id: `mock-casino-tx-${3 - i}`,
353
+ game_id: gameId,
354
+ game_name: GAMES.find((g) => g.id === gameId)?.name,
355
+ round_id: roundId,
356
+ type,
357
+ amount: String(amount),
358
+ // o gateway envia o int64 em texto
359
+ currency: "BRL",
360
+ currency_decimal_places: 2,
361
+ created_at: createdAt
362
+ }));
363
+ var WINNERS = [
364
+ ["Jo***", 15e5, "mock-game-5", "2026-09-28T20:00:00Z"],
365
+ ["Ma***", 82e4, "mock-game-1", "2026-09-27T18:30:00Z"],
366
+ ["Pe***", 455e3, "mock-game-7", "2026-09-26T22:10:00Z"],
367
+ ["An***", 21e4, "mock-game-4", "2026-09-25T14:45:00Z"],
368
+ ["***", 98e3, "mock-game-2", "2026-09-24T09:05:00Z"]
369
+ ].map(([player, amount, gameId, wonAt]) => ({
370
+ player,
371
+ amount: String(amount),
372
+ currency: "BRL",
373
+ currency_decimal_places: 2,
374
+ game_id: gameId,
375
+ game_name: GAMES.find((g) => g.id === gameId)?.name,
376
+ won_at: wonAt
377
+ }));
378
+ function json(body, status = 200) {
379
+ return new Response(JSON.stringify(body), { status, headers: { "content-type": "application/json" } });
380
+ }
381
+ function pageOf(req, items) {
382
+ const q = req.url.searchParams;
383
+ const page = Math.max(1, Number.parseInt(q.get("page") ?? "", 10) || 1);
384
+ const raw = Number.parseInt(q.get("limit") ?? "", 10);
385
+ const limit = raw >= 1 && raw <= 100 ? raw : 20;
386
+ return {
387
+ items: items.slice((page - 1) * limit, page * limit),
388
+ meta: { page, per_page: limit, total_pages: Math.ceil(items.length / limit), total_items: items.length }
389
+ };
390
+ }
391
+ var SORTS = {
392
+ popular: (a, b) => Number(b.is_popular) - Number(a.is_popular),
393
+ new: (a, b) => Number(b.is_new) - Number(a.is_new),
394
+ az: (a, b) => String(a.name).localeCompare(String(b.name))
395
+ };
396
+ function listGames(req) {
397
+ const q = req.url.searchParams;
398
+ const search = (q.get("search") ?? "").toLowerCase();
399
+ if (search.length > 100) return fail(400, "INVALID_ARGUMENT", "search parameter too long");
400
+ const ids = (q.get("ids") ?? "").split(",").map((id) => id.trim()).filter(Boolean);
401
+ if (ids.length > 100) return fail(400, "INVALID_ARGUMENT", "ids parameter too long");
402
+ const category = (q.get("category") ?? "").trim().toLowerCase();
403
+ const provider = q.get("provider") ?? "";
404
+ const games = GAMES.filter(
405
+ (g) => (!category || g.category === category) && (!provider || g.provider === provider) && (!search || String(g.name).toLowerCase().includes(search)) && (ids.length === 0 || ids.includes(String(g.id)))
406
+ );
407
+ const sort = SORTS[q.get("sort") ?? ""];
408
+ const { items, meta } = pageOf(req, sort ? [...games].sort(sort) : games);
409
+ return json({
410
+ success: true,
411
+ data: items,
412
+ availability: { status: "available", primary_provider_code: "pragmatic-play", missing: false },
413
+ meta
414
+ });
415
+ }
416
+ function launchLanguage(req, body) {
417
+ if (typeof body.language === "string" && body.language.trim() !== "") return body.language.trim();
418
+ return (req.headers.get("accept-language") ?? "").split(",")[0].split(";")[0].trim();
419
+ }
420
+ function createCasinoRoutes() {
421
+ const sessions = [
422
+ {
423
+ id: "mock-game-session-0",
424
+ game_id: "mock-game-1",
425
+ game_name: "Gates of Olympus",
426
+ provider: "pragmatic-play",
427
+ start_time: "2026-09-02T11:58:00Z",
428
+ total_bet: 2e3,
429
+ total_win: 7e3,
430
+ status: "SESSION_STATUS_ENDED"
431
+ }
432
+ ];
433
+ let seq = 0;
434
+ return {
435
+ "GET /api/v1/games": listGames,
436
+ "GET /api/v1/games/categories": () => ok(
437
+ CATEGORIES.map(([slug, name, icon, priority]) => ({
438
+ slug,
439
+ name,
440
+ icon,
441
+ game_count: GAMES.filter((g) => g.category === slug).length,
442
+ priority
443
+ }))
444
+ ),
445
+ "GET /api/v1/games/providers": () => ok(PROVIDERS.map(([id, name]) => ({ id, name, game_count: GAMES.filter((g) => g.provider === id).length }))),
446
+ "GET /api/v1/games/:gameId": (req) => {
447
+ const game = GAMES.find((g) => g.id === req.params?.gameId);
448
+ return game ? ok(game) : fail(404, "GAME_NOT_FOUND", "game not found");
449
+ },
450
+ "POST /api/v1/games/:gameId/launch": (req) => {
451
+ const game = GAMES.find((g) => g.id === req.params?.gameId);
452
+ if (!game) return fail(404, "GAME_NOT_FOUND", "game not found");
453
+ const body = typeof req.body === "object" && req.body !== null ? req.body : {};
454
+ for (const s of sessions) if (s.status === "SESSION_STATUS_ACTIVE") s.status = "SESSION_STATUS_ENDED";
455
+ seq += 1;
456
+ const session = {
457
+ id: `mock-game-session-${seq}`,
458
+ game_id: game.id,
459
+ game_name: game.name,
460
+ provider: game.provider,
461
+ start_time: (/* @__PURE__ */ new Date()).toISOString(),
462
+ total_bet: 0,
463
+ total_win: 0,
464
+ status: "SESSION_STATUS_ACTIVE"
465
+ };
466
+ sessions.unshift(session);
467
+ const url = new URL(`https://games.mock.local/play/${String(game.id)}`);
468
+ url.searchParams.set("token", `mock-launch-token-${seq}`);
469
+ url.searchParams.set("lang", launchLanguage(req, body));
470
+ if (body.is_demo === true) url.searchParams.set("demo", "true");
471
+ return ok({ session_id: session.id, game_url: url.href });
472
+ },
473
+ "GET /api/v1/games/sessions": (req) => {
474
+ const { items, meta } = pageOf(req, sessions);
475
+ return ok(items, meta);
476
+ },
477
+ "GET /api/v1/games/history": (req) => {
478
+ const { items, meta } = pageOf(req, HISTORY);
479
+ return ok(items, meta);
480
+ },
481
+ "GET /api/v1/games/biggest-winners": (req) => {
482
+ const raw = Number.parseInt(req.url.searchParams.get("limit") ?? "", 10);
483
+ return ok(WINNERS.slice(0, raw >= 1 ? raw : 10));
484
+ }
485
+ };
486
+ }
487
+ var POINT_VALUE_CENTS = 5;
488
+ function createLoyaltyRoutes() {
489
+ const state = { total: 5200, current: 1500, redeemed: 3700 };
490
+ return {
491
+ "GET /api/v1/loyalty": () => ok({
492
+ total_points_earned: state.total,
493
+ current_points: state.current,
494
+ points_redeemed: state.redeemed,
495
+ current_tier: "gold",
496
+ tier_points: 1200,
497
+ lifetime_wagered: 125e4,
498
+ lifetime_deposited: 8e5,
499
+ tier_benefits_json: JSON.stringify({ cashback_percent: 5, perks: ["vip_support"] }),
500
+ tier_expires_at: "2027-01-01T00:00:00Z"
501
+ }),
502
+ "POST /api/v1/loyalty/redeem": (req) => {
503
+ const body = req.body ?? {};
504
+ const points = body.points;
505
+ if (typeof points !== "number" || !Number.isInteger(points) || points <= 0)
506
+ return fail(400, "INVALID_ARGUMENT", "points must be greater than 0");
507
+ if (typeof body.redemption_type !== "string" || body.redemption_type === "")
508
+ return fail(400, "INVALID_ARGUMENT", "redemption_type is required");
509
+ if (points > state.current) return fail(422, "INSUFFICIENT_BALANCE", "insufficient loyalty points");
510
+ state.current -= points;
511
+ state.redeemed += points;
512
+ const bonus = body.redemption_type === "bonus";
513
+ return ok({
514
+ success: true,
515
+ redeemed_points: points,
516
+ value: points * POINT_VALUE_CENTS,
517
+ currency: "BRL",
518
+ ...bonus ? { bonus_id: `mock-loyalty-bonus-${state.redeemed}` } : {}
519
+ });
520
+ }
521
+ };
522
+ }
523
+ var EPOCH = "1970-01-01T00:00:00Z";
524
+ var MISSIONS = [
525
+ [
526
+ "Aposte R$ 100 hoje",
527
+ "daily",
528
+ "wager",
529
+ 1e4,
530
+ "",
531
+ null,
532
+ "points",
533
+ 50,
534
+ "2026-09-01T00:00:00Z",
535
+ "2026-12-31T23:59:59Z"
536
+ ],
537
+ [
538
+ "Fa\xE7a 20 apostas na semana",
539
+ "weekly",
540
+ "bet_count",
541
+ 20,
542
+ "slots",
543
+ null,
544
+ "free_spins",
545
+ 10,
546
+ "2026-09-01T00:00:00Z",
547
+ EPOCH
548
+ ],
549
+ ["Jogue Aviator", "event", "play_game", 5, "", ["mock-game-7"], "bonus", 500, EPOCH, EPOCH],
550
+ ["Primeiro dep\xF3sito do m\xEAs", "permanent", "deposit", 5e3, "", null, "free_bet", 1e3, EPOCH, EPOCH]
551
+ ].map(([name, type, objective, target, category, games, rewardType, rewardValue, from, to], i) => ({
552
+ id: `mock-mission-${i + 1}`,
553
+ name,
554
+ description: `Descri\xE7\xE3o da miss\xE3o ${i + 1}`,
555
+ mission_type: type,
556
+ objective_type: objective,
557
+ target_value: target,
558
+ target_game_category: category,
559
+ target_games: games === null ? null : [...games],
560
+ reward_type: rewardType,
561
+ reward_value: rewardValue,
562
+ valid_from: from,
563
+ valid_to: to
564
+ }));
565
+ var USER_MISSIONS = [
566
+ {
567
+ id: "mock-user-mission-1",
568
+ mission_id: "mock-mission-1",
569
+ mission_name: "Aposte R$ 100 hoje",
570
+ current_progress: 3750,
571
+ target_value: 1e4,
572
+ progress_percentage: 37.5,
573
+ status: "in_progress",
574
+ reward_type: "points",
575
+ reward_value: 50,
576
+ period_end: "2026-10-08T00:00:00Z"
577
+ },
578
+ {
579
+ id: "mock-user-mission-2",
580
+ mission_id: "mock-mission-4",
581
+ mission_name: "Primeiro dep\xF3sito do m\xEAs",
582
+ current_progress: 5e3,
583
+ target_value: 5e3,
584
+ progress_percentage: 100,
585
+ status: "completed",
586
+ reward_type: "free_bet",
587
+ reward_value: 1e3,
588
+ completed_at: "2026-10-02T15:30:00Z"
589
+ }
590
+ ];
591
+ function json2(body) {
592
+ return new Response(JSON.stringify(body), { status: 200, headers: { "content-type": "application/json" } });
593
+ }
594
+ function listMissions(req) {
595
+ const q = req.url.searchParams;
596
+ const page = Math.max(1, Number.parseInt(q.get("page") ?? "", 10) || 1);
597
+ const raw = Number.parseInt(q.get("limit") ?? "", 10);
598
+ const limit = raw >= 1 && raw <= 100 ? raw : 20;
599
+ return json2({
600
+ success: true,
601
+ data: MISSIONS.slice((page - 1) * limit, page * limit),
602
+ meta: { page, per_page: limit, total_pages: Math.ceil(MISSIONS.length / limit), total_items: MISSIONS.length }
603
+ });
604
+ }
605
+ function createMissionsRoutes() {
606
+ return {
607
+ "GET /api/v1/missions": listMissions,
608
+ "GET /api/v1/my/missions": () => ok({ missions: USER_MISSIONS })
609
+ };
610
+ }
611
+ var REFERRALS = [
612
+ {
613
+ id: "mock-referral-1",
614
+ referee_id: "mock-referee-1",
615
+ referee_email: "ana.mock@exemplo.com",
616
+ referee_name: "Ana Mock",
617
+ referral_code: "MOCK123",
618
+ status: "REFERRAL_STATUS_COMPLETED",
619
+ referrer_bonus: 10,
620
+ referee_bonus: 5.5,
621
+ created_at: "2026-09-01T10:00:00Z",
622
+ completed_at: "2026-09-05T10:00:00Z",
623
+ expires_at: "2026-12-01T10:00:00Z"
624
+ },
625
+ {
626
+ id: "mock-referral-2",
627
+ referee_id: "mock-referee-2",
628
+ referee_email: "bruno.mock@exemplo.com",
629
+ referee_name: "Bruno Mock",
630
+ referral_code: "MOCK123",
631
+ status: "REFERRAL_STATUS_PENDING",
632
+ referrer_bonus: 10,
633
+ referee_bonus: 5.5,
634
+ created_at: "2026-09-20T10:00:00Z",
635
+ expires_at: "2026-12-20T10:00:00Z"
636
+ },
637
+ {
638
+ id: "mock-referral-3",
639
+ referee_id: "mock-referee-3",
640
+ referee_email: "c@exemplo.com",
641
+ referee_name: "",
642
+ referral_code: "MOCK123",
643
+ status: "REFERRAL_STATUS_EXPIRED",
644
+ referrer_bonus: 0,
645
+ referee_bonus: 0,
646
+ created_at: "2026-06-01T10:00:00Z"
647
+ }
648
+ ];
649
+ var COMPLETED = REFERRALS.filter((r) => r.status === "REFERRAL_STATUS_COMPLETED").length;
650
+ function json3(body, status) {
651
+ return new Response(JSON.stringify(body), { status, headers: { "content-type": "application/json" } });
652
+ }
653
+ function listHistory(req) {
654
+ const q = req.url.searchParams;
655
+ const page = Math.max(1, Number.parseInt(q.get("page") ?? "", 10) || 1);
656
+ const raw = Number.parseInt(q.get("limit") ?? "", 10);
657
+ const limit = raw >= 1 && raw <= 100 ? raw : 20;
658
+ return ok({
659
+ referrals: REFERRALS.slice((page - 1) * limit, page * limit),
660
+ completed_count: COMPLETED,
661
+ total_earned: 10,
662
+ pagination: {
663
+ page,
664
+ page_size: limit,
665
+ total_items: REFERRALS.length,
666
+ total_pages: Math.ceil(REFERRALS.length / limit)
667
+ }
668
+ });
669
+ }
670
+ function createReferralsRoutes() {
671
+ return {
672
+ "GET /api/v1/referrals": () => ok({
673
+ referral_code: "MOCK123",
674
+ referral_link: "https://casino.mock.local/r/MOCK123",
675
+ total_referrals: REFERRALS.length,
676
+ completed_referrals: COMPLETED,
677
+ pending_referrals: 1,
678
+ total_earned: 10,
679
+ bonus_per_referral: 10,
680
+ min_deposit: 50
681
+ }),
682
+ "GET /api/v1/referrals/history": listHistory,
683
+ "POST /api/v1/referrals/register": (req) => {
684
+ const code = (req.body ?? {}).referral_code;
685
+ if (typeof code !== "string" || code === "") return fail(400, "INVALID_ARGUMENT", "referral_code is required");
686
+ if (code !== "BEMVINDO") return fail(404, "NOT_FOUND", "referral code not found");
687
+ return json3(
688
+ {
689
+ success: true,
690
+ data: {
691
+ id: "mock-referral-new",
692
+ referral_code: code,
693
+ status: "REFERRAL_STATUS_PENDING",
694
+ referee_bonus: 5.5,
695
+ created_at: "2026-10-07T12:00:00Z"
696
+ }
697
+ },
698
+ 201
699
+ );
700
+ }
701
+ };
702
+ }
703
+ var SESSION_TTL_SECONDS = 24 * 60 * 60;
704
+ function createSportsbookRoutes() {
705
+ let seq = 0;
706
+ return {
707
+ "GET /api/v1/first/session": () => {
708
+ seq += 1;
709
+ const token = `mock-operator-token-${seq}`;
710
+ const url = new URL("https://first.mock.local/sportsbook");
711
+ url.searchParams.set("operatorToken", token);
712
+ return ok({ operator_token: token, launch_url: url.href, expires_in_seconds: SESSION_TTL_SECONDS });
713
+ }
714
+ };
715
+ }
716
+
717
+ // src/testing/index.ts
718
+ function createIgamingRoutes() {
719
+ return {
720
+ ...createCasinoRoutes(),
721
+ ...createBonusRoutes(),
722
+ ...createSportsbookRoutes(),
723
+ ...createMissionsRoutes(),
724
+ ...createLoyaltyRoutes(),
725
+ ...createReferralsRoutes()
726
+ };
727
+ }
728
+ function withIgamingRoutes(options = {}) {
729
+ return { ...options, routes: { ...createIgamingRoutes(), ...options.routes } };
730
+ }
731
+
732
+ export { createIgamingRoutes, withIgamingRoutes };
733
+ //# sourceMappingURL=index.js.map
734
+ //# sourceMappingURL=index.js.map