@getenginex/sdk-igaming 0.0.0-stage → 0.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js ADDED
@@ -0,0 +1,1025 @@
1
+ import { EnginexError } from '@getenginex/sdk';
2
+ import * as extension from '@getenginex/sdk/extension';
3
+ import { lazy, wire, decimalPlaces, currencyCode, money as money$1, strictValue, moneyText } from '@getenginex/sdk/extension';
4
+ import { z } from 'zod/mini';
5
+
6
+ // src/client.ts
7
+ function protoEnum(prefix) {
8
+ return z.pipe(
9
+ z.optional(z.union([z.string(), z.number()])),
10
+ z.transform((value) => {
11
+ if (value === void 0 || value === 0) return "unspecified";
12
+ if (typeof value === "number") return String(value);
13
+ return (value.startsWith(prefix) ? value.slice(prefix.length) : value).toLowerCase();
14
+ })
15
+ );
16
+ }
17
+ function minorUnits() {
18
+ return moneyText();
19
+ }
20
+ function currencyOrEmpty() {
21
+ return currencyCode({ allowEmpty: true });
22
+ }
23
+ var INTEGER_TEXT = "Expected an integer within the safe range of number";
24
+ function integerText() {
25
+ return z.pipe(
26
+ z.union([
27
+ z.string().check(
28
+ z.refine((value) => /^-?\d+$/.test(value) && Number.isSafeInteger(Number(value)), { message: INTEGER_TEXT })
29
+ ),
30
+ z.number().check(z.refine((value) => Number.isSafeInteger(value), { message: INTEGER_TEXT }))
31
+ ]),
32
+ z.transform(Number)
33
+ );
34
+ }
35
+ function text() {
36
+ return z._default(z.string(), "");
37
+ }
38
+ function count() {
39
+ return z._default(z.number(), 0);
40
+ }
41
+ function list(item) {
42
+ return z._default(z.array(item), []);
43
+ }
44
+ function durationSeconds() {
45
+ return z.pipe(
46
+ z.string().check(z.regex(/^-?\d+(\.\d+)?s$/, { message: 'Expected a protobuf duration, e.g. "86400s"' })),
47
+ z.transform((value) => Number(value.slice(0, -1)))
48
+ );
49
+ }
50
+ var MAJOR_UNITS = "Expected a value in major units (a finite number) that fits in whole minor units";
51
+ function majorToMinorUnits(value) {
52
+ const minor = Math.sign(value) * Math.round(Math.abs(value) * 100);
53
+ return minor === 0 ? 0 : minor;
54
+ }
55
+ function majorUnits() {
56
+ return z.pipe(
57
+ strictValue(
58
+ (value) => typeof value === "number" && Number.isSafeInteger(majorToMinorUnits(value)),
59
+ MAJOR_UNITS
60
+ ),
61
+ z.transform((value) => majorToMinorUnits(value))
62
+ );
63
+ }
64
+
65
+ // src/modules/bonus.ts
66
+ var campaignCurrency = () => z._default(currencyOrEmpty(), "");
67
+ var money = () => wire({ amount: z._default(minorUnits(), 0), currency: campaignCurrency() });
68
+ var timeWindow = () => wire({ starts_at: z.optional(z.string()), ends_at: z.optional(z.string()) });
69
+ var ratio = () => wire({ decimal: z.optional(z.string()), basis_points: z.optional(z.number()), maximum_scale: count() });
70
+ var empty = () => wire({});
71
+ var policy = (prefix) => wire({ code: protoEnum(prefix), version: count() });
72
+ var casinoSelector = () => wire({
73
+ provider_instance_id: text(),
74
+ software_ids: list(z.string()),
75
+ game_ids: list(z.string()),
76
+ category_codes: list(z.string())
77
+ });
78
+ var sportsSelector = () => wire({
79
+ sport_codes: list(z.string()),
80
+ competition_ids: list(z.string()),
81
+ event_ids: list(z.string()),
82
+ market_codes: list(z.string()),
83
+ live: z.optional(z.boolean()),
84
+ bet_types: list(protoEnum("SPORTS_BET_TYPE_"))
85
+ });
86
+ var qualification = () => wire({
87
+ version: count(),
88
+ immediate: z.optional(empty()),
89
+ user_event: z.optional(
90
+ wire({
91
+ event_code: text(),
92
+ event_version: count(),
93
+ source_authority: text(),
94
+ identity_fields: list(z.string())
95
+ })
96
+ ),
97
+ deposit_settled: z.optional(
98
+ wire({
99
+ currency: campaignCurrency(),
100
+ eligible_method_codes: list(z.string()),
101
+ first_deposit_policy: protoEnum("FIRST_DEPOSIT_POLICY_"),
102
+ minimum_settled_net_amount: z.optional(money()),
103
+ maximum_settled_net_amount: z.optional(money()),
104
+ amount_basis: protoEnum("DEPOSIT_AMOUNT_BASIS_")
105
+ })
106
+ ),
107
+ activity_aggregate: z.optional(
108
+ wire({
109
+ basis: protoEnum("BASIS_"),
110
+ product_scope: protoEnum("PRODUCT_SCOPE_"),
111
+ currency: campaignCurrency(),
112
+ window: z.optional(durationSeconds()),
113
+ timezone: text(),
114
+ late_event_grace: z.optional(durationSeconds()),
115
+ casino: z.optional(casinoSelector()),
116
+ sportsbook: z.optional(sportsSelector())
117
+ })
118
+ )
119
+ });
120
+ var validity = () => wire({
121
+ no_expiry: z.optional(empty()),
122
+ absolute_expiry: z.optional(wire({ expires_at: z.optional(z.string()) })),
123
+ duration_from_grant: z.optional(wire({ duration: z.optional(durationSeconds()) }))
124
+ });
125
+ var rounding = () => protoEnum("ROUNDING_MODE_");
126
+ var proceedsClass = () => protoEnum("PROCEEDS_CLASS_");
127
+ var percent = () => wire({
128
+ percentage: z.optional(ratio()),
129
+ rounding: rounding(),
130
+ minimum_reward: z.optional(money()),
131
+ maximum_reward: z.optional(money())
132
+ });
133
+ var balanceCredit = () => wire({
134
+ fixed_amount: z.optional(wire({ amount: z.optional(money()) })),
135
+ percent_of_source_amount: z.optional(percent()),
136
+ aggregate_rebate: z.optional(
137
+ wire({
138
+ percentage: z.optional(ratio()),
139
+ rounding: rounding(),
140
+ minimum_basis: z.optional(money()),
141
+ maximum_reward: z.optional(money())
142
+ })
143
+ ),
144
+ balance_class: protoEnum("BALANCE_CLASS_"),
145
+ proceeds_class: proceedsClass(),
146
+ validity: z.optional(validity())
147
+ });
148
+ var maximumBet = () => wire({ mode: protoEnum("MAXIMUM_BET_MODE_"), campaign_maximum: z.optional(money()) });
149
+ var oddsPolicy = () => wire({
150
+ mode: protoEnum("MODE_"),
151
+ minimum_total_odds_decimal: z.optional(z.string()),
152
+ minimum_odds_per_leg_decimal: z.optional(z.string()),
153
+ minimum_legs: z.optional(z.number()),
154
+ maximum_legs: z.optional(z.number())
155
+ });
156
+ var cashoutMode = () => protoEnum("RESTRICTED_CASHOUT_MODE_");
157
+ var usePolicy = () => wire({
158
+ version: count(),
159
+ funds_consumption: z.optional(policy("FUNDS_CONSUMPTION_POLICY_CODE_")),
160
+ casino: z.optional(wire({ allowed_scopes: list(casinoSelector()), maximum_bet: z.optional(maximumBet()) })),
161
+ sportsbook: z.optional(
162
+ wire({
163
+ allowed_scopes: list(sportsSelector()),
164
+ excluded_scopes: list(sportsSelector()),
165
+ maximum_bet: z.optional(maximumBet()),
166
+ funding_odds: z.optional(oddsPolicy()),
167
+ cashout_mode: cashoutMode()
168
+ })
169
+ ),
170
+ casino_and_sportsbook: z.optional(
171
+ wire({
172
+ allowed_casino_scopes: list(casinoSelector()),
173
+ allowed_sportsbook_scopes: list(sportsSelector()),
174
+ excluded_sportsbook_scopes: list(sportsSelector()),
175
+ maximum_casino_bet: z.optional(maximumBet()),
176
+ maximum_sportsbook_bet: z.optional(maximumBet()),
177
+ sportsbook_funding_odds: z.optional(oddsPolicy()),
178
+ sportsbook_cashout_mode: cashoutMode()
179
+ })
180
+ ),
181
+ payout_allocation: z.optional(policy("PAYOUT_ALLOCATION_POLICY_CODE_"))
182
+ });
183
+ var wageringPolicy = () => wire({
184
+ version: count(),
185
+ none: z.optional(empty()),
186
+ multiplier: z.optional(
187
+ wire({
188
+ requirement_basis: protoEnum("REQUIREMENT_BASIS_"),
189
+ multiplier: z.optional(ratio()),
190
+ contribution_rates: list(
191
+ wire({
192
+ casino: z.optional(casinoSelector()),
193
+ sportsbook: z.optional(sportsSelector()),
194
+ rate: z.optional(ratio())
195
+ })
196
+ ),
197
+ deadline: z.optional(validity()),
198
+ rounding: rounding(),
199
+ sportsbook_contribution_odds: z.optional(oddsPolicy())
200
+ })
201
+ )
202
+ });
203
+ var stackingPolicy = () => wire({
204
+ version: count(),
205
+ exclusive_in_group: z.optional(wire({ stacking_group_key: text() })),
206
+ multiple_in_group: z.optional(wire({ stacking_group_key: text(), maximum_active_per_player: count() }))
207
+ });
208
+ var reward = () => wire({
209
+ reward_key: text(),
210
+ reward_kind: protoEnum("REWARD_KIND_"),
211
+ reward_kind_version: count(),
212
+ execution_profile_code: protoEnum("EXECUTION_PROFILE_CODE_"),
213
+ execution_profile_version: count(),
214
+ balance_credit: z.optional(balanceCredit()),
215
+ provider_managed_balance: z.optional(wire({ provider_code: text() })),
216
+ casino_free_spins: z.optional(
217
+ wire({
218
+ provider_code: text(),
219
+ casino_scope: z.optional(casinoSelector()),
220
+ quantity: count(),
221
+ denomination: z.optional(money()),
222
+ currency: campaignCurrency(),
223
+ grant_window: z.optional(timeWindow()),
224
+ proceeds_class: proceedsClass(),
225
+ maximum_winnings: z.optional(money())
226
+ })
227
+ ),
228
+ sports_bonus_bet: z.optional(
229
+ wire({
230
+ provider_code: text(),
231
+ sportsbook_scope: z.optional(sportsSelector()),
232
+ amount: z.optional(money()),
233
+ quantity: count(),
234
+ validity: z.optional(validity())
235
+ })
236
+ ),
237
+ sports_bet_coverage: z.optional(
238
+ wire({
239
+ provider_code: text(),
240
+ qualifying_bet_scope: z.optional(sportsSelector()),
241
+ coverage_cap: z.optional(money()),
242
+ validity: z.optional(validity())
243
+ })
244
+ ),
245
+ use_policy: z.optional(usePolicy()),
246
+ wagering_policy: z.optional(wageringPolicy()),
247
+ stacking_policy: z.optional(stackingPolicy()),
248
+ restricted_position_selection_policy: z.optional(
249
+ wire({
250
+ version: count(),
251
+ priority_then_earliest_expiry: z.optional(wire({ selection_priority: z.optional(z.number()) }))
252
+ })
253
+ )
254
+ });
255
+ var localizedContent = () => wire({ locale: text(), display_name: text(), description: text(), terms: text(), terms_revision: text() });
256
+ var content = () => wire({ default_locale: text(), supported_locales: list(z.string()), localized_content: list(localizedContent()) });
257
+ var offerSchema = /* @__PURE__ */ lazy(
258
+ () => wire({
259
+ campaign_id: text(),
260
+ campaign_version_id: text(),
261
+ publication_id: text(),
262
+ product_scope: protoEnum("PRODUCT_SCOPE_"),
263
+ timezone: text(),
264
+ enrollment_window: z.optional(timeWindow()),
265
+ qualification_window: z.optional(timeWindow()),
266
+ claim_window: z.optional(timeWindow()),
267
+ entry_policy: z.optional(policy("ENTRY_POLICY_CODE_")),
268
+ reward_claim_policy: z.optional(policy("REWARD_CLAIM_POLICY_CODE_")),
269
+ qualification: z.optional(qualification()),
270
+ reward: z.optional(reward()),
271
+ publication_starts_at: z.optional(z.string()),
272
+ publication_ends_at: z.optional(z.string()),
273
+ content: z.optional(content())
274
+ })
275
+ );
276
+ var participationSchema = /* @__PURE__ */ lazy(
277
+ () => z.pipe(
278
+ wire({
279
+ id: text(),
280
+ campaign_id: text(),
281
+ campaign_version_id: text(),
282
+ reward_key: text(),
283
+ qualification_snapshot: z.optional(qualification()),
284
+ // oneof `state`: only one of the cases is filled in.
285
+ enrolled: z.optional(empty()),
286
+ qualifying: z.optional(empty()),
287
+ qualified: z.optional(wire({ qualified_at: z.optional(z.string()) })),
288
+ reward_pending: z.optional(empty()),
289
+ completed: z.optional(wire({ completed_at: z.optional(z.string()) })),
290
+ reward_failed: z.optional(empty()),
291
+ expired: z.optional(wire({ expired_at: z.optional(z.string()) })),
292
+ cancelled: z.optional(empty()),
293
+ snapshot: z.optional(
294
+ wire({
295
+ reward: z.optional(reward()),
296
+ content: z.optional(content()),
297
+ terms_acceptance: z.optional(
298
+ wire({
299
+ locale: text(),
300
+ terms_revision: text(),
301
+ terms_digest_sha256_hex: text(),
302
+ accepted_at: z.optional(z.string())
303
+ })
304
+ )
305
+ })
306
+ )
307
+ }),
308
+ // The oneof becomes `status` (+ the timestamp of the case); the oneof's keys are not passed on.
309
+ z.transform(
310
+ ({ enrolled, qualifying, qualified, rewardPending, completed, rewardFailed, expired, cancelled, ...rest }) => {
311
+ const out = { ...rest, status: "unspecified" };
312
+ if (enrolled) out.status = "enrolled";
313
+ else if (qualifying) out.status = "qualifying";
314
+ else if (qualified) {
315
+ out.status = "qualified";
316
+ if (qualified.qualifiedAt !== void 0) out.qualifiedAt = qualified.qualifiedAt;
317
+ } else if (rewardPending) out.status = "reward_pending";
318
+ else if (completed) {
319
+ out.status = "completed";
320
+ if (completed.completedAt !== void 0) out.completedAt = completed.completedAt;
321
+ } else if (rewardFailed) out.status = "reward_failed";
322
+ else if (expired) {
323
+ out.status = "expired";
324
+ if (expired.expiredAt !== void 0) out.expiredAt = expired.expiredAt;
325
+ } else if (cancelled) out.status = "cancelled";
326
+ return out;
327
+ }
328
+ )
329
+ )
330
+ );
331
+ var cursorPageSchema = (key, item) => wire({ [key]: list(item), next_cursor: z.optional(z.string()) });
332
+ var offersPage = /* @__PURE__ */ lazy(() => cursorPageSchema("offers", offerSchema()));
333
+ var participationsPage = /* @__PURE__ */ lazy(() => cursorPageSchema("participations", participationSchema()));
334
+ var offerEnvelope = /* @__PURE__ */ lazy(() => wire({ offer: offerSchema() }));
335
+ var participationEnvelope = /* @__PURE__ */ lazy(() => wire({ participation: participationSchema() }));
336
+ var promoCodeOfferSchema = /* @__PURE__ */ lazy(
337
+ () => wire({ offer: offerSchema(), localized_content: localizedContent() })
338
+ );
339
+ function toCursorPage(key, data) {
340
+ const page = { items: data[key] };
341
+ if (data.nextCursor) page.nextCursor = data.nextCursor;
342
+ return page;
343
+ }
344
+ var terms = (acceptance) => acceptance && { locale: acceptance.locale, terms_revision: acceptance.termsRevision };
345
+ function createBonusApi(transport) {
346
+ const listPage = (path, key, schema, auth, input, options) => transport.request({
347
+ method: "GET",
348
+ path,
349
+ query: { page_size: input?.pageSize, cursor: input?.cursor },
350
+ auth,
351
+ schema,
352
+ options
353
+ }).then((data) => toCursorPage(key, data));
354
+ const participationCall = (path, body, options) => transport.request({
355
+ method: "POST",
356
+ path,
357
+ body,
358
+ auth: "required",
359
+ idempotent: true,
360
+ validation: "strict",
361
+ schema: participationEnvelope(),
362
+ options
363
+ }).then((data) => data.participation);
364
+ return {
365
+ listPublicOffers: (input, options) => listPage("/bonus-campaigns/public-offers", "offers", offersPage(), "none", input, options),
366
+ listOffers: (input, options) => listPage("/bonus-campaigns/offers", "offers", offersPage(), "required", input, options),
367
+ getOffer: ({ campaignId }, options) => transport.request({
368
+ method: "GET",
369
+ path: `/bonus-campaigns/offers/${encodeURIComponent(campaignId)}`,
370
+ auth: "required",
371
+ schema: offerEnvelope(),
372
+ options
373
+ }).then((data) => data.offer),
374
+ optIn: ({ campaignId, campaignVersionId, termsAcceptance }, options) => participationCall(
375
+ `/bonus-campaigns/offers/${encodeURIComponent(campaignId)}/opt-in`,
376
+ { campaign_version_id: campaignVersionId, terms_acceptance: terms(termsAcceptance) },
377
+ options
378
+ ),
379
+ claim: ({ participationId }, options) => participationCall(
380
+ `/bonus-campaigns/participations/${encodeURIComponent(participationId)}/claim`,
381
+ void 0,
382
+ options
383
+ ),
384
+ resolvePromoCode: ({ code, locale }, options) => transport.request({
385
+ method: "POST",
386
+ path: "/bonus-campaigns/promo-codes/resolve",
387
+ body: { plaintext: code, locale },
388
+ auth: "required",
389
+ schema: promoCodeOfferSchema(),
390
+ options
391
+ }),
392
+ redeemPromoCode: ({ code, termsAcceptance }, options) => participationCall(
393
+ "/bonus-campaigns/promo-codes/redeem",
394
+ { plaintext: code, terms_acceptance: terms(termsAcceptance) },
395
+ options
396
+ ),
397
+ listParticipations: (input, options) => listPage(
398
+ "/bonus-campaigns/participations",
399
+ "participations",
400
+ participationsPage(),
401
+ "required",
402
+ input,
403
+ options
404
+ ),
405
+ getParticipation: ({ participationId }, options) => transport.request({
406
+ method: "GET",
407
+ path: `/bonus-campaigns/participations/${encodeURIComponent(participationId)}`,
408
+ auth: "required",
409
+ schema: participationEnvelope(),
410
+ options
411
+ }).then((data) => data.participation)
412
+ };
413
+ }
414
+ var gameSchema = /* @__PURE__ */ lazy(
415
+ () => wire({
416
+ id: z.string(),
417
+ name: z.string(),
418
+ provider: z.string(),
419
+ category: z.string(),
420
+ type: z.string(),
421
+ thumbnail: z.string(),
422
+ is_new: z.boolean(),
423
+ is_popular: z.boolean(),
424
+ is_live: z.boolean(),
425
+ demo_available: z.boolean(),
426
+ rtp: z.number(),
427
+ volatility: z.string(),
428
+ priority: z.number()
429
+ })
430
+ );
431
+ var categoriesSchema = /* @__PURE__ */ lazy(
432
+ () => z.array(
433
+ wire({ slug: z.string(), name: z.string(), icon: z.string(), game_count: z.number(), priority: z.number() })
434
+ )
435
+ );
436
+ var providersSchema = /* @__PURE__ */ lazy(
437
+ () => z.array(wire({ id: z.string(), name: z.string(), game_count: z.number() }))
438
+ );
439
+ var launchSchema = /* @__PURE__ */ lazy(
440
+ () => z.pipe(
441
+ wire({
442
+ session_id: z.string().check(z.minLength(1)),
443
+ game_url: z.string().check(z.minLength(1)),
444
+ // Any text: a target the SDK does not know yet must not fail the (strict) launch.
445
+ launch_target: z.optional(z.string()),
446
+ provider_code: z.optional(z.string()),
447
+ expires_at: z.optional(z.string())
448
+ }),
449
+ // Without a target (an older gateway, or a custom mock), the launch keeps the behavior the SDK documented
450
+ // before the field existed: an iframe.
451
+ z.transform(({ launchTarget, ...rest }) => ({ ...rest, launchTarget: launchTarget || "iframe" }))
452
+ )
453
+ );
454
+ var sessionSchema = /* @__PURE__ */ lazy(
455
+ () => wire({
456
+ id: z.string(),
457
+ game_id: z.string(),
458
+ game_name: z.string(),
459
+ provider: z.string(),
460
+ start_time: z.string(),
461
+ total_bet: money$1(),
462
+ total_win: money$1(),
463
+ status: protoEnum("SESSION_STATUS_")
464
+ })
465
+ );
466
+ var transactionSchema = /* @__PURE__ */ lazy(
467
+ () => wire({
468
+ id: z.string(),
469
+ game_id: z.string(),
470
+ game_name: z.string(),
471
+ round_id: z.string(),
472
+ type: protoEnum("CASINO_TRANSACTION_TYPE_"),
473
+ amount: minorUnits(),
474
+ currency: currencyCode(),
475
+ currency_decimal_places: decimalPlaces(),
476
+ created_at: z.string()
477
+ })
478
+ );
479
+ var winnersSchema = /* @__PURE__ */ lazy(
480
+ () => z.array(
481
+ wire({
482
+ player: z.string(),
483
+ amount: minorUnits(),
484
+ currency: currencyCode(),
485
+ currency_decimal_places: decimalPlaces(),
486
+ game_id: z.string(),
487
+ game_name: z.string(),
488
+ won_at: z.string()
489
+ })
490
+ )
491
+ );
492
+ function createCasinoApi(transport) {
493
+ return {
494
+ listGames: (input, options) => transport.requestPage({
495
+ method: "GET",
496
+ path: "/games",
497
+ query: {
498
+ category: input?.category,
499
+ provider: input?.provider,
500
+ search: input?.search,
501
+ ids: input?.ids?.length ? input.ids.join(",") : void 0,
502
+ sort: input?.sort
503
+ },
504
+ page: input?.page,
505
+ perPage: input?.perPage,
506
+ perPageParam: "limit",
507
+ auth: "none",
508
+ item: gameSchema(),
509
+ options
510
+ }),
511
+ listCategories: (_params, options) => transport.request({ method: "GET", path: "/games/categories", schema: categoriesSchema(), options }),
512
+ listProviders: (_params, options) => transport.request({ method: "GET", path: "/games/providers", schema: providersSchema(), options }),
513
+ getGame: ({ gameId }, options) => transport.request({
514
+ method: "GET",
515
+ path: `/games/${encodeURIComponent(gameId)}`,
516
+ schema: gameSchema(),
517
+ options
518
+ }),
519
+ launchGame: ({ gameId, mode, isMobile, returnUrl, language }, options) => transport.request({
520
+ method: "POST",
521
+ path: `/games/${encodeURIComponent(gameId)}/launch`,
522
+ body: { is_demo: mode === "demo", is_mobile: isMobile === true, return_url: returnUrl, language },
523
+ auth: "required",
524
+ // The response carries the URL with the game session token: never through `warn` mode's recovery
525
+ // (which would deliver a raw field and the response to `onValidationIssue`).
526
+ validation: "strict",
527
+ schema: launchSchema(),
528
+ options
529
+ }),
530
+ listSessions: (input, options) => transport.requestPage({
531
+ method: "GET",
532
+ path: "/games/sessions",
533
+ page: input?.page,
534
+ perPage: input?.perPage,
535
+ perPageParam: "limit",
536
+ auth: "required",
537
+ item: sessionSchema(),
538
+ options
539
+ }),
540
+ getHistory: (input, options) => transport.requestPage({
541
+ method: "GET",
542
+ path: "/games/history",
543
+ page: input?.page,
544
+ perPage: input?.perPage,
545
+ perPageParam: "limit",
546
+ auth: "required",
547
+ item: transactionSchema(),
548
+ options
549
+ }),
550
+ getBiggestWinners: (input, options) => transport.request({
551
+ method: "GET",
552
+ path: "/games/biggest-winners",
553
+ query: { limit: input?.limit, days: input?.days },
554
+ auth: "required",
555
+ schema: winnersSchema(),
556
+ options
557
+ })
558
+ };
559
+ }
560
+
561
+ // src/internal/input.ts
562
+ function rejectInput(transport, message, route) {
563
+ return Promise.reject(
564
+ transport.reportError({ code: "CONFIGURATION_ERROR", message, status: 0 }, { ...route, attempt: 0 })
565
+ );
566
+ }
567
+ function pageInputProblem(name, input) {
568
+ if (input === void 0) return void 0;
569
+ if (typeof input !== "object" || input === null || Array.isArray(input)) return `${name}: input must be an object.`;
570
+ const { page, perPage } = input;
571
+ if (page !== void 0 && (typeof page !== "number" || !Number.isSafeInteger(page) || page < 1))
572
+ return `${name}: page must be an integer \u2265 1.`;
573
+ if (perPage !== void 0 && (typeof perPage !== "number" || !Number.isInteger(perPage) || perPage < 1 || perPage > 100))
574
+ return `${name}: perPage must be an integer from 1 to 100.`;
575
+ return void 0;
576
+ }
577
+ function optionalTimestamp() {
578
+ return z.pipe(
579
+ z.nullish(z.string().check(z.refine((value) => value === "" || !Number.isNaN(Date.parse(value)), "invalid date"))),
580
+ z.transform((value) => value == null || value === "" || Date.parse(value) === 0 ? null : value)
581
+ );
582
+ }
583
+ function optionalText() {
584
+ return z.pipe(
585
+ z.nullish(z.string()),
586
+ z.transform((value) => value == null || value === "" ? null : value)
587
+ );
588
+ }
589
+ function nullableList(item) {
590
+ return z.pipe(
591
+ z.nullish(z.array(item)),
592
+ z.transform((value) => value ?? [])
593
+ );
594
+ }
595
+
596
+ // src/modules/loyalty.ts
597
+ var tierBenefits = () => z.pipe(
598
+ z.nullish(z.string()),
599
+ z.transform((text2, ctx) => {
600
+ if (text2 == null || text2.trim() === "") return null;
601
+ let parsed;
602
+ try {
603
+ parsed = JSON.parse(text2);
604
+ } catch {
605
+ parsed = void 0;
606
+ }
607
+ if (typeof parsed === "object" && parsed !== null && !Array.isArray(parsed))
608
+ return parsed;
609
+ ctx.issues.push({ code: "custom", message: "tier_benefits_json is not a JSON object", input: void 0 });
610
+ return z.NEVER;
611
+ })
612
+ );
613
+ var loyaltySchema = /* @__PURE__ */ lazy(
614
+ () => z.pipe(
615
+ wire({
616
+ total_points_earned: integerText(),
617
+ current_points: integerText(),
618
+ points_redeemed: integerText(),
619
+ current_tier: optionalText(),
620
+ tier_points: integerText(),
621
+ lifetime_wagered: z._default(minorUnits(), 0),
622
+ lifetime_deposited: z._default(minorUnits(), 0),
623
+ tier_benefits_json: tierBenefits(),
624
+ tier_expires_at: optionalTimestamp()
625
+ }),
626
+ z.transform(({ tierBenefitsJson, ...rest }) => {
627
+ const benefits = typeof tierBenefitsJson === "object" && tierBenefitsJson !== null && !Array.isArray(tierBenefitsJson) ? tierBenefitsJson : null;
628
+ return { ...rest, tierBenefits: benefits };
629
+ })
630
+ )
631
+ );
632
+ var redeemSchema = /* @__PURE__ */ lazy(
633
+ () => z.pipe(
634
+ wire({
635
+ success: z.optional(z.boolean()),
636
+ message: z.optional(z.string()),
637
+ redeemed_points: integerText(),
638
+ value: z.nullish(minorUnits()),
639
+ // Currency strict even in `'warn'`; absent, `null` and `''` still become `null`.
640
+ currency: z.pipe(
641
+ z.nullish(currencyOrEmpty()),
642
+ z.transform((value) => value == null || value === "" ? null : value)
643
+ ),
644
+ bonus_id: optionalText()
645
+ }),
646
+ z.transform((data) => ({
647
+ success: data.success,
648
+ message: data.message,
649
+ redeemedPoints: data.redeemedPoints,
650
+ value: data.value ?? null,
651
+ currency: data.currency,
652
+ bonusId: data.bonusId
653
+ }))
654
+ )
655
+ );
656
+ var UNCONFIRMED_REDEEM = "loyalty.redeem: the gateway did not confirm the redemption.";
657
+ var REDEEM_ROUTE = { method: "POST", path: "/loyalty/redeem" };
658
+ function redeemInputProblem(input) {
659
+ if (typeof input !== "object" || input === null || Array.isArray(input))
660
+ return "loyalty.redeem: input must be an object { points, redemptionType }.";
661
+ const { points, redemptionType } = input;
662
+ if (typeof points !== "number" || !Number.isSafeInteger(points) || points <= 0)
663
+ return "loyalty.redeem: points must be an integer greater than 0.";
664
+ if (typeof redemptionType !== "string" || redemptionType.trim() === "")
665
+ return "loyalty.redeem: redemptionType must be non-empty text.";
666
+ return void 0;
667
+ }
668
+ function createLoyaltyApi(transport) {
669
+ return {
670
+ get: (_params, options) => transport.request({ method: "GET", path: "/loyalty", auth: "required", schema: loyaltySchema(), options }),
671
+ redeem: (input, options) => {
672
+ const problem = redeemInputProblem(input);
673
+ if (problem !== void 0) return rejectInput(transport, problem, REDEEM_ROUTE);
674
+ return transport.request({
675
+ ...REDEEM_ROUTE,
676
+ body: { points: input.points, redemption_type: input.redemptionType },
677
+ auth: "required",
678
+ idempotent: true,
679
+ schema: redeemSchema(),
680
+ options
681
+ }).then(({ success, message, ...result }) => {
682
+ if (success === true) return result;
683
+ const text2 = typeof message === "string" && message !== "" ? message : UNCONFIRMED_REDEEM;
684
+ throw transport.reportError({ code: "UNKNOWN", message: text2, status: 200 }, REDEEM_ROUTE);
685
+ });
686
+ }
687
+ };
688
+ }
689
+ function openUnion(values) {
690
+ return z.pipe(
691
+ z.pipe(
692
+ z.string(),
693
+ z.transform((value) => value.toLowerCase())
694
+ ),
695
+ z.enum(values)
696
+ );
697
+ }
698
+
699
+ // src/modules/missions.ts
700
+ var MISSION_TYPES = ["daily", "weekly", "event", "permanent"];
701
+ var OBJECTIVE_TYPES = ["wager", "bet_count", "win_amount", "play_game", "deposit"];
702
+ var REWARD_TYPES = ["bonus", "free_spins", "points", "free_bet"];
703
+ var USER_MISSION_STATUSES = ["in_progress", "completed", "expired", "claimed"];
704
+ var missionSchema = /* @__PURE__ */ lazy(
705
+ () => wire({
706
+ id: z.string(),
707
+ name: z.string(),
708
+ description: z._default(z.string(), ""),
709
+ mission_type: openUnion(MISSION_TYPES),
710
+ objective_type: openUnion(OBJECTIVE_TYPES),
711
+ target_value: integerText(),
712
+ target_game_category: optionalText(),
713
+ target_games: nullableList(z.string()),
714
+ reward_type: openUnion(REWARD_TYPES),
715
+ reward_value: minorUnits(),
716
+ valid_from: optionalTimestamp(),
717
+ valid_to: optionalTimestamp()
718
+ })
719
+ );
720
+ var userMissionsSchema = /* @__PURE__ */ lazy(
721
+ () => z.pipe(
722
+ wire({
723
+ missions: nullableList(
724
+ wire({
725
+ id: z.string(),
726
+ mission_id: z.string(),
727
+ mission_name: z._default(z.string(), ""),
728
+ current_progress: integerText(),
729
+ target_value: integerText(),
730
+ progress_percentage: z.number(),
731
+ status: openUnion(USER_MISSION_STATUSES),
732
+ reward_type: openUnion(REWARD_TYPES),
733
+ reward_value: minorUnits(),
734
+ period_end: optionalTimestamp(),
735
+ completed_at: optionalTimestamp()
736
+ })
737
+ )
738
+ }),
739
+ z.transform((data) => data.missions)
740
+ )
741
+ );
742
+ function createMissionsApi(transport) {
743
+ return {
744
+ list: (input, options) => {
745
+ const problem = pageInputProblem("missions.list", input);
746
+ if (problem !== void 0) return rejectInput(transport, problem, { method: "GET", path: "/missions" });
747
+ return transport.requestPage({
748
+ method: "GET",
749
+ path: "/missions",
750
+ page: input?.page,
751
+ perPage: input?.perPage,
752
+ perPageParam: "limit",
753
+ auth: "required",
754
+ item: missionSchema(),
755
+ options
756
+ });
757
+ },
758
+ listMine: (_params, options) => transport.request({
759
+ method: "GET",
760
+ path: "/my/missions",
761
+ auth: "required",
762
+ schema: userMissionsSchema(),
763
+ options
764
+ })
765
+ };
766
+ }
767
+ var STATUSES = ["pending", "qualified", "completed", "expired", "unspecified"];
768
+ var status = () => z.pipe(protoEnum("REFERRAL_STATUS_"), z.enum(STATUSES));
769
+ var DEFAULT_PER_PAGE = 20;
770
+ var count2 = () => z._default(z.number().check(z.refine((value) => Number.isInteger(value) && value >= 0, "invalid counter")), 0);
771
+ var HISTORY_PATH = "/referrals/history";
772
+ var REGISTER_ROUTE = { method: "POST", path: "/referrals/register" };
773
+ function maskEmail(value) {
774
+ if (typeof value !== "string") return null;
775
+ const email = value.trim();
776
+ const parts = email.split("@");
777
+ if (parts.length !== 2 || /\s/.test(email)) return null;
778
+ const [local, domain] = parts;
779
+ if (local === "" || domain === "") return null;
780
+ const chars = Array.from(local);
781
+ return `${chars.length === 1 ? "*" : chars[0] + "*".repeat(chars.length - 1)}@${domain}`;
782
+ }
783
+ var infoSchema = /* @__PURE__ */ lazy(
784
+ () => z.pipe(
785
+ wire({
786
+ referral_code: optionalText(),
787
+ referral_link: optionalText(),
788
+ total_referrals: count2(),
789
+ completed_referrals: count2(),
790
+ pending_referrals: count2(),
791
+ total_earned: majorUnits(),
792
+ bonus_per_referral: majorUnits(),
793
+ min_deposit: majorUnits()
794
+ }),
795
+ z.transform(
796
+ ({ referralCode, referralLink, ...rest }) => ({
797
+ code: referralCode,
798
+ link: referralLink,
799
+ ...rest
800
+ })
801
+ )
802
+ )
803
+ );
804
+ var MinorAmount = class {
805
+ constructor(value) {
806
+ this.value = value;
807
+ }
808
+ value;
809
+ };
810
+ var minorAmount = () => z.pipe(
811
+ majorUnits(),
812
+ z.transform((value) => new MinorAmount(value))
813
+ );
814
+ var BUILT = /* @__PURE__ */ new WeakSet();
815
+ var referralSchema = /* @__PURE__ */ lazy(
816
+ () => z.pipe(
817
+ wire({
818
+ id: z.string(),
819
+ referee_id: z.optional(z.string()),
820
+ referee_email: z.nullish(z.string()),
821
+ referee_name: optionalText(),
822
+ referral_code: z._default(z.string(), ""),
823
+ status: status(),
824
+ referrer_bonus: minorAmount(),
825
+ referee_bonus: minorAmount(),
826
+ created_at: optionalTimestamp(),
827
+ completed_at: optionalTimestamp(),
828
+ expires_at: optionalTimestamp()
829
+ }),
830
+ z.transform((r) => {
831
+ const referrerBonus = r.referrerBonus;
832
+ const refereeBonus = r.refereeBonus;
833
+ if (!(referrerBonus instanceof MinorAmount) || !(refereeBonus instanceof MinorAmount)) return null;
834
+ const item = {
835
+ id: r.id,
836
+ refereeName: r.refereeName,
837
+ refereeEmailMasked: maskEmail(r.refereeEmail),
838
+ code: r.referralCode,
839
+ status: r.status,
840
+ referrerBonus: referrerBonus.value,
841
+ refereeBonus: refereeBonus.value,
842
+ createdAt: r.createdAt,
843
+ completedAt: r.completedAt,
844
+ expiresAt: r.expiresAt
845
+ };
846
+ BUILT.add(item);
847
+ return item;
848
+ })
849
+ )
850
+ );
851
+ function rawReferral(value) {
852
+ if (typeof value !== "object" || value === null || Array.isArray(value)) return null;
853
+ const snake = {};
854
+ for (const [key, field] of Object.entries(value)) snake[key.replace(/[A-Z]/g, (c) => `_${c.toLowerCase()}`)] = field;
855
+ const result = referralSchema().safeParse(snake);
856
+ return result.success ? result.data : null;
857
+ }
858
+ function historyItems(list2) {
859
+ if (!Array.isArray(list2)) return [];
860
+ const items = [];
861
+ for (const entry of list2) {
862
+ const item = typeof entry === "object" && entry !== null && BUILT.has(entry) ? entry : rawReferral(entry);
863
+ if (item !== null) items.push(item);
864
+ }
865
+ return items;
866
+ }
867
+ var reportedTotal = (value) => typeof value === "number" && Number.isSafeInteger(value) && value >= 0 ? value : 0;
868
+ var historySchema = /* @__PURE__ */ lazy(
869
+ () => wire({
870
+ referrals: nullableList(referralSchema()),
871
+ completed_count: count2(),
872
+ total_earned: majorUnits(),
873
+ pagination: z.optional(
874
+ wire({
875
+ page: count2(),
876
+ page_size: count2(),
877
+ total_items: count2(),
878
+ total_pages: count2()
879
+ })
880
+ )
881
+ })
882
+ );
883
+ var registeredSchema = /* @__PURE__ */ lazy(
884
+ () => z.pipe(
885
+ wire({
886
+ id: z.string(),
887
+ referral_code: z._default(z.string(), ""),
888
+ status: status(),
889
+ referee_bonus: z._default(majorUnits(), 0),
890
+ created_at: optionalTimestamp()
891
+ }),
892
+ z.transform(
893
+ (r) => ({
894
+ id: r.id,
895
+ code: r.referralCode,
896
+ status: r.status,
897
+ refereeBonus: r.refereeBonus,
898
+ createdAt: r.createdAt
899
+ })
900
+ )
901
+ )
902
+ );
903
+ var positiveInt = (value, fallback) => typeof value === "number" && Number.isSafeInteger(value) && value >= 1 ? value : fallback;
904
+ function registerInputProblem(input) {
905
+ if (typeof input !== "object" || input === null || Array.isArray(input))
906
+ return "referrals.register: input must be an object { code }.";
907
+ const { code } = input;
908
+ if (typeof code !== "string" || code.trim() === "") return "referrals.register: code must be non-empty text.";
909
+ return void 0;
910
+ }
911
+ function createReferralsApi(transport) {
912
+ return {
913
+ get: (_params, options) => transport.request({ method: "GET", path: "/referrals", auth: "required", schema: infoSchema(), options }),
914
+ listHistory: (input, options) => {
915
+ const problem = pageInputProblem("referrals.listHistory", input);
916
+ if (problem !== void 0) return rejectInput(transport, problem, { method: "GET", path: HISTORY_PATH });
917
+ const requestedPage = input?.page;
918
+ const requestedPerPage = input?.perPage;
919
+ return transport.request({
920
+ method: "GET",
921
+ path: HISTORY_PATH,
922
+ query: { page: requestedPage, limit: requestedPerPage },
923
+ auth: "required",
924
+ schema: historySchema(),
925
+ options
926
+ }).then(({ referrals, completedCount, totalEarned, pagination }) => {
927
+ const items = historyItems(referrals);
928
+ const received = Array.isArray(referrals) ? referrals.length : 0;
929
+ const page = positiveInt(pagination?.page, requestedPage ?? 1);
930
+ const perPage = positiveInt(pagination?.pageSize, requestedPerPage ?? DEFAULT_PER_PAGE);
931
+ const seen = received > 0 ? (page - 1) * perPage + received : 0;
932
+ const totalItems = Math.max(reportedTotal(pagination?.totalItems), seen);
933
+ return {
934
+ items,
935
+ page,
936
+ perPage,
937
+ totalItems,
938
+ totalPages: totalItems > 0 ? Math.ceil(totalItems / perPage) : 0,
939
+ completedCount,
940
+ totalEarned
941
+ };
942
+ });
943
+ },
944
+ register: (input, options) => {
945
+ const problem = registerInputProblem(input);
946
+ if (problem !== void 0) return rejectInput(transport, problem, REGISTER_ROUTE);
947
+ return transport.request({
948
+ ...REGISTER_ROUTE,
949
+ body: { referral_code: input.code.trim() },
950
+ auth: "required",
951
+ schema: registeredSchema(),
952
+ options
953
+ });
954
+ }
955
+ };
956
+ }
957
+ var HTTP_URL = "Expected an absolute http(s) URL";
958
+ var sessionSchema2 = /* @__PURE__ */ lazy(
959
+ () => z.pipe(
960
+ wire({
961
+ // The separate token only exists on the wire: the schema declares it (strict contract) and the output drops it.
962
+ operator_token: z.string(),
963
+ launch_url: z.string().check(
964
+ z.refine(
965
+ (value) => {
966
+ try {
967
+ const { protocol } = new URL(value);
968
+ return protocol === "https:" || protocol === "http:";
969
+ } catch {
970
+ return false;
971
+ }
972
+ },
973
+ { message: HTTP_URL }
974
+ )
975
+ ),
976
+ expires_in_seconds: z.number().check(z.refine((n) => Number.isFinite(n) && n > 0, { message: "Esperava > 0" }))
977
+ }),
978
+ // The clock is read when the response is interpreted (= moment of the response).
979
+ z.transform(({ launchUrl, expiresInSeconds }) => ({
980
+ launchUrl,
981
+ expiresInSeconds,
982
+ expiresAt: Date.now() + expiresInSeconds * 1e3
983
+ }))
984
+ )
985
+ );
986
+ function createSportsbookApi(transport) {
987
+ return {
988
+ createSession: (_params, options) => transport.request({
989
+ method: "GET",
990
+ path: "/first/session",
991
+ auth: "required",
992
+ // The response carries the URL with the operator token: never through `warn` mode's recovery
993
+ // (which would deliver a raw field and the response to `onValidationIssue`).
994
+ validation: "strict",
995
+ schema: sessionSchema2(),
996
+ options
997
+ })
998
+ };
999
+ }
1000
+
1001
+ // src/client.ts
1002
+ function createIgaming(client) {
1003
+ const transport = extension.getExtensionTransport(client);
1004
+ const igaming = {
1005
+ casino: createCasinoApi(transport),
1006
+ bonus: createBonusApi(transport),
1007
+ missions: createMissionsApi(transport),
1008
+ loyalty: createLoyaltyApi(transport),
1009
+ referrals: createReferralsApi(transport),
1010
+ sportsbook: createSportsbookApi(transport)
1011
+ };
1012
+ if (typeof extension.registerProductClient !== "function") {
1013
+ throw new EnginexError({
1014
+ code: "CONFIGURATION_ERROR",
1015
+ status: 0,
1016
+ message: `createIgaming requires @getenginex/sdk >=0.5.0 <1.0.0 (peer): update the installed core.`
1017
+ });
1018
+ }
1019
+ extension.registerProductClient(igaming, client);
1020
+ return igaming;
1021
+ }
1022
+
1023
+ export { createIgaming };
1024
+ //# sourceMappingURL=index.js.map
1025
+ //# sourceMappingURL=index.js.map