@getenginex/sdk-igaming 0.10.0 → 0.11.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/CHANGELOG.md +43 -0
- package/README.md +4 -3
- package/dist/chunk-LMBQDSFV.js +620 -0
- package/dist/chunk-LMBQDSFV.js.map +1 -0
- package/dist/index.cjs +548 -16
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +747 -1
- package/dist/index.d.ts +747 -1
- package/dist/index.js +285 -366
- package/dist/index.js.map +1 -1
- package/dist/query/index.cjs +44 -5
- package/dist/query/index.cjs.map +1 -1
- package/dist/query/index.d.cts +17 -2
- package/dist/query/index.d.ts +17 -2
- package/dist/query/index.js +32 -6
- package/dist/query/index.js.map +1 -1
- package/dist/testing/index.cjs +450 -12
- package/dist/testing/index.cjs.map +1 -1
- package/dist/testing/index.d.cts +42 -4
- package/dist/testing/index.d.ts +42 -4
- package/dist/testing/index.js +450 -12
- package/dist/testing/index.js.map +1 -1
- package/package.json +7 -7
package/dist/index.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/internal/input.ts","../src/internal/optional-values.ts","../src/internal/schemas.ts","../src/modules/bets.ts","../src/modules/bonus.ts","../src/modules/casino.ts","../src/modules/loyalty.ts","../src/internal/open-union.ts","../src/modules/missions.ts","../src/modules/referrals.ts","../src/modules/sportsbook.ts","../src/client.ts"],"names":["z","z2","moneyText","currencyCode","strictValue","z3","lazy","wire","z4","offerSchema","z5","money","decimalPlaces","z6","text","z7","z8","count","z9","sessionSchema","z10","extension","EnginexError"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAeO,SAAS,WAAA,CAAY,SAAA,EAA+B,OAAA,EAAiB,KAAA,EAA8B;AACxG,EAAA,OAAO,OAAA,CAAQ,MAAA;AAAA,IACb,SAAA,CAAU,WAAA,CAAY,EAAE,IAAA,EAAM,uBAAuB,OAAA,EAAS,MAAA,EAAQ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,oBAAA,CAAA,qBAAA,CAAsB,SAAS,MAAM,CAAA;AAC/C,EAAA,OAAO,OAAA;AACT","file":"index.cjs","sourcesContent":["import type { ExtensionTransport } from '@getenginex/sdk/extension'\n\n/** Route of a call, to report the input error to `onError`. @internal */\nexport interface Route {\n /** HTTP method. */\n method: 'GET' | 'POST' | 'PUT' | 'DELETE'\n /** Path after `/api/v1`. */\n path: string\n}\n\n/**\n * Rejects with `CONFIGURATION_ERROR` (without a request) notifying `onError`, like the core does with invalid\n * input. `message` never carries the received value. The error comes out of `reportError`, which normalizes it into\n * `EnginexError` (the core does not export the constructor to product packages). @internal\n */\nexport function rejectInput(transport: ExtensionTransport, message: string, route: Route): Promise<never> {\n return Promise.reject(\n transport.reportError({ code: 'CONFIGURATION_ERROR', message, status: 0 }, { ...route, attempt: 0 }),\n )\n}\n\n/**\n * Checks `{ page, perPage }` of a listing: `page` an integer ≥ 1, `perPage` an integer from 1 to 100.\n * Returns the problem message or `undefined` if everything is fine. @internal\n */\nexport function pageInputProblem(name: string, input: unknown): string | undefined {\n if (input === undefined) return undefined\n if (typeof input !== 'object' || input === null || Array.isArray(input)) return `${name}: input must be an object.`\n const { page, perPage } = input as { page?: unknown; perPage?: unknown }\n if (page !== undefined && (typeof page !== 'number' || !Number.isSafeInteger(page) || page < 1))\n return `${name}: page must be an integer ≥ 1.`\n if (\n perPage !== undefined &&\n (typeof perPage !== 'number' || !Number.isInteger(perPage) || perPage < 1 || perPage > 100)\n )\n return `${name}: perPage must be an integer from 1 to 100.`\n return undefined\n}\n","import * as z from 'zod/mini'\n\n// The gateway writes an absent `google.protobuf.Timestamp` as `\"1970-01-01T00:00:00Z\"` (`AsTime()`\n// of zero) or omits the key; an absent text comes out as `\"\"`. The SDK delivers `null` in both cases.\n// `optionalTimestamp` and `optionalText` are copies of the core's internal helpers\n// (`packages/sdk/src/internal/optional-values.ts`, which are not public API), with one difference: these\n// versions also accept `null` and the absent key (the core's only accept text). Keep the copies in\n// sync with the core's when changing the empty/epoch rule.\n\n/**\n * Schema of an optional ISO 8601 date: absent, `null`, empty text and the epoch (`1970-01-01T00:00:00Z`,\n * in any timezone or precision) become `null`; another date passes as it came. Text that is not a date fails\n * validation (in `'warn'`, it arrives raw and is reported). Call only inside a `lazy`. @internal\n */\nexport function optionalTimestamp() {\n return z.pipe(\n z.nullish(z.string().check(z.refine((value) => value === '' || !Number.isNaN(Date.parse(value)), 'invalid date'))),\n z.transform((value): string | null => (value == null || value === '' || Date.parse(value) === 0 ? null : value)),\n )\n}\n\n/** Optional text: absent, `null` and `\"\"` become `null`. Call only inside a `lazy`. @internal */\nexport function optionalText() {\n return z.pipe(\n z.nullish(z.string()),\n z.transform((value): string | null => (value == null || value === '' ? null : value)),\n )\n}\n\n/**\n * A list the gateway may send as `null` (Go nil slice) or omit: becomes `[]`. Call only\n * inside a `lazy`. @internal\n */\nexport function nullableList<T extends z.ZodMiniType>(item: T) {\n return z.pipe(\n z.nullish(z.array(item)),\n z.transform((value) => value ?? []),\n )\n}\n","import { currencyCode, moneyText, strictValue } from '@getenginex/sdk/extension'\nimport * as z from 'zod/mini'\n\n// All helpers build schemas: call only inside a `lazy` (nothing runs at import).\n\n/**\n * Schema of a protobuf enum the gateway passes along as text (e.g. `SESSION_STATUS_ACTIVE`):\n * strips the prefix, if any, and returns lowercase (`active`) — the same format the gateway\n * already uses on other routes and that the core uses in its enums. A new value passes along in the same\n * format, without breaking validation. Absent (protojson omits the zero value) becomes `unspecified`; a\n * number (protojson writes a value the gateway does not know this way) becomes the number as text.\n * Equivalent to the core's internal helper (which is not public API). @internal\n */\nexport function protoEnum(prefix: string) {\n return z.pipe(\n z.optional(z.union([z.string(), z.number()])),\n z.transform((value) => {\n if (value === undefined || value === 0) return 'unspecified'\n if (typeof value === 'number') return String(value)\n return (value.startsWith(prefix) ? value.slice(prefix.length) : value).toLowerCase()\n }),\n )\n}\n\n/**\n * Money in minor units that the gateway sends as a 64-bit integer in text (e.g. `\"2000\"`,\n * as the gateway's `strconv.FormatInt` and protojson write it) or as a number, returned as\n * `number`. It is the core's `moneyText()`: strict even in `'warn'` mode (outside the format, the whole\n * response rejects). @internal\n */\nexport function minorUnits() {\n return moneyText()\n}\n\n/**\n * Currency code the gateway may send empty: `''` (protojson omits the empty currency) or ISO 4217 in\n * uppercase (`BRL`). Strict even in `'warn'` mode, like the core's `currencyCode()`; it only accepts\n * the `''` as well. Absent/`null` are up to the caller (e.g. `z._default(..., '')`). @internal\n */\nexport function currencyOrEmpty(): z.ZodMiniType<string> {\n return currencyCode({ allowEmpty: true })\n}\n\nconst NON_NEGATIVE_MONEY = 'Expected money in minor units: a non-negative integer within the safe range of number'\n\n/**\n * Money in minor units that can never be negative (a stake, a payout, a jackpot), as a JSON number (what\n * `encoding/json` writes for an `int64`) or as int64 text, returned as `number`. A value ≥ 2^53 (already\n * rounded by `JSON.parse` when it came as a number, or text that does not fit), a negative, a fraction or\n * anything else rejects the whole response, even in `'warn'` mode, like the core's `moneyText()`. @internal\n */\nexport function nonNegativeMinorUnits(): z.ZodMiniType<number> {\n return z.pipe(\n strictValue<number | string>(\n (v) =>\n (typeof v === 'number' && Number.isSafeInteger(v) && v >= 0) ||\n (typeof v === 'string' && /^\\d+$/.test(v) && Number.isSafeInteger(Number(v))),\n NON_NEGATIVE_MONEY,\n ),\n // `|| 0`: a JSON `-0` comes out as `0`.\n z.transform((v) => Number(v) || 0),\n ) as unknown as z.ZodMiniType<number>\n}\n\nconst INTEGER_TEXT = 'Expected an integer within the safe range of number'\n\n/**\n * Integer that is not money (loyalty points, mission progress), as int64 text or a number,\n * returned as `number`. The same validation as {@link minorUnits}, but it follows the normal\n * `'warn'` rule (the divergent field arrives raw and is reported). @internal\n */\nexport function integerText() {\n return z.pipe(\n z.union([\n z\n .string()\n .check(\n z.refine((value) => /^-?\\d+$/.test(value) && Number.isSafeInteger(Number(value)), { message: INTEGER_TEXT }),\n ),\n z.number().check(z.refine((value) => Number.isSafeInteger(value), { message: INTEGER_TEXT })),\n ]),\n z.transform(Number),\n )\n}\n\n/** Protobuf text: protojson omits `''`, which comes back as `''`. @internal */\nexport function text() {\n return z._default(z.string(), '')\n}\n\n/** Protobuf number (int32/uint32): protojson omits `0`, which comes back as `0`. @internal */\nexport function count() {\n return z._default(z.number(), 0)\n}\n\n/** Protobuf list (`repeated`): protojson omits the empty list, which comes back as an empty `[]`. @internal */\nexport function list<T extends z.ZodMiniType>(item: T) {\n return z._default(z.array(item), [])\n}\n\n/**\n * `google.protobuf.Duration` from protojson (e.g. `\"86400s\"`, `\"1.5s\"`), returned in seconds. @internal\n */\nexport function durationSeconds() {\n return z.pipe(\n z.string().check(z.regex(/^-?\\d+(\\.\\d+)?s$/, { message: 'Expected a protobuf duration, e.g. \"86400s\"' })),\n z.transform((value) => Number(value.slice(0, -1))),\n )\n}\n\nconst MAJOR_UNITS = 'Expected a value in major units (a finite number) that fits in whole minor units'\n\n/**\n * Converts a value in major units (float, as the gateway writes referrals: cents / 100)\n * for whole minor units: `Math.round(value * 100)`, rounding halves away from zero\n * (`-0.005` becomes `-1`, symmetric to `0.005` → `1`) and never returning `-0`. `19.99` → `1999`,\n * `0.1 + 0.2` → `30`, `1e-7` → `0`. It refuses what is not a finite number and what does not fit in a safe integer\n * after the conversion. @internal\n */\nexport function majorToMinorUnits(value: number): number {\n const minor = Math.sign(value) * Math.round(Math.abs(value) * 100)\n return minor === 0 ? 0 : minor\n}\n\n/**\n * Schema of a monetary value in major units (float) returned in minor units. See\n * {@link majorToMinorUnits}. Strict even in `'warn'` mode: outside the format, the whole response\n * rejects. @internal\n */\nexport function majorUnits() {\n // The core's `strictValue`: even the wrong type produces the issue marked as strict; a `z.number()` would emit\n // `invalid_type` without the mark and the field would be recovered raw in `'warn'`.\n return z.pipe(\n strictValue<number>(\n (value) => typeof value === 'number' && Number.isSafeInteger(majorToMinorUnits(value)),\n MAJOR_UNITS,\n ),\n z.transform((value) => majorToMinorUnits(value)),\n )\n}\n","// Public types come from the core's main entry: the /extension `.d.ts` exposes Zod, and this package's\n// public API cannot depend on it (check-api).\nimport type { CallOptions, Page } from '@getenginex/sdk'\nimport { lazy, wire, type ExtensionTransport } from '@getenginex/sdk/extension'\nimport * as z from 'zod/mini'\nimport { pageInputProblem, rejectInput, type Route } from '../internal/input'\nimport { nullableList, optionalTimestamp } from '../internal/optional-values'\nimport { nonNegativeMinorUnits, protoEnum } from '../internal/schemas'\n\n/**\n * Status of a sportsbook bet, without the gateway's `BET_STATUS_` prefix and in lowercase. A new value the SDK\n * does not know yet may arrive (a number as text, when the gateway does not know it either): handle the\n * default case.\n * @category Bets\n */\nexport type BetStatus =\n | 'pending'\n | 'open'\n | 'won'\n | 'lost'\n | 'void'\n | 'cashed_out'\n | 'partially_settled'\n | 'unspecified'\n | (string & {})\n\n/**\n * Result of a selection, without the gateway's `SELECTION_RESULT_` prefix and in lowercase. A new value may\n * arrive: handle the default case.\n * @category Bets\n */\nexport type BetSelectionResult =\n | 'pending'\n | 'won'\n | 'lost'\n | 'void'\n | 'half_won'\n | 'half_lost'\n | 'unspecified'\n | (string & {})\n\n/**\n * A sportsbook bet of the player (`GET /bets`).\n *\n * Amounts are in minor units of the **operator's currency** (`enginex.config.get()`): the gateway sends no\n * currency per bet.\n * @category Bets\n */\nexport interface Bet {\n /** Bet id, for {@link BetsApi.get}, {@link BetsApi.getCashoutOffer} and {@link BetsApi.cashout}. */\n id: string\n /** Status, e.g. `pending`, `won`, `cashed_out`. */\n status: BetStatus\n /** Stake in minor units (never negative). */\n stake: number\n /** Potential return in minor units (never negative). */\n potentialReturn: number\n /** Total odds (decimal), e.g. `2.35`. */\n totalOdds: number\n /** Placement date, ISO 8601 (UTC); `null` when the gateway did not have one. */\n createdAt: string | null\n}\n\n/**\n * A selection of a bet ({@link BetDetails.selections}).\n * @category Bets\n */\nexport interface BetSelection {\n /** Event name. */\n eventName: string\n /** Market name. */\n marketName: string\n /** Selection (outcome) name. */\n selectionName: string\n /** Odds (decimal) of the selection. */\n odds: number\n /** Result, e.g. `pending`, `won`. */\n result: BetSelectionResult\n}\n\n/**\n * A bet with its selections (`GET /bets/{id}`).\n * @category Bets\n */\nexport interface BetDetails extends Bet {\n /** The bet's selections; `[]` when the gateway sends none. */\n selections: BetSelection[]\n}\n\n/**\n * Pagination of {@link BetsApi.list}. There is no status filter: the gateway ignores one, so filter\n * `items` in the app.\n * @category Bets\n */\nexport interface ListBetsInput {\n /** Page (starts at 1). Gateway default: 1. */\n page?: number\n /** Items per page, from 1 to 100. Gateway default: 20 (out of range also becomes 20). */\n perPage?: number\n}\n\n/**\n * Cash-out offer of a bet (`GET /bets/{id}/cashout`). Offers expire: read it again shortly before cashing out.\n * @category Bets\n */\nexport interface CashoutOffer {\n /** Bet id. */\n betId: string\n /** Whether the bet can be cashed out now. `false`: do not show the cash-out button. */\n available: boolean\n /** Amount offered, in minor units of the operator's currency (never negative; `0` without an offer). */\n cashoutAmount: number\n /** Expiry of the offer, ISO 8601 (UTC); `null` without an offer. */\n expiresAt: string | null\n}\n\n/**\n * Result of a cash-out ({@link BetsApi.cashout}).\n * @category Bets\n */\nexport interface CashoutResult {\n /** Bet id. */\n betId: string\n /** Amount paid, in minor units of the operator's currency (never negative). */\n cashoutAmount: number\n /** Status of the bet after the cash-out, as the gateway sends it (`cashed_out`). */\n status: 'cashed_out' | (string & {})\n}\n\n/**\n * The player's sportsbook bets: history, details, cash-out offer and cash-out. Every method requires login.\n * Placing bets is not part of this namespace.\n * @category Bets\n */\nexport interface BetsApi {\n /**\n * The player's bets, from newest to oldest, paginated. The gateway sends no currency: format the amounts with the\n * operator's currency (`enginex.config.get()`).\n * @example\n * const { currency } = await enginex.config.get()\n * const page = await igaming.bets.list({ perPage: 20 })\n * page.items.forEach((bet) => render(bet.status, formatMoney(bet.stake, currency, 'pt-BR')))\n * @throws {EnginexError} `CONFIGURATION_ERROR` (no request) for a `page`/`perPage` out of range;\n * `VALIDATION_ERROR` for a negative amount or one that does not fit in a safe integer (even in `'warn'`);\n * `UNAUTHENTICATED` without a session.\n */\n list(input?: ListBetsInput, options?: CallOptions): Promise<Page<Bet>>\n /**\n * A bet with its selections.\n * @example\n * const bet = await igaming.bets.get({ betId })\n * bet.selections.forEach((s) => console.log(s.eventName, s.selectionName, s.result))\n * @throws {EnginexError} `CONFIGURATION_ERROR` (no request) for an empty `betId`; `BET_NOT_FOUND`/`NOT_FOUND`\n * (404) for an unknown id; `UNAUTHENTICATED` without a session.\n */\n get(input: { betId: string }, options?: CallOptions): Promise<BetDetails>\n /**\n * The bet's current cash-out offer. Show the cash-out button only with `available: true`, and read it again\n * before cashing out (offers expire).\n * @example\n * const offer = await igaming.bets.getCashoutOffer({ betId })\n * if (offer.available) showCashout(offer.cashoutAmount, offer.expiresAt)\n * @throws {EnginexError} `CONFIGURATION_ERROR` (no request) for an empty `betId`; `BET_NOT_FOUND`/`NOT_FOUND`\n * (404) for an unknown id; `UNAUTHENTICATED` without a session.\n */\n getCashoutOffer(input: { betId: string }, options?: CallOptions): Promise<CashoutOffer>\n /**\n * Cashes out the bet at the current offer. Idempotent: it sends an `Idempotency-Key` (the one in\n * `options.idempotencyKey` or, without it, one generated per call). To retry a cash-out whose outcome is\n * unknown (network error, timeout, 5xx), call again with the **same** `idempotencyKey`: the gateway answers\n * the first result instead of cashing out twice. Through `createIgamingMutations` the key is kept for you\n * after an ambiguous failure.\n * @example\n * const idempotencyKey = crypto.randomUUID()\n * const result = await igaming.bets.cashout({ betId }, { idempotencyKey })\n * @throws {EnginexError} `CONFIGURATION_ERROR` (no request) for an empty `betId` or an `idempotencyKey`\n * with surrounding spaces or longer than 255 characters; `FAILED_PRECONDITION` (422) when there is no\n * offer; `CASHOUT_UNAVAILABLE` (it arrives with HTTP 500: the gateway does not map it yet, identify it by the\n * code); `KEY_IN_USE` (409) while a cash-out with the same key is still being processed;\n * `PAYLOAD_MISMATCH` (422) for a key reused on another request; `UNAUTHENTICATED` without a session.\n */\n cashout(input: { betId: string }, options?: CallOptions): Promise<CashoutResult>\n}\n\n// The gateway's bet handlers (`betting.go`) write `encoding/json` maps: money as JSON numbers (`int64`), the\n// status as the protobuf name (`BET_STATUS_WON`) and the date as Go's `time.Time` (`AsTime()` of an absent\n// timestamp is the epoch).\nconst betFields = () => ({\n id: z.string(),\n status: protoEnum('BET_STATUS_'),\n stake: nonNegativeMinorUnits(),\n potential_return: nonNegativeMinorUnits(),\n total_odds: z.number(),\n created_at: optionalTimestamp(),\n})\n\nconst betSchema = /* @__PURE__ */ lazy((): z.ZodMiniType<Bet> => wire(betFields()))\n\nconst betDetailsSchema = /* @__PURE__ */ lazy(\n (): z.ZodMiniType<BetDetails> =>\n wire({\n ...betFields(),\n selections: nullableList(\n wire({\n event_name: z.string(),\n market_name: z.string(),\n selection_name: z.string(),\n odds: z.number(),\n result: protoEnum('SELECTION_RESULT_'),\n }),\n ),\n }),\n)\n\nconst offerSchema = /* @__PURE__ */ lazy(\n (): z.ZodMiniType<CashoutOffer> =>\n wire({\n bet_id: z.string(),\n available: z.boolean(),\n cashout_amount: nonNegativeMinorUnits(),\n expires_at: optionalTimestamp(),\n }),\n)\n\nconst cashoutSchema = /* @__PURE__ */ lazy(\n (): z.ZodMiniType<CashoutResult> =>\n wire({ bet_id: z.string(), cashout_amount: nonNegativeMinorUnits(), status: z.string() }),\n)\n\nconst LIST_ROUTE: Route = { method: 'GET', path: '/bets' }\nconst GET_ROUTE: Route = { method: 'GET', path: '/bets/{betId}' }\nconst OFFER_ROUTE: Route = { method: 'GET', path: '/bets/{betId}/cashout' }\nconst CASHOUT_ROUTE: Route = { method: 'POST', path: '/bets/{betId}/cashout' }\n\n// The gateway's idempotency middleware refuses a key above 255 characters, and the cash-out handler one with\n// surrounding spaces.\nconst MAX_IDEMPOTENCY_KEY = 255\n\nfunction betIdProblem(name: string, input: unknown): string | undefined {\n if (typeof input !== 'object' || input === null || Array.isArray(input)) return `${name}: input must be { betId }.`\n const { betId } = input as { betId?: unknown }\n return typeof betId === 'string' && betId.trim() !== '' ? undefined : `${name}: betId must be non-empty text.`\n}\n\nfunction idempotencyKeyProblem(options: CallOptions | undefined): string | undefined {\n const key = options?.idempotencyKey\n if (key === undefined || key === '') return undefined\n if (typeof key !== 'string' || key !== key.trim() || key.length > MAX_IDEMPOTENCY_KEY)\n return `bets.cashout: idempotencyKey must be text without surrounding spaces, up to ${MAX_IDEMPOTENCY_KEY} characters.`\n return undefined\n}\n\nconst betPath = (betId: string, suffix = '') => `/bets/${encodeURIComponent(betId)}${suffix}`\n\n/** Creates the `bets` namespace. @internal */\nexport function createBetsApi(transport: ExtensionTransport): BetsApi {\n return {\n list: (input, options) => {\n const problem = pageInputProblem('bets.list', input)\n if (problem !== undefined) return rejectInput(transport, problem, LIST_ROUTE)\n return transport.requestPage({\n ...LIST_ROUTE,\n page: input?.page,\n perPage: input?.perPage,\n perPageParam: 'limit',\n auth: 'required',\n item: betSchema(),\n options,\n })\n },\n get: (input, options) => {\n const problem = betIdProblem('bets.get', input)\n if (problem !== undefined) return rejectInput(transport, problem, GET_ROUTE)\n return transport.request({\n method: 'GET',\n path: betPath(input.betId),\n auth: 'required',\n schema: betDetailsSchema(),\n options,\n })\n },\n getCashoutOffer: (input, options) => {\n const problem = betIdProblem('bets.getCashoutOffer', input)\n if (problem !== undefined) return rejectInput(transport, problem, OFFER_ROUTE)\n return transport.request({\n method: 'GET',\n path: betPath(input.betId, '/cashout'),\n auth: 'required',\n schema: offerSchema(),\n options,\n })\n },\n cashout: (input, options) => {\n const problem = betIdProblem('bets.cashout', input) ?? idempotencyKeyProblem(options)\n if (problem !== undefined) return rejectInput(transport, problem, CASHOUT_ROUTE)\n return transport.request({\n method: 'POST',\n path: betPath(input.betId, '/cashout'),\n auth: 'required',\n // No body: the gateway's idempotency middleware fingerprints the (empty) body, so a replay always matches.\n idempotent: true,\n schema: cashoutSchema(),\n options,\n })\n },\n }\n}\n","// Public types come from the core's main entry: the /extension `.d.ts` exposes Zod, and this package's\n// public API cannot depend on it (check-api).\nimport type { CallOptions, CursorPage, CursorPageInput, NoParams } from '@getenginex/sdk'\nimport { lazy, wire, type ExtensionTransport } from '@getenginex/sdk/extension'\nimport * as z from 'zod/mini'\nimport { count, currencyOrEmpty, durationSeconds, list, minorUnits, protoEnum, text } from '../internal/schemas'\n\n// Wire format: the gateway writes the campaigns with protojson (the .proto names in snake_case,\n// without the zero values). The SDK returns camelCase, with the enums without the prefix and in lowercase,\n// money (int64 as text) as `number`, durations in seconds and the type's zero in place of the\n// omitted values (`''`, `0`, `[]`, `'unspecified'`). Absent messages stay absent\n// (`undefined`): protobuf guarantees none, and the app handles the absence.\n\n// ─── Basic types ───────────────────────────────────────────────────────────────────────────────\n\n/**\n * Money value of a campaign, in minor units of the currency (e.g. cents). The decimal places\n * are the currency's (`config.currency.decimalPlaces` for the operator's currency).\n * @category Bonus\n */\nexport interface CampaignMoney {\n /** Value in minor units of `currency` (the gateway sends it as text; the SDK converts). */\n amount: number\n /** Currency code, e.g. `BRL`. */\n currency: string\n}\n\n/**\n * Time window (ISO 8601, UTC). A missing side is left open.\n * @category Bonus\n */\nexport interface CampaignTimeWindow {\n /** Start. */\n startsAt?: string\n /** End. */\n endsAt?: string\n}\n\n/**\n * Exact ratio (percentage, multiplier), in one of two forms: `decimal` (text, e.g. `\"30\"`,\n * `\"0.5\"`) or `basisPoints` (10000 = 100%).\n * @category Bonus\n */\nexport interface CampaignExactRatio {\n /** Exact decimal value as text (do not convert to `number` if you need precision). */\n decimal?: string\n /** Value in basis points: `10000` = 100%. */\n basisPoints?: number\n /** Maximum decimal places of the result. */\n maximumScale: number\n}\n\n/**\n * Rounding mode of a campaign calculation.\n * @category Bonus\n */\nexport type CampaignRoundingMode = 'floor' | 'half_up' | 'ceiling' | 'unspecified' | (string & {})\n\n/**\n * Product where the campaign applies.\n * @category Bonus\n */\nexport type CampaignProductScope = 'casino' | 'sportsbook' | 'casino_and_sportsbook' | 'unspecified' | (string & {})\n\n/**\n * How the player enters the campaign: `automatic` (enters on its own on meeting the qualification), `opt_in`\n * (needs {@link BonusApi.optIn}), `promo_code` (needs {@link BonusApi.redeemPromoCode}) or\n * `manual` (the operator adds them).\n * @category Bonus\n */\nexport type CampaignEntryPolicyCode = 'automatic' | 'opt_in' | 'promo_code' | 'manual' | 'unspecified' | (string & {})\n\n/**\n * How the reward is delivered: `automatic` (credited on qualifying) or `player_claim` (the player\n * redeems it with {@link BonusApi.claim}).\n * @category Bonus\n */\nexport type CampaignRewardClaimPolicyCode = 'automatic' | 'player_claim' | 'unspecified' | (string & {})\n\n/**\n * Reward type: balance credit, free spins, free bet or sports bet coverage.\n * @category Bonus\n */\nexport type CampaignRewardKind =\n | 'balance_credit'\n | 'casino_free_spins'\n | 'sports_bonus_bet'\n | 'sports_bet_coverage'\n | 'unspecified'\n | (string & {})\n\n/**\n * Versioned policy (code + version).\n * @category Bonus\n */\nexport interface CampaignPolicy<C extends string> {\n /** Policy code. */\n code: C\n /** Policy version. @beta */\n version: number\n}\n\n// ─── Scopes and qualification ──────────────────────────────────────────────────────────────────────\n\n/**\n * Casino activity slice (empty lists = no restriction on that criterion).\n * Mirrors the bonus service protobuf and may change in 0.x (minor) versions.\n * @beta\n * @category Bonus\n */\nexport interface CasinoActivitySelector {\n /** Provider instance. */\n providerInstanceId: string\n /** Provider software. */\n softwareIds: string[]\n /** Games. */\n gameIds: string[]\n /** Categories (catalog slugs). */\n categoryCodes: string[]\n}\n\n/**\n * Sports bet type.\n * @category Bonus\n */\nexport type SportsBetType = 'single' | 'multiple' | 'system' | 'unspecified' | (string & {})\n\n/**\n * Sports activity slice (empty lists = no restriction on that criterion).\n * Mirrors the bonus service protobuf and may change in 0.x (minor) versions.\n * @beta\n * @category Bonus\n */\nexport interface SportsActivitySelector {\n /** Sports. */\n sportCodes: string[]\n /** Competitions. */\n competitionIds: string[]\n /** Events. */\n eventIds: string[]\n /** Markets. */\n marketCodes: string[]\n /** Live only (`true`), pre-match only (`false`) or both (absent). */\n live?: boolean\n /** Accepted bet types. */\n betTypes: SportsBetType[]\n}\n\n/**\n * Qualification by a player event (e.g. completed signup).\n * @category Bonus\n */\nexport interface UserEventQualification {\n /** Event code. */\n eventCode: string\n /** Event version. @beta */\n eventVersion: number\n /** Authorized origin of the event. */\n sourceAuthority: string\n /** Fields that identify the event. */\n identityFields: string[]\n}\n\n/**\n * Qualification by a confirmed deposit.\n * @category Bonus\n */\nexport interface DepositSettledQualification {\n /** Deposit currency. */\n currency: string\n /** Accepted payment methods (e.g. `pix`); empty = all. */\n eligibleMethodCodes: string[]\n /** `required` (only the first deposit), `excluded` (never the first) or `any`. */\n firstDepositPolicy: 'any' | 'required' | 'excluded' | 'unspecified' | (string & {})\n /** Minimum deposit. */\n minimumSettledNetAmount?: CampaignMoney\n /** Maximum deposit considered. */\n maximumSettledNetAmount?: CampaignMoney\n /** Value basis (e.g. `settled_net_deposit`). */\n amountBasis: string\n}\n\n/**\n * Qualification by activity accumulated over a window (e.g. net loss or total wagered).\n * @category Bonus\n */\nexport interface ActivityAggregateQualification {\n /** `net_loss` (net loss) or `settled_stake` (total wagered and settled). */\n basis: 'net_loss' | 'settled_stake' | 'unspecified' | (string & {})\n /** Product considered. */\n productScope: CampaignProductScope\n /** Currency. */\n currency: string\n /** Accumulation window, in seconds. */\n window?: number\n /** Window time zone. */\n timezone: string\n /** Tolerance for late events, in seconds. */\n lateEventGrace?: number\n /** Casino slice. */\n casino?: CasinoActivitySelector\n /** Sports betting slice. */\n sportsbook?: SportsActivitySelector\n}\n\n/**\n * What the player must do to qualify. Only one of the cases is filled in; `immediate`\n * means that joining already qualifies.\n * @category Bonus\n */\nexport interface CampaignQualification {\n /** Definition version. @beta */\n version: number\n /** Qualifies on joining. */\n immediate?: Record<string, never>\n /** Qualifies with a player event. */\n userEvent?: UserEventQualification\n /** Qualifies with a deposit. */\n depositSettled?: DepositSettledQualification\n /** Qualifies with accumulated activity. */\n activityAggregate?: ActivityAggregateQualification\n}\n\n// ─── Reward ──────────────────────────────────────────────────────────────────────────────────────\n\n/**\n * Reward validity: only one of the cases is filled in.\n * @category Bonus\n */\nexport interface CampaignRewardValidity {\n /** Does not expire. */\n noExpiry?: Record<string, never>\n /** Expires on a fixed date. */\n absoluteExpiry?: {\n /** Expiration date, ISO 8601 (UTC). */\n expiresAt?: string\n }\n /** Expires some time after the grant. */\n durationFromGrant?: {\n /** Duration, in seconds. */\n duration?: number\n }\n}\n\n/**\n * Percentage calculation over a source value (e.g. 100% of the deposit up to R$ 500) or over an\n * accumulated amount (rebate).\n * @category Bonus\n */\nexport interface CampaignPercentCalculation {\n /** Percentage. */\n percentage?: CampaignExactRatio\n /** Rounding. */\n rounding: CampaignRoundingMode\n /** Minimum reward. */\n minimumReward?: CampaignMoney\n /** Maximum reward. */\n maximumReward?: CampaignMoney\n}\n\n/**\n * Balance credit reward. The value comes from one of the three calculations.\n * @category Bonus\n */\nexport interface BalanceCreditReward {\n /** Fixed value. */\n fixedAmount?: {\n /** Reward value. */\n amount?: CampaignMoney\n }\n /** Percentage of the source value (e.g. of the deposit). */\n percentOfSourceAmount?: CampaignPercentCalculation\n /** Rebate over an accumulated amount. */\n aggregateRebate?: {\n /** Percentage. */\n percentage?: CampaignExactRatio\n /** Rounding. */\n rounding: CampaignRoundingMode\n /** Minimum base for there to be a reward. */\n minimumBasis?: CampaignMoney\n /** Maximum reward. */\n maximumReward?: CampaignMoney\n }\n /** Balance credited: `real` or `restricted` (bonus, with usage rules). */\n balanceClass: 'real' | 'restricted' | 'unspecified' | (string & {})\n /** Winnings from the reward: `real` or restricted until the rollover is met. */\n proceedsClass: 'real' | 'restricted_until_wagering_completion' | 'unspecified' | (string & {})\n /** Validity. */\n validity?: CampaignRewardValidity\n}\n\n/**\n * Free spins reward.\n * @category Bonus\n */\nexport interface CasinoFreeSpinsReward {\n /** Spin provider. */\n providerCode: string\n /** Games where the spins apply. */\n casinoScope?: CasinoActivitySelector\n /** Number of spins. */\n quantity: number\n /** Value of each spin. */\n denomination?: CampaignMoney\n /** Currency. */\n currency: string\n /** Window to use the spins. */\n grantWindow?: CampaignTimeWindow\n /** Winnings from the spins: `real` or restricted until the rollover is met. */\n proceedsClass: 'real' | 'restricted_until_wagering_completion' | 'unspecified' | (string & {})\n /** Maximum win. */\n maximumWinnings?: CampaignMoney\n}\n\n/**\n * Free sports bet reward.\n * @category Bonus\n */\nexport interface SportsBonusBetReward {\n /** Sportsbook provider. */\n providerCode: string\n /** Where the bet applies. */\n sportsbookScope?: SportsActivitySelector\n /** Value of each bet. */\n amount?: CampaignMoney\n /** Number of bets. */\n quantity: number\n /** Validity. */\n validity?: CampaignRewardValidity\n}\n\n/**\n * Sports bet coverage reward (returns the lost bet up to a cap).\n * @category Bonus\n */\nexport interface SportsBetCoverageReward {\n /** Sportsbook provider. */\n providerCode: string\n /** Bets covered. */\n qualifyingBetScope?: SportsActivitySelector\n /** Cap of the coverage. */\n coverageCap?: CampaignMoney\n /** Validity. */\n validity?: CampaignRewardValidity\n}\n\n/**\n * Maximum bet with bonus balance.\n * Mirrors the bonus service protobuf and may change in 0.x (minor) versions.\n * @beta\n * @category Bonus\n */\nexport interface CampaignMaximumBet {\n /** `product_limit_only` (only the product's limit) or `campaign_maximum` (the `campaignMaximum` one). */\n mode: 'product_limit_only' | 'campaign_maximum' | 'unspecified' | (string & {})\n /** Maximum bet of the campaign. */\n campaignMaximum?: CampaignMoney\n}\n\n/**\n * Sports betting odds rules.\n * Mirrors the bonus service protobuf and may change in 0.x (minor) versions.\n * @beta\n * @category Bonus\n */\nexport interface CampaignOddsPolicy {\n /** `all_product_accepted_odds` or `threshold` (uses the minimums below). */\n mode: 'all_product_accepted_odds' | 'threshold' | 'unspecified' | (string & {})\n /** Minimum total odds, decimal as text. */\n minimumTotalOddsDecimal?: string\n /** Minimum odds per selection, decimal as text. */\n minimumOddsPerLegDecimal?: string\n /** Minimum number of selections. */\n minimumLegs?: number\n /** Maximum number of selections. */\n maximumLegs?: number\n}\n\n/**\n * Cash out of bets made with restricted balance.\n * Mirrors the bonus service protobuf and may change in 0.x (minor) versions.\n * @beta\n * @category Bonus\n */\nexport type CampaignCashoutMode =\n | 'disallow_for_restricted_funding'\n | 'allow_without_wagering_contribution'\n | 'unspecified'\n | (string & {})\n\n/**\n * Where and how the bonus balance can be used. Only one of the cases (`casino`, `sportsbook`,\n * `casinoAndSportsbook`) is filled in.\n * Mirrors the bonus service protobuf and may change in 0.x (minor) versions.\n * @beta\n * @category Bonus\n */\nexport interface CampaignUsePolicy {\n /** Version. */\n version: number\n /** Consumption order: `real_then_restricted` or `restricted_then_real`. */\n fundsConsumption?: CampaignPolicy<'real_then_restricted' | 'restricted_then_real' | 'unspecified' | (string & {})>\n /** Casino use. */\n casino?: {\n /** Allowed slices. */\n allowedScopes: CasinoActivitySelector[]\n /** Maximum bet. */\n maximumBet?: CampaignMaximumBet\n }\n /** Sports betting use. */\n sportsbook?: {\n /** Allowed slices. */\n allowedScopes: SportsActivitySelector[]\n /** Excluded slices. */\n excludedScopes: SportsActivitySelector[]\n /** Maximum bet. */\n maximumBet?: CampaignMaximumBet\n /** Required odds. */\n fundingOdds?: CampaignOddsPolicy\n /** Cash out. */\n cashoutMode: CampaignCashoutMode\n }\n /** Use in casino and sports betting. */\n casinoAndSportsbook?: {\n /** Allowed casino slices. */\n allowedCasinoScopes: CasinoActivitySelector[]\n /** Allowed sports slices. */\n allowedSportsbookScopes: SportsActivitySelector[]\n /** Excluded sports slices. */\n excludedSportsbookScopes: SportsActivitySelector[]\n /** Maximum casino bet. */\n maximumCasinoBet?: CampaignMaximumBet\n /** Maximum sports bet. */\n maximumSportsbookBet?: CampaignMaximumBet\n /** Required odds. */\n sportsbookFundingOdds?: CampaignOddsPolicy\n /** Cash out. */\n sportsbookCashoutMode: CampaignCashoutMode\n }\n /** Split of winnings between real and restricted balance (e.g. `proportional_to_funding`). */\n payoutAllocation?: CampaignPolicy<string>\n}\n\n/**\n * Rollover (wagering requirement) of the reward: `none` (no rollover) or `multiplier`.\n * Mirrors the bonus service protobuf and may change in 0.x (minor) versions.\n * @beta\n * @category Bonus\n */\nexport interface CampaignWageringPolicy {\n /** Version. */\n version: number\n /** No rollover. */\n none?: Record<string, never>\n /** Rollover by multiplier (e.g. 30x the bonus). */\n multiplier?: {\n /** Basis: `granted_balance` (the bonus granted) or `reward_proceeds` (the reward's winnings). */\n requirementBasis: 'granted_balance' | 'reward_proceeds' | 'unspecified' | (string & {})\n /** Multiplier (e.g. `{ decimal: '30' }` = 30x). */\n multiplier?: CampaignExactRatio\n /** How much each bet type counts toward the rollover. */\n contributionRates: {\n /** Casino slice. */\n casino?: CasinoActivitySelector\n /** Sports slice. */\n sportsbook?: SportsActivitySelector\n /** Contribution rate (10000 basis points = 100%). */\n rate?: CampaignExactRatio\n }[]\n /** Deadline to complete. */\n deadline?: CampaignRewardValidity\n /** Rounding. */\n rounding: CampaignRoundingMode\n /** Minimum odds for the sports bet to count. */\n sportsbookContributionOdds?: CampaignOddsPolicy\n /**\n * Ceiling on the restricted balance that becomes real money when the rollover completes (\"maximum\n * withdrawal\"): the remainder above it is forfeited. Absent: the whole remaining balance converts.\n */\n maximumConversion?: CampaignMoney\n }\n}\n\n/**\n * Stacking with other campaigns of the same group: only one of the cases is filled in.\n * Mirrors the bonus service protobuf and may change in 0.x (minor) versions.\n * @beta\n * @category Bonus\n */\nexport interface CampaignStackingPolicy {\n /** Version. */\n version: number\n /** Exclusive in the group (one active at a time). */\n exclusiveInGroup?: {\n /** Group. */\n stackingGroupKey: string\n }\n /** Several in the group, up to a maximum per player. */\n multipleInGroup?: {\n /** Group. */\n stackingGroupKey: string\n /** Maximum active per player. */\n maximumActivePerPlayer: number\n }\n}\n\n/**\n * Reward of a campaign. `rewardKind` says which of the details (`balanceCredit`, `casinoFreeSpins`,\n * `sportsBonusBet`, `sportsBetCoverage`, `providerManagedBalance`) is filled in.\n * @category Bonus\n */\nexport interface CampaignReward {\n /** Reward key in the campaign. */\n rewardKey: string\n /** Reward type. */\n rewardKind: CampaignRewardKind\n /** Type version. @beta */\n rewardKindVersion: number\n /** Who executes the reward (e.g. `engine_managed_balance`, `provider_entitlement`). @beta */\n executionProfileCode:\n | 'engine_managed_balance'\n | 'provider_managed_balance'\n | 'provider_entitlement'\n | 'unspecified'\n | (string & {})\n /** Execution profile version. @beta */\n executionProfileVersion: number\n /** Balance credit. */\n balanceCredit?: BalanceCreditReward\n /** Provider-managed balance. */\n providerManagedBalance?: {\n /** Provider. */\n providerCode: string\n }\n /** Free spins. */\n casinoFreeSpins?: CasinoFreeSpinsReward\n /** Free sports bet. */\n sportsBonusBet?: SportsBonusBetReward\n /** Sports bet coverage. */\n sportsBetCoverage?: SportsBetCoverageReward\n /** Where the bonus balance can be used. */\n usePolicy?: CampaignUsePolicy\n /** Rollover. */\n wageringPolicy?: CampaignWageringPolicy\n /** Stacking with other campaigns. */\n stackingPolicy?: CampaignStackingPolicy\n /** Consumption order among restricted balances. @beta */\n restrictedPositionSelectionPolicy?: {\n /** Version. */\n version: number\n /** Priority and then the nearest expiration. */\n priorityThenEarliestExpiry?: {\n /** Selection priority. */\n selectionPriority?: number\n }\n }\n}\n\n// ─── Content, offer and participation ─────────────────────────────────────────────────────────────\n\n/**\n * Texts of a campaign in one language.\n * @category Bonus\n */\nexport interface CampaignLocalizedContent {\n /** Language, e.g. `pt-BR`. */\n locale: string\n /** Display name. */\n displayName: string\n /** Description. */\n description: string\n /** Terms and conditions. */\n terms: string\n /** Terms revision: send it on acceptance (`termsAcceptance.termsRevision`). */\n termsRevision: string\n}\n\n/**\n * Texts of a campaign in all published languages. Pick the one for the app's `locale` or, without it,\n * the one for `defaultLocale`.\n * @category Bonus\n */\nexport interface CampaignContent {\n /** Default language. */\n defaultLocale: string\n /** Published languages. */\n supportedLocales: string[]\n /** Texts by language. */\n localizedContent: CampaignLocalizedContent[]\n}\n\n/**\n * Bonus campaign offer (a published version of the campaign).\n * @category Bonus\n */\nexport interface CampaignOffer {\n /** Campaign id, for {@link BonusApi.getOffer} and {@link BonusApi.optIn}. */\n campaignId: string\n /** Published version, required in {@link BonusApi.optIn}. */\n campaignVersionId: string\n /** Publication id. */\n publicationId: string\n /** Product where it applies. */\n productScope: CampaignProductScope\n /** Time zone of the windows. */\n timezone: string\n /** When it is possible to join. */\n enrollmentWindow?: CampaignTimeWindow\n /** When it is possible to qualify. */\n qualificationWindow?: CampaignTimeWindow\n /** When it is possible to redeem (`player_claim` policy). */\n claimWindow?: CampaignTimeWindow\n /** How to join: `automatic`, `opt_in`, `promo_code` or `manual`. */\n entryPolicy?: CampaignPolicy<CampaignEntryPolicyCode>\n /** How to receive the reward: `automatic` or `player_claim`. */\n rewardClaimPolicy?: CampaignPolicy<CampaignRewardClaimPolicyCode>\n /** What is needed to qualify. */\n qualification?: CampaignQualification\n /** Reward. */\n reward?: CampaignReward\n /** Publication start, ISO 8601 (UTC). */\n publicationStartsAt?: string\n /** Publication end, ISO 8601 (UTC). */\n publicationEndsAt?: string\n /** Texts (name, description, terms) by language. */\n content?: CampaignContent\n}\n\n/**\n * Status of the player's participation in a campaign: `enrolled` (joined), `qualifying`\n * (in progress), `qualified` (done; with `player_claim`, can now redeem), `reward_pending`\n * (reward being granted), `completed` (reward granted), `reward_failed`, `expired` or\n * `cancelled`. A new value the SDK does not know yet may arrive: handle the default case.\n * @category Bonus\n */\nexport type CampaignParticipationStatus =\n | 'enrolled'\n | 'qualifying'\n | 'qualified'\n | 'reward_pending'\n | 'completed'\n | 'reward_failed'\n | 'expired'\n | 'cancelled'\n | 'unspecified'\n | (string & {})\n\n/**\n * Acceptance of the terms recorded in the participation.\n * @category Bonus\n */\nexport interface CampaignTermsAcceptanceRecord {\n /** Language of the accepted terms. */\n locale: string\n /** Accepted revision. */\n termsRevision: string\n /** SHA-256 (hex) of the accepted text. */\n termsDigestSha256Hex: string\n /** Acceptance date, ISO 8601 (UTC). */\n acceptedAt?: string\n}\n\n/**\n * Where the bonus balance granted by a participation stands: `active` (still to wager or to use),\n * `converted` (became real balance), `expired` or `forfeited` (e.g. lost to a withdrawal). A new value the SDK\n * does not know yet may arrive: handle the default case.\n * @category Bonus\n */\nexport type CampaignRewardGrantState = 'active' | 'converted' | 'expired' | 'forfeited' | 'unspecified' | (string & {})\n\n/**\n * Rollover progress of a granted bonus.\n * @category Bonus\n */\nexport interface CampaignWageringProgress {\n /** Amount to wager. */\n required: CampaignMoney\n /** Amount already wagered. */\n accumulated: CampaignMoney\n /** When the rollover was completed, ISO 8601 (UTC). */\n completedAt?: string\n}\n\n/**\n * The bonus balance a participation granted. protojson leaves zeros out: a missing amount comes as `0` in the\n * currency of the grant's other amounts (or `''` when none has one).\n * @category Bonus\n */\nexport interface CampaignRewardGrant {\n /** Where the balance stands. An `active` grant keeps the bonus among the player's active ones even after the participation completed. */\n state: CampaignRewardGrantState\n /** Amount granted. */\n granted: CampaignMoney\n /** Bonus balance left. */\n balance: CampaignMoney\n /** Amount converted to real balance. */\n converted: CampaignMoney\n /** When the bonus balance expires, ISO 8601 (UTC). */\n expiresAt?: string\n /** Rollover progress, when the bonus has a wagering requirement. */\n wagering?: CampaignWageringProgress\n}\n\n/**\n * The player's participation in a campaign, with the reward and the texts as they were when they joined.\n * @category Bonus\n */\nexport interface CampaignParticipation {\n /** Participation id, for {@link BonusApi.claim} and {@link BonusApi.getParticipation}. */\n id: string\n /** Campaign id. */\n campaignId: string\n /** Campaign version the player joined. */\n campaignVersionId: string\n /** Reward key. */\n rewardKey: string\n /** Required qualification (a copy from the time of joining). */\n qualificationSnapshot?: CampaignQualification\n /** Status. */\n status: CampaignParticipationStatus\n /** When it qualified (`status: 'qualified'`). */\n qualifiedAt?: string\n /** When the reward was granted (`status: 'completed'`). */\n completedAt?: string\n /** When it expired (`status: 'expired'`). */\n expiredAt?: string\n /** Reward, texts and terms acceptance as of the time of joining. */\n snapshot?: {\n /** Reward. */\n reward?: CampaignReward\n /** Texts. */\n content?: CampaignContent\n /** Terms acceptance, if there was one. */\n termsAcceptance?: CampaignTermsAcceptanceRecord\n }\n /** The bonus balance granted, once the reward was credited; missing before that. */\n rewardGrant?: CampaignRewardGrant\n}\n\n/**\n * Terms acceptance of the campaign, sent on opt-in or on promo code redemption.\n * @category Bonus\n */\nexport interface CampaignTermsAcceptance {\n /** Language of the terms shown ({@link CampaignLocalizedContent.locale}). */\n locale: string\n /** Revision of the terms shown ({@link CampaignLocalizedContent.termsRevision}). */\n termsRevision: string\n}\n\n/**\n * Input of {@link BonusApi.optIn}.\n * @category Bonus\n */\nexport interface OptInInput {\n /** Campaign id ({@link CampaignOffer.campaignId}). */\n campaignId: string\n /** Version shown to the player ({@link CampaignOffer.campaignVersionId}). */\n campaignVersionId: string\n /** Acceptance of the terms shown. */\n termsAcceptance?: CampaignTermsAcceptance\n}\n\n/**\n * Offer of a promo code, returned by {@link BonusApi.resolvePromoCode}.\n * @category Bonus\n */\nexport interface PromoCodeOffer {\n /** The offer. */\n offer: CampaignOffer\n /** The texts in the requested language. */\n localizedContent: CampaignLocalizedContent\n}\n\n// ─── The player's bonus balance ──────────────────────────────────────────────────────────────────\n\n/**\n * The player's restricted bonus balance in one currency (amounts in minor units of `currency`; amounts of\n * different currencies are never added).\n * @category Bonus\n */\nexport interface BonusOverviewCurrency {\n /** Currency code, e.g. `BRL`. */\n currency: string\n /** Decimal places of the currency, to format the amounts. */\n decimalPlaces: number\n /** Bonus balance in open positions. */\n restrictedTotal: number\n /** Part of `restrictedTotal` whose position expires in the next 7 days. */\n expiring7d: number\n /** Open bonus positions. */\n openPositions: number\n /** Nearest expiry among the open positions, ISO 8601 (UTC). */\n nextExpiresAt?: string\n /** Bonus balance already converted to real balance. */\n converted: number\n /** Campaigns with a conversion above zero. */\n convertedCampaigns: number\n}\n\n/**\n * Result of {@link BonusApi.getOverview}.\n * @category Bonus\n */\nexport interface BonusOverview {\n /** One line per currency; empty for a player without bonus history. */\n currencies: BonusOverviewCurrency[]\n /** When the figures were computed, ISO 8601 (UTC). */\n asOf?: string\n}\n\n/**\n * State of a bonus position: `open` or `terminal`. A new value may arrive.\n * @category Bonus\n */\nexport type BonusPositionState = 'open' | 'terminal' | (string & {})\n\n/**\n * How a terminal position ended, in lowercase: `expire`, `forfeit`, `convert` or `admin_cancel`.\n * @category Bonus\n */\nexport type BonusPositionTerminalAction = 'expire' | 'forfeit' | 'convert' | 'admin_cancel' | (string & {})\n\n/**\n * One bonus position of the player (the restricted balance of one grant) with its rollover progress. Amounts\n * in minor units of `currency`.\n * @category Bonus\n */\nexport interface BonusPosition {\n /** Position id. */\n positionId: string\n /** Campaign id: the name to show comes from the campaign's offer (`localizedContent`). */\n campaignId: string\n /** Currency code, e.g. `BRL`. */\n currency: string\n /** Decimal places of the currency. */\n decimalPlaces: number\n /** Amount granted. */\n granted: number\n /** Bonus balance left. */\n restricted: number\n /** Converted to real balance. */\n converted: number\n /** Amount to wager. */\n required: number\n /** Already wagered. */\n wagered: number\n /** Still to wager. */\n remaining: number\n /** `open` or `terminal`. */\n state: BonusPositionState\n /** How it ended (terminal positions only). */\n terminalAction?: BonusPositionTerminalAction\n /** When the bonus balance expires, ISO 8601 (UTC). */\n expiresAt?: string\n /** When the position was created, ISO 8601 (UTC). */\n createdAt?: string\n}\n\n/**\n * Filters and pagination of {@link BonusApi.listPositions}. On the wire `pageSize` goes as `limit` (1 to 100,\n * gateway default 25).\n * @category Bonus\n */\nexport interface ListBonusPositionsInput extends CursorPageInput {\n /** Only open or only terminal positions. Default: all. */\n state?: 'open' | 'terminal'\n /** Currency code. Default: all. */\n currency?: string\n}\n\n/**\n * Bonus campaigns and promo codes. Only `listPublicOffers` is public; the other methods require login.\n * @category Bonus\n */\nexport interface BonusApi {\n /**\n * Public catalog of offers (storefront, no login): it only describes the campaigns; eligibility,\n * joining and participations require login. Cursor-paginated.\n * @example\n * const { items, nextCursor } = await igaming.bonus.listPublicOffers({ pageSize: 20 })\n * @throws {EnginexError} `INVALID_ARGUMENT` (400) for a `pageSize` that is not a positive integer;\n * `UNAUTHENTICATED` (401) if the gateway does not resolve the operator by the domain.\n */\n listPublicOffers(input?: CursorPageInput, options?: CallOptions): Promise<CursorPage<CampaignOffer>>\n /**\n * Offers available to the logged-in player. Cursor-paginated.\n * @example\n * const { items } = await igaming.bonus.listOffers()\n * const optIns = items.filter((o) => o.entryPolicy?.code === 'opt_in')\n * @throws {EnginexError} `INVALID_ARGUMENT` (400) for an invalid `pageSize`; `UNAUTHENTICATED` without a session.\n */\n listOffers(input?: CursorPageInput, options?: CallOptions): Promise<CursorPage<CampaignOffer>>\n /**\n * An offer available to the player.\n * @example\n * const offer = await igaming.bonus.getOffer({ campaignId })\n * @throws {EnginexError} `BONUS_NOT_FOUND` (404) if the campaign does not exist or is not\n * available; `INVALID_ARGUMENT` (400) if `campaignId` is not a UUID; `UNAUTHENTICATED` without a session.\n */\n getOffer(input: { campaignId: string }, options?: CallOptions): Promise<CampaignOffer>\n /**\n * Joins an `opt_in` campaign. **Idempotent**: it sends `Idempotency-Key` — generated on\n * every call, or the one in `options.idempotencyKey` — and keeps it on the retry after renewing the session; to\n * repeat after `NETWORK_ERROR`/`TIMEOUT` without joining twice, generate the key beforehand and pass the\n * same one on both attempts. The response is always validated in strict mode.\n * @example\n * const participation = await igaming.bonus.optIn(\n * { campaignId: offer.campaignId, campaignVersionId: offer.campaignVersionId, termsAcceptance: { locale: 'pt-BR', termsRevision: text.termsRevision } },\n * { idempotencyKey: key },\n * )\n * @throws {EnginexError} `BONUS_NOT_ELIGIBLE` if the player cannot join; `BONUS_EXPIRED` outside\n * the entry window (the gateway still returns these two with HTTP 500: identify by the code);\n * `BONUS_NOT_FOUND` (404); `ALREADY_EXISTS`/`BONUS_ALREADY_CLAIMED` (409) if the player already\n * participates; `KYC_REQUIRED`/`FAILED_PRECONDITION` (422) for a precondition (e.g. KYC, terms);\n * `INVALID_ARGUMENT` (400) for ids that are not UUIDs or a malformed idempotency key;\n * `KEY_IN_USE` (409) with the same key still being processed; `PAYLOAD_MISMATCH` (422) if the key\n * was already used with another body; `VALIDATION_ERROR` if the response comes outside the format (the entry\n * may have happened: check `listParticipations`); `UNAUTHENTICATED` without a session.\n */\n optIn(input: OptInInput, options?: CallOptions): Promise<CampaignParticipation>\n /**\n * Redeems the reward of a qualified participation (campaigns with `player_claim`).\n * **Idempotent**, like {@link BonusApi.optIn}: repeat with the same `idempotencyKey` so as not to\n * redeem twice. The response is always validated in strict mode.\n * @example\n * const done = await igaming.bonus.claim({ participationId: participation.id }, { idempotencyKey: key })\n * @throws {EnginexError} `BONUS_ALREADY_CLAIMED` (409) if the reward was already redeemed;\n * `BONUS_EXPIRED` outside the redemption window and `BONUS_NOT_ELIGIBLE` if it has not qualified yet (HTTP\n * 500 on the gateway: identify by the code); `FAILED_PRECONDITION`/`KYC_REQUIRED` (422);\n * `BONUS_NOT_FOUND` (404); `INVALID_ARGUMENT` (400) for an id that is not a UUID; `KEY_IN_USE` (409);\n * `PAYLOAD_MISMATCH` (422); `VALIDATION_ERROR` if the response comes outside the format (the redemption may\n * have happened: check `getParticipation`); `UNAUTHENTICATED` without a session.\n */\n claim(input: { participationId: string }, options?: CallOptions): Promise<CampaignParticipation>\n /**\n * Shows the offer of a promo code before redemption (name, description and terms in the requested language).\n * It does not join the campaign. The code is a secret: it goes only in the body, never in the URL or the hooks.\n * @example\n * const { offer, localizedContent } = await igaming.bonus.resolvePromoCode({ code: input.value, locale: 'pt-BR' })\n * @throws {EnginexError} `BONUS_NOT_FOUND` (404) for a nonexistent or inactive code;\n * `BONUS_EXPIRED`/`BONUS_NOT_ELIGIBLE` (HTTP 500 on the gateway: identify by the code);\n * `RESOURCE_EXHAUSTED` (429) due to the attempt limit (see `e.retryAfter`); `UNAVAILABLE` (503)\n * if the gateway's limiter is down (the route fails closed for safety); `UNAUTHENTICATED` without a session.\n */\n resolvePromoCode(input: { code: string; locale: string }, options?: CallOptions): Promise<PromoCodeOffer>\n /**\n * Redeems a promo code: joins the code's campaign. **Idempotent** (the gateway requires the key):\n * repeat with the same `idempotencyKey` so as not to redeem twice. The response is always validated\n * in strict mode. The code goes only in the body.\n * @example\n * const participation = await igaming.bonus.redeemPromoCode(\n * { code: 'BEMVINDO', termsAcceptance: { locale: 'pt-BR', termsRevision: localizedContent.termsRevision } },\n * { idempotencyKey: key },\n * )\n * @throws {EnginexError} `BONUS_NOT_FOUND` (404) for a nonexistent code;\n * `BONUS_ALREADY_CLAIMED` (409) if the player already used the code; `BONUS_EXPIRED`/`BONUS_NOT_ELIGIBLE`\n * (HTTP 500 on the gateway: identify by the code); `KYC_REQUIRED`/`FAILED_PRECONDITION` (422);\n * `RESOURCE_EXHAUSTED` (429) due to the per-player promo code attempt limit, the same as\n * `resolvePromoCode` (see `e.retryAfter`); `UNAVAILABLE` (503) if the gateway's limiter is\n * down (the route fails closed for safety); `INVALID_ARGUMENT` (400) for a malformed idempotency\n * key; `VALIDATION_ERROR` if the response comes outside the format (the redemption may have happened:\n * check `listParticipations`); `UNAUTHENTICATED` without a session.\n */\n redeemPromoCode(\n input: { code: string; termsAcceptance?: CampaignTermsAcceptance },\n options?: CallOptions,\n ): Promise<CampaignParticipation>\n /**\n * The player's participations. Cursor-paginated.\n * @example\n * const { items } = await igaming.bonus.listParticipations()\n * const claimable = items.filter((p) => p.status === 'qualified')\n * @throws {EnginexError} `INVALID_ARGUMENT` (400) for an invalid `pageSize`; `UNAUTHENTICATED` without a session.\n */\n listParticipations(input?: CursorPageInput, options?: CallOptions): Promise<CursorPage<CampaignParticipation>>\n /**\n * One of the player's participations.\n * @example\n * const p = await igaming.bonus.getParticipation({ participationId })\n * @throws {EnginexError} `BONUS_NOT_FOUND` (404) if it does not exist (or belongs to another player);\n * `INVALID_ARGUMENT` (400) if the id is not a UUID; `UNAUTHENTICATED` without a session.\n */\n getParticipation(input: { participationId: string }, options?: CallOptions): Promise<CampaignParticipation>\n /**\n * The player's restricted bonus balance, one line per currency: total, what expires in 7 days, open\n * positions and what was converted to real balance.\n * @example\n * const { currencies } = await igaming.bonus.getOverview()\n * const brl = currencies.find((c) => c.currency === 'BRL')\n * @throws {EnginexError} `UNAUTHENTICATED` without a session; `VALIDATION_ERROR`, also in `'warn'`, with money\n * outside the format.\n */\n getOverview(params?: NoParams, options?: CallOptions): Promise<BonusOverview>\n /**\n * The player's bonus positions with their rollover progress, newest first. Cursor-paginated.\n * @example\n * const { items } = await igaming.bonus.listPositions({ state: 'open' })\n * items.forEach((p) => showProgress(p.wagered, p.required))\n * @throws {EnginexError} `INVALID_ARGUMENT` (400) for a `pageSize` outside 1-100, an unknown `state` or an\n * unsupported currency; `UNAUTHENTICATED` without a session; `VALIDATION_ERROR`, also in `'warn'`, with money\n * outside the format.\n */\n listPositions(input?: ListBonusPositionsInput, options?: CallOptions): Promise<CursorPage<BonusPosition>>\n}\n\n// ─── Schemas ─────────────────────────────────────────────────────────────────────────────────────\n// Functions (not constants): they only build inside the `lazy`s below, never at import.\n\n// Currency of campaign values: `''` or ISO 4217, strict even in `'warn'`. protojson omits the empty\n// currency, and a `CampaignMoney` of value 0 (or the currency of a rule that applies to all) may come without\n// it: absent becomes `''`.\nconst campaignCurrency = () => z._default(currencyOrEmpty(), '')\n\nconst money = (): z.ZodMiniType<CampaignMoney> =>\n wire({ amount: z._default(minorUnits(), 0), currency: campaignCurrency() })\n\nconst timeWindow = (): z.ZodMiniType<CampaignTimeWindow> =>\n wire({ starts_at: z.optional(z.string()), ends_at: z.optional(z.string()) })\n\nconst ratio = (): z.ZodMiniType<CampaignExactRatio> =>\n wire({ decimal: z.optional(z.string()), basis_points: z.optional(z.number()), maximum_scale: count() })\n\nconst empty = (): z.ZodMiniType<Record<string, never>> => wire({}) as z.ZodMiniType<Record<string, never>>\n\nconst policy = <C extends string>(prefix: string) =>\n wire({ code: protoEnum(prefix), version: count() }) as unknown as z.ZodMiniType<CampaignPolicy<C>>\n\nconst casinoSelector = (): z.ZodMiniType<CasinoActivitySelector> =>\n wire({\n provider_instance_id: text(),\n software_ids: list(z.string()),\n game_ids: list(z.string()),\n category_codes: list(z.string()),\n })\n\nconst sportsSelector = (): z.ZodMiniType<SportsActivitySelector> =>\n wire({\n sport_codes: list(z.string()),\n competition_ids: list(z.string()),\n event_ids: list(z.string()),\n market_codes: list(z.string()),\n live: z.optional(z.boolean()),\n bet_types: list(protoEnum('SPORTS_BET_TYPE_')),\n })\n\nconst qualification = (): z.ZodMiniType<CampaignQualification> =>\n wire({\n version: count(),\n immediate: z.optional(empty()),\n user_event: z.optional(\n wire({\n event_code: text(),\n event_version: count(),\n source_authority: text(),\n identity_fields: list(z.string()),\n }),\n ),\n deposit_settled: z.optional(\n wire({\n currency: campaignCurrency(),\n eligible_method_codes: list(z.string()),\n first_deposit_policy: protoEnum('FIRST_DEPOSIT_POLICY_'),\n minimum_settled_net_amount: z.optional(money()),\n maximum_settled_net_amount: z.optional(money()),\n amount_basis: protoEnum('DEPOSIT_AMOUNT_BASIS_'),\n }),\n ),\n activity_aggregate: z.optional(\n wire({\n basis: protoEnum('BASIS_'),\n product_scope: protoEnum('PRODUCT_SCOPE_'),\n currency: campaignCurrency(),\n window: z.optional(durationSeconds()),\n timezone: text(),\n late_event_grace: z.optional(durationSeconds()),\n casino: z.optional(casinoSelector()),\n sportsbook: z.optional(sportsSelector()),\n }),\n ),\n })\n\nconst validity = (): z.ZodMiniType<CampaignRewardValidity> =>\n wire({\n no_expiry: z.optional(empty()),\n absolute_expiry: z.optional(wire({ expires_at: z.optional(z.string()) })),\n duration_from_grant: z.optional(wire({ duration: z.optional(durationSeconds()) })),\n })\n\nconst rounding = () => protoEnum('ROUNDING_MODE_')\nconst proceedsClass = () => protoEnum('PROCEEDS_CLASS_')\n\nconst percent = (): z.ZodMiniType<CampaignPercentCalculation> =>\n wire({\n percentage: z.optional(ratio()),\n rounding: rounding(),\n minimum_reward: z.optional(money()),\n maximum_reward: z.optional(money()),\n })\n\nconst balanceCredit = (): z.ZodMiniType<BalanceCreditReward> =>\n wire({\n fixed_amount: z.optional(wire({ amount: z.optional(money()) })),\n percent_of_source_amount: z.optional(percent()),\n aggregate_rebate: z.optional(\n wire({\n percentage: z.optional(ratio()),\n rounding: rounding(),\n minimum_basis: z.optional(money()),\n maximum_reward: z.optional(money()),\n }),\n ),\n balance_class: protoEnum('BALANCE_CLASS_'),\n proceeds_class: proceedsClass(),\n validity: z.optional(validity()),\n })\n\nconst maximumBet = (): z.ZodMiniType<CampaignMaximumBet> =>\n wire({ mode: protoEnum('MAXIMUM_BET_MODE_'), campaign_maximum: z.optional(money()) })\n\nconst oddsPolicy = (): z.ZodMiniType<CampaignOddsPolicy> =>\n wire({\n mode: protoEnum('MODE_'),\n minimum_total_odds_decimal: z.optional(z.string()),\n minimum_odds_per_leg_decimal: z.optional(z.string()),\n minimum_legs: z.optional(z.number()),\n maximum_legs: z.optional(z.number()),\n })\n\nconst cashoutMode = () => protoEnum('RESTRICTED_CASHOUT_MODE_')\n\nconst usePolicy = (): z.ZodMiniType<CampaignUsePolicy> =>\n wire({\n version: count(),\n funds_consumption: z.optional(policy('FUNDS_CONSUMPTION_POLICY_CODE_')),\n casino: z.optional(wire({ allowed_scopes: list(casinoSelector()), maximum_bet: z.optional(maximumBet()) })),\n sportsbook: z.optional(\n wire({\n allowed_scopes: list(sportsSelector()),\n excluded_scopes: list(sportsSelector()),\n maximum_bet: z.optional(maximumBet()),\n funding_odds: z.optional(oddsPolicy()),\n cashout_mode: cashoutMode(),\n }),\n ),\n casino_and_sportsbook: z.optional(\n wire({\n allowed_casino_scopes: list(casinoSelector()),\n allowed_sportsbook_scopes: list(sportsSelector()),\n excluded_sportsbook_scopes: list(sportsSelector()),\n maximum_casino_bet: z.optional(maximumBet()),\n maximum_sportsbook_bet: z.optional(maximumBet()),\n sportsbook_funding_odds: z.optional(oddsPolicy()),\n sportsbook_cashout_mode: cashoutMode(),\n }),\n ),\n payout_allocation: z.optional(policy('PAYOUT_ALLOCATION_POLICY_CODE_')),\n })\n\nconst wageringPolicy = (): z.ZodMiniType<CampaignWageringPolicy> =>\n wire({\n version: count(),\n none: z.optional(empty()),\n multiplier: z.optional(\n wire({\n requirement_basis: protoEnum('REQUIREMENT_BASIS_'),\n multiplier: z.optional(ratio()),\n contribution_rates: list(\n wire({\n casino: z.optional(casinoSelector()),\n sportsbook: z.optional(sportsSelector()),\n rate: z.optional(ratio()),\n }),\n ),\n deadline: z.optional(validity()),\n rounding: rounding(),\n sportsbook_contribution_odds: z.optional(oddsPolicy()),\n maximum_conversion: z.optional(money()),\n }),\n ),\n })\n\nconst stackingPolicy = (): z.ZodMiniType<CampaignStackingPolicy> =>\n wire({\n version: count(),\n exclusive_in_group: z.optional(wire({ stacking_group_key: text() })),\n multiple_in_group: z.optional(wire({ stacking_group_key: text(), maximum_active_per_player: count() })),\n })\n\nconst reward = (): z.ZodMiniType<CampaignReward> =>\n wire({\n reward_key: text(),\n reward_kind: protoEnum('REWARD_KIND_'),\n reward_kind_version: count(),\n execution_profile_code: protoEnum('EXECUTION_PROFILE_CODE_'),\n execution_profile_version: count(),\n balance_credit: z.optional(balanceCredit()),\n provider_managed_balance: z.optional(wire({ provider_code: text() })),\n casino_free_spins: z.optional(\n wire({\n provider_code: text(),\n casino_scope: z.optional(casinoSelector()),\n quantity: count(),\n denomination: z.optional(money()),\n currency: campaignCurrency(),\n grant_window: z.optional(timeWindow()),\n proceeds_class: proceedsClass(),\n maximum_winnings: z.optional(money()),\n }),\n ),\n sports_bonus_bet: z.optional(\n wire({\n provider_code: text(),\n sportsbook_scope: z.optional(sportsSelector()),\n amount: z.optional(money()),\n quantity: count(),\n validity: z.optional(validity()),\n }),\n ),\n sports_bet_coverage: z.optional(\n wire({\n provider_code: text(),\n qualifying_bet_scope: z.optional(sportsSelector()),\n coverage_cap: z.optional(money()),\n validity: z.optional(validity()),\n }),\n ),\n use_policy: z.optional(usePolicy()),\n wagering_policy: z.optional(wageringPolicy()),\n stacking_policy: z.optional(stackingPolicy()),\n restricted_position_selection_policy: z.optional(\n wire({\n version: count(),\n priority_then_earliest_expiry: z.optional(wire({ selection_priority: z.optional(z.number()) })),\n }),\n ),\n })\n\nconst localizedContent = (): z.ZodMiniType<CampaignLocalizedContent> =>\n wire({ locale: text(), display_name: text(), description: text(), terms: text(), terms_revision: text() })\n\nconst content = (): z.ZodMiniType<CampaignContent> =>\n wire({ default_locale: text(), supported_locales: list(z.string()), localized_content: list(localizedContent()) })\n\nconst offerSchema = /* @__PURE__ */ lazy(\n (): z.ZodMiniType<CampaignOffer> =>\n wire({\n campaign_id: text(),\n campaign_version_id: text(),\n publication_id: text(),\n product_scope: protoEnum('PRODUCT_SCOPE_'),\n timezone: text(),\n enrollment_window: z.optional(timeWindow()),\n qualification_window: z.optional(timeWindow()),\n claim_window: z.optional(timeWindow()),\n entry_policy: z.optional(policy<CampaignEntryPolicyCode>('ENTRY_POLICY_CODE_')),\n reward_claim_policy: z.optional(policy<CampaignRewardClaimPolicyCode>('REWARD_CLAIM_POLICY_CODE_')),\n qualification: z.optional(qualification()),\n reward: z.optional(reward()),\n publication_starts_at: z.optional(z.string()),\n publication_ends_at: z.optional(z.string()),\n content: z.optional(content()),\n }),\n)\n\n/** A grant's money: absent becomes `0` in the currency of the grant's other amounts. */\nfunction grantMoney(value: CampaignMoney | undefined, currency: string): CampaignMoney {\n return { amount: value?.amount ?? 0, currency: value?.currency || currency }\n}\n\nconst rewardGrant = (): z.ZodMiniType<CampaignRewardGrant> =>\n z.pipe(\n wire({\n state: protoEnum('CAMPAIGN_PLAYER_REWARD_GRANT_STATE_'),\n granted: z.optional(money()),\n balance: z.optional(money()),\n converted: z.optional(money()),\n expires_at: z.optional(z.string()),\n wagering: z.optional(\n wire({ required: z.optional(money()), accumulated: z.optional(money()), completed_at: z.optional(z.string()) }),\n ),\n }),\n z.transform(({ state, granted, balance, converted, expiresAt, wagering }): CampaignRewardGrant => {\n const currency =\n [granted, balance, converted, wagering?.required, wagering?.accumulated].find((m) => m?.currency)?.currency ??\n ''\n const out: CampaignRewardGrant = {\n state,\n granted: grantMoney(granted, currency),\n balance: grantMoney(balance, currency),\n converted: grantMoney(converted, currency),\n }\n if (expiresAt !== undefined) out.expiresAt = expiresAt\n if (wagering) {\n out.wagering = {\n required: grantMoney(wagering.required, currency),\n accumulated: grantMoney(wagering.accumulated, currency),\n }\n if (wagering.completedAt !== undefined) out.wagering.completedAt = wagering.completedAt\n }\n return out\n }),\n )\n\nconst participationSchema = /* @__PURE__ */ lazy(\n (): z.ZodMiniType<CampaignParticipation> =>\n z.pipe(\n wire({\n id: text(),\n campaign_id: text(),\n campaign_version_id: text(),\n reward_key: text(),\n qualification_snapshot: z.optional(qualification()),\n // oneof `state`: only one of the cases is filled in.\n enrolled: z.optional(empty()),\n qualifying: z.optional(empty()),\n qualified: z.optional(wire({ qualified_at: z.optional(z.string()) })),\n reward_pending: z.optional(empty()),\n completed: z.optional(wire({ completed_at: z.optional(z.string()) })),\n reward_failed: z.optional(empty()),\n expired: z.optional(wire({ expired_at: z.optional(z.string()) })),\n cancelled: z.optional(empty()),\n reward_grant: z.optional(rewardGrant()),\n snapshot: z.optional(\n wire({\n reward: z.optional(reward()),\n content: z.optional(content()),\n terms_acceptance: z.optional(\n wire({\n locale: text(),\n terms_revision: text(),\n terms_digest_sha256_hex: text(),\n accepted_at: z.optional(z.string()),\n }),\n ),\n }),\n ),\n }),\n // The oneof becomes `status` (+ the timestamp of the case); the oneof's keys are not passed on.\n z.transform(\n ({ enrolled, qualifying, qualified, rewardPending, completed, rewardFailed, expired, cancelled, ...rest }) => {\n const out: CampaignParticipation = { ...rest, status: 'unspecified' }\n if (enrolled) out.status = 'enrolled'\n else if (qualifying) out.status = 'qualifying'\n else if (qualified) {\n out.status = 'qualified'\n if (qualified.qualifiedAt !== undefined) out.qualifiedAt = qualified.qualifiedAt\n } else if (rewardPending) out.status = 'reward_pending'\n else if (completed) {\n out.status = 'completed'\n if (completed.completedAt !== undefined) out.completedAt = completed.completedAt\n } else if (rewardFailed) out.status = 'reward_failed'\n else if (expired) {\n out.status = 'expired'\n if (expired.expiredAt !== undefined) out.expiredAt = expired.expiredAt\n } else if (cancelled) out.status = 'cancelled'\n return out\n },\n ),\n ),\n)\n\nconst cursorPageSchema = <T>(key: string, item: z.ZodMiniType<T>) =>\n wire({ [key]: list(item), next_cursor: z.optional(z.string()) }) as unknown as z.ZodMiniType<\n Record<string, T[] | undefined> & { nextCursor?: string }\n >\n\nconst offersPage = /* @__PURE__ */ lazy(() => cursorPageSchema('offers', offerSchema()))\nconst participationsPage = /* @__PURE__ */ lazy(() => cursorPageSchema('participations', participationSchema()))\nconst offerEnvelope = /* @__PURE__ */ lazy(() => wire({ offer: offerSchema() }))\nconst participationEnvelope = /* @__PURE__ */ lazy(() => wire({ participation: participationSchema() }))\nconst promoCodeOfferSchema = /* @__PURE__ */ lazy(\n (): z.ZodMiniType<PromoCodeOffer> => wire({ offer: offerSchema(), localized_content: localizedContent() }),\n)\n\nfunction toCursorPage<T>(key: string, data: Record<string, T[] | undefined> & { nextCursor?: string }): CursorPage<T> {\n // `list()` fills in `[]` when protojson omits the list; in `warn` mode, an out-of-format item\n // arrives raw, but the list is still a list (recovery is per field, see `decode` in the core).\n const page: CursorPage<T> = { items: data[key]! }\n // An empty cursor means \"no next page\" (protojson would omit it; the service may send `''`).\n if (data.nextCursor) page.nextCursor = data.nextCursor\n return page\n}\n\n// The overview and the positions are plain JSON (not protojson): every key is present, money as int64 text and\n// an absent timestamp as `null`, which becomes a missing key.\nconst nullableDate = () =>\n z.pipe(\n z.nullish(z.string()),\n z.transform((value) => value ?? undefined),\n )\n\n/** Drops the `undefined` values (the `null` dates), so they are missing keys. */\nfunction compact<T extends object>(value: T): T {\n return Object.fromEntries(Object.entries(value).filter(([, v]) => v !== undefined)) as T\n}\n\nconst overviewSchema = /* @__PURE__ */ lazy(\n (): z.ZodMiniType<BonusOverview> =>\n z.pipe(\n wire({\n currencies: list(\n z.pipe(\n wire({\n currency: currencyOrEmpty(),\n decimal_places: z.number(),\n restricted_total: minorUnits(),\n expiring_7d: minorUnits(),\n open_positions: z.number(),\n next_expires_at: nullableDate(),\n converted: minorUnits(),\n converted_campaigns: z.number(),\n }),\n z.transform(compact),\n ),\n ),\n as_of: nullableDate(),\n }),\n z.transform(compact),\n ),\n)\n\nconst positionsPage = /* @__PURE__ */ lazy(() =>\n wire({\n rows: list(\n z.pipe(\n wire({\n position_id: z.string(),\n campaign_id: z.string(),\n currency: currencyOrEmpty(),\n decimal_places: z.number(),\n granted: minorUnits(),\n restricted: minorUnits(),\n converted: minorUnits(),\n required: minorUnits(),\n wagered: minorUnits(),\n remaining: minorUnits(),\n state: z.string(),\n // The gateway answers `null` for an action it does not know; known ones are uppercase (`CONVERT`).\n terminal_action: z.pipe(\n z.nullish(z.string()),\n z.transform((value) => (value ? value.toLowerCase() : undefined)),\n ),\n expires_at: nullableDate(),\n created_at: nullableDate(),\n }),\n z.transform((row): BonusPosition => compact(row)),\n ),\n ),\n next_cursor: z.optional(z.string()),\n }),\n)\n\nconst terms = (acceptance: CampaignTermsAcceptance | undefined) =>\n acceptance && { locale: acceptance.locale, terms_revision: acceptance.termsRevision }\n\n/** Creates the `bonus` namespace. @internal */\nexport function createBonusApi(transport: ExtensionTransport): BonusApi {\n const listPage = <T>(\n path: string,\n key: string,\n schema: z.ZodMiniType<Record<string, T[] | undefined> & { nextCursor?: string }>,\n auth: 'none' | 'required',\n input: CursorPageInput | undefined,\n options: CallOptions | undefined,\n ) =>\n transport\n .request({\n method: 'GET',\n path,\n query: { page_size: input?.pageSize, cursor: input?.cursor },\n auth,\n schema,\n options,\n })\n .then((data) => toCursorPage<T>(key, data))\n\n const participationCall = (path: string, body: unknown, options: CallOptions | undefined) =>\n transport\n .request({\n method: 'POST',\n path,\n body,\n auth: 'required',\n idempotent: true,\n validation: 'strict',\n schema: participationEnvelope(),\n options,\n })\n .then((data) => data.participation)\n\n return {\n listPublicOffers: (input, options) =>\n listPage<CampaignOffer>('/bonus-campaigns/public-offers', 'offers', offersPage(), 'none', input, options),\n listOffers: (input, options) =>\n listPage<CampaignOffer>('/bonus-campaigns/offers', 'offers', offersPage(), 'required', input, options),\n getOffer: ({ campaignId }, options) =>\n transport\n .request({\n method: 'GET',\n path: `/bonus-campaigns/offers/${encodeURIComponent(campaignId)}`,\n auth: 'required',\n schema: offerEnvelope(),\n options,\n })\n .then((data) => data.offer),\n optIn: ({ campaignId, campaignVersionId, termsAcceptance }, options) =>\n participationCall(\n `/bonus-campaigns/offers/${encodeURIComponent(campaignId)}/opt-in`,\n { campaign_version_id: campaignVersionId, terms_acceptance: terms(termsAcceptance) },\n options,\n ),\n claim: ({ participationId }, options) =>\n participationCall(\n `/bonus-campaigns/participations/${encodeURIComponent(participationId)}/claim`,\n undefined,\n options,\n ),\n resolvePromoCode: ({ code, locale }, options) =>\n transport.request({\n method: 'POST',\n path: '/bonus-campaigns/promo-codes/resolve',\n body: { plaintext: code, locale },\n auth: 'required',\n schema: promoCodeOfferSchema(),\n options,\n }),\n redeemPromoCode: ({ code, termsAcceptance }, options) =>\n participationCall(\n '/bonus-campaigns/promo-codes/redeem',\n { plaintext: code, terms_acceptance: terms(termsAcceptance) },\n options,\n ),\n listParticipations: (input, options) =>\n listPage<CampaignParticipation>(\n '/bonus-campaigns/participations',\n 'participations',\n participationsPage(),\n 'required',\n input,\n options,\n ),\n getParticipation: ({ participationId }, options) =>\n transport\n .request({\n method: 'GET',\n path: `/bonus-campaigns/participations/${encodeURIComponent(participationId)}`,\n auth: 'required',\n schema: participationEnvelope(),\n options,\n })\n .then((data) => data.participation),\n getOverview: (_params, options) =>\n transport.request({\n method: 'GET',\n path: '/bonus/overview',\n auth: 'required',\n schema: overviewSchema(),\n options,\n }),\n listPositions: (input, options) =>\n transport\n .request({\n method: 'GET',\n path: '/bonus/positions',\n query: { limit: input?.pageSize, cursor: input?.cursor, state: input?.state, currency: input?.currency },\n auth: 'required',\n schema: positionsPage(),\n options,\n })\n .then(({ rows, nextCursor }) => {\n const page: CursorPage<BonusPosition> = { items: rows }\n if (nextCursor) page.nextCursor = nextCursor\n return page\n }),\n }\n}\n","// Public types come from the core's main entry: the /extension `.d.ts` exposes Zod, and this package's\n// public API cannot depend on it (check-api).\nimport type { CallOptions, NoParams, Page } from '@getenginex/sdk'\nimport { currencyCode, decimalPlaces, lazy, money, wire, type ExtensionTransport } from '@getenginex/sdk/extension'\nimport * as z from 'zod/mini'\nimport { rejectInput, type Route } from '../internal/input'\nimport { nullableList, optionalText } from '../internal/optional-values'\nimport { minorUnits, protoEnum } from '../internal/schemas'\n\n/**\n * Casino catalog game (`GET /games`, `GET /games/{id}`).\n * @category Casino\n */\nexport interface Game {\n /** Game id, for {@link CasinoApi.getGame} and {@link CasinoApi.launchGame}. */\n id: string\n /** Display name. */\n name: string\n /**\n * Provider id (the same as {@link GameProvider.id}). Treat it as an opaque identifier: depending on the\n * aggregator, it may be a code or the name itself (e.g. `Pragmatic Play`).\n */\n provider: string\n /** Category slug (the same as {@link GameCategory.slug}), e.g. `slots`. */\n category: string\n /** Game type, as the provider reports it (e.g. `slot`, `blackjack`, `roulette`); may come empty. */\n type: string\n /** Cover image URL; may come empty. */\n thumbnail: string\n /** Marked as new in the catalog. */\n isNew: boolean\n /** Marked as popular in the catalog. */\n isPopular: boolean\n /** Live game (live casino). */\n isLive: boolean\n /** Supports demo mode (`launchGame({ mode: 'demo' })`). */\n demoAvailable: boolean\n /** Return to player reported by the provider, as a percentage (e.g. `96.5`); `0` when not reported. */\n rtp: number\n /** Volatility reported by the provider (e.g. `low`, `medium`, `high`); may come empty. */\n volatility: string\n /** Sort priority set by the operator (lowest first). */\n priority: number\n}\n\n/**\n * Ordering of {@link CasinoApi.listGames}: `popular` (most played), `new` (newest) or `az`\n * (alphabetical). Omitted: the operator's default order.\n * @category Casino\n */\nexport type GameSort = 'popular' | 'new' | 'az'\n\n/**\n * The viewer's device, to filter the catalog: the casino leaves out the games that only run on the other\n * one. Any other value rejects with `CONFIGURATION_ERROR` before the request (the gateway would answer 400).\n * @category Casino\n */\nexport type GameDevice = 'mobile' | 'desktop'\n\n/**\n * Filters and pagination of {@link CasinoApi.listGames}.\n * @category Casino\n */\nexport interface ListGamesInput {\n /** Slug of a category from {@link CasinoApi.listCategories}. An unknown slug brings no games. */\n category?: string\n /** Id of a provider from {@link CasinoApi.listProviders}. */\n provider?: string\n /** Search by game name, up to 100 characters (above that, `INVALID_ARGUMENT`). */\n search?: string\n /**\n * Restricts the listing to these games (e.g. to validate favorites or recents saved in the app), up to 100\n * ids. Inactive games or ones outside the operator's catalog simply do not come back.\n */\n ids?: string[]\n /** Ordering. An unknown value is ignored by the gateway. */\n sort?: GameSort\n /**\n * The viewer's device: the casino leaves out the games that only run on the other one. Omitted: no device\n * filter (every game).\n */\n device?: GameDevice\n /** Page (starts at 1). Gateway default: 1. */\n page?: number\n /** Items per page, from 1 to 100. Gateway default: 20 (out of range also becomes 20). */\n perPage?: number\n}\n\n/**\n * State of the operator's casino, as the gateway reports it next to the game list\n * ({@link CasinoAvailability.status}): `available`, `no_casino_configured`, `temporarily_unavailable`,\n * `switching` (the operator is switching providers) or `maintenance`. A new value the SDK does not know yet\n * may arrive: handle the default case (e.g. as a generic empty state).\n * @category Casino\n */\nexport type CasinoAvailabilityStatus =\n | 'available'\n | 'no_casino_configured'\n | 'temporarily_unavailable'\n | 'switching'\n | 'maintenance'\n | (string & {})\n\n/**\n * Why the catalog may be empty or partial, without it being an error ({@link GamesPage.availability}).\n * @category Casino\n */\nexport interface CasinoAvailability {\n /**\n * State of the casino. The gateway reports an unset state as `available`, and so does the SDK for an\n * absent or empty one. An unknown value arrives in lowercase: decide in the app whether it opens the casino\n * (failing closed, e.g. as `temporarily_unavailable`, is the safe choice).\n */\n status: CasinoAvailabilityStatus\n /** Code of the operator's primary provider; `null` when the gateway sends none. */\n primaryProviderCode: string | null\n /** What the casino reports as missing (e.g. provider codes not yet set up); `[]` when nothing is. */\n missing: string[]\n}\n\n/**\n * A page of {@link CasinoApi.listGames}: the usual {@link Page} plus the casino's availability.\n * @category Casino\n */\nexport interface GamesPage extends Page<Game> {\n /**\n * State of the casino the gateway reports next to the list (maintenance, provider switch, temporary\n * unavailability, no casino configured). `null` when the gateway does not send it (an older gateway) or\n * the installed `@getenginex/sdk` is older than 0.11.0.\n */\n availability: CasinoAvailability | null\n}\n\n/**\n * Catalog category with active games (`GET /games/categories`).\n * @category Casino\n */\nexport interface GameCategory {\n /** Slug, for the `category` filter of {@link CasinoApi.listGames}. */\n slug: string\n /** Display name. */\n name: string\n /** Icon set by the operator (name or URL, depending on the setup); may come empty. */\n icon: string\n /** Number of active games in the category. */\n gameCount: number\n /** Sort priority set by the operator (lowest first). */\n priority: number\n}\n\n/**\n * Game provider with active games (`GET /games/providers`).\n * @category Casino\n */\nexport interface GameProvider {\n /**\n * Id, for the `provider` filter of {@link CasinoApi.listGames}. Opaque identifier: it may be a\n * code or the name itself (e.g. `Pragmatic Play`); pass it as it came.\n */\n id: string\n /** Display name. */\n name: string\n /** Number of games. */\n gameCount: number\n}\n\n/**\n * Input of {@link CasinoApi.launchGame}.\n * @category Casino\n */\nexport interface LaunchGameInput {\n /** Game id ({@link Game.id}). */\n gameId: string\n /** `real` (default) bets with the player's balance; `demo` opens demo mode, if the game supports it ({@link Game.demoAvailable}). */\n mode?: 'real' | 'demo'\n /** Opens the mobile version of the game, when the provider has one. Default: `false`. */\n isMobile?: boolean\n /**\n * Absolute URL (http/https) the game returns to on exit (the app's lobby). When omitted, the gateway\n * uses the request's `Origin` (or `Referer`) — the browser always sends it; on server calls\n * (SSR/Node) pass it explicitly.\n */\n returnUrl?: string\n /**\n * Absolute URL (http/https) of the app's deposit page: the provider shows it inside the game as a link\n * (e.g. when the balance runs out). The gateway forwards it only when it is absolute; anything else is\n * dropped without an error. Omitted: the game shows no deposit link.\n */\n depositUrl?: string\n /**\n * Game language (e.g. `pt-BR`). When omitted, the gateway uses the request's `Accept-Language`, which the SDK\n * fills in with the client's `locale` (see `enginex.setLocale`).\n */\n language?: string\n}\n\n/**\n * How the provider requires the game to be opened ({@link GameLaunch.launchTarget}): `iframe` (embedded in\n * the app's page), `redirect` (navigate the current tab to the game) or `new_tab` (open it in a new\n * tab or window). A new value the SDK does not know yet may arrive: handle the default case (e.g. as\n * `new_tab`, which works for any provider).\n * @category Casino\n */\nexport type LaunchTarget = 'iframe' | 'redirect' | 'new_tab' | (string & {})\n\n/**\n * Game opened by {@link CasinoApi.launchGame}.\n *\n * **Sensitive:** `gameUrl` carries the player's game session token. Use it only to open the game\n * (as {@link GameLaunch.launchTarget} says) and never log it to logs, analytics, error tracking, nor store it.\n * @category Casino\n */\nexport interface GameLaunch {\n /** Game session id (the same as {@link GameSession.id}). */\n sessionId: string\n /**\n * Game URL, with the game session token — do not log it. It may be absolute or relative\n * to the gateway, depending on the provider; it is never empty (a response without a URL is `VALIDATION_ERROR`).\n */\n gameUrl: string\n /**\n * How to open `gameUrl`: some providers refuse to run inside an iframe and need `redirect` or `new_tab`.\n * A response without it (an older gateway, or a custom mock) arrives as `iframe`, what the SDK documented\n * before the gateway sent this field.\n */\n launchTarget: LaunchTarget\n /** Code of the game's provider (e.g. `pragmatic-play`), as the gateway sends it; absent when it does not. */\n providerCode?: string\n /** Expiry of the game URL, ISO 8601 (UTC), when the provider reports one: open the game before it. */\n expiresAt?: string\n}\n\n/**\n * Status of a game session, without the gateway's `SESSION_STATUS_` prefix and in lowercase. A new\n * value the SDK does not know yet may arrive: handle the default case.\n * @category Casino\n */\nexport type GameSessionStatus = 'active' | 'ended' | 'unspecified' | (string & {})\n\n/**\n * The player's game session (`GET /games/sessions`). Opening a game ends the previous active session.\n * @category Casino\n */\nexport interface GameSession {\n /** Session id. */\n id: string\n /** Game id. */\n gameId: string\n /** Game name. */\n gameName: string\n /** Provider id. */\n provider: string\n /** Session start, ISO 8601 (UTC). */\n startTime: string\n /** Total wagered in the session, in minor units of the operator's currency. */\n totalBet: number\n /** Total won in the session, in minor units of the operator's currency. */\n totalWin: number\n /** Status, e.g. `active`. */\n status: GameSessionStatus\n}\n\n/**\n * Type of a casino movement (lowercase, without the `CASINO_TRANSACTION_TYPE_` prefix).\n * `reversal` reverses an already credited prize (debits the player); `refund` returns a bet. A new\n * value the SDK does not know yet may arrive: handle the default case.\n * @category Casino\n */\nexport type CasinoTransactionType =\n | 'bet'\n | 'win'\n | 'refund'\n | 'jackpot'\n | 'free_spin'\n | 'reversal'\n | 'unspecified'\n | (string & {})\n\n/**\n * Movement of a casino round (`GET /games/history`).\n * @category Casino\n */\nexport interface CasinoTransaction {\n /** Movement id. */\n id: string\n /** Game id. */\n gameId: string\n /** Game name. */\n gameName: string\n /** Round id (the bet and the prize of the same round share it). */\n roundId: string\n /** Type, e.g. `bet`, `win`. */\n type: CasinoTransactionType\n /** Value in minor units of `currency` (the gateway sends it as text; the SDK converts). */\n amount: number\n /** Currency code, e.g. `BRL`. */\n currency: string\n /** Decimal places of the currency (e.g. `2` for BRL), to format `amount`. */\n currencyDecimalPlaces: number\n /** Movement date, ISO 8601 (UTC). */\n createdAt: string\n}\n\n/**\n * Pagination of {@link CasinoApi.listSessions} and {@link CasinoApi.getHistory}.\n * @category Casino\n */\nexport interface CasinoPageInput {\n /** Page (starts at 1). Gateway default: 1. */\n page?: number\n /** Items per page, from 1 to 100. Gateway default: 20 (out of range also becomes 20). */\n perPage?: number\n}\n\n/**\n * Filters of {@link CasinoApi.getBiggestWinners}.\n * @category Casino\n */\nexport interface GetBiggestWinnersInput {\n /** How many winners (the casino service caps it; its default: 10). */\n limit?: number\n /** Window in days up to now. Omitted: the casino service's default. */\n days?: number\n}\n\n/**\n * Biggest prize of a round, for the casino home ranking (`GET /games/biggest-winners`).\n * @category Casino\n */\nexport interface BiggestWinner {\n /** Player name already masked by the gateway (e.g. `Jo***`); the player id never comes. */\n player: string\n /** Prize in minor units of `currency`. */\n amount: number\n /** Currency code, e.g. `BRL`. */\n currency: string\n /** Decimal places of the currency, to format `amount`. */\n currencyDecimalPlaces: number\n /** Game id. */\n gameId: string\n /** Game name. */\n gameName: string\n /** Prize date, ISO 8601 (UTC). */\n wonAt: string\n}\n\n/**\n * A published jackpot of the operator's lobby ({@link CasinoApi.listJackpots}).\n * @category Casino\n */\nexport interface CasinoJackpot {\n /** Public jackpot id (`jackpot_` + 64 hex characters), for {@link CasinoApi.listJackpotGames}. */\n id: string\n /** Display name. */\n name: string\n /** Currency code, always the one requested (e.g. `BRL`). */\n currency: string\n /**\n * Current value in minor units of `currency` (the gateway sends it as text; the SDK converts). Never\n * negative; a value that does not fit in a safe integer leaves the jackpot out instead of showing it rounded.\n */\n amount: number\n /** Decimal places of `currency` (the ISO 4217 ones, e.g. `2` for BRL, `0` for CLP, `3` for KWD), to format `amount`. */\n currencyDecimalPlaces: number\n}\n\n/**\n * The lobby's published jackpots ({@link CasinoApi.listJackpots}).\n * @category Casino\n */\nexport interface CasinoJackpots {\n /** Published jackpots in the requested currency, without repeated ids; `[]` when there are none. */\n items: CasinoJackpot[]\n /** Id of the featured jackpot, when it is one of `items`; otherwise `null`. */\n featuredId: string | null\n}\n\n/**\n * Input of {@link CasinoApi.listJackpots}.\n * @category Casino\n */\nexport interface ListJackpotsInput {\n /** The site's currency, ISO 4217 in uppercase (e.g. `BRL`, from `enginex.config.get()`). */\n currency: string\n}\n\n/**\n * Input of {@link CasinoApi.listJackpotGames}. Page 1 has no cursor; every next page needs the previous\n * page's {@link JackpotGamesPage.nextCursor}.\n * @category Casino\n */\nexport interface ListJackpotGamesInput {\n /** Jackpot id ({@link CasinoJackpot.id}). */\n jackpotId: string\n /** The site's currency, the same as in {@link CasinoApi.listJackpots}. */\n currency: string\n /** The viewer's device. Omitted: no device filter. */\n device?: GameDevice\n /** Page (starts at 1). Default: 1. Above 1 it requires `cursor`. */\n page?: number\n /** Items per page, from 1 to 48. Gateway default: 24. */\n perPage?: number\n /** The previous page's {@link JackpotGamesPage.nextCursor}. */\n cursor?: string\n}\n\n/**\n * How the jackpot's game list was resolved: `verified` (the games the provider confirms take part in the\n * jackpot) or `demonstration` (an illustrative selection). A new value may arrive: handle the default case.\n * @category Casino\n */\nexport type JackpotGamesMode = 'verified' | 'demonstration' | (string & {})\n\n/**\n * A page of a jackpot's games ({@link CasinoApi.listJackpotGames}), paginated by cursor.\n * @category Casino\n */\nexport interface JackpotGamesPage {\n /** Game cards on this page; `[]` when there are none. */\n items: Game[]\n /** How the list was resolved. */\n mode: JackpotGamesMode\n /** Page number, as requested. */\n page: number\n /** Items per page, as requested. */\n perPage: number\n /** Whether there is a next page. */\n hasNext: boolean\n /** Cursor for the next page (pass it with `page + 1`); `null` on the last one. */\n nextCursor: string | null\n}\n\n/**\n * Catalog, game launch and casino history. The catalog (`listGames`, `listCategories`,\n * `listProviders`, `getGame`) is public; the other methods require login.\n * @category Casino\n */\nexport interface CasinoApi {\n /**\n * Games of the operator's catalog, paginated and filterable. Public: it does not send the session, even with\n * login (the catalog does not depend on the player).\n *\n * Maintenance, a provider switch, temporary unavailability or an operator without a casino do **not**\n * become errors: the gateway answers 200 and reports the reason in {@link GamesPage.availability}, next to\n * the list. In those cases the list may come empty, without an error: branch on `availability.status`.\n * @example\n * const page = await igaming.casino.listGames({ category: 'slots', sort: 'popular', perPage: 24, device: 'mobile' })\n * if (page.availability?.status === 'maintenance') showMaintenance()\n * page.items.forEach((game) => renderCard(game.name, game.thumbnail))\n * @throws {EnginexError} `CONFIGURATION_ERROR` (no request) for a `device` other than `mobile`/`desktop`;\n * `INVALID_ARGUMENT` (400) for `search` above 100 characters or more than 100 `ids`;\n * `UNAVAILABLE`/`PROVIDER_ERROR` (503) only when the call to the casino service itself fails.\n */\n listGames(input?: ListGamesInput, options?: CallOptions): Promise<GamesPage>\n /**\n * Categories with active games, to build lobby tabs/filters. Public.\n * @example\n * const categories = await igaming.casino.listCategories()\n * categories.sort((a, b) => a.priority - b.priority)\n * @throws {EnginexError} `UNAVAILABLE`/`PROVIDER_ERROR` (503) when the call to the casino\n * service fails.\n */\n listCategories(params?: NoParams, options?: CallOptions): Promise<GameCategory[]>\n /**\n * Providers with active games. Public.\n * @example\n * const providers = await igaming.casino.listProviders()\n * @throws {EnginexError} `UNAVAILABLE`/`PROVIDER_ERROR` (503) when the call to the casino\n * service fails.\n */\n listProviders(params?: NoParams, options?: CallOptions): Promise<GameProvider[]>\n /**\n * A catalog game. Public.\n * @example\n * const game = await igaming.casino.getGame({ gameId: 'g-1' })\n * @throws {EnginexError} `GAME_NOT_FOUND` (404) if the id does not exist in the operator's catalog.\n */\n getGame(input: { gameId: string }, options?: CallOptions): Promise<Game>\n /**\n * Opens a game: creates the game session (ending the previous one, if any) and returns the URL and how to\n * open it ({@link GameLaunch.launchTarget}: in an iframe, by redirecting the tab, or in a new tab). Requires login, including in `demo` mode. It is not idempotent: each\n * call opens a new session.\n *\n * **The returned URL carries the game session token.** The SDK delivers it only in the return value: no\n * hook (`onRequest`/`onResponse`/`onError`) nor `onValidationIssue` receives it, and the response is always\n * validated in strict mode. Do not log it to logs, analytics or error tracking.\n * @example\n * const launch = await igaming.casino.launchGame({ gameId: game.id, isMobile: isPhone() })\n * // If gameUrl comes relative, resolve it against the gateway origin.\n * switch (launch.launchTarget) {\n * case 'iframe':\n * iframe.src = launch.gameUrl\n * break\n * case 'redirect':\n * window.location.assign(launch.gameUrl)\n * break\n * default: {\n * // 'new_tab', and any target the SDK does not know yet. Opened after an `await`, the tab may be\n * // blocked as a popup (`window.open` returns null): fall back to the current tab.\n * const tab = window.open(launch.gameUrl, '_blank')\n * if (tab) tab.opener = null\n * else window.location.assign(launch.gameUrl)\n * }\n * }\n * @throws {EnginexError} `GAME_NOT_FOUND` (404) for a nonexistent game; `FAILED_PRECONDITION` (422)\n * for an inactive game; `SELF_EXCLUDED` (422), `COOLING_OFF` or `ACCOUNT_BLOCKED` when responsible\n * gaming blocks the player (outside demo mode); `UNAVAILABLE` (503) when the casino cannot\n * verify the player's restrictions; `PROVIDER_ERROR` (503) and `CASINO_UNAVAILABLE`\n * (codes defined in `enginex-commons` for provider/casino failures; treat them as\n * unavailability); `VALIDATION_ERROR` if the response comes without `sessionId` or without `gameUrl`;\n * `INTERNAL_ERROR` (502) when the provider gave no way to open the game;\n * `UNAUTHENTICATED` without a session. `COOLING_OFF`, `ACCOUNT_BLOCKED` and `CASINO_UNAVAILABLE` arrive with\n * HTTP 500 (the gateway does not map them yet): identify by the code, not by the status.\n */\n launchGame(input: LaunchGameInput, options?: CallOptions): Promise<GameLaunch>\n /**\n * The player's game sessions, from newest to oldest, paginated.\n * @example\n * const { items } = await igaming.casino.listSessions({ perPage: 10 })\n * const active = items.find((s) => s.status === 'active')\n * @throws {EnginexError} `UNAUTHENTICATED` without a session.\n */\n listSessions(input?: CasinoPageInput, options?: CallOptions): Promise<Page<GameSession>>\n /**\n * The player's round history (bets, prizes, reversals), paginated.\n * @example\n * const page = await igaming.casino.getHistory({ page: 1, perPage: 20 })\n * page.items.forEach((tx) => console.log(tx.roundId, tx.type, tx.amount, tx.currency))\n * @throws {EnginexError} `INTERNAL_ERROR` (500) if the history has a currency the gateway does not\n * know; `UNAUTHENTICATED` without a session.\n */\n getHistory(input?: CasinoPageInput, options?: CallOptions): Promise<Page<CasinoTransaction>>\n /**\n * Biggest prizes of a round in the operator's casino (home ranking), with the player's name\n * masked. Requires login.\n * @example\n * const winners = await igaming.casino.getBiggestWinners({ limit: 10, days: 7 })\n * @throws {EnginexError} `INTERNAL_ERROR` (500) if a prize comes with an unknown currency;\n * `UNAUTHENTICATED` without a session.\n */\n getBiggestWinners(input?: GetBiggestWinnersInput, options?: CallOptions): Promise<BiggestWinner[]>\n /**\n * The lobby's published jackpots in the site's currency. Public (it does not send the session). A\n * `currency` other than the site's answers an empty list. An entry the SDK cannot show safely (no id or\n * name, another currency, a negative or non-integer amount, an amount that does not fit in a safe integer,\n * or invalid decimal places) is left out, and a repeated id keeps the first one.\n *\n * Available on gateways with lobby jackpots (the `dev` environment today); elsewhere the route answers 404.\n * @example\n * const { currency } = await enginex.config.get()\n * const { items, featuredId } = await igaming.casino.listJackpots({ currency: currency.code })\n * const featured = items.find((jackpot) => jackpot.id === featuredId)\n * @throws {EnginexError} `CONFIGURATION_ERROR` (no request) if `currency` is not three uppercase letters;\n * `INVALID_ARGUMENT` (400) for a currency the gateway does not support; `UNAVAILABLE` (503) when the site's\n * currency or the casino service is unavailable; `NOT_FOUND` (404) on a gateway without lobby jackpots.\n */\n listJackpots(input: ListJackpotsInput, options?: CallOptions): Promise<CasinoJackpots>\n /**\n * Game cards of a published jackpot, paginated by cursor. Public (it does not send the session). Ask for page\n * 1 without a cursor, then for `page + 1` with the previous page's `nextCursor` while `hasNext`.\n *\n * Available on gateways with lobby jackpots (the `dev` environment today); elsewhere the route answers 404.\n * @example\n * let page = await igaming.casino.listJackpotGames({ jackpotId, currency: 'BRL', device: 'mobile' })\n * while (page.hasNext && page.nextCursor) {\n * page = await igaming.casino.listJackpotGames({ jackpotId, currency: 'BRL', device: 'mobile', page: page.page + 1, cursor: page.nextCursor })\n * }\n * @throws {EnginexError} `CONFIGURATION_ERROR` (no request) for an empty `jackpotId`, a `currency` that is not\n * three uppercase letters, a `device` other than `mobile`/`desktop`, a `page` that is not an integer ≥ 1, a\n * `perPage` outside 1 to 48 or a `page` above 1 without `cursor`; `INVALID_ARGUMENT` (400) for an id that is\n * not a public jackpot id or an invalid cursor; `NOT_FOUND` (404) for a jackpot that is not published in\n * that currency (or a gateway without lobby jackpots); `UNAVAILABLE` (503) when the casino service fails or\n * answers an inconsistent page.\n */\n listJackpotGames(input: ListJackpotGamesInput, options?: CallOptions): Promise<JackpotGamesPage>\n}\n\nconst gameSchema = /* @__PURE__ */ lazy(\n (): z.ZodMiniType<Game> =>\n wire({\n id: z.string(),\n name: z.string(),\n provider: z.string(),\n category: z.string(),\n type: z.string(),\n thumbnail: z.string(),\n is_new: z.boolean(),\n is_popular: z.boolean(),\n is_live: z.boolean(),\n demo_available: z.boolean(),\n rtp: z.number(),\n volatility: z.string(),\n priority: z.number(),\n }),\n)\n\nconst categoriesSchema = /* @__PURE__ */ lazy(\n (): z.ZodMiniType<GameCategory[]> =>\n z.array(\n wire({ slug: z.string(), name: z.string(), icon: z.string(), game_count: z.number(), priority: z.number() }),\n ),\n)\n\nconst providersSchema = /* @__PURE__ */ lazy(\n (): z.ZodMiniType<GameProvider[]> => z.array(wire({ id: z.string(), name: z.string(), game_count: z.number() })),\n)\n\nconst launchSchema = /* @__PURE__ */ lazy(\n (): z.ZodMiniType<GameLaunch> =>\n z.pipe(\n wire({\n session_id: z.string().check(z.minLength(1)),\n game_url: z.string().check(z.minLength(1)),\n // Any text: a target the SDK does not know yet must not fail the (strict) launch.\n launch_target: z.optional(z.string()),\n provider_code: z.optional(z.string()),\n expires_at: z.optional(z.string()),\n }),\n // Without a target (an older gateway, or a custom mock), the launch keeps the behavior the SDK documented\n // before the field existed: an iframe.\n z.transform(({ launchTarget, ...rest }) => ({ ...rest, launchTarget: launchTarget || 'iframe' })),\n ),\n)\n\nconst sessionSchema = /* @__PURE__ */ lazy(\n (): z.ZodMiniType<GameSession> =>\n wire({\n id: z.string(),\n game_id: z.string(),\n game_name: z.string(),\n provider: z.string(),\n start_time: z.string(),\n total_bet: money(),\n total_win: money(),\n status: protoEnum('SESSION_STATUS_'),\n }),\n)\n\nconst transactionSchema = /* @__PURE__ */ lazy(\n (): z.ZodMiniType<CasinoTransaction> =>\n wire({\n id: z.string(),\n game_id: z.string(),\n game_name: z.string(),\n round_id: z.string(),\n type: protoEnum('CASINO_TRANSACTION_TYPE_'),\n amount: minorUnits(),\n currency: currencyCode(),\n currency_decimal_places: decimalPlaces(),\n created_at: z.string(),\n }),\n)\n\nconst winnersSchema = /* @__PURE__ */ lazy(\n (): z.ZodMiniType<BiggestWinner[]> =>\n z.array(\n wire({\n player: z.string(),\n amount: minorUnits(),\n currency: currencyCode(),\n currency_decimal_places: decimalPlaces(),\n game_id: z.string(),\n game_name: z.string(),\n won_at: z.string(),\n }),\n ),\n)\n\n// `availability` next to `data` in `GET /games` (`casino.go`, `encoding/json`): `missing` is a Go slice, so `null`\n// when empty; an older gateway sends no `availability` at all.\nconst gamesEnvelopeSchema = /* @__PURE__ */ lazy(\n (): z.ZodMiniType<{ availability: CasinoAvailability | null }> =>\n wire({\n availability: z.pipe(\n z.nullish(\n wire({\n // The gateway reports an unset status as `available`; the SDK does the same for an absent/empty one.\n status: z.pipe(\n z.nullish(z.string()),\n z.transform((value) => (value ? value.toLowerCase() : 'available')),\n ),\n primary_provider_code: optionalText(),\n missing: nullableList(z.string()),\n }),\n ),\n z.transform((value) => value ?? null),\n ),\n }),\n)\n\nconst CURRENCY = /^[A-Z]{3}$/\nconst DECIMAL_PLACES_MAX = 20\n\n// One entry of `GET /games/jackpots` (`casino_lobby_jackpots.go`): `amount_minor` is int64 text. Decoded one by\n// one (see `listJackpots`), so a bad entry is left out instead of failing the whole list.\nconst jackpotSchema = /* @__PURE__ */ lazy(\n (): z.ZodMiniType<CasinoJackpot> =>\n z.pipe(\n z.object({\n id: z.string().check(z.refine((value) => value.trim() !== '')),\n name: z.string().check(z.refine((value) => value.trim() !== '')),\n currency: z.string().check(z.regex(CURRENCY)),\n amount_minor: z.union([\n z.string().check(z.refine((value) => /^(0|[1-9]\\d*)$/.test(value) && Number.isSafeInteger(Number(value)))),\n z.number().check(z.refine((value) => Number.isSafeInteger(value) && value >= 0)),\n ]),\n decimal_places: z\n .number()\n .check(z.refine((value) => Number.isInteger(value) && value >= 0 && value <= DECIMAL_PLACES_MAX)),\n }),\n z.transform((raw) => ({\n id: raw.id,\n name: raw.name,\n currency: raw.currency,\n amount: Number(raw.amount_minor) || 0,\n currencyDecimalPlaces: raw.decimal_places,\n })),\n ),\n)\n\nconst jackpotsSchema = /* @__PURE__ */ lazy(\n (): z.ZodMiniType<{ items: unknown[]; featuredId: string | null }> =>\n wire({ items: nullableList(z.unknown()), featured_id: optionalText() }),\n)\n\nconst jackpotGamesSchema = /* @__PURE__ */ lazy(\n (): z.ZodMiniType<JackpotGamesPage> =>\n z.pipe(\n wire({\n games: nullableList(gameSchema()),\n mode: z.pipe(\n z.string(),\n z.transform((value) => value.toLowerCase()),\n ),\n pagination: wire({\n page: z.number(),\n per_page: z.number(),\n has_next: z.boolean(),\n next_cursor: optionalText(),\n }),\n }),\n z.transform(({ games, mode, pagination }) => ({\n items: games,\n mode,\n page: pagination.page,\n perPage: pagination.perPage,\n // A page that says there is more but has no cursor cannot be followed: it is the last one.\n hasNext: pagination.hasNext && pagination.nextCursor !== null,\n nextCursor: pagination.hasNext ? pagination.nextCursor : null,\n })),\n ),\n)\n\nconst DEVICES: readonly unknown[] = ['mobile', 'desktop']\nconst GAMES_ROUTE: Route = { method: 'GET', path: '/games' }\nconst JACKPOTS_ROUTE: Route = { method: 'GET', path: '/games/jackpots' }\nconst JACKPOT_GAMES_ROUTE: Route = { method: 'GET', path: '/games/jackpots/{jackpotId}/games' }\nconst JACKPOT_GAMES_MAX = 48\n\nfunction deviceProblem(name: string, device: unknown): string | undefined {\n return device === undefined || DEVICES.includes(device)\n ? undefined\n : `${name}: device must be 'mobile' or 'desktop' (or omitted).`\n}\n\nfunction currencyProblem(name: string, currency: unknown): string | undefined {\n return typeof currency === 'string' && CURRENCY.test(currency)\n ? undefined\n : `${name}: currency must be an ISO 4217 code in uppercase (e.g. BRL).`\n}\n\n// Checks the input of `listJackpotGames` before any request; the message never carries the received value.\nfunction jackpotGamesProblem(input: unknown): string | undefined {\n const name = 'casino.listJackpotGames'\n if (typeof input !== 'object' || input === null || Array.isArray(input))\n return `${name}: input must be an object { jackpotId, currency }.`\n const { jackpotId, currency, device, page, perPage, cursor } = input as Record<string, unknown>\n if (typeof jackpotId !== 'string' || jackpotId.trim() === '') return `${name}: jackpotId must be non-empty text.`\n const problem = currencyProblem(name, currency) ?? deviceProblem(name, device)\n if (problem !== undefined) return problem\n if (page !== undefined && (typeof page !== 'number' || !Number.isSafeInteger(page) || page < 1))\n return `${name}: page must be an integer ≥ 1.`\n if (\n perPage !== undefined &&\n (typeof perPage !== 'number' || !Number.isInteger(perPage) || perPage < 1 || perPage > JACKPOT_GAMES_MAX)\n )\n return `${name}: perPage must be an integer from 1 to ${JACKPOT_GAMES_MAX}.`\n if (cursor !== undefined && typeof cursor !== 'string') return `${name}: cursor must be text.`\n if (typeof page === 'number' && page > 1 && (cursor === undefined || cursor === ''))\n return `${name}: a page above 1 requires the previous page's nextCursor.`\n return undefined\n}\n\n/** Creates the `casino` namespace. @internal */\nexport function createCasinoApi(transport: ExtensionTransport): CasinoApi {\n return {\n listGames: async (input, options) => {\n const problem = deviceProblem('casino.listGames', input?.device)\n if (problem !== undefined) return rejectInput(transport, problem, GAMES_ROUTE)\n const spec = {\n ...GAMES_ROUTE,\n query: {\n category: input?.category,\n provider: input?.provider,\n search: input?.search,\n ids: input?.ids?.length ? input.ids.join(',') : undefined,\n sort: input?.sort,\n device: input?.device,\n },\n page: input?.page,\n perPage: input?.perPage,\n perPageParam: 'limit' as const,\n auth: 'none' as const,\n item: gameSchema(),\n options,\n }\n // A core older than 0.11.0 has no `requestPageWithEnvelope`: the page comes without the availability.\n if (typeof transport.requestPageWithEnvelope !== 'function')\n return { ...(await transport.requestPage(spec)), availability: null }\n const { page, envelope } = await transport.requestPageWithEnvelope({ ...spec, envelope: gamesEnvelopeSchema() })\n return { ...page, availability: envelope.availability }\n },\n listCategories: (_params, options) =>\n transport.request({ method: 'GET', path: '/games/categories', schema: categoriesSchema(), options }),\n listProviders: (_params, options) =>\n transport.request({ method: 'GET', path: '/games/providers', schema: providersSchema(), options }),\n getGame: ({ gameId }, options) =>\n transport.request({\n method: 'GET',\n path: `/games/${encodeURIComponent(gameId)}`,\n schema: gameSchema(),\n options,\n }),\n launchGame: ({ gameId, mode, isMobile, returnUrl, depositUrl, language }, options) =>\n transport.request({\n method: 'POST',\n path: `/games/${encodeURIComponent(gameId)}/launch`,\n body: {\n is_demo: mode === 'demo',\n is_mobile: isMobile === true,\n return_url: returnUrl,\n deposit_url: depositUrl,\n language,\n },\n auth: 'required',\n // The response carries the URL with the game session token: never through `warn` mode's recovery\n // (which would deliver a raw field and the response to `onValidationIssue`).\n validation: 'strict',\n schema: launchSchema(),\n options,\n }),\n listSessions: (input, options) =>\n transport.requestPage({\n method: 'GET',\n path: '/games/sessions',\n page: input?.page,\n perPage: input?.perPage,\n perPageParam: 'limit',\n auth: 'required',\n item: sessionSchema(),\n options,\n }),\n getHistory: (input, options) =>\n transport.requestPage({\n method: 'GET',\n path: '/games/history',\n page: input?.page,\n perPage: input?.perPage,\n perPageParam: 'limit',\n auth: 'required',\n item: transactionSchema(),\n options,\n }),\n getBiggestWinners: (input, options) =>\n transport.request({\n method: 'GET',\n path: '/games/biggest-winners',\n query: { limit: input?.limit, days: input?.days },\n auth: 'required',\n schema: winnersSchema(),\n options,\n }),\n listJackpots: async (input, options) => {\n const currency = (input as { currency?: unknown } | undefined)?.currency\n const problem = currencyProblem('casino.listJackpots', currency)\n if (problem !== undefined) return rejectInput(transport, problem, JACKPOTS_ROUTE)\n const raw = await transport.request({\n ...JACKPOTS_ROUTE,\n query: { currency: currency as string },\n auth: 'none',\n schema: jackpotsSchema(),\n options,\n })\n // Entry by entry, like the gateway already filters: what cannot be shown safely is left out.\n const items: CasinoJackpot[] = []\n for (const entry of Array.isArray(raw.items) ? raw.items : []) {\n const parsed = z.safeParse(jackpotSchema(), entry)\n if (!parsed.success || parsed.data.currency !== currency) continue\n if (items.some((item) => item.id === parsed.data.id)) continue\n items.push(parsed.data)\n }\n const featured = typeof raw.featuredId === 'string' ? raw.featuredId : null\n return { items, featuredId: items.some((item) => item.id === featured) ? featured : null }\n },\n listJackpotGames: (input, options) => {\n const problem = jackpotGamesProblem(input)\n if (problem !== undefined) return rejectInput(transport, problem, JACKPOT_GAMES_ROUTE)\n return transport.request({\n method: 'GET',\n path: `/games/jackpots/${encodeURIComponent(input.jackpotId)}/games`,\n query: {\n currency: input.currency,\n device: input.device,\n page: input.page,\n limit: input.perPage,\n cursor: input.cursor === '' ? undefined : input.cursor,\n },\n auth: 'none',\n schema: jackpotGamesSchema(),\n options,\n })\n },\n }\n}\n","// Public types come from the core's main entry: the /extension `.d.ts` exposes Zod, and this package's\n// public API cannot depend on it (check-api).\nimport type { CallOptions, NoParams } from '@getenginex/sdk'\nimport { lazy, wire, type ExtensionTransport } from '@getenginex/sdk/extension'\nimport * as z from 'zod/mini'\nimport { rejectInput } from '../internal/input'\nimport { optionalText, optionalTimestamp } from '../internal/optional-values'\nimport { currencyOrEmpty, integerText, minorUnits } from '../internal/schemas'\n\n/**\n * Type of points redemption. The `bonus.proto` mentions `bonus`, `cash` and `free_bet`, but the backend\n * treats the field as free text and the contract does not say which ones the operator enables: the SDK sends the value\n * as received (it only refuses empty) and the server decides.\n * @category Loyalty\n */\nexport type RedemptionType = 'bonus' | 'cash' | 'free_bet' | (string & {})\n\n/**\n * Benefits of a loyalty tier as the operator wrote them: an object keyed by benefit or a list of benefits.\n * @category Loyalty\n */\nexport type LoyaltyTierBenefits = Record<string, unknown> | unknown[]\n\n/**\n * The player's loyalty status (`GET /loyalty`).\n * @category Loyalty\n */\nexport interface LoyaltyStatus {\n /** Total points earned (integer). */\n totalPointsEarned: number\n /** Points available for redemption (integer). */\n currentPoints: number\n /** Points already redeemed (integer). */\n pointsRedeemed: number\n /** Current tier; `null` when the gateway does not report it (empty or absent). The contract does not list the possible tiers (the operator defines them). */\n currentTier: string | null\n /** Points that count toward the tier (integer); the calculation rule is not reported by the contract. */\n tierPoints: number\n /** Total wagered over the player's lifetime, in minor units (the contract field is called `*_cents`; the currency does not come with it). */\n lifetimeWagered: number\n /** Total deposited over the player's lifetime, in minor units (the currency does not come with it). */\n lifetimeDeposited: number\n /**\n * Benefits of the current tier, read from the JSON text the gateway passes along: an object (keyed by benefit)\n * or a list. The format is defined by the operator (the contract only says \"benefits of the current tier\"):\n * check before displaying. `null` when it comes empty or absent, and also when it is neither a JSON object nor\n * a JSON array (in this case `onValidationIssue` is notified, without the content).\n */\n tierBenefits: LoyaltyTierBenefits | null\n /** When the tier expires (ISO 8601, UTC); `null` when the gateway does not send it. */\n tierExpiresAt: string | null\n}\n\n/**\n * Input of {@link LoyaltyApi.redeem}.\n * @category Loyalty\n */\nexport interface RedeemPointsInput {\n /** Points to redeem: a safe integer > 0. */\n points: number\n /** Redemption type (non-empty text). */\n redemptionType: RedemptionType\n}\n\n/**\n * Result of {@link LoyaltyApi.redeem}.\n * @category Loyalty\n */\nexport interface RedeemedPoints {\n /** Points actually redeemed (integer). */\n redeemedPoints: number\n /** Redemption value in minor units of `currency`; `null` when the gateway does not send it. */\n value: number | null\n /** Currency of `value`; `null` when absent. */\n currency: string | null\n /** Id of the bonus generated, when the redemption was into a bonus; `null` otherwise. */\n bonusId: string | null\n}\n\n/**\n * The player's loyalty (points and tier). Both methods require login.\n * @category Loyalty\n */\nexport interface LoyaltyApi {\n /**\n * The player's points balance, tier and benefits.\n * @example\n * const loyalty = await igaming.loyalty.get()\n * console.log(loyalty.currentPoints, loyalty.currentTier, loyalty.tierBenefits)\n * @throws {EnginexError} `UNAUTHENTICATED` without a session. With `validation: 'strict'`,\n * `VALIDATION_ERROR` if `tier_benefits_json` is neither a JSON object nor a JSON array.\n */\n get(params?: NoParams, options?: CallOptions): Promise<LoyaltyStatus>\n /**\n * Exchanges points for a bonus, cash or a free bet. It sends `Idempotency-Key` (generated per call\n * or the one in `options.idempotencyKey`, kept on the retry after renewing the session), **but the gateway does not\n * apply the idempotency middleware on this route yet**: a double click may redeem twice.\n * Lock the button until the call finishes.\n * @example\n * const result = await igaming.loyalty.redeem({ points: 500, redemptionType: 'bonus' })\n * console.log(result.redeemedPoints, result.bonusId)\n * @throws {EnginexError} `CONFIGURATION_ERROR` (without a request) if `points` is not an integer > 0 or\n * `redemptionType` is empty; `INSUFFICIENT_BALANCE` or `FAILED_PRECONDITION` when the service\n * refuses the redemption (always identify by `error.code`); `UNKNOWN` with `status` 200 if the gateway\n * answers without confirming the redemption (`success: false`, absent or malformed; it also applies in\n * `validation: 'warn'`; `message` is the gateway's when it comes, otherwise the SDK's). General rule:\n * `UNKNOWN` with a 2xx `status` = unconfirmed operation: re-read the state ({@link LoyaltyApi.get})\n * before trying again. `UNAUTHENTICATED` without a session.\n */\n redeem(input: RedeemPointsInput, options?: CallOptions): Promise<RedeemedPoints>\n}\n\n// JSON object or array as text. Empty/absent is `null` without a warning; anything else becomes a\n// `tier_benefits_json` divergence (without the text, which may hold operator data, in the message).\n// The parsed value travels boxed, so that a raw value recovered in `'warn'` mode (a JSON array sent instead of\n// the text, say) is never taken for benefits the SDK parsed.\nclass ParsedBenefits {\n constructor(readonly value: LoyaltyTierBenefits) {}\n}\n\nconst tierBenefits = () =>\n z.pipe(\n z.nullish(z.string()),\n z.transform((text, ctx): ParsedBenefits | null => {\n if (text == null || text.trim() === '') return null\n let parsed: unknown\n try {\n parsed = JSON.parse(text)\n } catch {\n parsed = undefined\n }\n if (typeof parsed === 'object' && parsed !== null) return new ParsedBenefits(parsed as LoyaltyTierBenefits)\n ctx.issues.push({\n code: 'custom',\n message: 'tier_benefits_json is not a JSON object or array',\n input: undefined,\n })\n return z.NEVER\n }),\n )\n\n// `GetUserLoyalty`: int64 as a number; `tier_expires_at` only comes when filled in.\nconst loyaltySchema = /* @__PURE__ */ lazy(\n (): z.ZodMiniType<LoyaltyStatus> =>\n z.pipe(\n wire({\n total_points_earned: integerText(),\n current_points: integerText(),\n points_redeemed: integerText(),\n current_tier: optionalText(),\n tier_points: integerText(),\n lifetime_wagered: z._default(minorUnits(), 0),\n lifetime_deposited: z._default(minorUnits(), 0),\n tier_benefits_json: tierBenefits(),\n tier_expires_at: optionalTimestamp(),\n }),\n z.transform(({ tierBenefitsJson, ...rest }): LoyaltyStatus => {\n // With `validation: 'warn'`, a field that diverged arrives raw (the text): the SDK delivers `null`.\n const benefits = tierBenefitsJson instanceof ParsedBenefits ? tierBenefitsJson.value : null\n return { ...rest, tierBenefits: benefits } as LoyaltyStatus\n }),\n ),\n)\n\n// `RedeemLoyaltyPoints`: `value`/`currency` only come with `Money` filled in; `bonus_id` only if present;\n// `success` the gateway always sends; the SDK checks it (only `true` confirms) and does not expose it. The gateway does not\n// pass `message` along yet: if it comes, it becomes the message of the unconfirmed redemption error (as in KYC).\nconst redeemSchema = /* @__PURE__ */ lazy(\n (): z.ZodMiniType<RedeemedPoints & { success: unknown; message: unknown }> =>\n z.pipe(\n wire({\n success: z.optional(z.boolean()),\n message: z.optional(z.string()),\n redeemed_points: integerText(),\n value: z.nullish(minorUnits()),\n // Currency strict even in `'warn'`; absent, `null` and `''` still become `null`.\n currency: z.pipe(\n z.nullish(currencyOrEmpty()),\n z.transform((value): string | null => (value == null || value === '' ? null : value)),\n ),\n bonus_id: optionalText(),\n }),\n z.transform((data) => ({\n success: data.success,\n message: data.message,\n redeemedPoints: data.redeemedPoints,\n value: data.value ?? null,\n currency: data.currency,\n bonusId: data.bonusId,\n })),\n ),\n)\n\nconst UNCONFIRMED_REDEEM = 'loyalty.redeem: the gateway did not confirm the redemption.'\n\nconst REDEEM_ROUTE = { method: 'POST', path: '/loyalty/redeem' } as const\n\n// Checks the input before any request; the message never carries the received value.\nfunction redeemInputProblem(input: unknown): string | undefined {\n if (typeof input !== 'object' || input === null || Array.isArray(input))\n return 'loyalty.redeem: input must be an object { points, redemptionType }.'\n const { points, redemptionType } = input as { points?: unknown; redemptionType?: unknown }\n if (typeof points !== 'number' || !Number.isSafeInteger(points) || points <= 0)\n return 'loyalty.redeem: points must be an integer greater than 0.'\n if (typeof redemptionType !== 'string' || redemptionType.trim() === '')\n return 'loyalty.redeem: redemptionType must be non-empty text.'\n return undefined\n}\n\n/** Creates the `loyalty` namespace. @internal */\nexport function createLoyaltyApi(transport: ExtensionTransport): LoyaltyApi {\n return {\n get: (_params, options) =>\n transport.request({ method: 'GET', path: '/loyalty', auth: 'required', schema: loyaltySchema(), options }),\n redeem: (input, options) => {\n const problem = redeemInputProblem(input)\n if (problem !== undefined) return rejectInput(transport, problem, REDEEM_ROUTE)\n return transport\n .request({\n ...REDEEM_ROUTE,\n body: { points: input.points, redemption_type: input.redemptionType },\n auth: 'required',\n idempotent: true,\n schema: redeemSchema(),\n options,\n })\n .then(({ success, message, ...result }) => {\n // 200 without confirmation (`success: false`, absent or malformed, even in `warn`): the redemption may\n // not have happened; it never delivers a result as if it had.\n if (success === true) return result\n const text = typeof message === 'string' && message !== '' ? message : UNCONFIRMED_REDEEM\n throw transport.reportError({ code: 'UNKNOWN', message: text, status: 200 }, REDEEM_ROUTE)\n })\n },\n }\n}\n","import * as z from 'zod/mini'\n\n/**\n * Schema of a free-text backend value that the SDK knows in `values` (e.g. `daily`, `weekly`): compares\n * in lowercase and delivers the normalized value. A value the SDK does not know does not pass: with\n * `validation: 'strict'` the call rejects with `VALIDATION_ERROR`; in `'warn'` the field arrives raw, as it\n * came from the gateway, and `onValidationIssue` is notified. The matching public type is an open union\n * (`| (string & {})`). Equivalent to the core's internal helper. Call only inside a `lazy`. @internal\n */\nexport function openUnion<const V extends readonly [string, ...string[]]>(values: V) {\n return z.pipe(\n z.pipe(\n z.string(),\n z.transform((value) => value.toLowerCase()),\n ),\n z.enum(values),\n )\n}\n","// Public types come from the core's main entry: the /extension `.d.ts` exposes Zod, and this package's\n// public API cannot depend on it (check-api).\nimport type { CallOptions, NoParams, Page } from '@getenginex/sdk'\nimport { lazy, wire, type ExtensionTransport } from '@getenginex/sdk/extension'\nimport * as z from 'zod/mini'\nimport { pageInputProblem, rejectInput } from '../internal/input'\nimport { openUnion } from '../internal/open-union'\nimport { nullableList, optionalText, optionalTimestamp } from '../internal/optional-values'\nimport { integerText, minorUnits } from '../internal/schemas'\n\n/**\n * Mission periodicity: `daily`, `weekly`, `event` or `permanent`. The backend stores free text:\n * handle the default case (a new value arrives raw in `validation: 'warn'`).\n * @category Missions\n */\nexport type MissionType = 'daily' | 'weekly' | 'event' | 'permanent' | (string & {})\n\n/**\n * What the player must do: `wager` (bet), `bet_count` (number of bets), `win_amount`\n * (win), `play_game` (play the target games) or `deposit` (deposit). The contract\n * does not state the unit of `targetValue`; the \"Missions\" page gives an unconfirmed assumption per\n * type.\n * @category Missions\n */\nexport type MissionObjectiveType = 'wager' | 'bet_count' | 'win_amount' | 'play_game' | 'deposit' | (string & {})\n\n/**\n * Reward type: `bonus`, `free_spins`, `points` or `free_bet`. The contract does not\n * state the unit of `rewardValue`; the \"Missions\" page gives an unconfirmed assumption per type.\n * @category Missions\n */\nexport type MissionRewardType = 'bonus' | 'free_spins' | 'points' | 'free_bet' | (string & {})\n\n/**\n * Status of the player's mission: `in_progress`, `completed`, `expired` or `claimed`.\n * @category Missions\n */\nexport type UserMissionStatus = 'in_progress' | 'completed' | 'expired' | 'claimed' | (string & {})\n\n/**\n * Active operator mission (`GET /missions`).\n * @category Missions\n */\nexport interface Mission {\n /** Mission id (the same as {@link UserMission.missionId}). */\n id: string\n /** Display name. */\n name: string\n /** Description; may come empty. */\n description: string\n /** Periodicity. */\n missionType: MissionType\n /** Objective. */\n objectiveType: MissionObjectiveType\n /**\n * Target, an integer. The gateway contract does not state the unit (an assumption, unconfirmed:\n * minor units of the currency for `wager`/`win_amount`/`deposit`, a count for\n * `bet_count`/`play_game`); confirm with the operator before displaying.\n */\n targetValue: number\n /** Slug of the game category that counts toward the target; `null` when there is no restriction. */\n targetGameCategory: string | null\n /** Ids of the games that count toward the target; `[]` when there is no restriction. */\n targetGames: string[]\n /** Reward type. */\n rewardType: MissionRewardType\n /** Reward value, an integer. The contract does not state the unit (an assumption on the \"Missions\" page, unconfirmed). */\n rewardValue: number\n /** Start of validity (ISO 8601, UTC); `null` when the gateway sends an empty date (epoch). */\n validFrom: string | null\n /** End of validity (ISO 8601, UTC); `null` when the gateway sends an empty date (epoch). */\n validTo: string | null\n}\n\n/**\n * The player's progress on a mission (`GET /my/missions`).\n * @category Missions\n */\nexport interface UserMission {\n /** Progress id (of the player's mission in the period). */\n id: string\n /** Mission id ({@link Mission.id}). */\n missionId: string\n /** Mission name. */\n missionName: string\n /** Current progress, an integer; presumed to be the same unit as `targetValue` (not confirmed by the contract). */\n currentProgress: number\n /** Target, an integer. */\n targetValue: number\n /** Progress as a percentage, a number (e.g. `37.5`); computed by the service, may exceed `100`. */\n progressPercentage: number\n /** Status. */\n status: UserMissionStatus\n /** Reward type. */\n rewardType: MissionRewardType\n /** Reward value, an integer. */\n rewardValue: number\n /** End of the period (ISO 8601, UTC); `null` when the gateway does not send it. */\n periodEnd: string | null\n /** When it was completed (ISO 8601, UTC); `null` while not completed. */\n completedAt: string | null\n}\n\n/**\n * Input of {@link MissionsApi.list}.\n * @category Missions\n */\nexport interface ListMissionsInput {\n /** Page (starts at 1; integer ≥ 1). Gateway default: 1. */\n page?: number\n /** Items per page (integer from 1 to 100). Gateway default: 20 (out of range also becomes 20). */\n perPage?: number\n}\n\n/**\n * Operator missions and the player's progress. Both methods require login. There is no `claim()`: the\n * reward is automatic (inferred; see the \"Missions\" page).\n * @category Missions\n */\nexport interface MissionsApi {\n /**\n * Active operator missions, paginated. The gateway lists only the active ones and has no filter by type.\n * @example\n * const page = await igaming.missions.list({ perPage: 20 })\n * page.items.forEach((mission) => renderMission(mission.name, mission.targetValue))\n * @throws {EnginexError} `CONFIGURATION_ERROR` (without a request) for a `page` that is not an integer ≥ 1 or\n * a `perPage` outside 1–100 or not an integer; `UNAUTHENTICATED` without a session.\n */\n list(input?: ListMissionsInput, options?: CallOptions): Promise<Page<Mission>>\n /**\n * The player's progress on the active missions, without pagination.\n * @example\n * const mine = await igaming.missions.listMine()\n * const open = mine.filter((m) => m.status === 'in_progress')\n * @throws {EnginexError} `UNAUTHENTICATED` without a session.\n */\n listMine(params?: NoParams, options?: CallOptions): Promise<UserMission[]>\n}\n\n// Values the SDK knows (comments in `bonus.proto`); the rest fails in `strict` and arrives raw in `warn`.\nconst MISSION_TYPES = ['daily', 'weekly', 'event', 'permanent'] as const\nconst OBJECTIVE_TYPES = ['wager', 'bet_count', 'win_amount', 'play_game', 'deposit'] as const\nconst REWARD_TYPES = ['bonus', 'free_spins', 'points', 'free_bet'] as const\nconst USER_MISSION_STATUSES = ['in_progress', 'completed', 'expired', 'claimed'] as const\n\n// The gateway's `ListMissions`: `data` is an array of missions; the envelope's `meta` carries the pagination.\nconst missionSchema = /* @__PURE__ */ lazy(\n (): z.ZodMiniType<Mission> =>\n wire({\n id: z.string(),\n name: z.string(),\n description: z._default(z.string(), ''),\n mission_type: openUnion(MISSION_TYPES),\n objective_type: openUnion(OBJECTIVE_TYPES),\n target_value: integerText(),\n target_game_category: optionalText(),\n target_games: nullableList(z.string()),\n reward_type: openUnion(REWARD_TYPES),\n reward_value: minorUnits(),\n valid_from: optionalTimestamp(),\n valid_to: optionalTimestamp(),\n }),\n)\n\n// `GetUserMissions`: `data.missions`; `period_end` and `completed_at` only come when filled in.\nconst userMissionsSchema = /* @__PURE__ */ lazy(\n (): z.ZodMiniType<UserMission[]> =>\n z.pipe(\n wire({\n missions: nullableList(\n wire({\n id: z.string(),\n mission_id: z.string(),\n mission_name: z._default(z.string(), ''),\n current_progress: integerText(),\n target_value: integerText(),\n progress_percentage: z.number(),\n status: openUnion(USER_MISSION_STATUSES),\n reward_type: openUnion(REWARD_TYPES),\n reward_value: minorUnits(),\n period_end: optionalTimestamp(),\n completed_at: optionalTimestamp(),\n }),\n ),\n }),\n z.transform((data) => data.missions as UserMission[]),\n ),\n)\n\n/** Creates the `missions` namespace. @internal */\nexport function createMissionsApi(transport: ExtensionTransport): MissionsApi {\n return {\n list: (input, options) => {\n const problem = pageInputProblem('missions.list', input)\n if (problem !== undefined) return rejectInput(transport, problem, { method: 'GET', path: '/missions' })\n return transport.requestPage({\n method: 'GET',\n path: '/missions',\n page: input?.page,\n perPage: input?.perPage,\n perPageParam: 'limit',\n auth: 'required',\n item: missionSchema(),\n options,\n })\n },\n listMine: (_params, options) =>\n transport.request({\n method: 'GET',\n path: '/my/missions',\n auth: 'required',\n schema: userMissionsSchema(),\n options,\n }),\n }\n}\n","// Public types come from the core's main entry: the /extension `.d.ts` exposes Zod, and this package's\n// public API cannot depend on it (check-api).\nimport type { CallOptions, NoParams, Page } from '@getenginex/sdk'\nimport { lazy, wire, type ExtensionTransport } from '@getenginex/sdk/extension'\nimport * as z from 'zod/mini'\nimport { pageInputProblem, rejectInput } from '../internal/input'\nimport { nullableList, optionalText, optionalTimestamp } from '../internal/optional-values'\nimport { currencyOrEmpty, minorUnits } from '../internal/schemas'\n\n// Wire format: the gateway's `GetReferralInfo` and `ListReferrals` write a Go map with `encoding/json` (every key\n// present, an absent message as `null`), with money as `{ minor_units: \"5700\", currency: \"BRL\" }` (int64 as text).\n\n/**\n * Where a referred player stands, as the referrer sees it, in lowercase (the bonus service's\n * `CAMPAIGN_REFERRAL_STATUS_*`):\n * - `registered`: signed up, no deposit yet;\n * - `deposited`: deposited, real net loss still below the target;\n * - `in_hold`: qualified, waiting for the hold to end;\n * - `paid`: the referrer's reward is pending or granted;\n * - `not_eligible`: closed without reward by a block;\n * - `expired`: the window ended without qualifying;\n * - `cancelled`: paid, then cancelled.\n *\n * A status the SDK does not know yet arrives as the gateway sent it, in lowercase: handle the default case.\n * @category Referrals\n */\nexport type ReferralStatus =\n | 'registered'\n | 'deposited'\n | 'in_hold'\n | 'paid'\n | 'not_eligible'\n | 'expired'\n | 'cancelled'\n | (string & {})\n\n/**\n * Money of the referral program, in minor units of `currency` (the gateway sends the amount as text; the SDK\n * converts).\n * @category Referrals\n */\nexport interface ReferralMoney {\n /** Value in minor units of `currency`. */\n amount: number\n /** Currency code, e.g. `BRL`; `''` when the gateway sent none. */\n currency: string\n}\n\n/**\n * Rules of the operator's active referral campaign (part of {@link ReferralInfo}).\n * @category Referrals\n */\nexport interface ReferralRules {\n /** The referrer's reward per qualified referral. */\n reward: ReferralMoney\n /** Real net loss the referred player must reach (bets minus wins with real money) to qualify. */\n minimumRealNetLoss: ReferralMoney\n /** Days the referred player has, from the sign-up, to qualify. */\n refereeWindowDays: number\n /** Hours a qualified referral waits before the reward is paid. */\n holdHours: number\n /** Wagering multiplier of the reward, as an exact decimal in text (e.g. `\"80\"`). */\n wageringMultiplier: string\n /** Most of the reward that can be converted into withdrawable money; `null` without a cap. */\n maximumConversion: ReferralMoney | null\n}\n\n/**\n * How many of the player's referrals are in each status (integers), across all pages.\n * @category Referrals\n */\nexport interface ReferralTotals {\n /** In `registered`. */\n registered: number\n /** In `deposited`. */\n deposited: number\n /** In `in_hold`. */\n inHold: number\n /** In `paid`. */\n paid: number\n /** In `not_eligible`. */\n notEligible: number\n /** In `expired`. */\n expired: number\n /** In `cancelled`. */\n cancelled: number\n}\n\n/**\n * The player's referral code, the active program rules and the totals per status (`GET /referrals`).\n * @category Referrals\n */\nexport interface ReferralInfo {\n /**\n * `false` when the operator has no active referral campaign (and `rules` is `null`). Referrals already made keep\n * their windows open, so the totals and the history may still have rows.\n */\n enabled: boolean\n /** The player's referral code, from the profile; `null` when the gateway sends it empty. */\n code: string | null\n /**\n * Rules of the active campaign; `null` when there is none, and also when the gateway sends them without the\n * reward or the minimum real net loss (the program cannot be described without them).\n */\n rules: ReferralRules | null\n /** Totals per status. */\n totals: ReferralTotals\n}\n\n/**\n * The referred player's progress toward qualifying, in the campaign's currency.\n * @category Referrals\n */\nexport interface ReferralProgress {\n /** Whether the referred player already deposited. */\n depositDone: boolean\n /** Real net loss accumulated so far (`0` when the gateway sends none). */\n realNetLoss: ReferralMoney\n /** Real net loss required to qualify (the campaign's minimum). */\n target: ReferralMoney\n /** `max(0, target - realNetLoss)`; computed by the SDK when the gateway leaves it out. */\n remaining: ReferralMoney\n}\n\n/**\n * A referral of the history (`GET /referrals/history`): one row per referred player.\n * @category Referrals\n */\nexport interface Referral {\n /** Referral id. */\n id: string\n /**\n * The referred player's name, **already masked by the bonus service** (e.g. `\"Ma••• R.\"`): show it as it is,\n * never mask it again. `null` when empty.\n */\n refereeName: string | null\n /** Where the referred player stands (see {@link ReferralStatus}). */\n status: ReferralStatus\n /** Sign-up of the referred player (ISO 8601, UTC); `null` if the gateway does not send it. */\n createdAt: string | null\n /** End of the window to qualify (ISO 8601, UTC); `null` if the gateway does not send it. */\n deadlineAt: string | null\n /** Progress toward qualifying; `null` when the gateway sends no target. */\n progress: ReferralProgress | null\n}\n\n/**\n * Input of {@link ReferralsApi.listHistory}.\n * @category Referrals\n */\nexport interface ListReferralsInput {\n /** Page (starts at 1; integer ≥ 1). Gateway default: 1. */\n page?: number\n /** Items per page (integer from 1 to 100). Gateway default: 20. On the wire it goes as `limit`. */\n perPage?: number\n}\n\n/**\n * Page of the referral history, with the player's referral code.\n * @category Referrals\n */\nexport type ReferralHistory = Page<Referral> & {\n /** The player's referral code; `null` when the gateway sends it empty. */\n code: string | null\n}\n\n/**\n * The player's referrals. Both methods require login. A new player passes the code they were invited with in\n * the core's `auth.register({ referralCode })`: that is the only way to register a referral.\n * @category Referrals\n */\nexport interface ReferralsApi {\n /**\n * The player's referral code, the active program rules and the totals per status. Build the invitation\n * link in the app (your sign-up route with the code), so it always points at your site.\n * @example\n * const info = await igaming.referrals.get()\n * if (!info.enabled) showProgramUnavailable()\n * else showInvite(`${location.origin}/sign-up?ref=${info.code}`, info.rules)\n * @throws {EnginexError} `UNAUTHENTICATED` without a session; `UNAVAILABLE` when the bonus service does not\n * answer; `VALIDATION_ERROR`, also in `'warn'`, with money or currency outside the format.\n */\n get(params?: NoParams, options?: CallOptions): Promise<ReferralInfo>\n /**\n * Referral history, paginated, one row per referred player. Pagination comes inside `data` (not in the\n * envelope's `meta`): the SDK builds the `Page` and computes `totalPages` (`0` without items); a page beyond the\n * end returns `items: []`.\n * @example\n * const { items, totalPages } = await igaming.referrals.listHistory({ perPage: 20 })\n * items.forEach((r) => console.log(r.refereeName, r.status, r.progress?.remaining.amount))\n * @throws {EnginexError} `CONFIGURATION_ERROR` (without a request) for a `page` that is not an integer ≥ 1 or\n * a `perPage` outside 1–100 or not an integer; `UNAUTHENTICATED` without a session; `UNAVAILABLE` when the\n * bonus service does not answer; `VALIDATION_ERROR`, also in `'warn'`, with money or currency outside the\n * format.\n */\n listHistory(input?: ListReferralsInput, options?: CallOptions): Promise<ReferralHistory>\n}\n\nconst DEFAULT_PER_PAGE = 20\nconst HISTORY_PATH = '/referrals/history'\n\n// Gateway counter (integer >= 0), written explicitly by `encoding/json`; absent becomes 0 out of tolerance.\nconst count = () =>\n z._default(z.number().check(z.refine((value) => Number.isSafeInteger(value) && value >= 0, 'invalid counter')), 0)\n\n// `referralMoneyJSON`: `null` for an absent `common.Money`; the amount is int64 text (strict even in `'warn'`).\nconst money = () =>\n z.pipe(\n z.nullish(wire({ minor_units: minorUnits(), currency: z._default(currencyOrEmpty(), '') })),\n z.transform((value): ReferralMoney | null =>\n value == null ? null : { amount: value.minorUnits, currency: value.currency },\n ),\n )\n\nconst rulesSchema = () =>\n z.pipe(\n z.nullish(\n wire({\n reward: money(),\n minimum_real_net_loss: money(),\n referee_window_days: count(),\n hold_hours: count(),\n wagering_multiplier: z._default(z.string(), ''),\n maximum_conversion: money(),\n }),\n ),\n z.transform((rules): ReferralRules | null => {\n if (rules == null || rules.reward === null || rules.minimumRealNetLoss === null) return null\n return {\n reward: rules.reward,\n minimumRealNetLoss: rules.minimumRealNetLoss,\n refereeWindowDays: rules.refereeWindowDays,\n holdHours: rules.holdHours,\n wageringMultiplier: rules.wageringMultiplier,\n maximumConversion: rules.maximumConversion,\n }\n }),\n )\n\nconst infoSchema = /* @__PURE__ */ lazy(\n (): z.ZodMiniType<ReferralInfo> =>\n z.pipe(\n wire({\n enabled: z._default(z.boolean(), false),\n referral_code: optionalText(),\n rules: rulesSchema(),\n totals: z._default(\n wire({\n registered: count(),\n deposited: count(),\n in_hold: count(),\n paid: count(),\n not_eligible: count(),\n expired: count(),\n cancelled: count(),\n }),\n { registered: 0, deposited: 0, inHold: 0, paid: 0, notEligible: 0, expired: 0, cancelled: 0 },\n ),\n }),\n z.transform(\n ({ enabled, referralCode, rules, totals }): ReferralInfo => ({ enabled, code: referralCode, rules, totals }),\n ),\n ),\n)\n\n// `max(0, target - loss)` in BigInt, so a difference of two safe integers never rounds.\nfunction remainingOf(target: ReferralMoney, loss: ReferralMoney): ReferralMoney {\n const missing = BigInt(target.amount) - BigInt(loss.amount)\n return { amount: missing > 0n ? Number(missing) : 0, currency: target.currency }\n}\n\nconst progressSchema = () =>\n z.pipe(\n z.nullish(\n wire({\n deposit_done: z._default(z.boolean(), false),\n real_net_loss: money(),\n target: money(),\n remaining: money(),\n }),\n ),\n z.transform((progress): ReferralProgress | null => {\n if (progress == null || progress.target === null) return null\n const { target } = progress\n const realNetLoss = progress.realNetLoss ?? { amount: 0, currency: target.currency }\n return {\n depositDone: progress.depositDone,\n realNetLoss,\n target,\n remaining: progress.remaining ?? remainingOf(target, realNetLoss),\n }\n }),\n )\n\n// The legacy three-value `status` the older gateway sent alone; `player_status` replaces it.\nconst LEGACY_STATUS: Record<string, ReferralStatus> = { COMPLETED: 'paid', EXPIRED: 'expired', PENDING: 'registered' }\n\n/** `player_status` in lowercase; without it (an older gateway), derived from the legacy `status`. @internal */\nfunction statusOf(playerStatus: string | null, legacy: string | null): ReferralStatus {\n if (playerStatus !== null) return playerStatus.replace(/^CAMPAIGN_REFERRAL_STATUS_/, '').toLowerCase()\n return LEGACY_STATUS[(legacy ?? '').toUpperCase()] ?? 'registered'\n}\n\nconst referralSchema = () =>\n z.pipe(\n wire({\n id: z.string(),\n referee_name: optionalText(),\n status: optionalText(),\n player_status: optionalText(),\n created_at: optionalTimestamp(),\n deadline_at: optionalTimestamp(),\n progress: progressSchema(),\n }),\n z.transform(\n (r): Referral => ({\n id: r.id,\n refereeName: r.refereeName,\n status: statusOf(r.playerStatus, r.status),\n createdAt: r.createdAt,\n deadlineAt: r.deadlineAt,\n progress: r.progress,\n }),\n ),\n )\n\n// `ListReferrals`: pagination inside `data` (`page`, `limit`, `total_items`), no `meta`.\nconst historySchema = /* @__PURE__ */ lazy(() =>\n wire({\n referral_code: optionalText(),\n referrals: nullableList(referralSchema()),\n pagination: z.optional(wire({ page: count(), limit: count(), total_items: count() })),\n }),\n)\n\nconst positiveInt = (value: unknown, fallback: number): number =>\n typeof value === 'number' && Number.isSafeInteger(value) && value >= 1 ? value : fallback\n\n// Total reported by the gateway; in `warn` it may arrive raw (text, negative, absent): becomes 0.\nconst reportedTotal = (value: unknown): number =>\n typeof value === 'number' && Number.isSafeInteger(value) && value >= 0 ? value : 0\n\n/** Creates the `referrals` namespace. @internal */\nexport function createReferralsApi(transport: ExtensionTransport): ReferralsApi {\n return {\n get: (_params, options) =>\n transport.request({ method: 'GET', path: '/referrals', auth: 'required', schema: infoSchema(), options }),\n listHistory: (input, options) => {\n const problem = pageInputProblem('referrals.listHistory', input)\n if (problem !== undefined) return rejectInput(transport, problem, { method: 'GET', path: HISTORY_PATH })\n const requestedPage = input?.page\n const requestedPerPage = input?.perPage\n return transport\n .request({\n method: 'GET',\n path: HISTORY_PATH,\n query: { page: requestedPage, limit: requestedPerPage },\n auth: 'required',\n schema: historySchema(),\n options,\n })\n .then(({ referralCode, referrals, pagination }): ReferralHistory => {\n const items = Array.isArray(referrals) ? referrals : []\n const page = positiveInt(pagination?.page, requestedPage ?? 1)\n const perPage = positiveInt(pagination?.limit, requestedPerPage ?? DEFAULT_PER_PAGE)\n // A total smaller than the items already seen (or no pagination) must not turn into a `totalItems`\n // inconsistent with the delivered page.\n const seen = items.length > 0 ? (page - 1) * perPage + items.length : 0\n const totalItems = Math.max(reportedTotal(pagination?.totalItems), seen)\n return {\n items,\n page,\n perPage,\n totalItems,\n totalPages: totalItems > 0 ? Math.ceil(totalItems / perPage) : 0,\n code: referralCode,\n }\n })\n },\n }\n}\n","// Public types come from the core's main entry: the /extension `.d.ts` exposes Zod, and this package's\n// public API cannot depend on it (check-api).\nimport type { CallOptions, NoParams } from '@getenginex/sdk'\nimport { lazy, wire, type ExtensionTransport } from '@getenginex/sdk/extension'\nimport * as z from 'zod/mini'\n\n/**\n * FIRST sportsbook session created by {@link SportsbookApi.createSession}.\n *\n * **Sensitive:** `launchUrl` carries the player's operator token (`operatorToken`). Use it only to\n * open the sportsbook (iframe) and never log it to logs, analytics, error tracking.\n * @category Sportsbook\n */\nexport interface SportsbookSession {\n /**\n * FIRST sportsbook URL already with the operator token in the query — do not log it. Always\n * absolute (http/https); a response with anything else is `VALIDATION_ERROR`.\n */\n launchUrl: string\n /** Session validity from the response, in seconds (always greater than zero). */\n expiresInSeconds: number\n /**\n * Expiration instant in milliseconds since the epoch (like `Date.now()`): the client's clock at the\n * moment of the response plus `expiresInSeconds * 1000`. Reuse the session until `expiresAt - 30_000`.\n */\n expiresAt: number\n}\n\n/**\n * FIRST sportsbook (`GET /first/session`). The provider and the configuration come from\n * the core's `enginex.config.getSportsbook()`.\n * @category Sportsbook\n */\nexport interface SportsbookApi {\n /**\n * Creates the FIRST session for the logged-in player: returns the sportsbook URL (with the\n * operator token) to load in an iframe. Requires login. There is no cache in the SDK: each call generates a new\n * token; reuse the session until `expiresAt - 30_000` and call\n * `enginex.config.getSportsbook()` first to confirm `enabled && provider === 'first'`.\n *\n * **The returned URL carries the operator token.** The SDK delivers it only in the return value: no hook\n * (`onRequest`/`onResponse`/`onError`) nor `onValidationIssue` receives it, and the response is always\n * validated in strict mode. The separate token (`operator_token`) is never exposed. Do not log the URL\n * to logs, analytics or error tracking.\n * @example\n * const sb = await enginex.config.getSportsbook()\n * if (sb.enabled && sb.provider === 'first') {\n * const { launchUrl, expiresAt } = await igaming.sportsbook.createSession()\n * iframe.src = launchUrl\n * }\n * @throws {EnginexError} `UNAUTHENTICATED` without a session; the gateway envelope's code when FIRST\n * is not enabled for the operator (HTTP 400) and `UNAVAILABLE` (503) when the FIRST configuration is\n * incomplete, the session service is down or the bets service's sportsbook configuration\n * is not available; `VALIDATION_ERROR` if `launch_url` is not an\n * absolute http(s) URL or `expires_in_seconds` is not greater than zero.\n */\n createSession(params?: NoParams, options?: CallOptions): Promise<SportsbookSession>\n}\n\nconst HTTP_URL = 'Expected an absolute http(s) URL'\n\nconst sessionSchema = /* @__PURE__ */ lazy(\n (): z.ZodMiniType<SportsbookSession> =>\n z.pipe(\n wire({\n // The separate token only exists on the wire: the schema declares it (strict contract) and the output drops it.\n operator_token: z.string(),\n launch_url: z.string().check(\n z.refine(\n (value) => {\n try {\n const { protocol } = new URL(value)\n return protocol === 'https:' || protocol === 'http:'\n } catch {\n return false\n }\n },\n { message: HTTP_URL },\n ),\n ),\n expires_in_seconds: z.number().check(z.refine((n) => Number.isFinite(n) && n > 0, { message: 'Esperava > 0' })),\n }),\n // The clock is read when the response is interpreted (= moment of the response).\n z.transform(({ launchUrl, expiresInSeconds }) => ({\n launchUrl,\n expiresInSeconds,\n expiresAt: Date.now() + expiresInSeconds * 1000,\n })),\n ),\n)\n\n/** Creates the `sportsbook` namespace. @internal */\nexport function createSportsbookApi(transport: ExtensionTransport): SportsbookApi {\n return {\n createSession: (_params, options) =>\n transport.request({\n method: 'GET',\n path: '/first/session',\n auth: 'required',\n // The response carries the URL with the operator token: never through `warn` mode's recovery\n // (which would deliver a raw field and the response to `onValidationIssue`).\n validation: 'strict',\n schema: sessionSchema(),\n options,\n }),\n }\n}\n","import { EnginexError, type EnginexClient } from '@getenginex/sdk'\nimport * as extension from '@getenginex/sdk/extension'\nimport { createBetsApi, type BetsApi } from './modules/bets'\nimport { createBonusApi, type BonusApi } from './modules/bonus'\nimport { createCasinoApi, type CasinoApi } from './modules/casino'\nimport { createLoyaltyApi, type LoyaltyApi } from './modules/loyalty'\nimport { createMissionsApi, type MissionsApi } from './modules/missions'\nimport { createReferralsApi, type ReferralsApi } from './modules/referrals'\nimport { createSportsbookApi, type SportsbookApi } from './modules/sportsbook'\n\n/**\n * iGaming namespaces of an SDK client, returned by {@link createIgaming}. Every request\n * goes through the app's client: same session, token renewal, tenant, locale, hooks, validation and\n * `dispose()`.\n * @category Client\n */\nexport interface IgamingClient {\n /** Catalog, game launch and casino history. */\n casino: CasinoApi\n /** Bonus campaigns (offers, opt-in, redemption) and promo codes. */\n bonus: BonusApi\n /** Operator missions and the player's progress. */\n missions: MissionsApi\n /** Loyalty: points balance, tier, benefits and redemption. */\n loyalty: LoyaltyApi\n /** Referrals: code, program rules, totals per status and history with each referral's progress. */\n referrals: ReferralsApi\n /** FIRST sportsbook: session to open the sportsbook in an iframe. */\n sportsbook: SportsbookApi\n /** The player's sportsbook bets: history, details, cash-out offer and cash-out. */\n bets: BetsApi\n}\n\n/**\n * Creates the iGaming namespaces on top of a `@getenginex/sdk` client. It creates no session, tenant or\n * transport of its own and makes no request: call it once per client (in the browser, one per app;\n * on the server, one per request, together with the client).\n *\n * After `enginex.dispose()`, `createIgaming` still accepts the client, but every iGaming method\n * rejects with `CONFIGURATION_ERROR`, like the core methods.\n * @param client - The client returned by `createEnginexClient` (the object itself, not a copy).\n * @example\n * import { createEnginexClient } from '@getenginex/sdk'\n * import { createIgaming } from '@getenginex/sdk-igaming'\n *\n * export const enginex = createEnginexClient({ locale: 'pt-BR' })\n * export const igaming = createIgaming(enginex)\n * @throws {EnginexError} `CONFIGURATION_ERROR` if `client` is not a client created by\n * `createEnginexClient` (e.g. an arbitrary object or a `{ ...enginex }` copy), or if it was created\n * by an incompatible copy of `@getenginex/sdk` (install a single core version). Identify\n * with `isEnginexError(error, 'CONFIGURATION_ERROR')`.\n * @category Client\n */\nexport function createIgaming(client: EnginexClient): IgamingClient {\n // Validates the client right at creation (throws `CONFIGURATION_ERROR`); every namespace uses this\n // transport, the same as the app client's.\n const transport = extension.getExtensionTransport(client)\n const igaming: IgamingClient = {\n casino: createCasinoApi(transport),\n bonus: createBonusApi(transport),\n missions: createMissionsApi(transport),\n loyalty: createLoyaltyApi(transport),\n referrals: createReferralsApi(transport),\n sportsbook: createSportsbookApi(transport),\n bets: createBetsApi(transport),\n }\n // Links the object to the app's client: `@getenginex/sdk-igaming/query` reaches the session (the `userId` of the\n // user keys) from the iGaming object alone. Requires core `>=0.5.0`.\n // Namespace import: with an old core (without the function) `import { registerProductClient }` would fail at\n // module load, before any useful message.\n if (typeof extension.registerProductClient !== 'function') {\n throw new EnginexError({\n code: 'CONFIGURATION_ERROR',\n status: 0,\n message: `createIgaming requires @getenginex/sdk >=0.5.0 <1.0.0 (peer): update the installed core.`,\n })\n }\n extension.registerProductClient(igaming, client)\n return igaming\n}\n"]}
|
|
1
|
+
{"version":3,"sources":["../src/internal/input.ts","../src/internal/optional-values.ts","../src/internal/schemas.ts","../src/modules/bets.ts","../src/modules/bonus.ts","../src/modules/casino.ts","../src/modules/club.ts","../src/modules/loyalty.ts","../src/internal/open-union.ts","../src/modules/missions.ts","../src/modules/referrals.ts","../src/modules/sportsbook.ts","../src/client.ts"],"names":["z","z2","moneyText","currencyCode","strictValue","z3","lazy","wire","z4","offerSchema","code","nextCursor","z5","money","decimalPlaces","isEnginexError","isAmbiguousFailure","z6","mapOf","overviewSchema","MAX_IDEMPOTENCY_KEY","z7","text","z8","missionSchema","z9","count","z10","historySchema","sessionSchema","z11","extension","EnginexError"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAeO,SAAS,WAAA,CAAY,SAAA,EAA+B,OAAA,EAAiB,KAAA,EAA8B;AACxG,EAAA,OAAO,OAAA,CAAQ,MAAA;AAAA,IACb,SAAA,CAAU,WAAA,CAAY,EAAE,IAAA,EAAM,uBAAuB,OAAA,EAAS,MAAA,EAAQ,CAAA,EAAE,EAAG,EAAE,GAAG,KAAA,EAAO,OAAA,EAAS,GAAG;AAAA,GACrG;AACF;AAMO,SAAS,gBAAA,CAAiB,MAAc,KAAA,EAAoC;AACjF,EAAA,IAAI,KAAA,KAAU,QAAW,OAAO,MAAA;AAChC,EAAA,IAAI,OAAO,KAAA,KAAU,QAAA,IAAY,KAAA,KAAU,IAAA,IAAQ,KAAA,CAAM,OAAA,CAAQ,KAAK,CAAA,EAAG,OAAO,CAAA,EAAG,IAAI,CAAA,0BAAA,CAAA;AACvF,EAAA,MAAM,EAAE,IAAA,EAAM,OAAA,EAAQ,GAAI,KAAA;AAC1B,EAAA,IAAI,IAAA,KAAS,MAAA,KAAc,OAAO,IAAA,KAAS,QAAA,IAAY,CAAC,MAAA,CAAO,aAAA,CAAc,IAAI,CAAA,IAAK,IAAA,GAAO,CAAA,CAAA;AAC3F,IAAA,OAAO,GAAG,IAAI,CAAA,mCAAA,CAAA;AAChB,EAAA,IACE,OAAA,KAAY,MAAA,KACX,OAAO,OAAA,KAAY,QAAA,IAAY,CAAC,MAAA,CA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,MAAA,EAAQ,gBAAgB,SAAS,CAAA;AAAA,IACjC,IAAA,EAAM,cAAc,SAAS,CAAA;AAAA,IAC7B,KAAA,EAAO,eAAe,SAAS,CAAA;AAAA,IAC/B,QAAA,EAAU,kBAAkB,SAAS,CAAA;AAAA,IACrC,OAAA,EAAS,iBAAiB,SAAS,CAAA;AAAA,IACnC,SAAA,EAAW,mBAAmB,SAAS,CAAA;AAAA,IACvC,UAAA,EAAY,oBAAoB,SAAS,CAAA;AAAA,IACzC,IAAA,EAAM,cAAc,SAAS;AAAA,GAC/B;AAKA,EAAA,IAAI,OAAiBA,+CAA0B,UAAA,EAAY;AACzD,IAAA,MAAM,IAAIC,gBAAA,CAAa;AAAA,MACrB,IAAA,EAAM,qBAAA;AAAA,MACN,MAAA,EAAQ,CAAA;AAAA,MACR,OAAA,EAAS,CAAA,wFAAA;AAAA,KACV,CAAA;AAAA,EACH;AACA,EAAUD,oBAAA,CAAA,qBAAA,CAAsB,SAAS,MAAM,CAAA;AAG/C,EAAA,MAAA,CAAO,cAAA,CAAe,SAAS,MAAA,EAAQ;AAAA,IACrC,KAAA,EAAO,MAAO,OAAO,SAAA,CAAU,cAAc,UAAA,GAAa,SAAA,CAAU,WAAU,GAAI;AAAA,GACnF,CAAA;AACD,EAAA,OAAO,OAAA;AACT","file":"index.cjs","sourcesContent":["import type { ExtensionTransport } from '@getenginex/sdk/extension'\n\n/** Route of a call, to report the input error to `onError`. @internal */\nexport interface Route {\n /** HTTP method. */\n method: 'GET' | 'POST' | 'PUT' | 'DELETE'\n /** Path after `/api/v1`. */\n path: string\n}\n\n/**\n * Rejects with `CONFIGURATION_ERROR` (without a request) notifying `onError`, like the core does with invalid\n * input. `message` never carries the received value. The error comes out of `reportError`, which normalizes it into\n * `EnginexError` (the core does not export the constructor to product packages). @internal\n */\nexport function rejectInput(transport: ExtensionTransport, message: string, route: Route): Promise<never> {\n return Promise.reject(\n transport.reportError({ code: 'CONFIGURATION_ERROR', message, status: 0 }, { ...route, attempt: 0 }),\n )\n}\n\n/**\n * Checks `{ page, perPage }` of a listing: `page` an integer ≥ 1, `perPage` an integer from 1 to 100.\n * Returns the problem message or `undefined` if everything is fine. @internal\n */\nexport function pageInputProblem(name: string, input: unknown): string | undefined {\n if (input === undefined) return undefined\n if (typeof input !== 'object' || input === null || Array.isArray(input)) return `${name}: input must be an object.`\n const { page, perPage } = input as { page?: unknown; perPage?: unknown }\n if (page !== undefined && (typeof page !== 'number' || !Number.isSafeInteger(page) || page < 1))\n return `${name}: page must be an integer ≥ 1.`\n if (\n perPage !== undefined &&\n (typeof perPage !== 'number' || !Number.isInteger(perPage) || perPage < 1 || perPage > 100)\n )\n return `${name}: perPage must be an integer from 1 to 100.`\n return undefined\n}\n/**\n * Symbol (non-enumerable) of the client's current locale getter on the iGaming object. `Symbol.for`: `/query` may be\n * another copy of this package's code (CommonJS entries are separate files). @internal\n */\nexport const LOCALE: unique symbol = /* @__PURE__ */ Symbol.for('@getenginex/sdk-igaming/locale') as never\n","import * as z from 'zod/mini'\n\n// The gateway writes an absent `google.protobuf.Timestamp` as `\"1970-01-01T00:00:00Z\"` (`AsTime()`\n// of zero) or omits the key; an absent text comes out as `\"\"`. The SDK delivers `null` in both cases.\n// `optionalTimestamp` and `optionalText` are copies of the core's internal helpers\n// (`packages/sdk/src/internal/optional-values.ts`, which are not public API), with one difference: these\n// versions also accept `null` and the absent key (the core's only accept text). Keep the copies in\n// sync with the core's when changing the empty/epoch rule.\n\n/**\n * Schema of an optional ISO 8601 date: absent, `null`, empty text and the epoch (`1970-01-01T00:00:00Z`,\n * in any timezone or precision) become `null`; another date passes as it came. Text that is not a date fails\n * validation (in `'warn'`, it arrives raw and is reported). Call only inside a `lazy`. @internal\n */\nexport function optionalTimestamp() {\n return z.pipe(\n z.nullish(z.string().check(z.refine((value) => value === '' || !Number.isNaN(Date.parse(value)), 'invalid date'))),\n z.transform((value): string | null => (value == null || value === '' || Date.parse(value) === 0 ? null : value)),\n )\n}\n\n/** Optional text: absent, `null` and `\"\"` become `null`. Call only inside a `lazy`. @internal */\nexport function optionalText() {\n return z.pipe(\n z.nullish(z.string()),\n z.transform((value): string | null => (value == null || value === '' ? null : value)),\n )\n}\n\n/**\n * A list the gateway may send as `null` (Go nil slice) or omit: becomes `[]`, in every validation mode. Any other\n * non-list fails validation; in `'warn'`, with a core from 0.11.1 on, it becomes `[]` as well and a `null` item is\n * dropped (the core's per-field recovery). Call only inside a `lazy`. @internal\n */\nexport function nullableList<T extends z.ZodMiniType>(item: T) {\n return z.pipe(\n z.nullish(z.array(item)),\n z.transform((value): z.output<T>[] => value ?? []),\n )\n}\n","import { currencyCode, moneyText, strictValue } from '@getenginex/sdk/extension'\nimport * as z from 'zod/mini'\nimport { nullableList } from './optional-values'\n\n// All helpers build schemas: call only inside a `lazy` (nothing runs at import).\n\n/**\n * Schema of a protobuf enum the gateway passes along as text (e.g. `SESSION_STATUS_ACTIVE`):\n * strips the prefix, if any, and returns lowercase (`active`) — the same format the gateway\n * already uses on other routes and that the core uses in its enums. A new value passes along in the same\n * format, without breaking validation. Absent (protojson omits the zero value) becomes `unspecified`; a\n * number (protojson writes a value the gateway does not know this way) becomes the number as text.\n * Equivalent to the core's internal helper (which is not public API). @internal\n */\nexport function protoEnum(prefix: string) {\n return z.pipe(\n z.optional(z.union([z.string(), z.number()])),\n z.transform((value) => {\n if (value === undefined || value === 0) return 'unspecified'\n if (typeof value === 'number') return String(value)\n return (value.startsWith(prefix) ? value.slice(prefix.length) : value).toLowerCase()\n }),\n )\n}\n\n/**\n * Money in minor units that the gateway sends as a 64-bit integer in text (e.g. `\"2000\"`,\n * as the gateway's `strconv.FormatInt` and protojson write it) or as a number, returned as\n * `number`. It is the core's `moneyText()`: strict even in `'warn'` mode (outside the format, the whole\n * response rejects). @internal\n */\nexport function minorUnits() {\n return moneyText()\n}\n\n/**\n * Currency code the gateway may send empty: `''` (protojson omits the empty currency) or ISO 4217 in\n * uppercase (`BRL`). Strict even in `'warn'` mode, like the core's `currencyCode()`; it only accepts\n * the `''` as well. Absent/`null` are up to the caller (e.g. `z._default(..., '')`). @internal\n */\nexport function currencyOrEmpty(): z.ZodMiniType<string> {\n return currencyCode({ allowEmpty: true })\n}\n\nconst NON_NEGATIVE_MONEY = 'Expected money in minor units: a non-negative integer within the safe range of number'\n\n/**\n * Money in minor units that can never be negative (a stake, a payout, a jackpot), as a JSON number (what\n * `encoding/json` writes for an `int64`) or as int64 text, returned as `number`. A value ≥ 2^53 (already\n * rounded by `JSON.parse` when it came as a number, or text that does not fit), a negative, a fraction or\n * anything else rejects the whole response, even in `'warn'` mode, like the core's `moneyText()`. @internal\n */\nexport function nonNegativeMinorUnits(): z.ZodMiniType<number> {\n return z.pipe(\n strictValue<number | string>(\n (v) =>\n (typeof v === 'number' && Number.isSafeInteger(v) && v >= 0) ||\n (typeof v === 'string' && /^\\d+$/.test(v) && Number.isSafeInteger(Number(v))),\n NON_NEGATIVE_MONEY,\n ),\n // `|| 0`: a JSON `-0` comes out as `0`.\n z.transform((v) => Number(v) || 0),\n ) as unknown as z.ZodMiniType<number>\n}\n\nconst INTEGER_TEXT = 'Expected an integer within the safe range of number'\n\n/**\n * Integer that is not money (loyalty points, mission progress), as int64 text or a number,\n * returned as `number`. The same validation as {@link minorUnits}, but it follows the normal\n * `'warn'` rule (the divergent field arrives raw and is reported). @internal\n */\nexport function integerText() {\n return z.pipe(\n z.union([\n z\n .string()\n .check(\n z.refine((value) => /^-?\\d+$/.test(value) && Number.isSafeInteger(Number(value)), { message: INTEGER_TEXT }),\n ),\n z.number().check(z.refine((value) => Number.isSafeInteger(value), { message: INTEGER_TEXT })),\n ]),\n z.transform(Number),\n )\n}\n\n/** Protobuf text: protojson omits `''`, which comes back as `''`. @internal */\nexport function text() {\n return z._default(z.string(), '')\n}\n\n/** Protobuf number (int32/uint32): protojson omits `0`, which comes back as `0`. @internal */\nexport function count() {\n return z._default(z.number(), 0)\n}\n\n/**\n * Protobuf list (`repeated`): protojson omits the empty list and a handler on `encoding/json` writes a nil slice as\n * `null`; both come back as an empty `[]`, in every validation mode. The same as {@link nullableList}. @internal\n */\nexport function list<T extends z.ZodMiniType>(item: T) {\n return nullableList(item)\n}\n\n/**\n * `google.protobuf.Duration` from protojson (e.g. `\"86400s\"`, `\"1.5s\"`), returned in seconds. @internal\n */\nexport function durationSeconds() {\n return z.pipe(\n z.string().check(z.regex(/^-?\\d+(\\.\\d+)?s$/, { message: 'Expected a protobuf duration, e.g. \"86400s\"' })),\n z.transform((value) => Number(value.slice(0, -1))),\n )\n}\n\nconst MAJOR_UNITS = 'Expected a value in major units (a finite number) that fits in whole minor units'\n\n/**\n * Converts a value in major units (float, as the gateway writes referrals: cents / 100)\n * for whole minor units: `Math.round(value * 100)`, rounding halves away from zero\n * (`-0.005` becomes `-1`, symmetric to `0.005` → `1`) and never returning `-0`. `19.99` → `1999`,\n * `0.1 + 0.2` → `30`, `1e-7` → `0`. It refuses what is not a finite number and what does not fit in a safe integer\n * after the conversion. @internal\n */\nexport function majorToMinorUnits(value: number): number {\n const minor = Math.sign(value) * Math.round(Math.abs(value) * 100)\n return minor === 0 ? 0 : minor\n}\n\n/**\n * Schema of a monetary value in major units (float) returned in minor units. See\n * {@link majorToMinorUnits}. Strict even in `'warn'` mode: outside the format, the whole response\n * rejects. @internal\n */\nexport function majorUnits() {\n // The core's `strictValue`: even the wrong type produces the issue marked as strict; a `z.number()` would emit\n // `invalid_type` without the mark and the field would be recovered raw in `'warn'`.\n return z.pipe(\n strictValue<number>(\n (value) => typeof value === 'number' && Number.isSafeInteger(majorToMinorUnits(value)),\n MAJOR_UNITS,\n ),\n z.transform((value) => majorToMinorUnits(value)),\n )\n}\n","// Public types come from the core's main entry: the /extension `.d.ts` exposes Zod, and this package's\n// public API cannot depend on it (check-api).\nimport type { CallOptions, Page } from '@getenginex/sdk'\nimport { lazy, wire, type ExtensionTransport } from '@getenginex/sdk/extension'\nimport * as z from 'zod/mini'\nimport { pageInputProblem, rejectInput, type Route } from '../internal/input'\nimport { nullableList, optionalTimestamp } from '../internal/optional-values'\nimport { nonNegativeMinorUnits, protoEnum } from '../internal/schemas'\n\n/**\n * Status of a sportsbook bet, without the gateway's `BET_STATUS_` prefix and in lowercase. A new value the SDK\n * does not know yet may arrive (a number as text, when the gateway does not know it either): handle the\n * default case.\n * @category Bets\n */\nexport type BetStatus =\n | 'pending'\n | 'open'\n | 'won'\n | 'lost'\n | 'void'\n | 'cashed_out'\n | 'partially_settled'\n | 'unspecified'\n | (string & {})\n\n/**\n * Result of a selection, without the gateway's `SELECTION_RESULT_` prefix and in lowercase. A new value may\n * arrive: handle the default case.\n * @category Bets\n */\nexport type BetSelectionResult =\n | 'pending'\n | 'won'\n | 'lost'\n | 'void'\n | 'half_won'\n | 'half_lost'\n | 'unspecified'\n | (string & {})\n\n/**\n * A sportsbook bet of the player (`GET /bets`).\n *\n * Amounts are in minor units of the **operator's currency** (`enginex.config.get()`): the gateway sends no\n * currency per bet.\n * @category Bets\n */\nexport interface Bet {\n /** Bet id, for {@link BetsApi.get}, {@link BetsApi.getCashoutOffer} and {@link BetsApi.cashout}. */\n id: string\n /** Status, e.g. `pending`, `won`, `cashed_out`. */\n status: BetStatus\n /** Stake in minor units (never negative). */\n stake: number\n /** Potential return in minor units (never negative). */\n potentialReturn: number\n /** Total odds (decimal), e.g. `2.35`. */\n totalOdds: number\n /** Placement date, ISO 8601 (UTC); `null` when the gateway did not have one. */\n createdAt: string | null\n}\n\n/**\n * A selection of a bet ({@link BetDetails.selections}).\n * @category Bets\n */\nexport interface BetSelection {\n /** Event name. */\n eventName: string\n /** Market name. */\n marketName: string\n /** Selection (outcome) name. */\n selectionName: string\n /** Odds (decimal) of the selection. */\n odds: number\n /** Result, e.g. `pending`, `won`. */\n result: BetSelectionResult\n}\n\n/**\n * A bet with its selections (`GET /bets/{id}`).\n * @category Bets\n */\nexport interface BetDetails extends Bet {\n /** The bet's selections; `[]` when the gateway sends none. */\n selections: BetSelection[]\n}\n\n/**\n * Pagination of {@link BetsApi.list}. There is no status filter: the gateway ignores one, so filter\n * `items` in the app.\n * @category Bets\n */\nexport interface ListBetsInput {\n /** Page (starts at 1). Gateway default: 1. */\n page?: number\n /** Items per page, from 1 to 100. Gateway default: 20 (out of range also becomes 20). */\n perPage?: number\n}\n\n/**\n * Cash-out offer of a bet (`GET /bets/{id}/cashout`). Offers expire: read it again shortly before cashing out.\n * @category Bets\n */\nexport interface CashoutOffer {\n /** Bet id. */\n betId: string\n /** Whether the bet can be cashed out now. `false`: do not show the cash-out button. */\n available: boolean\n /** Amount offered, in minor units of the operator's currency (never negative; `0` without an offer). */\n cashoutAmount: number\n /** Expiry of the offer, ISO 8601 (UTC); `null` without an offer. */\n expiresAt: string | null\n}\n\n/**\n * Result of a cash-out ({@link BetsApi.cashout}).\n * @category Bets\n */\nexport interface CashoutResult {\n /** Bet id. */\n betId: string\n /** Amount paid, in minor units of the operator's currency (never negative). */\n cashoutAmount: number\n /** Status of the bet after the cash-out, as the gateway sends it (`cashed_out`). */\n status: 'cashed_out' | (string & {})\n}\n\n/**\n * The player's sportsbook bets: history, details, cash-out offer and cash-out. Every method requires login.\n * Placing bets is not part of this namespace.\n * @category Bets\n */\nexport interface BetsApi {\n /**\n * The player's bets, from newest to oldest, paginated. The gateway sends no currency: format the amounts with the\n * operator's currency (`enginex.config.get()`).\n * @example\n * const { currency } = await enginex.config.get()\n * const page = await igaming.bets.list({ perPage: 20 })\n * page.items.forEach((bet) => render(bet.status, formatMoney(bet.stake, currency, 'pt-BR')))\n * @throws {EnginexError} `CONFIGURATION_ERROR` (no request) for a `page`/`perPage` out of range;\n * `VALIDATION_ERROR` for a negative amount or one that does not fit in a safe integer (even in `'warn'`);\n * `UNAUTHENTICATED` without a session.\n */\n list(input?: ListBetsInput, options?: CallOptions): Promise<Page<Bet>>\n /**\n * A bet with its selections.\n * @example\n * const bet = await igaming.bets.get({ betId })\n * bet.selections.forEach((s) => console.log(s.eventName, s.selectionName, s.result))\n * @throws {EnginexError} `CONFIGURATION_ERROR` (no request) for an empty `betId`; `BET_NOT_FOUND`/`NOT_FOUND`\n * (404) for an unknown id; `UNAUTHENTICATED` without a session.\n */\n get(input: { betId: string }, options?: CallOptions): Promise<BetDetails>\n /**\n * The bet's current cash-out offer. Show the cash-out button only with `available: true`, and read it again\n * before cashing out (offers expire).\n * @example\n * const offer = await igaming.bets.getCashoutOffer({ betId })\n * if (offer.available) showCashout(offer.cashoutAmount, offer.expiresAt)\n * @throws {EnginexError} `CONFIGURATION_ERROR` (no request) for an empty `betId`; `BET_NOT_FOUND`/`NOT_FOUND`\n * (404) for an unknown id; `UNAUTHENTICATED` without a session.\n */\n getCashoutOffer(input: { betId: string }, options?: CallOptions): Promise<CashoutOffer>\n /**\n * Cashes out the bet at the current offer. Idempotent: it sends an `Idempotency-Key` (the one in\n * `options.idempotencyKey` or, without it, one generated per call). To retry a cash-out whose outcome is\n * unknown (network error, timeout, 5xx), call again with the **same** `idempotencyKey`: the gateway answers\n * the first result instead of cashing out twice. Through `createIgamingMutations` the key is kept for you\n * after an ambiguous failure.\n * @example\n * const idempotencyKey = crypto.randomUUID()\n * const result = await igaming.bets.cashout({ betId }, { idempotencyKey })\n * @throws {EnginexError} `CONFIGURATION_ERROR` (no request) for an empty `betId` or an `idempotencyKey`\n * with surrounding spaces or longer than 255 characters; `FAILED_PRECONDITION` (422) when there is no\n * offer; `CASHOUT_UNAVAILABLE` (it arrives with HTTP 500: the gateway does not map it yet, identify it by the\n * code); `KEY_IN_USE` (409) while a cash-out with the same key is still being processed;\n * `PAYLOAD_MISMATCH` (422) for a key reused on another request; `UNAUTHENTICATED` without a session.\n */\n cashout(input: { betId: string }, options?: CallOptions): Promise<CashoutResult>\n}\n\n// The gateway's bet handlers (`betting.go`) write `encoding/json` maps: money as JSON numbers (`int64`), the\n// status as the protobuf name (`BET_STATUS_WON`) and the date as Go's `time.Time` (`AsTime()` of an absent\n// timestamp is the epoch).\nconst betFields = () => ({\n id: z.string(),\n status: protoEnum('BET_STATUS_'),\n stake: nonNegativeMinorUnits(),\n potential_return: nonNegativeMinorUnits(),\n total_odds: z.number(),\n created_at: optionalTimestamp(),\n})\n\nconst betSchema = /* @__PURE__ */ lazy((): z.ZodMiniType<Bet> => wire(betFields()))\n\nconst betDetailsSchema = /* @__PURE__ */ lazy(\n (): z.ZodMiniType<BetDetails> =>\n wire({\n ...betFields(),\n selections: nullableList(\n wire({\n event_name: z.string(),\n market_name: z.string(),\n selection_name: z.string(),\n odds: z.number(),\n result: protoEnum('SELECTION_RESULT_'),\n }),\n ),\n }),\n)\n\nconst offerSchema = /* @__PURE__ */ lazy(\n (): z.ZodMiniType<CashoutOffer> =>\n wire({\n bet_id: z.string(),\n available: z.boolean(),\n cashout_amount: nonNegativeMinorUnits(),\n expires_at: optionalTimestamp(),\n }),\n)\n\nconst cashoutSchema = /* @__PURE__ */ lazy(\n (): z.ZodMiniType<CashoutResult> =>\n wire({ bet_id: z.string(), cashout_amount: nonNegativeMinorUnits(), status: z.string() }),\n)\n\nconst LIST_ROUTE: Route = { method: 'GET', path: '/bets' }\nconst GET_ROUTE: Route = { method: 'GET', path: '/bets/{betId}' }\nconst OFFER_ROUTE: Route = { method: 'GET', path: '/bets/{betId}/cashout' }\nconst CASHOUT_ROUTE: Route = { method: 'POST', path: '/bets/{betId}/cashout' }\n\n// The gateway's idempotency middleware refuses a key above 255 characters, and the cash-out handler one with\n// surrounding spaces.\nconst MAX_IDEMPOTENCY_KEY = 255\n\nfunction betIdProblem(name: string, input: unknown): string | undefined {\n if (typeof input !== 'object' || input === null || Array.isArray(input)) return `${name}: input must be { betId }.`\n const { betId } = input as { betId?: unknown }\n return typeof betId === 'string' && betId.trim() !== '' ? undefined : `${name}: betId must be non-empty text.`\n}\n\nfunction idempotencyKeyProblem(options: CallOptions | undefined): string | undefined {\n const key = options?.idempotencyKey\n if (key === undefined || key === '') return undefined\n if (typeof key !== 'string' || key !== key.trim() || key.length > MAX_IDEMPOTENCY_KEY)\n return `bets.cashout: idempotencyKey must be text without surrounding spaces, up to ${MAX_IDEMPOTENCY_KEY} characters.`\n return undefined\n}\n\nconst betPath = (betId: string, suffix = '') => `/bets/${encodeURIComponent(betId)}${suffix}`\n\n/** Creates the `bets` namespace. @internal */\nexport function createBetsApi(transport: ExtensionTransport): BetsApi {\n return {\n list: (input, options) => {\n const problem = pageInputProblem('bets.list', input)\n if (problem !== undefined) return rejectInput(transport, problem, LIST_ROUTE)\n return transport.requestPage({\n ...LIST_ROUTE,\n page: input?.page,\n perPage: input?.perPage,\n perPageParam: 'limit',\n auth: 'required',\n item: betSchema(),\n options,\n })\n },\n get: (input, options) => {\n const problem = betIdProblem('bets.get', input)\n if (problem !== undefined) return rejectInput(transport, problem, GET_ROUTE)\n return transport.request({\n method: 'GET',\n path: betPath(input.betId),\n auth: 'required',\n schema: betDetailsSchema(),\n options,\n })\n },\n getCashoutOffer: (input, options) => {\n const problem = betIdProblem('bets.getCashoutOffer', input)\n if (problem !== undefined) return rejectInput(transport, problem, OFFER_ROUTE)\n return transport.request({\n method: 'GET',\n path: betPath(input.betId, '/cashout'),\n auth: 'required',\n schema: offerSchema(),\n options,\n })\n },\n cashout: (input, options) => {\n const problem = betIdProblem('bets.cashout', input) ?? idempotencyKeyProblem(options)\n if (problem !== undefined) return rejectInput(transport, problem, CASHOUT_ROUTE)\n return transport.request({\n method: 'POST',\n path: betPath(input.betId, '/cashout'),\n auth: 'required',\n // No body: the gateway's idempotency middleware fingerprints the (empty) body, so a replay always matches.\n idempotent: true,\n schema: cashoutSchema(),\n options,\n })\n },\n }\n}\n","// Public types come from the core's main entry: the /extension `.d.ts` exposes Zod, and this package's\n// public API cannot depend on it (check-api).\nimport type { CallOptions, CursorPage, CursorPageInput, NoParams } from '@getenginex/sdk'\nimport { lazy, wire, type ExtensionTransport } from '@getenginex/sdk/extension'\nimport * as z from 'zod/mini'\nimport { count, currencyOrEmpty, durationSeconds, list, minorUnits, protoEnum, text } from '../internal/schemas'\n\n// Wire format: the gateway writes the campaigns with protojson (the .proto names in snake_case,\n// without the zero values). The SDK returns camelCase, with the enums without the prefix and in lowercase,\n// money (int64 as text) as `number`, durations in seconds and the type's zero in place of the\n// omitted values (`''`, `0`, `[]`, `'unspecified'`). Absent messages stay absent\n// (`undefined`): protobuf guarantees none, and the app handles the absence.\n\n// ─── Basic types ───────────────────────────────────────────────────────────────────────────────\n\n/**\n * Money value of a campaign, in minor units of the currency (e.g. cents). The decimal places\n * are the currency's (`config.currency.decimalPlaces` for the operator's currency).\n * @category Bonus\n */\nexport interface CampaignMoney {\n /** Value in minor units of `currency` (the gateway sends it as text; the SDK converts). */\n amount: number\n /** Currency code, e.g. `BRL`. */\n currency: string\n}\n\n/**\n * Time window (ISO 8601, UTC). A missing side is left open.\n * @category Bonus\n */\nexport interface CampaignTimeWindow {\n /** Start. */\n startsAt?: string\n /** End. */\n endsAt?: string\n}\n\n/**\n * Exact ratio (percentage, multiplier), in one of two forms: `decimal` (text, e.g. `\"30\"`,\n * `\"0.5\"`) or `basisPoints` (10000 = 100%).\n * @category Bonus\n */\nexport interface CampaignExactRatio {\n /** Exact decimal value as text (do not convert to `number` if you need precision). */\n decimal?: string\n /** Value in basis points: `10000` = 100%. */\n basisPoints?: number\n /** Maximum decimal places of the result. */\n maximumScale: number\n}\n\n/**\n * Rounding mode of a campaign calculation.\n * @category Bonus\n */\nexport type CampaignRoundingMode = 'floor' | 'half_up' | 'ceiling' | 'unspecified' | (string & {})\n\n/**\n * Product where the campaign applies.\n * @category Bonus\n */\nexport type CampaignProductScope = 'casino' | 'sportsbook' | 'casino_and_sportsbook' | 'unspecified' | (string & {})\n\n/**\n * How the player enters the campaign: `automatic` (enters on its own on meeting the qualification), `opt_in`\n * (needs {@link BonusApi.optIn}), `promo_code` (needs {@link BonusApi.redeemPromoCode}) or\n * `manual` (the operator adds them).\n * @category Bonus\n */\nexport type CampaignEntryPolicyCode = 'automatic' | 'opt_in' | 'promo_code' | 'manual' | 'unspecified' | (string & {})\n\n/**\n * How the reward is delivered: `automatic` (credited on qualifying) or `player_claim` (the player\n * redeems it with {@link BonusApi.claim}).\n * @category Bonus\n */\nexport type CampaignRewardClaimPolicyCode = 'automatic' | 'player_claim' | 'unspecified' | (string & {})\n\n/**\n * Reward type: balance credit, free spins, free bet or sports bet coverage.\n * @category Bonus\n */\nexport type CampaignRewardKind =\n | 'balance_credit'\n | 'casino_free_spins'\n | 'sports_bonus_bet'\n | 'sports_bet_coverage'\n | 'unspecified'\n | (string & {})\n\n/**\n * Versioned policy (code + version).\n * @category Bonus\n */\nexport interface CampaignPolicy<C extends string> {\n /** Policy code. */\n code: C\n /** Policy version. @beta */\n version: number\n}\n\n// ─── Scopes and qualification ──────────────────────────────────────────────────────────────────────\n\n/**\n * Casino activity slice (empty lists = no restriction on that criterion).\n * Mirrors the bonus service protobuf and may change in 0.x (minor) versions.\n * @beta\n * @category Bonus\n */\nexport interface CasinoActivitySelector {\n /** Provider instance. */\n providerInstanceId: string\n /** Provider software. */\n softwareIds: string[]\n /** Games. */\n gameIds: string[]\n /** Categories (catalog slugs). */\n categoryCodes: string[]\n}\n\n/**\n * Sports bet type.\n * @category Bonus\n */\nexport type SportsBetType = 'single' | 'multiple' | 'system' | 'unspecified' | (string & {})\n\n/**\n * Sports activity slice (empty lists = no restriction on that criterion).\n * Mirrors the bonus service protobuf and may change in 0.x (minor) versions.\n * @beta\n * @category Bonus\n */\nexport interface SportsActivitySelector {\n /** Sports. */\n sportCodes: string[]\n /** Competitions. */\n competitionIds: string[]\n /** Events. */\n eventIds: string[]\n /** Markets. */\n marketCodes: string[]\n /** Live only (`true`), pre-match only (`false`) or both (absent). */\n live?: boolean\n /** Accepted bet types. */\n betTypes: SportsBetType[]\n}\n\n/**\n * Qualification by a player event (e.g. completed signup).\n * @category Bonus\n */\nexport interface UserEventQualification {\n /** Event code. */\n eventCode: string\n /** Event version. @beta */\n eventVersion: number\n /** Authorized origin of the event. */\n sourceAuthority: string\n /** Fields that identify the event. */\n identityFields: string[]\n}\n\n/**\n * Qualification by a confirmed deposit.\n * @category Bonus\n */\nexport interface DepositSettledQualification {\n /** Deposit currency. */\n currency: string\n /** Accepted payment methods (e.g. `pix`); empty = all. */\n eligibleMethodCodes: string[]\n /** `required` (only the first deposit), `excluded` (never the first) or `any`. */\n firstDepositPolicy: 'any' | 'required' | 'excluded' | 'unspecified' | (string & {})\n /** Minimum deposit. */\n minimumSettledNetAmount?: CampaignMoney\n /** Maximum deposit considered. */\n maximumSettledNetAmount?: CampaignMoney\n /** Value basis (e.g. `settled_net_deposit`). */\n amountBasis: string\n}\n\n/**\n * Qualification by activity accumulated over a window (e.g. net loss or total wagered).\n * @category Bonus\n */\nexport interface ActivityAggregateQualification {\n /** `net_loss` (net loss) or `settled_stake` (total wagered and settled). */\n basis: 'net_loss' | 'settled_stake' | 'unspecified' | (string & {})\n /** Product considered. */\n productScope: CampaignProductScope\n /** Currency. */\n currency: string\n /** Accumulation window, in seconds. */\n window?: number\n /** Window time zone. */\n timezone: string\n /** Tolerance for late events, in seconds. */\n lateEventGrace?: number\n /** Casino slice. */\n casino?: CasinoActivitySelector\n /** Sports betting slice. */\n sportsbook?: SportsActivitySelector\n}\n\n/**\n * What the player must do to qualify. Only one of the cases is filled in; `immediate`\n * means that joining already qualifies.\n * @category Bonus\n */\nexport interface CampaignQualification {\n /** Definition version. @beta */\n version: number\n /** Qualifies on joining. */\n immediate?: Record<string, never>\n /** Qualifies with a player event. */\n userEvent?: UserEventQualification\n /** Qualifies with a deposit. */\n depositSettled?: DepositSettledQualification\n /** Qualifies with accumulated activity. */\n activityAggregate?: ActivityAggregateQualification\n}\n\n// ─── Reward ──────────────────────────────────────────────────────────────────────────────────────\n\n/**\n * Reward validity: only one of the cases is filled in.\n * @category Bonus\n */\nexport interface CampaignRewardValidity {\n /** Does not expire. */\n noExpiry?: Record<string, never>\n /** Expires on a fixed date. */\n absoluteExpiry?: {\n /** Expiration date, ISO 8601 (UTC). */\n expiresAt?: string\n }\n /** Expires some time after the grant. */\n durationFromGrant?: {\n /** Duration, in seconds. */\n duration?: number\n }\n}\n\n/**\n * Percentage calculation over a source value (e.g. 100% of the deposit up to R$ 500) or over an\n * accumulated amount (rebate).\n * @category Bonus\n */\nexport interface CampaignPercentCalculation {\n /** Percentage. */\n percentage?: CampaignExactRatio\n /** Rounding. */\n rounding: CampaignRoundingMode\n /** Minimum reward. */\n minimumReward?: CampaignMoney\n /** Maximum reward. */\n maximumReward?: CampaignMoney\n}\n\n/**\n * Balance credit reward. The value comes from one of the three calculations.\n * @category Bonus\n */\nexport interface BalanceCreditReward {\n /** Fixed value. */\n fixedAmount?: {\n /** Reward value. */\n amount?: CampaignMoney\n }\n /** Percentage of the source value (e.g. of the deposit). */\n percentOfSourceAmount?: CampaignPercentCalculation\n /** Rebate over an accumulated amount. */\n aggregateRebate?: {\n /** Percentage. */\n percentage?: CampaignExactRatio\n /** Rounding. */\n rounding: CampaignRoundingMode\n /** Minimum base for there to be a reward. */\n minimumBasis?: CampaignMoney\n /** Maximum reward. */\n maximumReward?: CampaignMoney\n }\n /** Balance credited: `real` or `restricted` (bonus, with usage rules). */\n balanceClass: 'real' | 'restricted' | 'unspecified' | (string & {})\n /** Winnings from the reward: `real` or restricted until the rollover is met. */\n proceedsClass: 'real' | 'restricted_until_wagering_completion' | 'unspecified' | (string & {})\n /** Validity. */\n validity?: CampaignRewardValidity\n}\n\n/**\n * Free spins reward.\n * @category Bonus\n */\nexport interface CasinoFreeSpinsReward {\n /** Spin provider. */\n providerCode: string\n /** Games where the spins apply. */\n casinoScope?: CasinoActivitySelector\n /** Number of spins. */\n quantity: number\n /** Value of each spin. */\n denomination?: CampaignMoney\n /** Currency. */\n currency: string\n /** Window to use the spins. */\n grantWindow?: CampaignTimeWindow\n /** Winnings from the spins: `real` or restricted until the rollover is met. */\n proceedsClass: 'real' | 'restricted_until_wagering_completion' | 'unspecified' | (string & {})\n /** Maximum win. */\n maximumWinnings?: CampaignMoney\n}\n\n/**\n * Free sports bet reward.\n * @category Bonus\n */\nexport interface SportsBonusBetReward {\n /** Sportsbook provider. */\n providerCode: string\n /** Where the bet applies. */\n sportsbookScope?: SportsActivitySelector\n /** Value of each bet. */\n amount?: CampaignMoney\n /** Number of bets. */\n quantity: number\n /** Validity. */\n validity?: CampaignRewardValidity\n}\n\n/**\n * Sports bet coverage reward (returns the lost bet up to a cap).\n * @category Bonus\n */\nexport interface SportsBetCoverageReward {\n /** Sportsbook provider. */\n providerCode: string\n /** Bets covered. */\n qualifyingBetScope?: SportsActivitySelector\n /** Cap of the coverage. */\n coverageCap?: CampaignMoney\n /** Validity. */\n validity?: CampaignRewardValidity\n}\n\n/**\n * Maximum bet with bonus balance.\n * Mirrors the bonus service protobuf and may change in 0.x (minor) versions.\n * @beta\n * @category Bonus\n */\nexport interface CampaignMaximumBet {\n /** `product_limit_only` (only the product's limit) or `campaign_maximum` (the `campaignMaximum` one). */\n mode: 'product_limit_only' | 'campaign_maximum' | 'unspecified' | (string & {})\n /** Maximum bet of the campaign. */\n campaignMaximum?: CampaignMoney\n}\n\n/**\n * Sports betting odds rules.\n * Mirrors the bonus service protobuf and may change in 0.x (minor) versions.\n * @beta\n * @category Bonus\n */\nexport interface CampaignOddsPolicy {\n /** `all_product_accepted_odds` or `threshold` (uses the minimums below). */\n mode: 'all_product_accepted_odds' | 'threshold' | 'unspecified' | (string & {})\n /** Minimum total odds, decimal as text. */\n minimumTotalOddsDecimal?: string\n /** Minimum odds per selection, decimal as text. */\n minimumOddsPerLegDecimal?: string\n /** Minimum number of selections. */\n minimumLegs?: number\n /** Maximum number of selections. */\n maximumLegs?: number\n}\n\n/**\n * Cash out of bets made with restricted balance.\n * Mirrors the bonus service protobuf and may change in 0.x (minor) versions.\n * @beta\n * @category Bonus\n */\nexport type CampaignCashoutMode =\n | 'disallow_for_restricted_funding'\n | 'allow_without_wagering_contribution'\n | 'unspecified'\n | (string & {})\n\n/**\n * Where and how the bonus balance can be used. Only one of the cases (`casino`, `sportsbook`,\n * `casinoAndSportsbook`) is filled in.\n * Mirrors the bonus service protobuf and may change in 0.x (minor) versions.\n * @beta\n * @category Bonus\n */\nexport interface CampaignUsePolicy {\n /** Version. */\n version: number\n /** Consumption order: `real_then_restricted` or `restricted_then_real`. */\n fundsConsumption?: CampaignPolicy<'real_then_restricted' | 'restricted_then_real' | 'unspecified' | (string & {})>\n /** Casino use. */\n casino?: {\n /** Allowed slices. */\n allowedScopes: CasinoActivitySelector[]\n /** Maximum bet. */\n maximumBet?: CampaignMaximumBet\n }\n /** Sports betting use. */\n sportsbook?: {\n /** Allowed slices. */\n allowedScopes: SportsActivitySelector[]\n /** Excluded slices. */\n excludedScopes: SportsActivitySelector[]\n /** Maximum bet. */\n maximumBet?: CampaignMaximumBet\n /** Required odds. */\n fundingOdds?: CampaignOddsPolicy\n /** Cash out. */\n cashoutMode: CampaignCashoutMode\n }\n /** Use in casino and sports betting. */\n casinoAndSportsbook?: {\n /** Allowed casino slices. */\n allowedCasinoScopes: CasinoActivitySelector[]\n /** Allowed sports slices. */\n allowedSportsbookScopes: SportsActivitySelector[]\n /** Excluded sports slices. */\n excludedSportsbookScopes: SportsActivitySelector[]\n /** Maximum casino bet. */\n maximumCasinoBet?: CampaignMaximumBet\n /** Maximum sports bet. */\n maximumSportsbookBet?: CampaignMaximumBet\n /** Required odds. */\n sportsbookFundingOdds?: CampaignOddsPolicy\n /** Cash out. */\n sportsbookCashoutMode: CampaignCashoutMode\n }\n /** Split of winnings between real and restricted balance (e.g. `proportional_to_funding`). */\n payoutAllocation?: CampaignPolicy<string>\n}\n\n/**\n * Rollover (wagering requirement) of the reward: `none` (no rollover) or `multiplier`.\n * Mirrors the bonus service protobuf and may change in 0.x (minor) versions.\n * @beta\n * @category Bonus\n */\nexport interface CampaignWageringPolicy {\n /** Version. */\n version: number\n /** No rollover. */\n none?: Record<string, never>\n /** Rollover by multiplier (e.g. 30x the bonus). */\n multiplier?: {\n /** Basis: `granted_balance` (the bonus granted) or `reward_proceeds` (the reward's winnings). */\n requirementBasis: 'granted_balance' | 'reward_proceeds' | 'unspecified' | (string & {})\n /** Multiplier (e.g. `{ decimal: '30' }` = 30x). */\n multiplier?: CampaignExactRatio\n /** How much each bet type counts toward the rollover. */\n contributionRates: {\n /** Casino slice. */\n casino?: CasinoActivitySelector\n /** Sports slice. */\n sportsbook?: SportsActivitySelector\n /** Contribution rate (10000 basis points = 100%). */\n rate?: CampaignExactRatio\n }[]\n /** Deadline to complete. */\n deadline?: CampaignRewardValidity\n /** Rounding. */\n rounding: CampaignRoundingMode\n /** Minimum odds for the sports bet to count. */\n sportsbookContributionOdds?: CampaignOddsPolicy\n /**\n * Ceiling on the restricted balance that becomes real money when the rollover completes (\"maximum\n * withdrawal\"): the remainder above it is forfeited. Absent: the whole remaining balance converts.\n */\n maximumConversion?: CampaignMoney\n }\n}\n\n/**\n * Stacking with other campaigns of the same group: only one of the cases is filled in.\n * Mirrors the bonus service protobuf and may change in 0.x (minor) versions.\n * @beta\n * @category Bonus\n */\nexport interface CampaignStackingPolicy {\n /** Version. */\n version: number\n /** Exclusive in the group (one active at a time). */\n exclusiveInGroup?: {\n /** Group. */\n stackingGroupKey: string\n }\n /** Several in the group, up to a maximum per player. */\n multipleInGroup?: {\n /** Group. */\n stackingGroupKey: string\n /** Maximum active per player. */\n maximumActivePerPlayer: number\n }\n}\n\n/**\n * Reward of a campaign. `rewardKind` says which of the details (`balanceCredit`, `casinoFreeSpins`,\n * `sportsBonusBet`, `sportsBetCoverage`, `providerManagedBalance`) is filled in.\n * @category Bonus\n */\nexport interface CampaignReward {\n /** Reward key in the campaign. */\n rewardKey: string\n /** Reward type. */\n rewardKind: CampaignRewardKind\n /** Type version. @beta */\n rewardKindVersion: number\n /** Who executes the reward (e.g. `engine_managed_balance`, `provider_entitlement`). @beta */\n executionProfileCode:\n | 'engine_managed_balance'\n | 'provider_managed_balance'\n | 'provider_entitlement'\n | 'unspecified'\n | (string & {})\n /** Execution profile version. @beta */\n executionProfileVersion: number\n /** Balance credit. */\n balanceCredit?: BalanceCreditReward\n /** Provider-managed balance. */\n providerManagedBalance?: {\n /** Provider. */\n providerCode: string\n }\n /** Free spins. */\n casinoFreeSpins?: CasinoFreeSpinsReward\n /** Free sports bet. */\n sportsBonusBet?: SportsBonusBetReward\n /** Sports bet coverage. */\n sportsBetCoverage?: SportsBetCoverageReward\n /** Where the bonus balance can be used. */\n usePolicy?: CampaignUsePolicy\n /** Rollover. */\n wageringPolicy?: CampaignWageringPolicy\n /** Stacking with other campaigns. */\n stackingPolicy?: CampaignStackingPolicy\n /** Consumption order among restricted balances. @beta */\n restrictedPositionSelectionPolicy?: {\n /** Version. */\n version: number\n /** Priority and then the nearest expiration. */\n priorityThenEarliestExpiry?: {\n /** Selection priority. */\n selectionPriority?: number\n }\n }\n}\n\n// ─── Content, offer and participation ─────────────────────────────────────────────────────────────\n\n/**\n * Texts of a campaign in one language.\n * @category Bonus\n */\nexport interface CampaignLocalizedContent {\n /** Language, e.g. `pt-BR`. */\n locale: string\n /** Display name. */\n displayName: string\n /** Description. */\n description: string\n /** Terms and conditions. */\n terms: string\n /** Terms revision: send it on acceptance (`termsAcceptance.termsRevision`). */\n termsRevision: string\n}\n\n/**\n * Texts of a campaign in all published languages. Pick the one for the app's `locale` or, without it,\n * the one for `defaultLocale`.\n * @category Bonus\n */\nexport interface CampaignContent {\n /** Default language. */\n defaultLocale: string\n /** Published languages. */\n supportedLocales: string[]\n /** Texts by language. */\n localizedContent: CampaignLocalizedContent[]\n}\n\n/**\n * Bonus campaign offer (a published version of the campaign).\n * @category Bonus\n */\nexport interface CampaignOffer {\n /** Campaign id, for {@link BonusApi.getOffer} and {@link BonusApi.optIn}. */\n campaignId: string\n /** Published version, required in {@link BonusApi.optIn}. */\n campaignVersionId: string\n /** Publication id. */\n publicationId: string\n /** Product where it applies. */\n productScope: CampaignProductScope\n /** Time zone of the windows. */\n timezone: string\n /** When it is possible to join. */\n enrollmentWindow?: CampaignTimeWindow\n /** When it is possible to qualify. */\n qualificationWindow?: CampaignTimeWindow\n /** When it is possible to redeem (`player_claim` policy). */\n claimWindow?: CampaignTimeWindow\n /** How to join: `automatic`, `opt_in`, `promo_code` or `manual`. */\n entryPolicy?: CampaignPolicy<CampaignEntryPolicyCode>\n /** How to receive the reward: `automatic` or `player_claim`. */\n rewardClaimPolicy?: CampaignPolicy<CampaignRewardClaimPolicyCode>\n /** What is needed to qualify. */\n qualification?: CampaignQualification\n /** Reward. */\n reward?: CampaignReward\n /** Publication start, ISO 8601 (UTC). */\n publicationStartsAt?: string\n /** Publication end, ISO 8601 (UTC). */\n publicationEndsAt?: string\n /** Texts (name, description, terms) by language. */\n content?: CampaignContent\n}\n\n/**\n * Status of the player's participation in a campaign: `enrolled` (joined), `qualifying`\n * (in progress), `qualified` (done; with `player_claim`, can now redeem), `reward_pending`\n * (reward being granted), `completed` (reward granted), `reward_failed`, `expired` or\n * `cancelled`. A new value the SDK does not know yet may arrive: handle the default case.\n * @category Bonus\n */\nexport type CampaignParticipationStatus =\n | 'enrolled'\n | 'qualifying'\n | 'qualified'\n | 'reward_pending'\n | 'completed'\n | 'reward_failed'\n | 'expired'\n | 'cancelled'\n | 'unspecified'\n | (string & {})\n\n/**\n * Acceptance of the terms recorded in the participation.\n * @category Bonus\n */\nexport interface CampaignTermsAcceptanceRecord {\n /** Language of the accepted terms. */\n locale: string\n /** Accepted revision. */\n termsRevision: string\n /** SHA-256 (hex) of the accepted text. */\n termsDigestSha256Hex: string\n /** Acceptance date, ISO 8601 (UTC). */\n acceptedAt?: string\n}\n\n/**\n * Where the bonus balance granted by a participation stands: `active` (still to wager or to use),\n * `converted` (became real balance), `expired` or `forfeited` (e.g. lost to a withdrawal). A new value the SDK\n * does not know yet may arrive: handle the default case.\n * @category Bonus\n */\nexport type CampaignRewardGrantState = 'active' | 'converted' | 'expired' | 'forfeited' | 'unspecified' | (string & {})\n\n/**\n * Rollover progress of a granted bonus.\n * @category Bonus\n */\nexport interface CampaignWageringProgress {\n /** Amount to wager. */\n required: CampaignMoney\n /** Amount already wagered. */\n accumulated: CampaignMoney\n /** When the rollover was completed, ISO 8601 (UTC). */\n completedAt?: string\n}\n\n/**\n * The bonus balance a participation granted. protojson leaves zeros out: a missing amount comes as `0` in the\n * currency of the grant's other amounts (or `''` when none has one).\n * @category Bonus\n */\nexport interface CampaignRewardGrant {\n /** Where the balance stands. An `active` grant keeps the bonus among the player's active ones even after the participation completed. */\n state: CampaignRewardGrantState\n /** Amount granted. */\n granted: CampaignMoney\n /** Bonus balance left. */\n balance: CampaignMoney\n /** Amount converted to real balance. */\n converted: CampaignMoney\n /** When the bonus balance expires, ISO 8601 (UTC). */\n expiresAt?: string\n /** Rollover progress, when the bonus has a wagering requirement. */\n wagering?: CampaignWageringProgress\n}\n\n/**\n * The player's participation in a campaign, with the reward and the texts as they were when they joined.\n * @category Bonus\n */\nexport interface CampaignParticipation {\n /** Participation id, for {@link BonusApi.claim} and {@link BonusApi.getParticipation}. */\n id: string\n /** Campaign id. */\n campaignId: string\n /** Campaign version the player joined. */\n campaignVersionId: string\n /** Reward key. */\n rewardKey: string\n /** Required qualification (a copy from the time of joining). */\n qualificationSnapshot?: CampaignQualification\n /** Status. */\n status: CampaignParticipationStatus\n /** When it qualified (`status: 'qualified'`). */\n qualifiedAt?: string\n /** When the reward was granted (`status: 'completed'`). */\n completedAt?: string\n /** When it expired (`status: 'expired'`). */\n expiredAt?: string\n /** Reward, texts and terms acceptance as of the time of joining. */\n snapshot?: {\n /** Reward. */\n reward?: CampaignReward\n /** Texts. */\n content?: CampaignContent\n /** Terms acceptance, if there was one. */\n termsAcceptance?: CampaignTermsAcceptanceRecord\n }\n /** The bonus balance granted, once the reward was credited; missing before that. */\n rewardGrant?: CampaignRewardGrant\n}\n\n/**\n * Terms acceptance of the campaign, sent on opt-in or on promo code redemption.\n * @category Bonus\n */\nexport interface CampaignTermsAcceptance {\n /** Language of the terms shown ({@link CampaignLocalizedContent.locale}). */\n locale: string\n /** Revision of the terms shown ({@link CampaignLocalizedContent.termsRevision}). */\n termsRevision: string\n}\n\n/**\n * Input of {@link BonusApi.optIn}.\n * @category Bonus\n */\nexport interface OptInInput {\n /** Campaign id ({@link CampaignOffer.campaignId}). */\n campaignId: string\n /** Version shown to the player ({@link CampaignOffer.campaignVersionId}). */\n campaignVersionId: string\n /** Acceptance of the terms shown. */\n termsAcceptance?: CampaignTermsAcceptance\n}\n\n/**\n * Offer of a promo code, returned by {@link BonusApi.resolvePromoCode}.\n * @category Bonus\n */\nexport interface PromoCodeOffer {\n /** The offer. */\n offer: CampaignOffer\n /** The texts in the requested language. */\n localizedContent: CampaignLocalizedContent\n}\n\n// ─── The player's bonus balance ──────────────────────────────────────────────────────────────────\n\n/**\n * The player's restricted bonus balance in one currency (amounts in minor units of `currency`; amounts of\n * different currencies are never added).\n * @category Bonus\n */\nexport interface BonusOverviewCurrency {\n /** Currency code, e.g. `BRL`. */\n currency: string\n /** Decimal places of the currency, to format the amounts. */\n decimalPlaces: number\n /** Bonus balance in open positions. */\n restrictedTotal: number\n /** Part of `restrictedTotal` whose position expires in the next 7 days. */\n expiring7d: number\n /** Open bonus positions. */\n openPositions: number\n /** Nearest expiry among the open positions, ISO 8601 (UTC). */\n nextExpiresAt?: string\n /** Bonus balance already converted to real balance. */\n converted: number\n /** Campaigns with a conversion above zero. */\n convertedCampaigns: number\n}\n\n/**\n * Result of {@link BonusApi.getOverview}.\n * @category Bonus\n */\nexport interface BonusOverview {\n /** One line per currency; empty for a player without bonus history. */\n currencies: BonusOverviewCurrency[]\n /** When the figures were computed, ISO 8601 (UTC). */\n asOf?: string\n}\n\n/**\n * State of a bonus position: `open` or `terminal`. A new value may arrive.\n * @category Bonus\n */\nexport type BonusPositionState = 'open' | 'terminal' | (string & {})\n\n/**\n * How a terminal position ended, in lowercase: `expire`, `forfeit`, `convert` or `admin_cancel`.\n * @category Bonus\n */\nexport type BonusPositionTerminalAction = 'expire' | 'forfeit' | 'convert' | 'admin_cancel' | (string & {})\n\n/**\n * One bonus position of the player (the restricted balance of one grant) with its rollover progress. Amounts\n * in minor units of `currency`.\n * @category Bonus\n */\nexport interface BonusPosition {\n /** Position id. */\n positionId: string\n /** Campaign id: the name to show comes from the campaign's offer (`localizedContent`). */\n campaignId: string\n /** Currency code, e.g. `BRL`. */\n currency: string\n /** Decimal places of the currency. */\n decimalPlaces: number\n /** Amount granted. */\n granted: number\n /** Bonus balance left. */\n restricted: number\n /** Converted to real balance. */\n converted: number\n /** Amount to wager. */\n required: number\n /** Already wagered. */\n wagered: number\n /** Still to wager. */\n remaining: number\n /** `open` or `terminal`. */\n state: BonusPositionState\n /** How it ended (terminal positions only). */\n terminalAction?: BonusPositionTerminalAction\n /** When the bonus balance expires, ISO 8601 (UTC). */\n expiresAt?: string\n /** When the position was created, ISO 8601 (UTC). */\n createdAt?: string\n}\n\n/**\n * Filters and pagination of {@link BonusApi.listPositions}. On the wire `pageSize` goes as `limit` (1 to 100,\n * gateway default 25).\n * @category Bonus\n */\nexport interface ListBonusPositionsInput extends CursorPageInput {\n /** Only open or only terminal positions. Default: all. */\n state?: 'open' | 'terminal'\n /** Currency code. Default: all. */\n currency?: string\n}\n\n/**\n * Bonus campaigns and promo codes. Only `listPublicOffers` is public; the other methods require login.\n * @category Bonus\n */\nexport interface BonusApi {\n /**\n * Public catalog of offers (storefront, no login): it only describes the campaigns; eligibility,\n * joining and participations require login. Cursor-paginated.\n * @example\n * const { items, nextCursor } = await igaming.bonus.listPublicOffers({ pageSize: 20 })\n * @throws {EnginexError} `INVALID_ARGUMENT` (400) for a `pageSize` that is not a positive integer;\n * `UNAUTHENTICATED` (401) if the gateway does not resolve the operator by the domain.\n */\n listPublicOffers(input?: CursorPageInput, options?: CallOptions): Promise<CursorPage<CampaignOffer>>\n /**\n * Offers available to the logged-in player. Cursor-paginated.\n * @example\n * const { items } = await igaming.bonus.listOffers()\n * const optIns = items.filter((o) => o.entryPolicy?.code === 'opt_in')\n * @throws {EnginexError} `INVALID_ARGUMENT` (400) for an invalid `pageSize`; `UNAUTHENTICATED` without a session.\n */\n listOffers(input?: CursorPageInput, options?: CallOptions): Promise<CursorPage<CampaignOffer>>\n /**\n * An offer available to the player.\n * @example\n * const offer = await igaming.bonus.getOffer({ campaignId })\n * @throws {EnginexError} `BONUS_NOT_FOUND` (404) if the campaign does not exist or is not\n * available; `INVALID_ARGUMENT` (400) if `campaignId` is not a UUID; `UNAUTHENTICATED` without a session.\n */\n getOffer(input: { campaignId: string }, options?: CallOptions): Promise<CampaignOffer>\n /**\n * Joins an `opt_in` campaign. **Idempotent**: it sends `Idempotency-Key` — generated on\n * every call, or the one in `options.idempotencyKey` — and keeps it on the retry after renewing the session; to\n * repeat after `NETWORK_ERROR`/`TIMEOUT` without joining twice, generate the key beforehand and pass the\n * same one on both attempts. The response is always validated in strict mode.\n * @example\n * const participation = await igaming.bonus.optIn(\n * { campaignId: offer.campaignId, campaignVersionId: offer.campaignVersionId, termsAcceptance: { locale: 'pt-BR', termsRevision: text.termsRevision } },\n * { idempotencyKey: key },\n * )\n * @throws {EnginexError} `BONUS_NOT_ELIGIBLE` if the player cannot join; `BONUS_EXPIRED` outside\n * the entry window (the gateway still returns these two with HTTP 500: identify by the code);\n * `BONUS_NOT_FOUND` (404); `ALREADY_EXISTS`/`BONUS_ALREADY_CLAIMED` (409) if the player already\n * participates; `KYC_REQUIRED`/`FAILED_PRECONDITION` (422) for a precondition (e.g. KYC, terms);\n * `INVALID_ARGUMENT` (400) for ids that are not UUIDs or a malformed idempotency key;\n * `KEY_IN_USE` (409) with the same key still being processed; `PAYLOAD_MISMATCH` (422) if the key\n * was already used with another body; `VALIDATION_ERROR` if the response comes outside the format (the entry\n * may have happened: check `listParticipations`); `UNAUTHENTICATED` without a session.\n */\n optIn(input: OptInInput, options?: CallOptions): Promise<CampaignParticipation>\n /**\n * Redeems the reward of a qualified participation (campaigns with `player_claim`).\n * **Idempotent**, like {@link BonusApi.optIn}: repeat with the same `idempotencyKey` so as not to\n * redeem twice. The response is always validated in strict mode.\n * @example\n * const done = await igaming.bonus.claim({ participationId: participation.id }, { idempotencyKey: key })\n * @throws {EnginexError} `BONUS_ALREADY_CLAIMED` (409) if the reward was already redeemed;\n * `BONUS_EXPIRED` outside the redemption window and `BONUS_NOT_ELIGIBLE` if it has not qualified yet (HTTP\n * 500 on the gateway: identify by the code); `FAILED_PRECONDITION`/`KYC_REQUIRED` (422);\n * `BONUS_NOT_FOUND` (404); `INVALID_ARGUMENT` (400) for an id that is not a UUID; `KEY_IN_USE` (409);\n * `PAYLOAD_MISMATCH` (422); `VALIDATION_ERROR` if the response comes outside the format (the redemption may\n * have happened: check `getParticipation`); `UNAUTHENTICATED` without a session.\n */\n claim(input: { participationId: string }, options?: CallOptions): Promise<CampaignParticipation>\n /**\n * Shows the offer of a promo code before redemption (name, description and terms in the requested language).\n * It does not join the campaign. The code is a secret: it goes only in the body, never in the URL or the hooks.\n * @example\n * const { offer, localizedContent } = await igaming.bonus.resolvePromoCode({ code: input.value, locale: 'pt-BR' })\n * @throws {EnginexError} `BONUS_NOT_FOUND` (404) for a nonexistent or inactive code;\n * `BONUS_EXPIRED`/`BONUS_NOT_ELIGIBLE` (HTTP 500 on the gateway: identify by the code);\n * `RESOURCE_EXHAUSTED` (429) due to the attempt limit (see `e.retryAfter`); `UNAVAILABLE` (503)\n * if the gateway's limiter is down (the route fails closed for safety); `UNAUTHENTICATED` without a session.\n */\n resolvePromoCode(input: { code: string; locale: string }, options?: CallOptions): Promise<PromoCodeOffer>\n /**\n * Redeems a promo code: joins the code's campaign. **Idempotent** (the gateway requires the key):\n * repeat with the same `idempotencyKey` so as not to redeem twice. The response is always validated\n * in strict mode. The code goes only in the body.\n * @example\n * const participation = await igaming.bonus.redeemPromoCode(\n * { code: 'BEMVINDO', termsAcceptance: { locale: 'pt-BR', termsRevision: localizedContent.termsRevision } },\n * { idempotencyKey: key },\n * )\n * @throws {EnginexError} `BONUS_NOT_FOUND` (404) for a nonexistent code;\n * `BONUS_ALREADY_CLAIMED` (409) if the player already used the code; `BONUS_EXPIRED`/`BONUS_NOT_ELIGIBLE`\n * (HTTP 500 on the gateway: identify by the code); `KYC_REQUIRED`/`FAILED_PRECONDITION` (422);\n * `RESOURCE_EXHAUSTED` (429) due to the per-player promo code attempt limit, the same as\n * `resolvePromoCode` (see `e.retryAfter`); `UNAVAILABLE` (503) if the gateway's limiter is\n * down (the route fails closed for safety); `INVALID_ARGUMENT` (400) for a malformed idempotency\n * key; `VALIDATION_ERROR` if the response comes outside the format (the redemption may have happened:\n * check `listParticipations`); `UNAUTHENTICATED` without a session.\n */\n redeemPromoCode(\n input: { code: string; termsAcceptance?: CampaignTermsAcceptance },\n options?: CallOptions,\n ): Promise<CampaignParticipation>\n /**\n * The player's participations. Cursor-paginated.\n * @example\n * const { items } = await igaming.bonus.listParticipations()\n * const claimable = items.filter((p) => p.status === 'qualified')\n * @throws {EnginexError} `INVALID_ARGUMENT` (400) for an invalid `pageSize`; `UNAUTHENTICATED` without a session.\n */\n listParticipations(input?: CursorPageInput, options?: CallOptions): Promise<CursorPage<CampaignParticipation>>\n /**\n * One of the player's participations.\n * @example\n * const p = await igaming.bonus.getParticipation({ participationId })\n * @throws {EnginexError} `BONUS_NOT_FOUND` (404) if it does not exist (or belongs to another player);\n * `INVALID_ARGUMENT` (400) if the id is not a UUID; `UNAUTHENTICATED` without a session.\n */\n getParticipation(input: { participationId: string }, options?: CallOptions): Promise<CampaignParticipation>\n /**\n * The player's restricted bonus balance, one line per currency: total, what expires in 7 days, open\n * positions and what was converted to real balance.\n * @example\n * const { currencies } = await igaming.bonus.getOverview()\n * const brl = currencies.find((c) => c.currency === 'BRL')\n * @throws {EnginexError} `UNAUTHENTICATED` without a session; `VALIDATION_ERROR`, also in `'warn'`, with money\n * outside the format.\n */\n getOverview(params?: NoParams, options?: CallOptions): Promise<BonusOverview>\n /**\n * The player's bonus positions with their rollover progress, newest first. Cursor-paginated.\n * @example\n * const { items } = await igaming.bonus.listPositions({ state: 'open' })\n * items.forEach((p) => showProgress(p.wagered, p.required))\n * @throws {EnginexError} `INVALID_ARGUMENT` (400) for a `pageSize` outside 1-100, an unknown `state` or an\n * unsupported currency; `UNAUTHENTICATED` without a session; `VALIDATION_ERROR`, also in `'warn'`, with money\n * outside the format.\n */\n listPositions(input?: ListBonusPositionsInput, options?: CallOptions): Promise<CursorPage<BonusPosition>>\n}\n\n// ─── Schemas ─────────────────────────────────────────────────────────────────────────────────────\n// Functions (not constants): they only build inside the `lazy`s below, never at import.\n\n// Currency of campaign values: `''` or ISO 4217, strict even in `'warn'`. protojson omits the empty\n// currency, and a `CampaignMoney` of value 0 (or the currency of a rule that applies to all) may come without\n// it: absent becomes `''`.\nconst campaignCurrency = () => z._default(currencyOrEmpty(), '')\n\nconst money = (): z.ZodMiniType<CampaignMoney> =>\n wire({ amount: z._default(minorUnits(), 0), currency: campaignCurrency() })\n\nconst timeWindow = (): z.ZodMiniType<CampaignTimeWindow> =>\n wire({ starts_at: z.optional(z.string()), ends_at: z.optional(z.string()) })\n\nconst ratio = (): z.ZodMiniType<CampaignExactRatio> =>\n wire({ decimal: z.optional(z.string()), basis_points: z.optional(z.number()), maximum_scale: count() })\n\nconst empty = (): z.ZodMiniType<Record<string, never>> => wire({}) as z.ZodMiniType<Record<string, never>>\n\nconst policy = <C extends string>(prefix: string) =>\n wire({ code: protoEnum(prefix), version: count() }) as unknown as z.ZodMiniType<CampaignPolicy<C>>\n\nconst casinoSelector = (): z.ZodMiniType<CasinoActivitySelector> =>\n wire({\n provider_instance_id: text(),\n software_ids: list(z.string()),\n game_ids: list(z.string()),\n category_codes: list(z.string()),\n })\n\nconst sportsSelector = (): z.ZodMiniType<SportsActivitySelector> =>\n wire({\n sport_codes: list(z.string()),\n competition_ids: list(z.string()),\n event_ids: list(z.string()),\n market_codes: list(z.string()),\n live: z.optional(z.boolean()),\n bet_types: list(protoEnum('SPORTS_BET_TYPE_')),\n })\n\nconst qualification = (): z.ZodMiniType<CampaignQualification> =>\n wire({\n version: count(),\n immediate: z.optional(empty()),\n user_event: z.optional(\n wire({\n event_code: text(),\n event_version: count(),\n source_authority: text(),\n identity_fields: list(z.string()),\n }),\n ),\n deposit_settled: z.optional(\n wire({\n currency: campaignCurrency(),\n eligible_method_codes: list(z.string()),\n first_deposit_policy: protoEnum('FIRST_DEPOSIT_POLICY_'),\n minimum_settled_net_amount: z.optional(money()),\n maximum_settled_net_amount: z.optional(money()),\n amount_basis: protoEnum('DEPOSIT_AMOUNT_BASIS_'),\n }),\n ),\n activity_aggregate: z.optional(\n wire({\n basis: protoEnum('BASIS_'),\n product_scope: protoEnum('PRODUCT_SCOPE_'),\n currency: campaignCurrency(),\n window: z.optional(durationSeconds()),\n timezone: text(),\n late_event_grace: z.optional(durationSeconds()),\n casino: z.optional(casinoSelector()),\n sportsbook: z.optional(sportsSelector()),\n }),\n ),\n })\n\nconst validity = (): z.ZodMiniType<CampaignRewardValidity> =>\n wire({\n no_expiry: z.optional(empty()),\n absolute_expiry: z.optional(wire({ expires_at: z.optional(z.string()) })),\n duration_from_grant: z.optional(wire({ duration: z.optional(durationSeconds()) })),\n })\n\nconst rounding = () => protoEnum('ROUNDING_MODE_')\nconst proceedsClass = () => protoEnum('PROCEEDS_CLASS_')\n\nconst percent = (): z.ZodMiniType<CampaignPercentCalculation> =>\n wire({\n percentage: z.optional(ratio()),\n rounding: rounding(),\n minimum_reward: z.optional(money()),\n maximum_reward: z.optional(money()),\n })\n\nconst balanceCredit = (): z.ZodMiniType<BalanceCreditReward> =>\n wire({\n fixed_amount: z.optional(wire({ amount: z.optional(money()) })),\n percent_of_source_amount: z.optional(percent()),\n aggregate_rebate: z.optional(\n wire({\n percentage: z.optional(ratio()),\n rounding: rounding(),\n minimum_basis: z.optional(money()),\n maximum_reward: z.optional(money()),\n }),\n ),\n balance_class: protoEnum('BALANCE_CLASS_'),\n proceeds_class: proceedsClass(),\n validity: z.optional(validity()),\n })\n\nconst maximumBet = (): z.ZodMiniType<CampaignMaximumBet> =>\n wire({ mode: protoEnum('MAXIMUM_BET_MODE_'), campaign_maximum: z.optional(money()) })\n\nconst oddsPolicy = (): z.ZodMiniType<CampaignOddsPolicy> =>\n wire({\n mode: protoEnum('MODE_'),\n minimum_total_odds_decimal: z.optional(z.string()),\n minimum_odds_per_leg_decimal: z.optional(z.string()),\n minimum_legs: z.optional(z.number()),\n maximum_legs: z.optional(z.number()),\n })\n\nconst cashoutMode = () => protoEnum('RESTRICTED_CASHOUT_MODE_')\n\nconst usePolicy = (): z.ZodMiniType<CampaignUsePolicy> =>\n wire({\n version: count(),\n funds_consumption: z.optional(policy('FUNDS_CONSUMPTION_POLICY_CODE_')),\n casino: z.optional(wire({ allowed_scopes: list(casinoSelector()), maximum_bet: z.optional(maximumBet()) })),\n sportsbook: z.optional(\n wire({\n allowed_scopes: list(sportsSelector()),\n excluded_scopes: list(sportsSelector()),\n maximum_bet: z.optional(maximumBet()),\n funding_odds: z.optional(oddsPolicy()),\n cashout_mode: cashoutMode(),\n }),\n ),\n casino_and_sportsbook: z.optional(\n wire({\n allowed_casino_scopes: list(casinoSelector()),\n allowed_sportsbook_scopes: list(sportsSelector()),\n excluded_sportsbook_scopes: list(sportsSelector()),\n maximum_casino_bet: z.optional(maximumBet()),\n maximum_sportsbook_bet: z.optional(maximumBet()),\n sportsbook_funding_odds: z.optional(oddsPolicy()),\n sportsbook_cashout_mode: cashoutMode(),\n }),\n ),\n payout_allocation: z.optional(policy('PAYOUT_ALLOCATION_POLICY_CODE_')),\n })\n\nconst wageringPolicy = (): z.ZodMiniType<CampaignWageringPolicy> =>\n wire({\n version: count(),\n none: z.optional(empty()),\n multiplier: z.optional(\n wire({\n requirement_basis: protoEnum('REQUIREMENT_BASIS_'),\n multiplier: z.optional(ratio()),\n contribution_rates: list(\n wire({\n casino: z.optional(casinoSelector()),\n sportsbook: z.optional(sportsSelector()),\n rate: z.optional(ratio()),\n }),\n ),\n deadline: z.optional(validity()),\n rounding: rounding(),\n sportsbook_contribution_odds: z.optional(oddsPolicy()),\n maximum_conversion: z.optional(money()),\n }),\n ),\n })\n\nconst stackingPolicy = (): z.ZodMiniType<CampaignStackingPolicy> =>\n wire({\n version: count(),\n exclusive_in_group: z.optional(wire({ stacking_group_key: text() })),\n multiple_in_group: z.optional(wire({ stacking_group_key: text(), maximum_active_per_player: count() })),\n })\n\nconst reward = (): z.ZodMiniType<CampaignReward> =>\n wire({\n reward_key: text(),\n reward_kind: protoEnum('REWARD_KIND_'),\n reward_kind_version: count(),\n execution_profile_code: protoEnum('EXECUTION_PROFILE_CODE_'),\n execution_profile_version: count(),\n balance_credit: z.optional(balanceCredit()),\n provider_managed_balance: z.optional(wire({ provider_code: text() })),\n casino_free_spins: z.optional(\n wire({\n provider_code: text(),\n casino_scope: z.optional(casinoSelector()),\n quantity: count(),\n denomination: z.optional(money()),\n currency: campaignCurrency(),\n grant_window: z.optional(timeWindow()),\n proceeds_class: proceedsClass(),\n maximum_winnings: z.optional(money()),\n }),\n ),\n sports_bonus_bet: z.optional(\n wire({\n provider_code: text(),\n sportsbook_scope: z.optional(sportsSelector()),\n amount: z.optional(money()),\n quantity: count(),\n validity: z.optional(validity()),\n }),\n ),\n sports_bet_coverage: z.optional(\n wire({\n provider_code: text(),\n qualifying_bet_scope: z.optional(sportsSelector()),\n coverage_cap: z.optional(money()),\n validity: z.optional(validity()),\n }),\n ),\n use_policy: z.optional(usePolicy()),\n wagering_policy: z.optional(wageringPolicy()),\n stacking_policy: z.optional(stackingPolicy()),\n restricted_position_selection_policy: z.optional(\n wire({\n version: count(),\n priority_then_earliest_expiry: z.optional(wire({ selection_priority: z.optional(z.number()) })),\n }),\n ),\n })\n\nconst localizedContent = (): z.ZodMiniType<CampaignLocalizedContent> =>\n wire({ locale: text(), display_name: text(), description: text(), terms: text(), terms_revision: text() })\n\nconst content = (): z.ZodMiniType<CampaignContent> =>\n wire({ default_locale: text(), supported_locales: list(z.string()), localized_content: list(localizedContent()) })\n\nconst offerSchema = /* @__PURE__ */ lazy(\n (): z.ZodMiniType<CampaignOffer> =>\n wire({\n campaign_id: text(),\n campaign_version_id: text(),\n publication_id: text(),\n product_scope: protoEnum('PRODUCT_SCOPE_'),\n timezone: text(),\n enrollment_window: z.optional(timeWindow()),\n qualification_window: z.optional(timeWindow()),\n claim_window: z.optional(timeWindow()),\n entry_policy: z.optional(policy<CampaignEntryPolicyCode>('ENTRY_POLICY_CODE_')),\n reward_claim_policy: z.optional(policy<CampaignRewardClaimPolicyCode>('REWARD_CLAIM_POLICY_CODE_')),\n qualification: z.optional(qualification()),\n reward: z.optional(reward()),\n publication_starts_at: z.optional(z.string()),\n publication_ends_at: z.optional(z.string()),\n content: z.optional(content()),\n }),\n)\n\n/** A grant's money: absent becomes `0` in the currency of the grant's other amounts. */\nfunction grantMoney(value: CampaignMoney | undefined, currency: string): CampaignMoney {\n return { amount: value?.amount ?? 0, currency: value?.currency || currency }\n}\n\nconst rewardGrant = (): z.ZodMiniType<CampaignRewardGrant> =>\n z.pipe(\n wire({\n state: protoEnum('CAMPAIGN_PLAYER_REWARD_GRANT_STATE_'),\n granted: z.optional(money()),\n balance: z.optional(money()),\n converted: z.optional(money()),\n expires_at: z.optional(z.string()),\n wagering: z.optional(\n wire({ required: z.optional(money()), accumulated: z.optional(money()), completed_at: z.optional(z.string()) }),\n ),\n }),\n z.transform(({ state, granted, balance, converted, expiresAt, wagering }): CampaignRewardGrant => {\n const currency =\n [granted, balance, converted, wagering?.required, wagering?.accumulated].find((m) => m?.currency)?.currency ??\n ''\n const out: CampaignRewardGrant = {\n state,\n granted: grantMoney(granted, currency),\n balance: grantMoney(balance, currency),\n converted: grantMoney(converted, currency),\n }\n if (expiresAt !== undefined) out.expiresAt = expiresAt\n if (wagering) {\n out.wagering = {\n required: grantMoney(wagering.required, currency),\n accumulated: grantMoney(wagering.accumulated, currency),\n }\n if (wagering.completedAt !== undefined) out.wagering.completedAt = wagering.completedAt\n }\n return out\n }),\n )\n\nconst participationSchema = /* @__PURE__ */ lazy(\n (): z.ZodMiniType<CampaignParticipation> =>\n z.pipe(\n wire({\n id: text(),\n campaign_id: text(),\n campaign_version_id: text(),\n reward_key: text(),\n qualification_snapshot: z.optional(qualification()),\n // oneof `state`: only one of the cases is filled in.\n enrolled: z.optional(empty()),\n qualifying: z.optional(empty()),\n qualified: z.optional(wire({ qualified_at: z.optional(z.string()) })),\n reward_pending: z.optional(empty()),\n completed: z.optional(wire({ completed_at: z.optional(z.string()) })),\n reward_failed: z.optional(empty()),\n expired: z.optional(wire({ expired_at: z.optional(z.string()) })),\n cancelled: z.optional(empty()),\n reward_grant: z.optional(rewardGrant()),\n snapshot: z.optional(\n wire({\n reward: z.optional(reward()),\n content: z.optional(content()),\n terms_acceptance: z.optional(\n wire({\n locale: text(),\n terms_revision: text(),\n terms_digest_sha256_hex: text(),\n accepted_at: z.optional(z.string()),\n }),\n ),\n }),\n ),\n }),\n // The oneof becomes `status` (+ the timestamp of the case); the oneof's keys are not passed on.\n z.transform(\n ({ enrolled, qualifying, qualified, rewardPending, completed, rewardFailed, expired, cancelled, ...rest }) => {\n const out: CampaignParticipation = { ...rest, status: 'unspecified' }\n if (enrolled) out.status = 'enrolled'\n else if (qualifying) out.status = 'qualifying'\n else if (qualified) {\n out.status = 'qualified'\n if (qualified.qualifiedAt !== undefined) out.qualifiedAt = qualified.qualifiedAt\n } else if (rewardPending) out.status = 'reward_pending'\n else if (completed) {\n out.status = 'completed'\n if (completed.completedAt !== undefined) out.completedAt = completed.completedAt\n } else if (rewardFailed) out.status = 'reward_failed'\n else if (expired) {\n out.status = 'expired'\n if (expired.expiredAt !== undefined) out.expiredAt = expired.expiredAt\n } else if (cancelled) out.status = 'cancelled'\n return out\n },\n ),\n ),\n)\n\nconst cursorPageSchema = <T>(key: string, item: z.ZodMiniType<T>) =>\n wire({ [key]: list(item), next_cursor: z.optional(z.string()) }) as unknown as z.ZodMiniType<\n Record<string, T[] | undefined> & { nextCursor?: string }\n >\n\nconst offersPage = /* @__PURE__ */ lazy(() => cursorPageSchema('offers', offerSchema()))\nconst participationsPage = /* @__PURE__ */ lazy(() => cursorPageSchema('participations', participationSchema()))\nconst offerEnvelope = /* @__PURE__ */ lazy(() => wire({ offer: offerSchema() }))\nconst participationEnvelope = /* @__PURE__ */ lazy(() => wire({ participation: participationSchema() }))\nconst promoCodeOfferSchema = /* @__PURE__ */ lazy(\n (): z.ZodMiniType<PromoCodeOffer> => wire({ offer: offerSchema(), localized_content: localizedContent() }),\n)\n\nfunction toCursorPage<T>(key: string, data: Record<string, T[] | undefined> & { nextCursor?: string }): CursorPage<T> {\n // `list()` turns an omitted (protojson) or `null` (nil slice) list into `[]`; in `warn` mode, an out-of-format\n // item arrives raw, but the list is still a list (recovery is per field, see `decode` in the core). The\n // `Array.isArray` guard keeps that promise with a core older than 0.11.1, whose `warn` delivers a list of the\n // wrong type (text, a number) as it came.\n const items = data[key]\n const page: CursorPage<T> = { items: Array.isArray(items) ? items : [] }\n // An empty cursor means \"no next page\" (protojson would omit it; the service may send `''`).\n if (data.nextCursor) page.nextCursor = data.nextCursor\n return page\n}\n\n// The overview and the positions are plain JSON (not protojson): every key is present, money as int64 text and\n// an absent timestamp as `null`, which becomes a missing key.\nconst nullableDate = () =>\n z.pipe(\n z.nullish(z.string()),\n z.transform((value) => value ?? undefined),\n )\n\n/** Drops the `undefined` values (the `null` dates), so they are missing keys. */\nfunction compact<T extends object>(value: T): T {\n return Object.fromEntries(Object.entries(value).filter(([, v]) => v !== undefined)) as T\n}\n\nconst overviewSchema = /* @__PURE__ */ lazy(\n (): z.ZodMiniType<BonusOverview> =>\n z.pipe(\n wire({\n currencies: list(\n z.pipe(\n wire({\n currency: currencyOrEmpty(),\n decimal_places: z.number(),\n restricted_total: minorUnits(),\n expiring_7d: minorUnits(),\n open_positions: z.number(),\n next_expires_at: nullableDate(),\n converted: minorUnits(),\n converted_campaigns: z.number(),\n }),\n z.transform(compact),\n ),\n ),\n as_of: nullableDate(),\n }),\n z.transform(compact),\n ),\n)\n\nconst positionsPage = /* @__PURE__ */ lazy(() =>\n wire({\n rows: list(\n z.pipe(\n wire({\n position_id: z.string(),\n campaign_id: z.string(),\n currency: currencyOrEmpty(),\n decimal_places: z.number(),\n granted: minorUnits(),\n restricted: minorUnits(),\n converted: minorUnits(),\n required: minorUnits(),\n wagered: minorUnits(),\n remaining: minorUnits(),\n state: z.string(),\n // The gateway answers `null` for an action it does not know; known ones are uppercase (`CONVERT`).\n terminal_action: z.pipe(\n z.nullish(z.string()),\n z.transform((value) => (value ? value.toLowerCase() : undefined)),\n ),\n expires_at: nullableDate(),\n created_at: nullableDate(),\n }),\n z.transform((row): BonusPosition => compact(row)),\n ),\n ),\n next_cursor: z.optional(z.string()),\n }),\n)\n\nconst terms = (acceptance: CampaignTermsAcceptance | undefined) =>\n acceptance && { locale: acceptance.locale, terms_revision: acceptance.termsRevision }\n\n/** Creates the `bonus` namespace. @internal */\nexport function createBonusApi(transport: ExtensionTransport): BonusApi {\n const listPage = <T>(\n path: string,\n key: string,\n schema: z.ZodMiniType<Record<string, T[] | undefined> & { nextCursor?: string }>,\n auth: 'none' | 'required',\n input: CursorPageInput | undefined,\n options: CallOptions | undefined,\n ) =>\n transport\n .request({\n method: 'GET',\n path,\n query: { page_size: input?.pageSize, cursor: input?.cursor },\n auth,\n schema,\n options,\n })\n .then((data) => toCursorPage<T>(key, data))\n\n const participationCall = (path: string, body: unknown, options: CallOptions | undefined) =>\n transport\n .request({\n method: 'POST',\n path,\n body,\n auth: 'required',\n idempotent: true,\n validation: 'strict',\n schema: participationEnvelope(),\n options,\n })\n .then((data) => data.participation)\n\n return {\n listPublicOffers: (input, options) =>\n listPage<CampaignOffer>('/bonus-campaigns/public-offers', 'offers', offersPage(), 'none', input, options),\n listOffers: (input, options) =>\n listPage<CampaignOffer>('/bonus-campaigns/offers', 'offers', offersPage(), 'required', input, options),\n getOffer: ({ campaignId }, options) =>\n transport\n .request({\n method: 'GET',\n path: `/bonus-campaigns/offers/${encodeURIComponent(campaignId)}`,\n auth: 'required',\n schema: offerEnvelope(),\n options,\n })\n .then((data) => data.offer),\n optIn: ({ campaignId, campaignVersionId, termsAcceptance }, options) =>\n participationCall(\n `/bonus-campaigns/offers/${encodeURIComponent(campaignId)}/opt-in`,\n { campaign_version_id: campaignVersionId, terms_acceptance: terms(termsAcceptance) },\n options,\n ),\n claim: ({ participationId }, options) =>\n participationCall(\n `/bonus-campaigns/participations/${encodeURIComponent(participationId)}/claim`,\n undefined,\n options,\n ),\n resolvePromoCode: ({ code, locale }, options) =>\n transport.request({\n method: 'POST',\n path: '/bonus-campaigns/promo-codes/resolve',\n body: { plaintext: code, locale },\n auth: 'required',\n schema: promoCodeOfferSchema(),\n options,\n }),\n redeemPromoCode: ({ code, termsAcceptance }, options) =>\n participationCall(\n '/bonus-campaigns/promo-codes/redeem',\n { plaintext: code, terms_acceptance: terms(termsAcceptance) },\n options,\n ),\n listParticipations: (input, options) =>\n listPage<CampaignParticipation>(\n '/bonus-campaigns/participations',\n 'participations',\n participationsPage(),\n 'required',\n input,\n options,\n ),\n getParticipation: ({ participationId }, options) =>\n transport\n .request({\n method: 'GET',\n path: `/bonus-campaigns/participations/${encodeURIComponent(participationId)}`,\n auth: 'required',\n schema: participationEnvelope(),\n options,\n })\n .then((data) => data.participation),\n getOverview: (_params, options) =>\n transport.request({\n method: 'GET',\n path: '/bonus/overview',\n auth: 'required',\n schema: overviewSchema(),\n options,\n }),\n listPositions: (input, options) =>\n transport\n .request({\n method: 'GET',\n path: '/bonus/positions',\n query: { limit: input?.pageSize, cursor: input?.cursor, state: input?.state, currency: input?.currency },\n auth: 'required',\n schema: positionsPage(),\n options,\n })\n .then(({ rows, nextCursor }) => {\n const page: CursorPage<BonusPosition> = { items: rows }\n if (nextCursor) page.nextCursor = nextCursor\n return page\n }),\n }\n}\n","// Public types come from the core's main entry: the /extension `.d.ts` exposes Zod, and this package's\n// public API cannot depend on it (check-api).\nimport type { CallOptions, NoParams, Page } from '@getenginex/sdk'\nimport { currencyCode, decimalPlaces, lazy, money, wire, type ExtensionTransport } from '@getenginex/sdk/extension'\nimport * as z from 'zod/mini'\nimport { rejectInput, type Route } from '../internal/input'\nimport { nullableList, optionalText } from '../internal/optional-values'\nimport { minorUnits, protoEnum } from '../internal/schemas'\n\n/**\n * Casino catalog game (`GET /games`, `GET /games/{id}`).\n * @category Casino\n */\nexport interface Game {\n /** Game id, for {@link CasinoApi.getGame} and {@link CasinoApi.launchGame}. */\n id: string\n /** Display name. */\n name: string\n /**\n * Provider id (the same as {@link GameProvider.id}). Treat it as an opaque identifier: depending on the\n * aggregator, it may be a code or the name itself (e.g. `Pragmatic Play`).\n */\n provider: string\n /** Category slug (the same as {@link GameCategory.slug}), e.g. `slots`. */\n category: string\n /** Game type, as the provider reports it (e.g. `slot`, `blackjack`, `roulette`); may come empty. */\n type: string\n /** Cover image URL; may come empty. */\n thumbnail: string\n /** Marked as new in the catalog. */\n isNew: boolean\n /** Marked as popular in the catalog. */\n isPopular: boolean\n /** Live game (live casino). */\n isLive: boolean\n /** Supports demo mode (`launchGame({ mode: 'demo' })`). */\n demoAvailable: boolean\n /** Return to player reported by the provider, as a percentage (e.g. `96.5`); `0` when not reported. */\n rtp: number\n /** Volatility reported by the provider (e.g. `low`, `medium`, `high`); may come empty. */\n volatility: string\n /** Sort priority set by the operator (lowest first). */\n priority: number\n}\n\n/**\n * Ordering of {@link CasinoApi.listGames}: `popular` (most played), `new` (newest) or `az`\n * (alphabetical). Omitted: the operator's default order.\n * @category Casino\n */\nexport type GameSort = 'popular' | 'new' | 'az'\n\n/**\n * The viewer's device, to filter the catalog: the casino leaves out the games that only run on the other\n * one. Any other value rejects with `CONFIGURATION_ERROR` before the request (the gateway would answer 400).\n * @category Casino\n */\nexport type GameDevice = 'mobile' | 'desktop'\n\n/**\n * Filters and pagination of {@link CasinoApi.listGames}.\n * @category Casino\n */\nexport interface ListGamesInput {\n /** Slug of a category from {@link CasinoApi.listCategories}. An unknown slug brings no games. */\n category?: string\n /** Id of a provider from {@link CasinoApi.listProviders}. */\n provider?: string\n /** Search by game name, up to 100 characters (above that, `INVALID_ARGUMENT`). */\n search?: string\n /**\n * Restricts the listing to these games (e.g. to validate favorites or recents saved in the app), up to 100\n * ids. Inactive games or ones outside the operator's catalog simply do not come back.\n */\n ids?: string[]\n /** Ordering. An unknown value is ignored by the gateway. */\n sort?: GameSort\n /**\n * The viewer's device: the casino leaves out the games that only run on the other one. Omitted: no device\n * filter (every game).\n */\n device?: GameDevice\n /** Page (starts at 1). Gateway default: 1. */\n page?: number\n /** Items per page, from 1 to 100. Gateway default: 20 (out of range also becomes 20). */\n perPage?: number\n}\n\n/**\n * State of the operator's casino, as the gateway reports it next to the game list\n * ({@link CasinoAvailability.status}): `available`, `no_casino_configured`, `temporarily_unavailable`,\n * `switching` (the operator is switching providers) or `maintenance`. A new value the SDK does not know yet\n * may arrive: handle the default case (e.g. as a generic empty state).\n * @category Casino\n */\nexport type CasinoAvailabilityStatus =\n | 'available'\n | 'no_casino_configured'\n | 'temporarily_unavailable'\n | 'switching'\n | 'maintenance'\n | (string & {})\n\n/**\n * Why the catalog may be empty or partial, without it being an error ({@link GamesPage.availability}).\n * @category Casino\n */\nexport interface CasinoAvailability {\n /**\n * State of the casino. The gateway reports an unset state as `available`, and so does the SDK for an\n * absent or empty one. An unknown value arrives in lowercase: decide in the app whether it opens the casino\n * (failing closed, e.g. as `temporarily_unavailable`, is the safe choice).\n */\n status: CasinoAvailabilityStatus\n /** Code of the operator's primary provider; `null` when the gateway sends none. */\n primaryProviderCode: string | null\n /** What the casino reports as missing (e.g. provider codes not yet set up); `[]` when nothing is. */\n missing: string[]\n}\n\n/**\n * A page of {@link CasinoApi.listGames}: the usual {@link Page} plus the casino's availability.\n * @category Casino\n */\nexport interface GamesPage extends Page<Game> {\n /**\n * State of the casino the gateway reports next to the list (maintenance, provider switch, temporary\n * unavailability, no casino configured). `null` when the gateway does not send it (an older gateway) or\n * the installed `@getenginex/sdk` is older than 0.11.0.\n */\n availability: CasinoAvailability | null\n}\n\n/**\n * Catalog category with active games (`GET /games/categories`).\n * @category Casino\n */\nexport interface GameCategory {\n /** Slug, for the `category` filter of {@link CasinoApi.listGames}. */\n slug: string\n /** Display name. */\n name: string\n /** Icon set by the operator (name or URL, depending on the setup); may come empty. */\n icon: string\n /** Number of active games in the category. */\n gameCount: number\n /** Sort priority set by the operator (lowest first). */\n priority: number\n}\n\n/**\n * Game provider with active games (`GET /games/providers`).\n * @category Casino\n */\nexport interface GameProvider {\n /**\n * Id, for the `provider` filter of {@link CasinoApi.listGames}. Opaque identifier: it may be a\n * code or the name itself (e.g. `Pragmatic Play`); pass it as it came.\n */\n id: string\n /** Display name. */\n name: string\n /** Number of games. */\n gameCount: number\n}\n\n/**\n * Input of {@link CasinoApi.launchGame}.\n * @category Casino\n */\nexport interface LaunchGameInput {\n /** Game id ({@link Game.id}). */\n gameId: string\n /** `real` (default) bets with the player's balance; `demo` opens demo mode, if the game supports it ({@link Game.demoAvailable}). */\n mode?: 'real' | 'demo'\n /** Opens the mobile version of the game, when the provider has one. Default: `false`. */\n isMobile?: boolean\n /**\n * Absolute URL (http/https) the game returns to on exit (the app's lobby). When omitted, the gateway\n * uses the request's `Origin` (or `Referer`) — the browser always sends it; on server calls\n * (SSR/Node) pass it explicitly.\n */\n returnUrl?: string\n /**\n * Absolute URL (http/https) of the app's deposit page: the provider shows it inside the game as a link\n * (e.g. when the balance runs out). The gateway forwards it only when it is absolute; anything else is\n * dropped without an error. Omitted: the game shows no deposit link.\n */\n depositUrl?: string\n /**\n * Game language (e.g. `pt-BR`). When omitted, the gateway uses the request's `Accept-Language`, which the SDK\n * fills in with the client's `locale` (see `enginex.setLocale`).\n */\n language?: string\n}\n\n/**\n * How the provider requires the game to be opened ({@link GameLaunch.launchTarget}): `iframe` (embedded in\n * the app's page), `redirect` (navigate the current tab to the game) or `new_tab` (open it in a new\n * tab or window). A new value the SDK does not know yet may arrive: handle the default case (e.g. as\n * `new_tab`, which works for any provider).\n * @category Casino\n */\nexport type LaunchTarget = 'iframe' | 'redirect' | 'new_tab' | (string & {})\n\n/**\n * Game opened by {@link CasinoApi.launchGame}.\n *\n * **Sensitive:** `gameUrl` carries the player's game session token. Use it only to open the game\n * (as {@link GameLaunch.launchTarget} says) and never log it to logs, analytics, error tracking, nor store it.\n * @category Casino\n */\nexport interface GameLaunch {\n /** Game session id (the same as {@link GameSession.id}). */\n sessionId: string\n /**\n * Game URL, with the game session token — do not log it. It may be absolute or relative\n * to the gateway, depending on the provider; it is never empty (a response without a URL is `VALIDATION_ERROR`).\n */\n gameUrl: string\n /**\n * How to open `gameUrl`: some providers refuse to run inside an iframe and need `redirect` or `new_tab`.\n * A response without it (an older gateway, or a custom mock) arrives as `iframe`, what the SDK documented\n * before the gateway sent this field.\n */\n launchTarget: LaunchTarget\n /** Code of the game's provider (e.g. `pragmatic-play`), as the gateway sends it; absent when it does not. */\n providerCode?: string\n /** Expiry of the game URL, ISO 8601 (UTC), when the provider reports one: open the game before it. */\n expiresAt?: string\n}\n\n/**\n * Status of a game session, without the gateway's `SESSION_STATUS_` prefix and in lowercase. A new\n * value the SDK does not know yet may arrive: handle the default case.\n * @category Casino\n */\nexport type GameSessionStatus = 'active' | 'ended' | 'unspecified' | (string & {})\n\n/**\n * The player's game session (`GET /games/sessions`). Opening a game ends the previous active session.\n * @category Casino\n */\nexport interface GameSession {\n /** Session id. */\n id: string\n /** Game id. */\n gameId: string\n /** Game name. */\n gameName: string\n /** Provider id. */\n provider: string\n /** Session start, ISO 8601 (UTC). */\n startTime: string\n /** Total wagered in the session, in minor units of the operator's currency. */\n totalBet: number\n /** Total won in the session, in minor units of the operator's currency. */\n totalWin: number\n /** Status, e.g. `active`. */\n status: GameSessionStatus\n}\n\n/**\n * Type of a casino movement (lowercase, without the `CASINO_TRANSACTION_TYPE_` prefix).\n * `reversal` reverses an already credited prize (debits the player); `refund` returns a bet. A new\n * value the SDK does not know yet may arrive: handle the default case.\n * @category Casino\n */\nexport type CasinoTransactionType =\n | 'bet'\n | 'win'\n | 'refund'\n | 'jackpot'\n | 'free_spin'\n | 'reversal'\n | 'unspecified'\n | (string & {})\n\n/**\n * Movement of a casino round (`GET /games/history`).\n * @category Casino\n */\nexport interface CasinoTransaction {\n /** Movement id. */\n id: string\n /** Game id. */\n gameId: string\n /** Game name. */\n gameName: string\n /** Round id (the bet and the prize of the same round share it). */\n roundId: string\n /** Type, e.g. `bet`, `win`. */\n type: CasinoTransactionType\n /** Value in minor units of `currency` (the gateway sends it as text; the SDK converts). */\n amount: number\n /** Currency code, e.g. `BRL`. */\n currency: string\n /** Decimal places of the currency (e.g. `2` for BRL), to format `amount`. */\n currencyDecimalPlaces: number\n /** Movement date, ISO 8601 (UTC). */\n createdAt: string\n}\n\n/**\n * Pagination of {@link CasinoApi.listSessions} and {@link CasinoApi.getHistory}.\n * @category Casino\n */\nexport interface CasinoPageInput {\n /** Page (starts at 1). Gateway default: 1. */\n page?: number\n /** Items per page, from 1 to 100. Gateway default: 20 (out of range also becomes 20). */\n perPage?: number\n}\n\n/**\n * Filters of {@link CasinoApi.getBiggestWinners}.\n * @category Casino\n */\nexport interface GetBiggestWinnersInput {\n /** How many winners (the casino service caps it; its default: 10). */\n limit?: number\n /** Window in days up to now. Omitted: the casino service's default. */\n days?: number\n}\n\n/**\n * Biggest prize of a round, for the casino home ranking (`GET /games/biggest-winners`).\n * @category Casino\n */\nexport interface BiggestWinner {\n /** Player name already masked by the gateway (e.g. `Jo***`); the player id never comes. */\n player: string\n /** Prize in minor units of `currency`. */\n amount: number\n /** Currency code, e.g. `BRL`. */\n currency: string\n /** Decimal places of the currency, to format `amount`. */\n currencyDecimalPlaces: number\n /** Game id. */\n gameId: string\n /** Game name. */\n gameName: string\n /** Prize date, ISO 8601 (UTC). */\n wonAt: string\n}\n\n/**\n * A published jackpot of the operator's lobby ({@link CasinoApi.listJackpots}).\n * @category Casino\n */\nexport interface CasinoJackpot {\n /** Public jackpot id (`jackpot_` + 64 hex characters), for {@link CasinoApi.listJackpotGames}. */\n id: string\n /** Display name. */\n name: string\n /** Currency code, always the one requested (e.g. `BRL`). */\n currency: string\n /**\n * Current value in minor units of `currency` (the gateway sends it as text; the SDK converts). Never\n * negative; a value that does not fit in a safe integer leaves the jackpot out instead of showing it rounded.\n */\n amount: number\n /** Decimal places of `currency` (the ISO 4217 ones, e.g. `2` for BRL, `0` for CLP, `3` for KWD), to format `amount`. */\n currencyDecimalPlaces: number\n}\n\n/**\n * The lobby's published jackpots ({@link CasinoApi.listJackpots}).\n * @category Casino\n */\nexport interface CasinoJackpots {\n /** Published jackpots in the requested currency, without repeated ids; `[]` when there are none. */\n items: CasinoJackpot[]\n /** Id of the featured jackpot, when it is one of `items`; otherwise `null`. */\n featuredId: string | null\n}\n\n/**\n * Input of {@link CasinoApi.listJackpots}.\n * @category Casino\n */\nexport interface ListJackpotsInput {\n /** The site's currency, ISO 4217 in uppercase (e.g. `BRL`, from `enginex.config.get()`). */\n currency: string\n}\n\n/**\n * Input of {@link CasinoApi.listJackpotGames}. Page 1 has no cursor; every next page needs the previous\n * page's {@link JackpotGamesPage.nextCursor}.\n * @category Casino\n */\nexport interface ListJackpotGamesInput {\n /** Jackpot id ({@link CasinoJackpot.id}). */\n jackpotId: string\n /** The site's currency, the same as in {@link CasinoApi.listJackpots}. */\n currency: string\n /** The viewer's device. Omitted: no device filter. */\n device?: GameDevice\n /** Page (starts at 1). Default: 1. Above 1 it requires `cursor`. */\n page?: number\n /** Items per page, from 1 to 48. Gateway default: 24. */\n perPage?: number\n /** The previous page's {@link JackpotGamesPage.nextCursor}. */\n cursor?: string\n}\n\n/**\n * How the jackpot's game list was resolved: `verified` (the games the provider confirms take part in the\n * jackpot) or `demonstration` (an illustrative selection). A new value may arrive: handle the default case.\n * @category Casino\n */\nexport type JackpotGamesMode = 'verified' | 'demonstration' | (string & {})\n\n/**\n * A page of a jackpot's games ({@link CasinoApi.listJackpotGames}), paginated by cursor.\n * @category Casino\n */\nexport interface JackpotGamesPage {\n /** Game cards on this page; `[]` when there are none. */\n items: Game[]\n /** How the list was resolved. */\n mode: JackpotGamesMode\n /** Page number, as requested. */\n page: number\n /** Items per page, as requested. */\n perPage: number\n /** Whether there is a next page. */\n hasNext: boolean\n /** Cursor for the next page (pass it with `page + 1`); `null` on the last one. */\n nextCursor: string | null\n}\n\n/**\n * Catalog, game launch and casino history. The catalog (`listGames`, `listCategories`,\n * `listProviders`, `getGame`) is public; the other methods require login.\n * @category Casino\n */\nexport interface CasinoApi {\n /**\n * Games of the operator's catalog, paginated and filterable. Public: it does not send the session, even with\n * login (the catalog does not depend on the player).\n *\n * Maintenance, a provider switch, temporary unavailability or an operator without a casino do **not**\n * become errors: the gateway answers 200 and reports the reason in {@link GamesPage.availability}, next to\n * the list. In those cases the list may come empty, without an error: branch on `availability.status`.\n * @example\n * const page = await igaming.casino.listGames({ category: 'slots', sort: 'popular', perPage: 24, device: 'mobile' })\n * if (page.availability?.status === 'maintenance') showMaintenance()\n * page.items.forEach((game) => renderCard(game.name, game.thumbnail))\n * @throws {EnginexError} `CONFIGURATION_ERROR` (no request) for a `device` other than `mobile`/`desktop`;\n * `INVALID_ARGUMENT` (400) for `search` above 100 characters or more than 100 `ids`;\n * `UNAVAILABLE`/`PROVIDER_ERROR` (503) only when the call to the casino service itself fails.\n */\n listGames(input?: ListGamesInput, options?: CallOptions): Promise<GamesPage>\n /**\n * Categories with active games, to build lobby tabs/filters. Public.\n * @example\n * const categories = await igaming.casino.listCategories()\n * categories.sort((a, b) => a.priority - b.priority)\n * @throws {EnginexError} `UNAVAILABLE`/`PROVIDER_ERROR` (503) when the call to the casino\n * service fails.\n */\n listCategories(params?: NoParams, options?: CallOptions): Promise<GameCategory[]>\n /**\n * Providers with active games. Public.\n * @example\n * const providers = await igaming.casino.listProviders()\n * @throws {EnginexError} `UNAVAILABLE`/`PROVIDER_ERROR` (503) when the call to the casino\n * service fails.\n */\n listProviders(params?: NoParams, options?: CallOptions): Promise<GameProvider[]>\n /**\n * A catalog game. Public.\n * @example\n * const game = await igaming.casino.getGame({ gameId: 'g-1' })\n * @throws {EnginexError} `GAME_NOT_FOUND` (404) if the id does not exist in the operator's catalog.\n */\n getGame(input: { gameId: string }, options?: CallOptions): Promise<Game>\n /**\n * Opens a game: creates the game session (ending the previous one, if any) and returns the URL and how to\n * open it ({@link GameLaunch.launchTarget}: in an iframe, by redirecting the tab, or in a new tab). Requires login, including in `demo` mode. It is not idempotent: each\n * call opens a new session.\n *\n * **The returned URL carries the game session token.** The SDK delivers it only in the return value: no\n * hook (`onRequest`/`onResponse`/`onError`) nor `onValidationIssue` receives it, and the response is always\n * validated in strict mode. Do not log it to logs, analytics or error tracking.\n * @example\n * const launch = await igaming.casino.launchGame({ gameId: game.id, isMobile: isPhone() })\n * // If gameUrl comes relative, resolve it against the gateway origin.\n * switch (launch.launchTarget) {\n * case 'iframe':\n * iframe.src = launch.gameUrl\n * break\n * case 'redirect':\n * window.location.assign(launch.gameUrl)\n * break\n * default: {\n * // 'new_tab', and any target the SDK does not know yet. Opened after an `await`, the tab may be\n * // blocked as a popup (`window.open` returns null): fall back to the current tab.\n * const tab = window.open(launch.gameUrl, '_blank')\n * if (tab) tab.opener = null\n * else window.location.assign(launch.gameUrl)\n * }\n * }\n * @throws {EnginexError} `GAME_NOT_FOUND` (404) for a nonexistent game; `FAILED_PRECONDITION` (422)\n * for an inactive game; `SELF_EXCLUDED` (422), `COOLING_OFF` or `ACCOUNT_BLOCKED` when responsible\n * gaming blocks the player (outside demo mode); `UNAVAILABLE` (503) when the casino cannot\n * verify the player's restrictions; `PROVIDER_ERROR` (503) and `CASINO_UNAVAILABLE`\n * (codes defined in `enginex-commons` for provider/casino failures; treat them as\n * unavailability); `VALIDATION_ERROR` if the response comes without `sessionId` or without `gameUrl`;\n * `INTERNAL_ERROR` (502) when the provider gave no way to open the game;\n * `UNAUTHENTICATED` without a session. `COOLING_OFF`, `ACCOUNT_BLOCKED` and `CASINO_UNAVAILABLE` arrive with\n * HTTP 500 (the gateway does not map them yet): identify by the code, not by the status.\n */\n launchGame(input: LaunchGameInput, options?: CallOptions): Promise<GameLaunch>\n /**\n * The player's game sessions, from newest to oldest, paginated.\n * @example\n * const { items } = await igaming.casino.listSessions({ perPage: 10 })\n * const active = items.find((s) => s.status === 'active')\n * @throws {EnginexError} `UNAUTHENTICATED` without a session.\n */\n listSessions(input?: CasinoPageInput, options?: CallOptions): Promise<Page<GameSession>>\n /**\n * The player's round history (bets, prizes, reversals), paginated.\n * @example\n * const page = await igaming.casino.getHistory({ page: 1, perPage: 20 })\n * page.items.forEach((tx) => console.log(tx.roundId, tx.type, tx.amount, tx.currency))\n * @throws {EnginexError} `INTERNAL_ERROR` (500) if the history has a currency the gateway does not\n * know; `UNAUTHENTICATED` without a session.\n */\n getHistory(input?: CasinoPageInput, options?: CallOptions): Promise<Page<CasinoTransaction>>\n /**\n * Biggest prizes of a round in the operator's casino (home ranking), with the player's name\n * masked. Requires login.\n * @example\n * const winners = await igaming.casino.getBiggestWinners({ limit: 10, days: 7 })\n * @throws {EnginexError} `INTERNAL_ERROR` (500) if a prize comes with an unknown currency;\n * `UNAUTHENTICATED` without a session.\n */\n getBiggestWinners(input?: GetBiggestWinnersInput, options?: CallOptions): Promise<BiggestWinner[]>\n /**\n * The lobby's published jackpots in the site's currency. Public (it does not send the session). A\n * `currency` other than the site's answers an empty list. An entry the SDK cannot show safely (no id or\n * name, another currency, a negative or non-integer amount, an amount that does not fit in a safe integer,\n * or invalid decimal places) is left out, and a repeated id keeps the first one.\n *\n * Available on gateways with lobby jackpots (the `dev` environment today); elsewhere the route answers 404.\n * @example\n * const { currency } = await enginex.config.get()\n * const { items, featuredId } = await igaming.casino.listJackpots({ currency: currency.code })\n * const featured = items.find((jackpot) => jackpot.id === featuredId)\n * @throws {EnginexError} `CONFIGURATION_ERROR` (no request) if `currency` is not three uppercase letters;\n * `INVALID_ARGUMENT` (400) for a currency the gateway does not support; `UNAVAILABLE` (503) when the site's\n * currency or the casino service is unavailable; `NOT_FOUND` (404) on a gateway without lobby jackpots.\n */\n listJackpots(input: ListJackpotsInput, options?: CallOptions): Promise<CasinoJackpots>\n /**\n * Game cards of a published jackpot, paginated by cursor. Public (it does not send the session). Ask for page\n * 1 without a cursor, then for `page + 1` with the previous page's `nextCursor` while `hasNext`.\n *\n * Available on gateways with lobby jackpots (the `dev` environment today); elsewhere the route answers 404.\n * @example\n * let page = await igaming.casino.listJackpotGames({ jackpotId, currency: 'BRL', device: 'mobile' })\n * while (page.hasNext && page.nextCursor) {\n * page = await igaming.casino.listJackpotGames({ jackpotId, currency: 'BRL', device: 'mobile', page: page.page + 1, cursor: page.nextCursor })\n * }\n * @throws {EnginexError} `CONFIGURATION_ERROR` (no request) for an empty `jackpotId`, a `currency` that is not\n * three uppercase letters, a `device` other than `mobile`/`desktop`, a `page` that is not an integer ≥ 1, a\n * `perPage` outside 1 to 48 or a `page` above 1 without `cursor`; `INVALID_ARGUMENT` (400) for an id that is\n * not a public jackpot id or an invalid cursor; `NOT_FOUND` (404) for a jackpot that is not published in\n * that currency (or a gateway without lobby jackpots); `UNAVAILABLE` (503) when the casino service fails or\n * answers an inconsistent page.\n */\n listJackpotGames(input: ListJackpotGamesInput, options?: CallOptions): Promise<JackpotGamesPage>\n}\n\nconst gameSchema = /* @__PURE__ */ lazy(\n (): z.ZodMiniType<Game> =>\n wire({\n id: z.string(),\n name: z.string(),\n provider: z.string(),\n category: z.string(),\n type: z.string(),\n thumbnail: z.string(),\n is_new: z.boolean(),\n is_popular: z.boolean(),\n is_live: z.boolean(),\n demo_available: z.boolean(),\n rtp: z.number(),\n volatility: z.string(),\n priority: z.number(),\n }),\n)\n\nconst categoriesSchema = /* @__PURE__ */ lazy(\n (): z.ZodMiniType<GameCategory[]> =>\n nullableList(\n wire({ slug: z.string(), name: z.string(), icon: z.string(), game_count: z.number(), priority: z.number() }),\n ),\n)\n\nconst providersSchema = /* @__PURE__ */ lazy(\n (): z.ZodMiniType<GameProvider[]> => nullableList(wire({ id: z.string(), name: z.string(), game_count: z.number() })),\n)\n\nconst launchSchema = /* @__PURE__ */ lazy(\n (): z.ZodMiniType<GameLaunch> =>\n z.pipe(\n wire({\n session_id: z.string().check(z.minLength(1)),\n game_url: z.string().check(z.minLength(1)),\n // Any text: a target the SDK does not know yet must not fail the (strict) launch.\n launch_target: z.optional(z.string()),\n provider_code: z.optional(z.string()),\n expires_at: z.optional(z.string()),\n }),\n // Without a target (an older gateway, or a custom mock), the launch keeps the behavior the SDK documented\n // before the field existed: an iframe.\n z.transform(({ launchTarget, ...rest }) => ({ ...rest, launchTarget: launchTarget || 'iframe' })),\n ),\n)\n\nconst sessionSchema = /* @__PURE__ */ lazy(\n (): z.ZodMiniType<GameSession> =>\n wire({\n id: z.string(),\n game_id: z.string(),\n game_name: z.string(),\n provider: z.string(),\n start_time: z.string(),\n total_bet: money(),\n total_win: money(),\n status: protoEnum('SESSION_STATUS_'),\n }),\n)\n\nconst transactionSchema = /* @__PURE__ */ lazy(\n (): z.ZodMiniType<CasinoTransaction> =>\n wire({\n id: z.string(),\n game_id: z.string(),\n game_name: z.string(),\n round_id: z.string(),\n type: protoEnum('CASINO_TRANSACTION_TYPE_'),\n amount: minorUnits(),\n currency: currencyCode(),\n currency_decimal_places: decimalPlaces(),\n created_at: z.string(),\n }),\n)\n\nconst winnersSchema = /* @__PURE__ */ lazy(\n (): z.ZodMiniType<BiggestWinner[]> =>\n nullableList(\n wire({\n player: z.string(),\n amount: minorUnits(),\n currency: currencyCode(),\n currency_decimal_places: decimalPlaces(),\n game_id: z.string(),\n game_name: z.string(),\n won_at: z.string(),\n }),\n ),\n)\n\n// `availability` next to `data` in `GET /games` (`casino.go`, `encoding/json`): `missing` is a Go slice, so `null`\n// when empty; an older gateway sends no `availability` at all.\nconst gamesEnvelopeSchema = /* @__PURE__ */ lazy(\n (): z.ZodMiniType<{ availability: CasinoAvailability | null }> =>\n wire({\n availability: z.pipe(\n z.nullish(\n wire({\n // The gateway reports an unset status as `available`; the SDK does the same for an absent/empty one.\n status: z.pipe(\n z.nullish(z.string()),\n z.transform((value) => (value ? value.toLowerCase() : 'available')),\n ),\n primary_provider_code: optionalText(),\n missing: nullableList(z.string()),\n }),\n ),\n z.transform((value) => value ?? null),\n ),\n }),\n)\n\nconst CURRENCY = /^[A-Z]{3}$/\nconst DECIMAL_PLACES_MAX = 20\n\n// One entry of `GET /games/jackpots` (`casino_lobby_jackpots.go`): `amount_minor` is int64 text. Decoded one by\n// one (see `listJackpots`), so a bad entry is left out instead of failing the whole list.\nconst jackpotSchema = /* @__PURE__ */ lazy(\n (): z.ZodMiniType<CasinoJackpot> =>\n z.pipe(\n z.object({\n id: z.string().check(z.refine((value) => value.trim() !== '')),\n name: z.string().check(z.refine((value) => value.trim() !== '')),\n currency: z.string().check(z.regex(CURRENCY)),\n amount_minor: z.union([\n z.string().check(z.refine((value) => /^(0|[1-9]\\d*)$/.test(value) && Number.isSafeInteger(Number(value)))),\n z.number().check(z.refine((value) => Number.isSafeInteger(value) && value >= 0)),\n ]),\n decimal_places: z\n .number()\n .check(z.refine((value) => Number.isInteger(value) && value >= 0 && value <= DECIMAL_PLACES_MAX)),\n }),\n z.transform((raw) => ({\n id: raw.id,\n name: raw.name,\n currency: raw.currency,\n amount: Number(raw.amount_minor) || 0,\n currencyDecimalPlaces: raw.decimal_places,\n })),\n ),\n)\n\nconst jackpotsSchema = /* @__PURE__ */ lazy(\n (): z.ZodMiniType<{ items: unknown[]; featuredId: string | null }> =>\n wire({ items: nullableList(z.unknown()), featured_id: optionalText() }),\n)\n\nconst jackpotGamesSchema = /* @__PURE__ */ lazy(\n (): z.ZodMiniType<JackpotGamesPage> =>\n z.pipe(\n wire({\n games: nullableList(gameSchema()),\n mode: z.pipe(\n z.string(),\n z.transform((value) => value.toLowerCase()),\n ),\n pagination: wire({\n page: z.number(),\n per_page: z.number(),\n has_next: z.boolean(),\n next_cursor: optionalText(),\n }),\n }),\n z.transform(({ games, mode, pagination }) => ({\n items: games,\n mode,\n page: pagination.page,\n perPage: pagination.perPage,\n // A page that says there is more but has no cursor cannot be followed: it is the last one.\n hasNext: pagination.hasNext && pagination.nextCursor !== null,\n nextCursor: pagination.hasNext ? pagination.nextCursor : null,\n })),\n ),\n)\n\nconst DEVICES: readonly unknown[] = ['mobile', 'desktop']\nconst GAMES_ROUTE: Route = { method: 'GET', path: '/games' }\nconst JACKPOTS_ROUTE: Route = { method: 'GET', path: '/games/jackpots' }\nconst JACKPOT_GAMES_ROUTE: Route = { method: 'GET', path: '/games/jackpots/{jackpotId}/games' }\nconst JACKPOT_GAMES_MAX = 48\n\nfunction deviceProblem(name: string, device: unknown): string | undefined {\n return device === undefined || DEVICES.includes(device)\n ? undefined\n : `${name}: device must be 'mobile' or 'desktop' (or omitted).`\n}\n\nfunction currencyProblem(name: string, currency: unknown): string | undefined {\n return typeof currency === 'string' && CURRENCY.test(currency)\n ? undefined\n : `${name}: currency must be an ISO 4217 code in uppercase (e.g. BRL).`\n}\n\n// Checks the input of `listJackpotGames` before any request; the message never carries the received value.\nfunction jackpotGamesProblem(input: unknown): string | undefined {\n const name = 'casino.listJackpotGames'\n if (typeof input !== 'object' || input === null || Array.isArray(input))\n return `${name}: input must be an object { jackpotId, currency }.`\n const { jackpotId, currency, device, page, perPage, cursor } = input as Record<string, unknown>\n if (typeof jackpotId !== 'string' || jackpotId.trim() === '') return `${name}: jackpotId must be non-empty text.`\n const problem = currencyProblem(name, currency) ?? deviceProblem(name, device)\n if (problem !== undefined) return problem\n if (page !== undefined && (typeof page !== 'number' || !Number.isSafeInteger(page) || page < 1))\n return `${name}: page must be an integer ≥ 1.`\n if (\n perPage !== undefined &&\n (typeof perPage !== 'number' || !Number.isInteger(perPage) || perPage < 1 || perPage > JACKPOT_GAMES_MAX)\n )\n return `${name}: perPage must be an integer from 1 to ${JACKPOT_GAMES_MAX}.`\n if (cursor !== undefined && typeof cursor !== 'string') return `${name}: cursor must be text.`\n if (typeof page === 'number' && page > 1 && (cursor === undefined || cursor === ''))\n return `${name}: a page above 1 requires the previous page's nextCursor.`\n return undefined\n}\n\n/** Creates the `casino` namespace. @internal */\nexport function createCasinoApi(transport: ExtensionTransport): CasinoApi {\n return {\n listGames: async (input, options) => {\n const problem = deviceProblem('casino.listGames', input?.device)\n if (problem !== undefined) return rejectInput(transport, problem, GAMES_ROUTE)\n const spec = {\n ...GAMES_ROUTE,\n query: {\n category: input?.category,\n provider: input?.provider,\n search: input?.search,\n ids: input?.ids?.length ? input.ids.join(',') : undefined,\n sort: input?.sort,\n device: input?.device,\n },\n page: input?.page,\n perPage: input?.perPage,\n perPageParam: 'limit' as const,\n auth: 'none' as const,\n item: gameSchema(),\n options,\n }\n // A core older than 0.11.0 has no `requestPageWithEnvelope`: the page comes without the availability.\n if (typeof transport.requestPageWithEnvelope !== 'function')\n return { ...(await transport.requestPage(spec)), availability: null }\n const { page, envelope } = await transport.requestPageWithEnvelope({ ...spec, envelope: gamesEnvelopeSchema() })\n return { ...page, availability: envelope.availability }\n },\n listCategories: (_params, options) =>\n transport.request({ method: 'GET', path: '/games/categories', schema: categoriesSchema(), options }),\n listProviders: (_params, options) =>\n transport.request({ method: 'GET', path: '/games/providers', schema: providersSchema(), options }),\n getGame: ({ gameId }, options) =>\n transport.request({\n method: 'GET',\n path: `/games/${encodeURIComponent(gameId)}`,\n schema: gameSchema(),\n options,\n }),\n launchGame: ({ gameId, mode, isMobile, returnUrl, depositUrl, language }, options) =>\n transport.request({\n method: 'POST',\n path: `/games/${encodeURIComponent(gameId)}/launch`,\n body: {\n is_demo: mode === 'demo',\n is_mobile: isMobile === true,\n return_url: returnUrl,\n deposit_url: depositUrl,\n language,\n },\n auth: 'required',\n // The response carries the URL with the game session token: never through `warn` mode's recovery\n // (which would deliver a raw field and the response to `onValidationIssue`).\n validation: 'strict',\n schema: launchSchema(),\n options,\n }),\n listSessions: (input, options) =>\n transport.requestPage({\n method: 'GET',\n path: '/games/sessions',\n page: input?.page,\n perPage: input?.perPage,\n perPageParam: 'limit',\n auth: 'required',\n item: sessionSchema(),\n options,\n }),\n getHistory: (input, options) =>\n transport.requestPage({\n method: 'GET',\n path: '/games/history',\n page: input?.page,\n perPage: input?.perPage,\n perPageParam: 'limit',\n auth: 'required',\n item: transactionSchema(),\n options,\n }),\n getBiggestWinners: (input, options) =>\n transport.request({\n method: 'GET',\n path: '/games/biggest-winners',\n query: { limit: input?.limit, days: input?.days },\n auth: 'required',\n schema: winnersSchema(),\n options,\n }),\n listJackpots: async (input, options) => {\n const currency = (input as { currency?: unknown } | undefined)?.currency\n const problem = currencyProblem('casino.listJackpots', currency)\n if (problem !== undefined) return rejectInput(transport, problem, JACKPOTS_ROUTE)\n const raw = await transport.request({\n ...JACKPOTS_ROUTE,\n query: { currency: currency as string },\n auth: 'none',\n schema: jackpotsSchema(),\n options,\n })\n // Entry by entry, like the gateway already filters: what cannot be shown safely is left out.\n const items: CasinoJackpot[] = []\n for (const entry of Array.isArray(raw.items) ? raw.items : []) {\n const parsed = z.safeParse(jackpotSchema(), entry)\n if (!parsed.success || parsed.data.currency !== currency) continue\n if (items.some((item) => item.id === parsed.data.id)) continue\n items.push(parsed.data)\n }\n const featured = typeof raw.featuredId === 'string' ? raw.featuredId : null\n return { items, featuredId: items.some((item) => item.id === featured) ? featured : null }\n },\n listJackpotGames: (input, options) => {\n const problem = jackpotGamesProblem(input)\n if (problem !== undefined) return rejectInput(transport, problem, JACKPOT_GAMES_ROUTE)\n return transport.request({\n method: 'GET',\n path: `/games/jackpots/${encodeURIComponent(input.jackpotId)}/games`,\n query: {\n currency: input.currency,\n device: input.device,\n page: input.page,\n limit: input.perPage,\n cursor: input.cursor === '' ? undefined : input.cursor,\n },\n auth: 'none',\n schema: jackpotGamesSchema(),\n options,\n })\n },\n }\n}\n","// Public types come from the core's main entry: the /extension `.d.ts` exposes Zod, and this package's\n// public API cannot depend on it (check-api).\nimport { isEnginexError, type CallOptions, type NoParams } from '@getenginex/sdk'\nimport {\n currencyCode,\n decimalPlaces,\n isAmbiguousFailure,\n lazy,\n mapOf,\n wire,\n type ExtensionTransport,\n} from '@getenginex/sdk/extension'\nimport * as z from 'zod/mini'\nimport { rejectInput, type Route } from '../internal/input'\nimport { nullableList, optionalText } from '../internal/optional-values'\nimport { currencyOrEmpty, integerText, nonNegativeMinorUnits, protoEnum } from '../internal/schemas'\n\n// Wire format: every `/casino/club` route answers WITHOUT the `{ success, data }` envelope. All of them but one are\n// protojson written by `writeClubResponse` with `EmitDefaultValues: true`: scalars, lists and maps are always\n// present (an empty list as `[]`, int64 as text), while an unset message or an unset proto3 `optional` is omitted.\n// The exception is `GET /casino/club/tournaments?relatedTo=`, written by `encoding/json` (`httputil.JSON`): a nil\n// map comes out as `null` and a zero `time.Time` as `\"0001-01-01T00:00:00Z\"`. The SDK reads both shapes the same\n// way: an omitted or `null` list is `[]`, an omitted or `null` message is `null`, an empty text that means \"none\" is\n// `null`, and an absent date (omitted, `null`, `\"\"`, the epoch or Go's zero time) is `null`.\n\n// ─── Types ─────────────────────────────────────────────────────────────────────────────────────\n\n/**\n * Text per locale, as the operator wrote it (`{ \"pt-BR\": \"...\", \"en\": \"...\" }`). `{}` when the gateway sends none.\n * @category Club\n */\nexport type ClubLocalized = Record<string, string>\n\n/**\n * Money of the club, in minor units of `currency`.\n * @category Club\n */\nexport interface ClubMoney {\n /** Value in minor units of `currency` (the gateway sends it as int64 text; the SDK converts). Never negative. */\n amount: number\n /** ISO 4217 currency code, e.g. `BRL`. */\n currency: string\n /**\n * Decimal places of `amount` as the gateway resolved them (the currency's ISO exponent; for a free-spin\n * denomination, the provider's scale); `null` when the gateway omits them.\n */\n decimalPlaces: number | null\n}\n\n/**\n * Kind of a club reward, in lowercase. A kind the SDK does not know yet arrives as the gateway sent it, in\n * lowercase: handle the default case.\n * @category Club\n */\nexport type ClubRewardKind =\n | 'coins'\n | 'digital'\n | 'cashback'\n | 'bonus_balance'\n | 'free_spins'\n | 'tournament_ticket'\n | 'real_balance'\n | 'manual'\n | 'unspecified'\n | (string & {})\n\n/**\n * Coin award published in place of a reward in a given situation (e.g. the player already holds the ticket).\n * @category Club\n */\nexport interface ClubAlternateReward {\n /** Kind of the alternate, `coins` today. */\n kind: ClubRewardKind\n /** Label per locale. */\n label: ClubLocalized\n /** Quantity (integer). */\n quantity: number\n}\n\n/**\n * Cashback terms of a `cashback` reward.\n * @category Club\n */\nexport interface ClubCashbackTerms {\n /** Percentage in basis points (`1000` = 10%). */\n percentageBps: number\n /** `edition`, `daily`, `weekly` or another period; `null` when absent. */\n period: 'edition' | 'daily' | 'weekly' | (string & {}) | null\n /** `net_loss` or another basis; `null` when absent. */\n basis: 'net_loss' | (string & {}) | null\n /** Where the cashback is credited: `real`, `restricted` or another; `null` when absent. */\n destination: 'real' | 'restricted' | (string & {}) | null\n /** Start of the frozen basis window (ISO 8601); `null` when absent. */\n startsAt: string | null\n /** End of the frozen basis window (ISO 8601); `null` when absent. */\n endsAt: string | null\n /** Catalogue game ids eligible for the basis. */\n gameIds: string[]\n /** Coin award when the basis is zero; `null` when none. */\n zeroBasisAlternate: ClubAlternateReward | null\n /** Coin award when the basis was already rewarded; `null` when none. */\n priorAwardAlternate: ClubAlternateReward | null\n}\n\n/**\n * A club reward: of a wheel slice, a mission chest, a store item or a tournament prize.\n * @category Club\n */\nexport interface ClubReward {\n /** Reward id (`''` when the gateway sends none, e.g. in a projected tournament prize). */\n id: string\n /** Label per locale. */\n label: ClubLocalized\n /** Kind of the reward (see {@link ClubRewardKind}). */\n kind: ClubRewardKind\n /** Quantity (integer: coins, spins, items). */\n quantity: number\n /** Money of the reward; `null` when it has none. */\n money: ClubMoney | null\n /** Free-spin campaign: spins and the catalogue game; `null` when not a campaign. */\n campaign: { spins: number; gameId: string | null } | null\n /** Cashback terms; `null` when not a cashback. */\n cashback: ClubCashbackTerms | null\n /** Manual delivery (`physical` or `experience`) with the instructions; `null` when not manual. */\n manual: { deliveryType: 'physical' | 'experience' | (string & {}) | null; instructions: ClubLocalized } | null\n /** Validity in seconds after delivery (integer; `0` without one). */\n ttlSeconds: number\n /** Tournament edition of a `tournament_ticket`; `null` otherwise. */\n editionId: string | null\n /** Coin award when the player already holds the ticket or entry; `null` when none. */\n ticketOwnedAlternate: ClubAlternateReward | null\n}\n\n/**\n * Status of a receipt, in lowercase: `pending`, `delivered`, `failed`, `no_value` (a confirmed zero cashback) or a\n * status the SDK does not know yet.\n * @category Club\n */\nexport type ClubReceiptStatus = 'pending' | 'delivered' | 'failed' | 'no_value' | 'unspecified' | (string & {})\n\n/**\n * Receipt of a play, a redemption, a mission chest or a tournament award.\n * @category Club\n */\nexport interface ClubReceipt {\n /** Receipt id. */\n id: string\n /** Status (see {@link ClubReceiptStatus}). */\n status: ClubReceiptStatus\n /** What produced it, in lowercase: `activity` (a wheel, scratch card or gift), `chest` (a mission chest), `store` or `tournament`. */\n sourceKind: 'activity' | 'chest' | 'store' | 'tournament' | 'unspecified' | (string & {})\n /** Id of the source (activity, mission right, item, edition); `null` when absent. */\n sourceId: string | null\n /** Wheel slice that was drawn; `null` when not a draw. */\n sliceId: string | null\n /** The reward; `null` when absent. */\n reward: ClubReward | null\n /** Money actually settled; `null` when absent. */\n settlement: ClubMoney | null\n /** Coins spent (integer; `0` when free). */\n costCoins: number\n /** When it was accepted (ISO 8601); `null` when absent. */\n acceptedAt: string | null\n /** When the delivery was confirmed (ISO 8601); `null` while not delivered. */\n deliveredAt: string | null\n /** When the reward expires (ISO 8601); `null` without expiry. */\n expiresAt: string | null\n /** Frozen final rank of a tournament award; `null` otherwise. */\n tournamentRank: number | null\n /** Whether a tournament ticket was consumed. */\n ticketConsumed: boolean\n}\n\n/**\n * A level of the program.\n * @category Club\n */\nexport interface ClubLevel {\n /** Level id. */\n id: string\n /** Name per locale. */\n name: ClubLocalized\n /** XP needed to reach it (integer). */\n minXp: number\n /** Benefit per locale. */\n benefit: ClubLocalized\n}\n\n/**\n * The club program as the player sees it (part of {@link ClubOverview}; also the result of\n * {@link ClubApi.setMembership}).\n * @category Club\n */\nexport interface ClubProgram {\n /** Whether the program is active for the operator. */\n enabled: boolean\n /** Whether the player joined. */\n joined: boolean\n /** Whether joining is required before playing. */\n membershipRequired: boolean\n /** Whether the player can join now. */\n canJoin: boolean\n /** Whether the history can be read (also when the program is paused). */\n historyAvailable: boolean\n /** Published version: pass it back as `versionId` in every write; `null` without a published version. */\n versionId: string | null\n /** Locale the gateway resolved from `Accept-Language` (the client's locale); `null` when absent. */\n locale: string | null\n /** Key of the membership terms shown for that locale: pass it as `termsLocale` when joining. */\n termsLocale: string | null\n /** Program time zone (IANA); `null` when absent. */\n timeZone: string | null\n /** The player's wallet currency the program uses; `null` while not confirmed. */\n currency: string | null\n /** Name per locale. */\n name: ClubLocalized\n /** Terms per locale. */\n terms: ClubLocalized\n /** Name of the coin per locale. */\n coinName: ClubLocalized\n /** Cover image; `null` when absent. */\n coverUrl: string | null\n /** Levels, in the order the operator published them (a repeated id keeps the first). */\n levels: ClubLevel[]\n}\n\n/**\n * Kind of an activity: `wheel`, `scratch`, `gift` or a kind the SDK does not know yet.\n * @category Club\n */\nexport type ClubActivityKind = 'wheel' | 'scratch' | 'gift' | 'unspecified' | (string & {})\n\n/**\n * An activity (wheel, scratch card, gift) and the player's state in it.\n * @category Club\n */\nexport interface ClubActivityState {\n /** The activity. */\n activity: {\n /** Activity id: pass it to {@link ClubApi.play}. */\n id: string\n /** Kind (see {@link ClubActivityKind}). */\n kind: ClubActivityKind\n /** Name per locale. */\n name: ClubLocalized\n /** Terms per locale. */\n terms: ClubLocalized\n /** Cover image; `null` when absent. */\n coverUrl: string | null\n /** Wheel theme: `emerald`, `midnight`, `berry` or another; `null` when absent. */\n wheelTheme: 'emerald' | 'midnight' | 'berry' | (string & {}) | null\n /** Label of the play button per locale. */\n playLabel: ClubLocalized\n /** Slices, without the draw weights (a repeated id keeps the first). */\n slices: { id: string; reward: ClubReward | null }[]\n }\n /** Whether the player can play now. */\n canPlay: boolean\n /** Why the player cannot play (e.g. `daily_budget_exhausted`); `null` when absent. */\n unavailableReason: 'daily_budget_exhausted' | (string & {}) | null\n /** The player's last receipt in this activity; `null` when none. */\n latestReceipt: ClubReceipt | null\n /** When the player can play again (ISO 8601); `null` when absent. */\n availableAt: string | null\n}\n\n/**\n * A mission and the player's progress and chest right.\n * @category Club\n */\nexport interface ClubMissionState {\n /** The mission. */\n mission: {\n /** Mission id. */\n id: string\n /** Title per locale. */\n title: ClubLocalized\n /** Terms per locale. */\n terms: ClubLocalized\n /** `daily`, `weekly`, `edition` or another, in lowercase. */\n recurrence: string\n /** `fact`, `day`, `edition` or another, in lowercase. */\n countBy: string\n /** Target (integer). */\n target: number\n /** Cover image; `null` when absent. */\n coverUrl: string | null\n }\n /** Edition (period) of the mission; `null` when absent. */\n editionId: string | null\n /** Progress (integer). */\n progress: number\n /** Chest right: pass it as `activityId` to {@link ClubApi.play} to open the chest; `null` without a right. */\n rightId: string | null\n /**\n * Version of the right. The gateway sends it on the pending chests of a paused program; `null` when absent.\n */\n rightVersionId: string | null\n /** Chest options: pass the chosen `id` as `optionId` to {@link ClubApi.play}. */\n chestOptions: ClubReward[]\n /** Whether the chest can be opened now. */\n canClaim: boolean\n /** Receipt of the opened chest; `null` while not opened. */\n receipt: ClubReceipt | null\n /** End of the edition (ISO 8601); `null` when absent. */\n endsAt: string | null\n /** Deadline to open the chest (ISO 8601); `null` when absent. */\n claimExpiresAt: string | null\n /** Days already stamped (`YYYY-MM-DD`). */\n stampedDays: string[]\n}\n\n/**\n * An item of the coin store and whether the player can redeem it.\n * @category Club\n */\nexport interface ClubStoreItemState {\n /** The item. */\n item: {\n /** Item id: pass it as `rewardId` to {@link ClubApi.redeem}. */\n id: string\n /** Label per locale. */\n label: ClubLocalized\n /** Terms per locale. */\n terms: ClubLocalized\n /** Price in coins (integer). */\n costCoins: number\n /** The reward; `null` when absent. */\n reward: ClubReward | null\n /** Cover image; `null` when absent. */\n coverUrl: string | null\n }\n /** Whether the player can redeem it now. */\n canRedeem: boolean\n /** Why it cannot be redeemed, in lowercase; `null` when absent. */\n unavailableReason: string | null\n}\n\n/**\n * The player's balances, activities, missions and store.\n * @category Club\n */\nexport interface ClubRewards {\n /** XP (integer). */\n xp: number\n /** Coin balance (integer). */\n coins: number\n /** Current level id; `null` when none. */\n levelId: string | null\n /** Activities (a repeated activity id keeps the first). Empty while the program is paused. */\n activities: ClubActivityState[]\n /** Missions (a repeated mission right keeps the first). While paused, only the pending chests. */\n missions: ClubMissionState[]\n /** Store items (a repeated item id keeps the first). Empty while the program is paused. */\n storeItems: ClubStoreItemState[]\n}\n\n/**\n * The club overview (`GET /casino/club`).\n * @category Club\n */\nexport interface ClubOverview {\n /** The program. */\n program: ClubProgram\n /** The player's state; `null` when the program is disabled and has no history. */\n rewards: ClubRewards | null\n}\n\n/**\n * A balance movement of the history.\n * @category Club\n */\nexport interface ClubMovement {\n /** Movement id. */\n id: string\n /** `xp`, `coins` or another kind, in lowercase. */\n kind: string\n /** Units moved (integer; negative for a debit). */\n units: number\n /** Id of the source; `null` when absent. */\n sourceId: string | null\n /** When it happened (ISO 8601); `null` when absent. */\n occurredAt: string | null\n}\n\n/**\n * A page of the club history.\n * @category Club\n */\nexport interface ClubHistory {\n /** Receipts on this page (a repeated id keeps the first). */\n receipts: ClubReceipt[]\n /** Movements on this page (a repeated id keeps the first). */\n movements: ClubMovement[]\n /** Pass it as `cursor` for the next page; absent on the last one. */\n nextCursor?: string\n}\n\n/**\n * Status of a tournament, in lowercase.\n * @category Club\n */\nexport type ClubTournamentStatus =\n | 'draft'\n | 'upcoming'\n | 'live'\n | 'awaiting_confirmation'\n | 'completed'\n | 'cancelled'\n | 'unspecified'\n | (string & {})\n\n/**\n * The player's registration in a tournament.\n * @category Club\n */\nexport interface ClubTournamentRegistration {\n /** Registration id. */\n id: string\n /** Edition id. */\n editionId: string\n /** Version registered; `null` when absent. */\n versionId: string | null\n /** When the player registered (ISO 8601); `null` when absent. */\n joinedAt: string | null\n}\n\n/**\n * A prize range of a tournament.\n * @category Club\n */\nexport interface ClubTournamentPrize {\n /** First rank of the range (integer). */\n fromRank: number\n /** Last rank of the range (integer). */\n toRank: number\n /** The reward; `null` when absent (e.g. an external listing). */\n reward: ClubReward | null\n /** Announced amount (external listings); `null` when absent. Under `'warn'` a prize with an invalid one is dropped. */\n announcedAmount: ClubMoney | null\n /** Prize terms per locale (`{}` when none). */\n terms: ClubLocalized\n /** Frozen offer conditions of a `bonus_balance`/`free_spins` prize; `null` when none. */\n offerTerms: {\n /** Value of each free spin, in the provider's scale; `null` when unconfirmed. */\n spinDenomination: ClubMoney | null\n /** Exact decimal wagering multiplier (`\"0\"` = no wagering); `null` when unconfirmed. */\n wageringMultiplier: string | null\n /** Validity in seconds; `null` when unconfirmed. */\n validForSeconds: number | null\n /** Expiry of the offer (ISO 8601); `null` when absent. */\n expiresAt: string | null\n /** End of the grant window (ISO 8601); `null` when absent. */\n grantEndsAt: string | null\n } | null\n}\n\n/**\n * A club tournament (own or external).\n * @category Club\n */\nexport interface ClubTournament {\n /** Edition id (external ones start with `ext_`). */\n id: string\n /** `own`, `external` or another source, in lowercase. */\n source: string\n /** Published version: pass it as `versionId` to {@link ClubApi.registerForTournament}; `null` when absent. */\n versionId: string | null\n /** Title per locale. */\n title: ClubLocalized\n /** Terms per locale. */\n terms: ClubLocalized\n /** Status (see {@link ClubTournamentStatus}). */\n status: ClubTournamentStatus\n /** Start (ISO 8601); `null` when absent. */\n startsAt: string | null\n /** End (ISO 8601); `null` when absent. */\n endsAt: string | null\n /** Last update (ISO 8601); `null` when absent. */\n updatedAt: string | null\n /** Scoring rule, in lowercase; `null` when absent. */\n scoringRule: string | null\n /** Tie-break rule, in lowercase; `null` when absent. */\n tieBreak: string | null\n /** Currency of the edition (ISO 4217); `null` when absent. */\n currency: string | null\n /** Time zone (IANA); `null` when absent. */\n timeZone: string | null\n /** Catalogue games of the edition (a repeated id keeps the first). */\n gameIds: string[]\n /** Prize ranges. */\n prizes: ClubTournamentPrize[]\n /** `registration`, `in_game` or another; `null` when no action is confirmed. */\n joinMode: 'registration' | 'in_game' | (string & {}) | null\n /** Locale of the terms shown; `null` when absent. */\n locale: string | null\n /** Whether {@link ClubApi.getRanking} can be read. */\n rankingAvailable: boolean\n /** Whether the player can register now. */\n canRegister: boolean\n /** Whether registering consumes a ticket. */\n requiresTicket: boolean\n /** The player's registration; `null` when not registered. */\n registration: ClubTournamentRegistration | null\n /** The player's award from the frozen result (detail only); `null` when none. */\n personalAward: ClubReceipt | null\n /** Whether the source data is stale. */\n stale: boolean\n /** Registration opening (ISO 8601); `null` when absent. */\n registrationStartsAt: string | null\n /** Registration closing (ISO 8601); `null` when absent. */\n registrationEndsAt: string | null\n /** Cover image; `null` when absent. */\n coverUrl: string | null\n}\n\n/**\n * A page of club tournaments.\n * @category Club\n */\nexport interface ClubTournamentPage {\n /** Tournaments on this page (a repeated id keeps the first). */\n items: ClubTournament[]\n /** Whether external tournaments are on the page. */\n externalAvailable: boolean\n /** Whether an external tournament on the page is stale. */\n externalStale: boolean\n /** Pass it as `cursor` for the next page; absent on the last one. */\n nextCursor?: string\n}\n\n/**\n * Another edition of the same external schedule.\n * @category Club\n */\nexport interface ClubRelatedTournament {\n /** Edition id (`ext_...`). */\n id: string\n /** Title per locale. */\n title: ClubLocalized\n /** Status (see {@link ClubTournamentStatus}). */\n status: ClubTournamentStatus\n /** Start (ISO 8601); `null` when absent. */\n startsAt: string | null\n /** End (ISO 8601); `null` when absent. */\n endsAt: string | null\n}\n\n/**\n * A page of related editions.\n * @category Club\n */\nexport interface ClubRelatedTournamentPage {\n /** Related editions (a repeated id keeps the first). */\n items: ClubRelatedTournament[]\n /** Pass it as `cursor` for the next page; absent on the last one. */\n nextCursor?: string\n}\n\n/**\n * A row of a tournament ranking.\n * @category Club\n */\nexport interface ClubRank {\n /** Position (integer ≥ 1). */\n position: number\n /** Display name, already masked by the source. */\n displayName: string\n /** Score as decimal text (display only). */\n score: string\n}\n\n/**\n * A tournament ranking.\n * @category Club\n */\nexport interface ClubRanking {\n /** Top rows. */\n entries: ClubRank[]\n /** The player's row; `null` when not ranked. */\n personal: ClubRank | null\n /** Last update (ISO 8601); `null` when absent. */\n updatedAt: string | null\n /** Whether the ranking is final. */\n final: boolean\n}\n\n/**\n * Result of {@link ClubApi.play}.\n * @category Club\n */\nexport interface ClubPlayResult {\n /** The receipt. */\n receipt: ClubReceipt\n /** Slice drawn; `null` when not a draw (e.g. a mission chest). */\n sliceId: string | null\n /** The player's state after the play; `null` when absent. */\n rewards: ClubRewards | null\n}\n\n/**\n * Cursor pagination of the club listings.\n * @category Club\n */\nexport interface ClubCursorInput {\n /** The previous page's `nextCursor`. Omitted: the first page. */\n cursor?: string\n /** Items per page: an integer from 1 to 100. Omitted: the gateway default. */\n limit?: number\n}\n\n/**\n * Input of {@link ClubApi.listRelatedTournaments}.\n * @category Club\n */\nexport interface ListRelatedClubTournamentsInput extends ClubCursorInput {\n /** External edition (`ext_` followed by letters, digits, `_` or `-`). */\n editionId: string\n}\n\n/**\n * Input of {@link ClubApi.getRanking}.\n * @category Club\n */\nexport interface GetClubRankingInput {\n /** Edition id. */\n editionId: string\n /** Rows: an integer from 1 to 100. Omitted: the gateway default. */\n limit?: number\n}\n\n/**\n * Input of {@link ClubApi.setMembership}: join (with the terms locale shown) or leave.\n * @category Club\n */\nexport type SetClubMembershipInput =\n | {\n /** {@link ClubProgram.versionId}. */\n versionId: string\n /** Join. */\n joined: true\n /** {@link ClubProgram.termsLocale}: the key of the terms the player saw. */\n termsLocale: string\n }\n | {\n /** {@link ClubProgram.versionId}. */\n versionId: string\n /** Leave. */\n joined: false\n }\n\n/**\n * Input of {@link ClubApi.play}.\n * @category Club\n */\nexport interface PlayClubActivityInput {\n /** An activity id, or a mission's `rightId` to open its chest. */\n activityId: string\n /** {@link ClubProgram.versionId} (or the mission's `rightVersionId`). */\n versionId: string\n /** Chosen chest option (`chestOptions[i].id`). */\n optionId?: string\n}\n\n/**\n * Input of {@link ClubApi.redeem}.\n * @category Club\n */\nexport interface RedeemClubRewardInput {\n /** Store item id. */\n rewardId: string\n /** {@link ClubProgram.versionId}. */\n versionId: string\n}\n\n/**\n * Input of {@link ClubApi.registerForTournament}.\n * @category Club\n */\nexport interface RegisterClubTournamentInput {\n /** Edition id. */\n editionId: string\n /** {@link ClubTournament.versionId}. */\n versionId: string\n /** Ticket to consume, when the tournament requires one. */\n ticketId?: string\n}\n\n/**\n * The casino club: program, activities (wheel, scratch, gift), missions with chests, coin store, history and\n * tournaments. Every method requires login. The gateway resolves the texts from the client's locale\n * (`Accept-Language`): change it with the core's `setLocale`.\n *\n * Writes are **idempotent**: each sends an `Idempotency-Key` (the one in `options.idempotencyKey` or one generated per\n * call; printable ASCII up to 128 characters, without surrounding spaces) that the club service stores. To retry a write whose\n * outcome is unknown, call again with the **same** key: the service answers the first result. The club answers a\n * duplicate still in flight with a plain 409 (`ALREADY_EXISTS`, never `KEY_IN_USE`), so a 409 is not a definitive\n * refusal: keep the key after anything but a 400, 403, 404 or 422 ({@link keepsClubIdempotencyKey} tells which).\n * Through `createIgamingMutations` the club writes follow that rule for you; an app that persists the key (e.g. per\n * action in `sessionStorage`, to survive a reload) uses the same helper to decide when to drop it.\n *\n * Errors to expect (identify by `error.code`): `NOT_FOUND` (404, also when the club is not active),\n * `PERMISSION_DENIED` (403), `ALREADY_EXISTS` (409, a conflict with the version, the availability or the account\n * state), `CLUB_WALLET_UNAVAILABLE` (503, or 409 when the wallet currency is not confirmed), `CLUB_RATE_LIMITED`\n * (429), `INVALID_ARGUMENT` (400), `UNAVAILABLE` (503).\n * @category Club\n */\nexport interface ClubApi {\n /**\n * The program, the player's balances, activities, missions and store.\n * @example\n * const { program, rewards } = await igaming.club.getOverview()\n * if (program.enabled && !program.joined && program.canJoin) showJoin(program.terms, program.termsLocale)\n * @throws {EnginexError} `UNAUTHENTICATED` without a session; `VALIDATION_ERROR`, also in `'warn'`, with money\n * outside the format.\n */\n getOverview(params?: NoParams, options?: CallOptions): Promise<ClubOverview>\n /**\n * The player's receipts and balance movements, newest first, cursor-paginated.\n * @example\n * const page = await igaming.club.listHistory({ limit: 30 })\n * const next = page.nextCursor && (await igaming.club.listHistory({ cursor: page.nextCursor, limit: 30 }))\n * @throws {EnginexError} `CONFIGURATION_ERROR` (no request) for a `cursor` that is not text or a `limit` outside\n * 1–100; `UNAUTHENTICATED` without a session.\n */\n listHistory(input?: ClubCursorInput, options?: CallOptions): Promise<ClubHistory>\n /**\n * Own and external tournaments, merged and cursor-paginated (gateway default: 50 per page).\n * @example\n * const { items, nextCursor } = await igaming.club.listTournaments()\n * @throws {EnginexError} `CONFIGURATION_ERROR` (no request) for a bad `cursor` or `limit`; `NOT_FOUND` when the\n * club is not active.\n */\n listTournaments(input?: ClubCursorInput, options?: CallOptions): Promise<ClubTournamentPage>\n /**\n * Other editions of the same external schedule as `editionId` (the gateway caps the page at 20). A page that\n * answers for another edition is read as empty.\n * @example\n * const { items } = await igaming.club.listRelatedTournaments({ editionId: 'ext_tlt_123', limit: 10 })\n * @throws {EnginexError} `CONFIGURATION_ERROR` (no request) for an `editionId` that is not an external edition id,\n * or a bad `cursor`/`limit`; `NOT_FOUND` for an unknown edition.\n */\n listRelatedTournaments(\n input: ListRelatedClubTournamentsInput,\n options?: CallOptions,\n ): Promise<ClubRelatedTournamentPage>\n /**\n * A tournament's detail, with the player's registration and award.\n * @example\n * const tournament = await igaming.club.getTournament({ editionId })\n * @throws {EnginexError} `CONFIGURATION_ERROR` (no request) for an empty `editionId` or one over 128 UTF-8 bytes;\n * `NOT_FOUND` for an unknown edition.\n */\n getTournament(input: { editionId: string }, options?: CallOptions): Promise<ClubTournament>\n /**\n * A tournament's ranking.\n * @example\n * const ranking = await igaming.club.getRanking({ editionId, limit: 20 })\n * @throws {EnginexError} `CONFIGURATION_ERROR` (no request) for a bad `editionId` or `limit`;\n * `CLUB_RANKING_UNAVAILABLE` (404) when the source cannot disclose it.\n */\n getRanking(input: GetClubRankingInput, options?: CallOptions): Promise<ClubRanking>\n /**\n * Joins the club (accepting the terms shown in `termsLocale`) or leaves it. Idempotent (see {@link ClubApi}).\n * @example\n * const program = await igaming.club.setMembership({ versionId, joined: true, termsLocale })\n * @throws {EnginexError} `CONFIGURATION_ERROR` (no request) for an empty `versionId`, a `joined` that is not a\n * boolean, an empty `termsLocale` when joining or a bad `idempotencyKey`; `ALREADY_EXISTS` (409) for a stale\n * version.\n */\n setMembership(input: SetClubMembershipInput, options?: CallOptions): Promise<ClubProgram>\n /**\n * Plays an activity, or opens a mission chest (`activityId` = `rightId`, `optionId` = the chosen option).\n * Idempotent (see {@link ClubApi}).\n * @example\n * const { receipt, sliceId } = await igaming.club.play({ activityId, versionId }, { idempotencyKey })\n * @throws {EnginexError} `CONFIGURATION_ERROR` (no request) for an empty `activityId`/`versionId`, a non-text\n * `optionId` or a bad `idempotencyKey`; `ALREADY_EXISTS` (409) when it cannot be played now.\n */\n play(input: PlayClubActivityInput, options?: CallOptions): Promise<ClubPlayResult>\n /**\n * Redeems a store item with coins. Idempotent (see {@link ClubApi}).\n * @example\n * const receipt = await igaming.club.redeem({ rewardId: item.id, versionId }, { idempotencyKey })\n * @throws {EnginexError} `CONFIGURATION_ERROR` (no request) for an empty `rewardId`/`versionId` or a bad\n * `idempotencyKey`; `ALREADY_EXISTS` (409) without enough coins or stock.\n */\n redeem(input: RedeemClubRewardInput, options?: CallOptions): Promise<ClubReceipt>\n /**\n * Registers the player in an own tournament. Idempotent (see {@link ClubApi}).\n * @example\n * const registration = await igaming.club.registerForTournament({ editionId, versionId: t.versionId })\n * @throws {EnginexError} `CONFIGURATION_ERROR` (no request) for an empty `editionId`/`versionId`, a non-text\n * `ticketId` or a bad `idempotencyKey`; `ALREADY_EXISTS` (409) when registration is closed.\n */\n registerForTournament(input: RegisterClubTournamentInput, options?: CallOptions): Promise<ClubTournamentRegistration>\n}\n\n/**\n * Whether a failed club write must keep its `Idempotency-Key` for the retry. The club service stores the key and\n * answers a duplicate that is still being processed with a plain 409, the same answer as a stale version: releasing\n * the key after it would let the next tap pay twice. So the key is kept after everything except a definitive\n * refusal (400, 403, 404, 422) or an error that never reached the club (`CONFIGURATION_ERROR`, `ABORTED`): network\n * errors, timeouts, 5xx, 401, 409, 429 and a 2xx outside the format all keep it. `createIgamingMutations` applies it\n * to the `club` writes; use it where the app keeps its own key (e.g. one per action, persisted across a reload).\n * @param error - What the write rejected with.\n * @example\n * try {\n * await igaming.club.redeem({ rewardId, versionId }, { idempotencyKey: pendingKey })\n * forget(pendingKey)\n * } catch (error) {\n * if (!keepsClubIdempotencyKey(error)) forget(pendingKey)\n * throw error\n * }\n * @throws Never throws: anything that is not an `EnginexError` returns `false`.\n * @category Club\n */\nexport function keepsClubIdempotencyKey(error: unknown): boolean {\n if (!isEnginexError(error)) return false\n if (isAmbiguousFailure(error)) return true\n return error.status >= 400 && !DEFINITIVE_CLUB_STATUS.has(error.status)\n}\n\nconst DEFINITIVE_CLUB_STATUS: ReadonlySet<number> = /* @__PURE__ */ new Set([400, 403, 404, 422])\n\n// ─── Schemas ───────────────────────────────────────────────────────────────────────────────────\n\nconst ISO_DATE_TIME = /^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}(?:\\.\\d{1,9})?(?:Z|[+-]\\d{2}:\\d{2})$/\nconst ISO_DAY = /^\\d{4}-\\d{2}-\\d{2}$/\nconst DECIMAL = /^(?:0|[1-9]\\d{0,19})(?:\\.\\d{1,20})?$/\nconst EXTERNAL_EDITION = /^ext_[A-Za-z0-9_-]+$/\nconst GO_ZERO_TIME = /^0001-01-01T00:00:00(?:\\.0+)?(?:Z|[+-]00:00)$/\n\n/**\n * Optional ISO 8601 date-time: absent, `null`, `\"\"`, the epoch (protojson's zero `Timestamp` as `AsTime()`) and\n * Go's zero `time.Time` (`encoding/json`) become `null`. Anything else that is not an RFC 3339 date-time fails.\n */\nconst time = () =>\n z.pipe(\n z.nullish(\n z\n .string()\n .check(\n z.refine(\n (value) => value === '' || (ISO_DATE_TIME.test(value) && !Number.isNaN(Date.parse(value))),\n 'Expected an ISO 8601 date-time',\n ),\n ),\n ),\n z.transform((value): string | null =>\n value == null || value === '' || Date.parse(value) === 0 || GO_ZERO_TIME.test(value) ? null : value,\n ),\n )\n\nconst flag = () => z._default(z.boolean(), false)\nconst textOrEmpty = () => z._default(z.string(), '')\nconst id = () => z.string().check(z.minLength(1, 'Expected a non-empty id'))\nconst localized = () => mapOf(z.string())\n// int64 counters that are not money (coins, XP, quantities): int64 text or a number, safe integers, normal `'warn'`\n// rule (the divergent field arrives raw and is reported).\nconst units = () => z._default(integerText(), 0)\nconst int32 = () =>\n z._default(z.number().check(z.refine((value) => Number.isSafeInteger(value), 'Expected an integer')), 0)\nconst rank = () =>\n z.number().check(z.refine((value) => Number.isSafeInteger(value) && value >= 1, 'Expected an integer ≥ 1'))\n// Free-text codes the gateway writes in lowercase: lowercased, `''`/absent as `unspecified`, a new value passes.\nconst code = () =>\n z.pipe(\n protoEnum(''),\n z.transform((value) => (value === '' ? 'unspecified' : value)),\n )\n// An optional code: `''`/absent/`null` as `null`, otherwise lowercased.\nconst optionalCode = () =>\n z.pipe(\n z.nullish(z.string()),\n z.transform((value): string | null => (value ? value.toLowerCase() : null)),\n )\nconst nullable = <T extends z.ZodMiniType>(schema: T) =>\n z.pipe(\n z.nullish(schema),\n z.transform((value): z.output<T> | null => value ?? null),\n )\n\n/** A list (omitted/`null` as `[]`) whose repeated keys keep the first occurrence. */\nfunction uniqueList<T extends z.ZodMiniType>(item: T, key: (value: z.output<T>) => string | undefined) {\n return z.pipe(\n nullableList(item),\n z.transform((items): z.output<T>[] => {\n const seen = new Set<string>()\n return items.filter((value) => {\n // In `'warn'` an item whose identity came in raw (e.g. the `activity` of an activity state as text) has no\n // key: it is dropped, so the app never reads a field of a text where it expects an object.\n const k = typeof value === 'object' && value !== null ? safeKey(() => key(value)) : String(value)\n if (k === undefined || seen.has(k)) return false\n seen.add(k)\n return true\n })\n }),\n )\n}\n\nfunction safeKey(read: () => string | undefined): string | undefined {\n try {\n const value = read()\n return typeof value === 'string' && value !== '' ? value : undefined\n } catch {\n return undefined\n }\n}\n\n// `ClubMoney` (and `ClubSpinDenomination`, same shape): strict even in `'warn'`, like the other money of the SDK.\nconst moneySchema = /* @__PURE__ */ lazy(\n (): z.ZodMiniType<ClubMoney> =>\n z.pipe(\n wire({\n currency: currencyCode(),\n amountMinor: nonNegativeMinorUnits(),\n decimalPlaces: z.optional(decimalPlaces()),\n }),\n z.transform(\n (m): ClubMoney => ({ amount: m.amountMinor, currency: m.currency, decimalPlaces: m.decimalPlaces ?? null }),\n ),\n ),\n)\n\nconst alternateSchema = /* @__PURE__ */ lazy(\n (): z.ZodMiniType<ClubAlternateReward> => wire({ kind: code(), label: localized(), quantity: units() }),\n)\n\nconst rewardSchema = /* @__PURE__ */ lazy(\n (): z.ZodMiniType<ClubReward> =>\n wire({\n id: textOrEmpty(),\n label: localized(),\n kind: code(),\n quantity: units(),\n money: nullable(moneySchema()),\n campaign: nullable(wire({ spins: units(), gameId: optionalText() })),\n cashback: nullable(\n wire({\n percentageBps: int32(),\n period: optionalCode(),\n basis: optionalCode(),\n destination: optionalCode(),\n startsAt: time(),\n endsAt: time(),\n gameIds: uniqueList(z.string(), String),\n zeroBasisAlternate: nullable(alternateSchema()),\n priorAwardAlternate: nullable(alternateSchema()),\n }),\n ),\n manual: nullable(wire({ deliveryType: optionalCode(), instructions: localized() })),\n ttlSeconds: units(),\n editionId: optionalText(),\n ticketOwnedAlternate: nullable(alternateSchema()),\n }),\n)\n\nconst receiptSchema = /* @__PURE__ */ lazy(\n (): z.ZodMiniType<ClubReceipt> =>\n wire({\n id: id(),\n status: code(),\n sourceKind: code(),\n sourceId: optionalText(),\n sliceId: optionalText(),\n reward: nullable(rewardSchema()),\n settlement: nullable(moneySchema()),\n costCoins: units(),\n acceptedAt: time(),\n deliveredAt: time(),\n expiresAt: time(),\n tournamentRank: nullable(rank()),\n ticketConsumed: flag(),\n }),\n)\n\nconst levelSchema = () => wire({ id: id(), name: localized(), minXp: units(), benefit: localized() })\n\nconst programSchema = /* @__PURE__ */ lazy(\n (): z.ZodMiniType<ClubProgram> =>\n wire({\n enabled: flag(),\n joined: flag(),\n membershipRequired: flag(),\n canJoin: flag(),\n historyAvailable: flag(),\n versionId: optionalText(),\n locale: optionalText(),\n termsLocale: optionalText(),\n timeZone: optionalText(),\n currency: z.pipe(\n z._default(currencyOrEmpty(), ''),\n z.transform((value): string | null => value || null),\n ),\n name: localized(),\n terms: localized(),\n coinName: localized(),\n coverUrl: optionalText(),\n levels: uniqueList(levelSchema(), (level) => level.id),\n }),\n)\n\nconst activitySchema = () =>\n wire({\n activity: wire({\n id: id(),\n kind: code(),\n name: localized(),\n terms: localized(),\n coverUrl: optionalText(),\n wheelTheme: optionalCode(),\n playLabel: localized(),\n slices: uniqueList(wire({ id: id(), reward: nullable(rewardSchema()) }), (slice) => slice.id),\n }),\n canPlay: flag(),\n unavailableReason: optionalCode(),\n latestReceipt: nullable(receiptSchema()),\n availableAt: time(),\n })\n\nconst missionSchema = () =>\n wire({\n mission: wire({\n id: id(),\n title: localized(),\n terms: localized(),\n recurrence: code(),\n countBy: code(),\n target: units(),\n coverUrl: optionalText(),\n }),\n editionId: optionalText(),\n progress: units(),\n rightId: optionalText(),\n rightVersionId: optionalText(),\n chestOptions: nullableList(rewardSchema()),\n canClaim: flag(),\n receipt: nullable(receiptSchema()),\n endsAt: time(),\n claimExpiresAt: time(),\n stampedDays: uniqueList(\n z\n .string()\n .check(\n z.refine((value) => ISO_DAY.test(value) && !Number.isNaN(Date.parse(value)), 'Expected a YYYY-MM-DD day'),\n ),\n String,\n ),\n })\n\nconst storeItemSchema = () =>\n wire({\n item: wire({\n id: id(),\n label: localized(),\n terms: localized(),\n costCoins: units(),\n reward: nullable(rewardSchema()),\n coverUrl: optionalText(),\n }),\n canRedeem: flag(),\n unavailableReason: optionalCode(),\n })\n\nconst rewardsSchema = /* @__PURE__ */ lazy(\n (): z.ZodMiniType<ClubRewards> =>\n wire({\n xp: units(),\n coins: units(),\n levelId: optionalText(),\n activities: uniqueList(activitySchema(), (state) => state.activity.id),\n // The same mission may hold several rights (one per period): a repeat is the same mission, right and period.\n missions: uniqueList(missionSchema(), (state) =>\n typeof state.mission.id === 'string'\n ? JSON.stringify([state.mission.id, state.rightId ?? state.editionId, state.endsAt])\n : undefined,\n ),\n storeItems: uniqueList(storeItemSchema(), (state) => state.item.id),\n }),\n)\n\nconst overviewSchema = /* @__PURE__ */ lazy(\n (): z.ZodMiniType<ClubOverview> => wire({ program: programSchema(), rewards: nullable(rewardsSchema()) }),\n)\n\nconst nextCursor = () =>\n z.pipe(\n optionalText(),\n z.transform((value) => value ?? undefined),\n )\n\n/** Drops an `undefined` `nextCursor`, so the last page has no such key. */\nfunction compactCursor<T extends { nextCursor?: string | undefined }>(page: T): T {\n if (page.nextCursor === undefined) delete page.nextCursor\n return page\n}\n\nconst historySchema = /* @__PURE__ */ lazy(\n (): z.ZodMiniType<ClubHistory> =>\n z.pipe(\n wire({\n receipts: uniqueList(receiptSchema(), (receipt) => receipt.id),\n movements: uniqueList(\n wire({ id: id(), kind: code(), units: units(), sourceId: optionalText(), occurredAt: time() }),\n (movement) => movement.id,\n ),\n nextCursor: nextCursor(),\n }),\n z.transform(compactCursor),\n ),\n)\n\nconst registrationSchema = /* @__PURE__ */ lazy(\n (): z.ZodMiniType<ClubTournamentRegistration> =>\n wire({ id: id(), editionId: id(), versionId: optionalText(), joinedAt: time() }),\n)\n\nconst isMinorUnits = (v: unknown): boolean =>\n (typeof v === 'number' && Number.isSafeInteger(v) && v >= 0) ||\n (typeof v === 'string' && /^\\d+$/.test(v) && Number.isSafeInteger(Number(v)))\n\n// Not strict: a value outside the format is a normal issue (reported, the field arriving raw in `'warn'`), never\n// rounded (≥ 2^53 as text fails like any other malformed amount).\nconst announcedMoney = () =>\n z.pipe(\n wire({\n currency: z.string().check(z.regex(/^[A-Z]{3}$/, 'Expected a currency code, e.g. BRL')),\n amountMinor: z.union([z.string(), z.number()]).check(z.refine(isMinorUnits, 'Expected non-negative minor units')),\n decimalPlaces: z.optional(\n z.number().check(z.refine((v) => Number.isInteger(v) && v >= 0 && v <= 8, 'Expected decimal places 0 to 8')),\n ),\n }),\n // In `'warn'` the amount may come in raw: only an exact non-negative integer becomes `amount`; anything else stays\n // as it came, so `hasValidAnnouncedAmount` drops the prize (never `Number('1e3')`, never a rounded value).\n z.transform(\n (m): ClubMoney => ({\n amount: isMinorUnits(m.amountMinor) ? Number(m.amountMinor) || 0 : (m.amountMinor as unknown as number),\n currency: m.currency,\n decimalPlaces: m.decimalPlaces ?? null,\n }),\n ),\n )\n\nconst prizeSchema = () =>\n wire({\n fromRank: int32(),\n toRank: int32(),\n reward: nullable(rewardSchema()),\n announcedAmount: nullable(announcedMoney()),\n terms: localized(),\n offerTerms: nullable(\n wire({\n spinDenomination: nullable(moneySchema()),\n wageringMultiplier: nullable(z.string().check(z.regex(DECIMAL, 'Expected an exact decimal'))),\n validForSeconds: nullable(integerText()),\n expiresAt: time(),\n grantEndsAt: time(),\n }),\n ),\n })\n\n/** `false` for a prize whose announced amount came in raw (recovered in `'warn'`): it is dropped, already reported. */\nfunction hasValidAnnouncedAmount(prize: { announcedAmount: unknown }): boolean {\n const amount = prize.announcedAmount\n if (amount === null) return true\n if (typeof amount !== 'object') return false\n const { amount: value, currency } = amount as Record<string, unknown>\n return (\n typeof value === 'number' &&\n Number.isSafeInteger(value) &&\n value >= 0 &&\n typeof currency === 'string' &&\n /^[A-Z]{3}$/.test(currency)\n )\n}\n\nconst tournamentSchema = /* @__PURE__ */ lazy(\n (): z.ZodMiniType<ClubTournament> =>\n wire({\n id: id(),\n source: code(),\n versionId: optionalText(),\n title: localized(),\n terms: localized(),\n status: code(),\n startsAt: time(),\n endsAt: time(),\n updatedAt: time(),\n scoringRule: optionalCode(),\n tieBreak: optionalCode(),\n currency: z.pipe(\n z._default(currencyOrEmpty(), ''),\n z.transform((value): string | null => value || null),\n ),\n timeZone: optionalText(),\n gameIds: uniqueList(z.string(), String),\n // An announced amount (an external listing) is display data, not a prize the player wins: one outside the\n // format (negative, a fraction, ≥ 2^53, a bad currency) fails without the strict mark, so `'warn'` reports it\n // and drops that prize instead of failing the whole page. Strict mode still rejects it.\n prizes: z.pipe(\n nullableList(prizeSchema()),\n z.transform((prizes) => prizes.filter(hasValidAnnouncedAmount)),\n ),\n joinMode: optionalCode(),\n locale: optionalText(),\n rankingAvailable: flag(),\n canRegister: flag(),\n requiresTicket: flag(),\n registration: nullable(registrationSchema()),\n personalAward: nullable(receiptSchema()),\n stale: flag(),\n registrationStartsAt: time(),\n registrationEndsAt: time(),\n coverUrl: optionalText(),\n }),\n)\n\nconst tournamentPageSchema = /* @__PURE__ */ lazy(\n (): z.ZodMiniType<ClubTournamentPage> =>\n z.pipe(\n wire({\n items: uniqueList(tournamentSchema(), (tournament) => tournament.id),\n externalAvailable: flag(),\n externalStale: flag(),\n nextCursor: nextCursor(),\n }),\n z.transform(compactCursor),\n ),\n)\n\nconst relatedPageSchema = /* @__PURE__ */ lazy(() =>\n wire({\n relatedTo: textOrEmpty(),\n items: uniqueList(\n wire({\n id: z.string().check(z.regex(EXTERNAL_EDITION, 'Expected an external edition id')),\n title: localized(),\n status: code(),\n startsAt: time(),\n endsAt: time(),\n }),\n (item) => item.id,\n ),\n nextCursor: nextCursor(),\n }),\n)\n\nconst rankSchema = () => wire({ position: rank(), displayName: textOrEmpty(), score: textOrEmpty() })\n\nconst rankingSchema = /* @__PURE__ */ lazy(\n (): z.ZodMiniType<ClubRanking> =>\n wire({ entries: nullableList(rankSchema()), personal: nullable(rankSchema()), updatedAt: time(), final: flag() }),\n)\n\nconst playSchema = /* @__PURE__ */ lazy(\n (): z.ZodMiniType<ClubPlayResult> =>\n wire({ receipt: receiptSchema(), sliceId: optionalText(), rewards: nullable(rewardsSchema()) }),\n)\n\n// ─── Input checks ──────────────────────────────────────────────────────────────────────────────\n\nconst BASE = '/casino/club'\n// The gateway's `clubSetPathID` and `clubMutationKey` refuse anything above 128 bytes (Go `len`).\nconst MAX_ID = 128\nconst MAX_IDEMPOTENCY_KEY = 128\n\nconst ROUTES = {\n overview: { method: 'GET', path: BASE },\n history: { method: 'GET', path: `${BASE}/history` },\n tournaments: { method: 'GET', path: `${BASE}/tournaments` },\n tournament: { method: 'GET', path: `${BASE}/tournaments/{editionId}` },\n ranking: { method: 'GET', path: `${BASE}/tournaments/{editionId}/ranking` },\n membership: { method: 'PUT', path: `${BASE}/membership` },\n play: { method: 'POST', path: `${BASE}/activities/{activityId}/plays` },\n redeem: { method: 'POST', path: `${BASE}/rewards/{rewardId}/redemptions` },\n register: { method: 'POST', path: `${BASE}/tournaments/{editionId}/registrations` },\n} satisfies Record<string, Route>\n\nconst isObject = (value: unknown): value is Record<string, unknown> =>\n typeof value === 'object' && value !== null && !Array.isArray(value)\n\n/** Length in UTF-8 bytes: the gateway's `len()` in Go, not JavaScript's UTF-16 units. */\nfunction utf8Length(value: string): number {\n return new TextEncoder().encode(value).length\n}\n\nfunction idProblem(name: string, field: string, value: unknown): string | undefined {\n return typeof value === 'string' && value.trim() !== '' && utf8Length(value) <= MAX_ID\n ? undefined\n : `${name}: ${field} must be non-empty text up to ${MAX_ID} UTF-8 bytes.`\n}\n\nfunction optionalTextProblem(name: string, field: string, value: unknown): string | undefined {\n return value === undefined || typeof value === 'string' ? undefined : `${name}: ${field} must be text.`\n}\n\nfunction limitProblem(name: string, value: unknown): string | undefined {\n return value === undefined || (typeof value === 'number' && Number.isInteger(value) && value >= 1 && value <= 100)\n ? undefined\n : `${name}: limit must be an integer from 1 to 100.`\n}\n\nfunction cursorProblem(name: string, input: unknown): string | undefined {\n if (input === undefined) return undefined\n if (!isObject(input)) return `${name}: input must be an object.`\n return optionalTextProblem(name, 'cursor', input.cursor) ?? limitProblem(name, input.limit)\n}\n\nfunction keyProblem(name: string, options: CallOptions | undefined): string | undefined {\n const key = options?.idempotencyKey\n if (key === undefined || key === '') return undefined\n // A header value is a byte string: only printable ASCII travels as itself (an emoji makes `fetch` throw, a Latin-1\n // letter reaches the gateway as other bytes), so one ASCII character is one of the gateway's bytes.\n return typeof key === 'string' &&\n key === key.trim() &&\n /^[\\x20-\\x7E]+$/.test(key) &&\n key.length <= MAX_IDEMPOTENCY_KEY\n ? undefined\n : `${name}: idempotencyKey must be printable ASCII without surrounding spaces, up to ${MAX_IDEMPOTENCY_KEY} characters.`\n}\n\nfunction membershipProblem(input: unknown): string | undefined {\n const name = 'club.setMembership'\n if (!isObject(input)) return `${name}: input must be { versionId, joined, termsLocale? }.`\n if (typeof input.joined !== 'boolean') return `${name}: joined must be true or false.`\n const versionProblem = idProblem(name, 'versionId', input.versionId)\n if (versionProblem) return versionProblem\n if (input.joined && (typeof input.termsLocale !== 'string' || input.termsLocale.trim() === ''))\n return `${name}: termsLocale must be non-empty text when joining.`\n return undefined\n}\n\nconst segment = (value: string) => encodeURIComponent(value)\n\n/**\n * In `'warn'` a required message of the wrong type (text, a number) arrives raw. The overview without its program and\n * a play without its receipt mean nothing: they reject with `VALIDATION_ERROR` (status 200, so an idempotent retry\n * keeps the key and replays the result) instead of handing the app a text where it reads an object.\n */\nfunction requireObject<T extends object>(transport: ExtensionTransport, route: Route, field: keyof T & string) {\n return (value: T): T => {\n if (isObject(value[field])) return value\n throw transport.reportError(\n {\n code: 'VALIDATION_ERROR',\n message: `Unexpected gateway response on ${route.method} ${route.path}: ${field}`,\n status: 200,\n },\n route,\n )\n }\n}\n\n/** Creates the `club` namespace. @internal */\nexport function createClubApi(transport: ExtensionTransport): ClubApi {\n const get = <T>(\n path: string,\n query: Record<string, string | number | undefined>,\n schema: z.ZodMiniType<T>,\n options?: CallOptions,\n ) => transport.request({ method: 'GET', path, query, auth: 'required', schema, options })\n\n const write = <T>(\n method: 'POST' | 'PUT',\n path: string,\n body: Record<string, unknown>,\n schema: z.ZodMiniType<T>,\n options: CallOptions | undefined,\n ) =>\n // The key goes only in the `Idempotency-Key` header: the gateway reads it from there when the body has none\n // (a body key that differed from the header would be refused).\n transport.request({ method, path, body, auth: 'required', idempotent: true, schema, options })\n\n return {\n getOverview: (_params, options) =>\n get(BASE, {}, overviewSchema(), options).then(requireObject<ClubOverview>(transport, ROUTES.overview, 'program')),\n\n listHistory: (input, options) => {\n const problem = cursorProblem('club.listHistory', input)\n if (problem !== undefined) return rejectInput(transport, problem, ROUTES.history)\n return get(\n ROUTES.history.path,\n { cursor: input?.cursor || undefined, limit: input?.limit },\n historySchema(),\n options,\n )\n },\n\n listTournaments: (input, options) => {\n const problem = cursorProblem('club.listTournaments', input)\n if (problem !== undefined) return rejectInput(transport, problem, ROUTES.tournaments)\n return get(\n ROUTES.tournaments.path,\n { cursor: input?.cursor || undefined, limit: input?.limit },\n tournamentPageSchema(),\n options,\n )\n },\n\n listRelatedTournaments: (input, options) => {\n const name = 'club.listRelatedTournaments'\n const problem = !isObject(input)\n ? `${name}: input must be { editionId }.`\n : typeof input.editionId !== 'string' ||\n utf8Length(input.editionId) > MAX_ID ||\n !EXTERNAL_EDITION.test(input.editionId)\n ? `${name}: editionId must be an external edition id (ext_...), up to ${MAX_ID} characters.`\n : cursorProblem(name, input)\n if (problem !== undefined) return rejectInput(transport, problem, ROUTES.tournaments)\n return get(\n ROUTES.tournaments.path,\n { relatedTo: input.editionId, cursor: input.cursor || undefined, limit: input.limit },\n relatedPageSchema(),\n options,\n ).then(({ relatedTo, items, nextCursor: cursor }): ClubRelatedTournamentPage => {\n // A page about another edition is not about this one: read as empty, never mixed in.\n if (relatedTo !== input.editionId) return { items: [] }\n return cursor === undefined ? { items } : { items, nextCursor: cursor }\n })\n },\n\n getTournament: (input, options) => {\n const problem = idProblem('club.getTournament', 'editionId', isObject(input) ? input.editionId : undefined)\n if (problem !== undefined) return rejectInput(transport, problem, ROUTES.tournament)\n return get(`${BASE}/tournaments/${segment(input.editionId)}`, {}, tournamentSchema(), options)\n },\n\n getRanking: (input, options) => {\n const name = 'club.getRanking'\n const problem = isObject(input)\n ? (idProblem(name, 'editionId', input.editionId) ?? limitProblem(name, input.limit))\n : `${name}: input must be { editionId }.`\n if (problem !== undefined) return rejectInput(transport, problem, ROUTES.ranking)\n return get(\n `${BASE}/tournaments/${segment(input.editionId)}/ranking`,\n { limit: input.limit },\n rankingSchema(),\n options,\n )\n },\n\n setMembership: (input, options) => {\n const problem = membershipProblem(input) ?? keyProblem('club.setMembership', options)\n if (problem !== undefined) return rejectInput(transport, problem, ROUTES.membership)\n const body = input.joined\n ? { versionId: input.versionId, joined: true, termsLocale: input.termsLocale }\n : { versionId: input.versionId, joined: false }\n return write('PUT', ROUTES.membership.path, body, programSchema(), options)\n },\n\n play: (input, options) => {\n const name = 'club.play'\n const problem = isObject(input)\n ? (idProblem(name, 'activityId', input.activityId) ??\n idProblem(name, 'versionId', input.versionId) ??\n optionalTextProblem(name, 'optionId', input.optionId) ??\n keyProblem(name, options))\n : `${name}: input must be { activityId, versionId, optionId? }.`\n if (problem !== undefined) return rejectInput(transport, problem, ROUTES.play)\n const body: Record<string, unknown> = { versionId: input.versionId }\n if (input.optionId) body.optionId = input.optionId\n return write('POST', `${BASE}/activities/${segment(input.activityId)}/plays`, body, playSchema(), options).then(\n requireObject<ClubPlayResult>(transport, ROUTES.play, 'receipt'),\n )\n },\n\n redeem: (input, options) => {\n const name = 'club.redeem'\n const problem = isObject(input)\n ? (idProblem(name, 'rewardId', input.rewardId) ??\n idProblem(name, 'versionId', input.versionId) ??\n keyProblem(name, options))\n : `${name}: input must be { rewardId, versionId }.`\n if (problem !== undefined) return rejectInput(transport, problem, ROUTES.redeem)\n return write(\n 'POST',\n `${BASE}/rewards/${segment(input.rewardId)}/redemptions`,\n { versionId: input.versionId },\n receiptSchema(),\n options,\n )\n },\n\n registerForTournament: (input, options) => {\n const name = 'club.registerForTournament'\n const problem = isObject(input)\n ? (idProblem(name, 'editionId', input.editionId) ??\n idProblem(name, 'versionId', input.versionId) ??\n optionalTextProblem(name, 'ticketId', input.ticketId) ??\n keyProblem(name, options))\n : `${name}: input must be { editionId, versionId, ticketId? }.`\n if (problem !== undefined) return rejectInput(transport, problem, ROUTES.register)\n const body: Record<string, unknown> = { versionId: input.versionId }\n if (input.ticketId) body.ticketId = input.ticketId\n return write(\n 'POST',\n `${BASE}/tournaments/${segment(input.editionId)}/registrations`,\n body,\n registrationSchema(),\n options,\n )\n },\n }\n}\n","// Public types come from the core's main entry: the /extension `.d.ts` exposes Zod, and this package's\n// public API cannot depend on it (check-api).\nimport type { CallOptions, NoParams } from '@getenginex/sdk'\nimport { lazy, wire, type ExtensionTransport } from '@getenginex/sdk/extension'\nimport * as z from 'zod/mini'\nimport { rejectInput } from '../internal/input'\nimport { optionalText, optionalTimestamp } from '../internal/optional-values'\nimport { currencyOrEmpty, integerText, minorUnits } from '../internal/schemas'\n\n/**\n * Type of points redemption. The `bonus.proto` mentions `bonus`, `cash` and `free_bet`, but the backend\n * treats the field as free text and the contract does not say which ones the operator enables: the SDK sends the value\n * as received (it only refuses empty) and the server decides.\n * @category Loyalty\n */\nexport type RedemptionType = 'bonus' | 'cash' | 'free_bet' | (string & {})\n\n/**\n * Benefits of a loyalty tier as the operator wrote them: an object keyed by benefit or a list of benefits.\n * @category Loyalty\n */\nexport type LoyaltyTierBenefits = Record<string, unknown> | unknown[]\n\n/**\n * The player's loyalty status (`GET /loyalty`).\n * @category Loyalty\n */\nexport interface LoyaltyStatus {\n /** Total points earned (integer). */\n totalPointsEarned: number\n /** Points available for redemption (integer). */\n currentPoints: number\n /** Points already redeemed (integer). */\n pointsRedeemed: number\n /** Current tier; `null` when the gateway does not report it (empty or absent). The contract does not list the possible tiers (the operator defines them). */\n currentTier: string | null\n /** Points that count toward the tier (integer); the calculation rule is not reported by the contract. */\n tierPoints: number\n /** Total wagered over the player's lifetime, in minor units (the contract field is called `*_cents`; the currency does not come with it). */\n lifetimeWagered: number\n /** Total deposited over the player's lifetime, in minor units (the currency does not come with it). */\n lifetimeDeposited: number\n /**\n * Benefits of the current tier, read from the JSON text the gateway passes along: an object (keyed by benefit)\n * or a list. The format is defined by the operator (the contract only says \"benefits of the current tier\"):\n * check before displaying. `null` when it comes empty or absent, and also when it is neither a JSON object nor\n * a JSON array (in this case `onValidationIssue` is notified, without the content).\n */\n tierBenefits: LoyaltyTierBenefits | null\n /** When the tier expires (ISO 8601, UTC); `null` when the gateway does not send it. */\n tierExpiresAt: string | null\n}\n\n/**\n * Input of {@link LoyaltyApi.redeem}.\n * @category Loyalty\n */\nexport interface RedeemPointsInput {\n /** Points to redeem: a safe integer > 0. */\n points: number\n /** Redemption type (non-empty text). */\n redemptionType: RedemptionType\n}\n\n/**\n * Result of {@link LoyaltyApi.redeem}.\n * @category Loyalty\n */\nexport interface RedeemedPoints {\n /** Points actually redeemed (integer). */\n redeemedPoints: number\n /** Redemption value in minor units of `currency`; `null` when the gateway does not send it. */\n value: number | null\n /** Currency of `value`; `null` when absent. */\n currency: string | null\n /** Id of the bonus generated, when the redemption was into a bonus; `null` otherwise. */\n bonusId: string | null\n}\n\n/**\n * The player's loyalty (points and tier). Both methods require login.\n * @category Loyalty\n */\nexport interface LoyaltyApi {\n /**\n * The player's points balance, tier and benefits.\n * @example\n * const loyalty = await igaming.loyalty.get()\n * console.log(loyalty.currentPoints, loyalty.currentTier, loyalty.tierBenefits)\n * @throws {EnginexError} `UNAUTHENTICATED` without a session. With `validation: 'strict'`,\n * `VALIDATION_ERROR` if `tier_benefits_json` is neither a JSON object nor a JSON array.\n */\n get(params?: NoParams, options?: CallOptions): Promise<LoyaltyStatus>\n /**\n * Exchanges points for a bonus, cash or a free bet. It sends `Idempotency-Key` (generated per call\n * or the one in `options.idempotencyKey`, kept on the retry after renewing the session), **but the gateway does not\n * apply the idempotency middleware on this route yet**: a double click may redeem twice.\n * Lock the button until the call finishes.\n * @example\n * const result = await igaming.loyalty.redeem({ points: 500, redemptionType: 'bonus' })\n * console.log(result.redeemedPoints, result.bonusId)\n * @throws {EnginexError} `CONFIGURATION_ERROR` (without a request) if `points` is not an integer > 0 or\n * `redemptionType` is empty; `INSUFFICIENT_BALANCE` or `FAILED_PRECONDITION` when the service\n * refuses the redemption (always identify by `error.code`); `UNKNOWN` with `status` 200 if the gateway\n * answers without confirming the redemption (`success: false`, absent or malformed; it also applies in\n * `validation: 'warn'`; `message` is the gateway's when it comes, otherwise the SDK's). General rule:\n * `UNKNOWN` with a 2xx `status` = unconfirmed operation: re-read the state ({@link LoyaltyApi.get})\n * before trying again. `UNAUTHENTICATED` without a session.\n */\n redeem(input: RedeemPointsInput, options?: CallOptions): Promise<RedeemedPoints>\n}\n\n// JSON object or array as text. Empty/absent is `null` without a warning; anything else becomes a\n// `tier_benefits_json` divergence (without the text, which may hold operator data, in the message).\n// The parsed value travels boxed, so that a raw value recovered in `'warn'` mode (a JSON array sent instead of\n// the text, say) is never taken for benefits the SDK parsed.\nclass ParsedBenefits {\n constructor(readonly value: LoyaltyTierBenefits) {}\n}\n\nconst tierBenefits = () =>\n z.pipe(\n z.nullish(z.string()),\n z.transform((text, ctx): ParsedBenefits | null => {\n if (text == null || text.trim() === '') return null\n let parsed: unknown\n try {\n parsed = JSON.parse(text)\n } catch {\n parsed = undefined\n }\n if (typeof parsed === 'object' && parsed !== null) return new ParsedBenefits(parsed as LoyaltyTierBenefits)\n ctx.issues.push({\n code: 'custom',\n message: 'tier_benefits_json is not a JSON object or array',\n input: undefined,\n })\n return z.NEVER\n }),\n )\n\n// `GetUserLoyalty`: int64 as a number; `tier_expires_at` only comes when filled in.\nconst loyaltySchema = /* @__PURE__ */ lazy(\n (): z.ZodMiniType<LoyaltyStatus> =>\n z.pipe(\n wire({\n total_points_earned: integerText(),\n current_points: integerText(),\n points_redeemed: integerText(),\n current_tier: optionalText(),\n tier_points: integerText(),\n lifetime_wagered: z._default(minorUnits(), 0),\n lifetime_deposited: z._default(minorUnits(), 0),\n tier_benefits_json: tierBenefits(),\n tier_expires_at: optionalTimestamp(),\n }),\n z.transform(({ tierBenefitsJson, ...rest }): LoyaltyStatus => {\n // With `validation: 'warn'`, a field that diverged arrives raw (the text): the SDK delivers `null`.\n const benefits = tierBenefitsJson instanceof ParsedBenefits ? tierBenefitsJson.value : null\n return { ...rest, tierBenefits: benefits } as LoyaltyStatus\n }),\n ),\n)\n\n// `RedeemLoyaltyPoints`: `value`/`currency` only come with `Money` filled in; `bonus_id` only if present;\n// `success` the gateway always sends; the SDK checks it (only `true` confirms) and does not expose it. The gateway does not\n// pass `message` along yet: if it comes, it becomes the message of the unconfirmed redemption error (as in KYC).\nconst redeemSchema = /* @__PURE__ */ lazy(\n (): z.ZodMiniType<RedeemedPoints & { success: unknown; message: unknown }> =>\n z.pipe(\n wire({\n success: z.optional(z.boolean()),\n message: z.optional(z.string()),\n redeemed_points: integerText(),\n value: z.nullish(minorUnits()),\n // Currency strict even in `'warn'`; absent, `null` and `''` still become `null`.\n currency: z.pipe(\n z.nullish(currencyOrEmpty()),\n z.transform((value): string | null => (value == null || value === '' ? null : value)),\n ),\n bonus_id: optionalText(),\n }),\n z.transform((data) => ({\n success: data.success,\n message: data.message,\n redeemedPoints: data.redeemedPoints,\n value: data.value ?? null,\n currency: data.currency,\n bonusId: data.bonusId,\n })),\n ),\n)\n\nconst UNCONFIRMED_REDEEM = 'loyalty.redeem: the gateway did not confirm the redemption.'\n\nconst REDEEM_ROUTE = { method: 'POST', path: '/loyalty/redeem' } as const\n\n// Checks the input before any request; the message never carries the received value.\nfunction redeemInputProblem(input: unknown): string | undefined {\n if (typeof input !== 'object' || input === null || Array.isArray(input))\n return 'loyalty.redeem: input must be an object { points, redemptionType }.'\n const { points, redemptionType } = input as { points?: unknown; redemptionType?: unknown }\n if (typeof points !== 'number' || !Number.isSafeInteger(points) || points <= 0)\n return 'loyalty.redeem: points must be an integer greater than 0.'\n if (typeof redemptionType !== 'string' || redemptionType.trim() === '')\n return 'loyalty.redeem: redemptionType must be non-empty text.'\n return undefined\n}\n\n/** Creates the `loyalty` namespace. @internal */\nexport function createLoyaltyApi(transport: ExtensionTransport): LoyaltyApi {\n return {\n get: (_params, options) =>\n transport.request({ method: 'GET', path: '/loyalty', auth: 'required', schema: loyaltySchema(), options }),\n redeem: (input, options) => {\n const problem = redeemInputProblem(input)\n if (problem !== undefined) return rejectInput(transport, problem, REDEEM_ROUTE)\n return transport\n .request({\n ...REDEEM_ROUTE,\n body: { points: input.points, redemption_type: input.redemptionType },\n auth: 'required',\n idempotent: true,\n schema: redeemSchema(),\n options,\n })\n .then(({ success, message, ...result }) => {\n // 200 without confirmation (`success: false`, absent or malformed, even in `warn`): the redemption may\n // not have happened; it never delivers a result as if it had.\n if (success === true) return result\n const text = typeof message === 'string' && message !== '' ? message : UNCONFIRMED_REDEEM\n throw transport.reportError({ code: 'UNKNOWN', message: text, status: 200 }, REDEEM_ROUTE)\n })\n },\n }\n}\n","import * as z from 'zod/mini'\n\n/**\n * Schema of a free-text backend value that the SDK knows in `values` (e.g. `daily`, `weekly`): compares\n * in lowercase and delivers the normalized value. A value the SDK does not know does not pass: with\n * `validation: 'strict'` the call rejects with `VALIDATION_ERROR`; in `'warn'` the field arrives raw, as it\n * came from the gateway, and `onValidationIssue` is notified. The matching public type is an open union\n * (`| (string & {})`). Equivalent to the core's internal helper. Call only inside a `lazy`. @internal\n */\nexport function openUnion<const V extends readonly [string, ...string[]]>(values: V) {\n return z.pipe(\n z.pipe(\n z.string(),\n z.transform((value) => value.toLowerCase()),\n ),\n z.enum(values),\n )\n}\n","// Public types come from the core's main entry: the /extension `.d.ts` exposes Zod, and this package's\n// public API cannot depend on it (check-api).\nimport type { CallOptions, NoParams, Page } from '@getenginex/sdk'\nimport { lazy, wire, type ExtensionTransport } from '@getenginex/sdk/extension'\nimport * as z from 'zod/mini'\nimport { pageInputProblem, rejectInput } from '../internal/input'\nimport { openUnion } from '../internal/open-union'\nimport { nullableList, optionalText, optionalTimestamp } from '../internal/optional-values'\nimport { integerText, minorUnits } from '../internal/schemas'\n\n/**\n * Mission periodicity: `daily`, `weekly`, `event` or `permanent`. The backend stores free text:\n * handle the default case (a new value arrives raw in `validation: 'warn'`).\n * @category Missions\n */\nexport type MissionType = 'daily' | 'weekly' | 'event' | 'permanent' | (string & {})\n\n/**\n * What the player must do: `wager` (bet), `bet_count` (number of bets), `win_amount`\n * (win), `play_game` (play the target games) or `deposit` (deposit). The contract\n * does not state the unit of `targetValue`; the \"Missions\" page gives an unconfirmed assumption per\n * type.\n * @category Missions\n */\nexport type MissionObjectiveType = 'wager' | 'bet_count' | 'win_amount' | 'play_game' | 'deposit' | (string & {})\n\n/**\n * Reward type: `bonus`, `free_spins`, `points` or `free_bet`. The contract does not\n * state the unit of `rewardValue`; the \"Missions\" page gives an unconfirmed assumption per type.\n * @category Missions\n */\nexport type MissionRewardType = 'bonus' | 'free_spins' | 'points' | 'free_bet' | (string & {})\n\n/**\n * Status of the player's mission: `in_progress`, `completed`, `expired` or `claimed`.\n * @category Missions\n */\nexport type UserMissionStatus = 'in_progress' | 'completed' | 'expired' | 'claimed' | (string & {})\n\n/**\n * Active operator mission (`GET /missions`).\n * @category Missions\n */\nexport interface Mission {\n /** Mission id (the same as {@link UserMission.missionId}). */\n id: string\n /** Display name. */\n name: string\n /** Description; may come empty. */\n description: string\n /** Periodicity. */\n missionType: MissionType\n /** Objective. */\n objectiveType: MissionObjectiveType\n /**\n * Target, an integer. The gateway contract does not state the unit (an assumption, unconfirmed:\n * minor units of the currency for `wager`/`win_amount`/`deposit`, a count for\n * `bet_count`/`play_game`); confirm with the operator before displaying.\n */\n targetValue: number\n /** Slug of the game category that counts toward the target; `null` when there is no restriction. */\n targetGameCategory: string | null\n /** Ids of the games that count toward the target; `[]` when there is no restriction. */\n targetGames: string[]\n /** Reward type. */\n rewardType: MissionRewardType\n /** Reward value, an integer. The contract does not state the unit (an assumption on the \"Missions\" page, unconfirmed). */\n rewardValue: number\n /** Start of validity (ISO 8601, UTC); `null` when the gateway sends an empty date (epoch). */\n validFrom: string | null\n /** End of validity (ISO 8601, UTC); `null` when the gateway sends an empty date (epoch). */\n validTo: string | null\n}\n\n/**\n * The player's progress on a mission (`GET /my/missions`).\n * @category Missions\n */\nexport interface UserMission {\n /** Progress id (of the player's mission in the period). */\n id: string\n /** Mission id ({@link Mission.id}). */\n missionId: string\n /** Mission name. */\n missionName: string\n /** Current progress, an integer; presumed to be the same unit as `targetValue` (not confirmed by the contract). */\n currentProgress: number\n /** Target, an integer. */\n targetValue: number\n /** Progress as a percentage, a number (e.g. `37.5`); computed by the service, may exceed `100`. */\n progressPercentage: number\n /** Status. */\n status: UserMissionStatus\n /** Reward type. */\n rewardType: MissionRewardType\n /** Reward value, an integer. */\n rewardValue: number\n /** End of the period (ISO 8601, UTC); `null` when the gateway does not send it. */\n periodEnd: string | null\n /** When it was completed (ISO 8601, UTC); `null` while not completed. */\n completedAt: string | null\n}\n\n/**\n * Input of {@link MissionsApi.list}.\n * @category Missions\n */\nexport interface ListMissionsInput {\n /** Page (starts at 1; integer ≥ 1). Gateway default: 1. */\n page?: number\n /** Items per page (integer from 1 to 100). Gateway default: 20 (out of range also becomes 20). */\n perPage?: number\n}\n\n/**\n * Operator missions and the player's progress. Both methods require login. There is no `claim()`: the\n * reward is automatic (inferred; see the \"Missions\" page).\n * @category Missions\n */\nexport interface MissionsApi {\n /**\n * Active operator missions, paginated. The gateway lists only the active ones and has no filter by type.\n * @example\n * const page = await igaming.missions.list({ perPage: 20 })\n * page.items.forEach((mission) => renderMission(mission.name, mission.targetValue))\n * @throws {EnginexError} `CONFIGURATION_ERROR` (without a request) for a `page` that is not an integer ≥ 1 or\n * a `perPage` outside 1–100 or not an integer; `UNAUTHENTICATED` without a session.\n */\n list(input?: ListMissionsInput, options?: CallOptions): Promise<Page<Mission>>\n /**\n * The player's progress on the active missions, without pagination.\n * @example\n * const mine = await igaming.missions.listMine()\n * const open = mine.filter((m) => m.status === 'in_progress')\n * @throws {EnginexError} `UNAUTHENTICATED` without a session.\n */\n listMine(params?: NoParams, options?: CallOptions): Promise<UserMission[]>\n}\n\n// Values the SDK knows (comments in `bonus.proto`); the rest fails in `strict` and arrives raw in `warn`.\nconst MISSION_TYPES = ['daily', 'weekly', 'event', 'permanent'] as const\nconst OBJECTIVE_TYPES = ['wager', 'bet_count', 'win_amount', 'play_game', 'deposit'] as const\nconst REWARD_TYPES = ['bonus', 'free_spins', 'points', 'free_bet'] as const\nconst USER_MISSION_STATUSES = ['in_progress', 'completed', 'expired', 'claimed'] as const\n\n// The gateway's `ListMissions`: `data` is an array of missions; the envelope's `meta` carries the pagination.\nconst missionSchema = /* @__PURE__ */ lazy(\n (): z.ZodMiniType<Mission> =>\n wire({\n id: z.string(),\n name: z.string(),\n description: z._default(z.string(), ''),\n mission_type: openUnion(MISSION_TYPES),\n objective_type: openUnion(OBJECTIVE_TYPES),\n target_value: integerText(),\n target_game_category: optionalText(),\n target_games: nullableList(z.string()),\n reward_type: openUnion(REWARD_TYPES),\n reward_value: minorUnits(),\n valid_from: optionalTimestamp(),\n valid_to: optionalTimestamp(),\n }),\n)\n\n// `GetUserMissions`: `data.missions`; `period_end` and `completed_at` only come when filled in.\nconst userMissionsSchema = /* @__PURE__ */ lazy(\n (): z.ZodMiniType<UserMission[]> =>\n z.pipe(\n wire({\n missions: nullableList(\n wire({\n id: z.string(),\n mission_id: z.string(),\n mission_name: z._default(z.string(), ''),\n current_progress: integerText(),\n target_value: integerText(),\n progress_percentage: z.number(),\n status: openUnion(USER_MISSION_STATUSES),\n reward_type: openUnion(REWARD_TYPES),\n reward_value: minorUnits(),\n period_end: optionalTimestamp(),\n completed_at: optionalTimestamp(),\n }),\n ),\n }),\n z.transform((data) => data.missions as UserMission[]),\n ),\n)\n\n/** Creates the `missions` namespace. @internal */\nexport function createMissionsApi(transport: ExtensionTransport): MissionsApi {\n return {\n list: (input, options) => {\n const problem = pageInputProblem('missions.list', input)\n if (problem !== undefined) return rejectInput(transport, problem, { method: 'GET', path: '/missions' })\n return transport.requestPage({\n method: 'GET',\n path: '/missions',\n page: input?.page,\n perPage: input?.perPage,\n perPageParam: 'limit',\n auth: 'required',\n item: missionSchema(),\n options,\n })\n },\n listMine: (_params, options) =>\n transport.request({\n method: 'GET',\n path: '/my/missions',\n auth: 'required',\n schema: userMissionsSchema(),\n options,\n }),\n }\n}\n","// Public types come from the core's main entry: the /extension `.d.ts` exposes Zod, and this package's\n// public API cannot depend on it (check-api).\nimport type { CallOptions, NoParams, Page } from '@getenginex/sdk'\nimport { lazy, wire, type ExtensionTransport } from '@getenginex/sdk/extension'\nimport * as z from 'zod/mini'\nimport { pageInputProblem, rejectInput } from '../internal/input'\nimport { nullableList, optionalText, optionalTimestamp } from '../internal/optional-values'\nimport { currencyOrEmpty, minorUnits } from '../internal/schemas'\n\n// Wire format: the gateway's `GetReferralInfo` and `ListReferrals` write a Go map with `encoding/json` (every key\n// present, an absent message as `null`), with money as `{ minor_units: \"5700\", currency: \"BRL\" }` (int64 as text).\n\n/**\n * Where a referred player stands, as the referrer sees it, in lowercase (the bonus service's\n * `CAMPAIGN_REFERRAL_STATUS_*`):\n * - `registered`: signed up, no deposit yet;\n * - `deposited`: deposited, real net loss still below the target;\n * - `in_hold`: qualified, waiting for the hold to end;\n * - `paid`: the referrer's reward is pending or granted;\n * - `not_eligible`: closed without reward by a block;\n * - `expired`: the window ended without qualifying;\n * - `cancelled`: paid, then cancelled.\n *\n * A status the SDK does not know yet arrives as the gateway sent it, in lowercase: handle the default case.\n * @category Referrals\n */\nexport type ReferralStatus =\n | 'registered'\n | 'deposited'\n | 'in_hold'\n | 'paid'\n | 'not_eligible'\n | 'expired'\n | 'cancelled'\n | (string & {})\n\n/**\n * Money of the referral program, in minor units of `currency` (the gateway sends the amount as text; the SDK\n * converts).\n * @category Referrals\n */\nexport interface ReferralMoney {\n /** Value in minor units of `currency`. */\n amount: number\n /** Currency code, e.g. `BRL`; `''` when the gateway sent none. */\n currency: string\n}\n\n/**\n * Rules of the operator's active referral campaign (part of {@link ReferralInfo}).\n * @category Referrals\n */\nexport interface ReferralRules {\n /** The referrer's reward per qualified referral. */\n reward: ReferralMoney\n /** Real net loss the referred player must reach (bets minus wins with real money) to qualify. */\n minimumRealNetLoss: ReferralMoney\n /** Days the referred player has, from the sign-up, to qualify. */\n refereeWindowDays: number\n /** Hours a qualified referral waits before the reward is paid. */\n holdHours: number\n /** Wagering multiplier of the reward, as an exact decimal in text (e.g. `\"80\"`). */\n wageringMultiplier: string\n /** Most of the reward that can be converted into withdrawable money; `null` without a cap. */\n maximumConversion: ReferralMoney | null\n}\n\n/**\n * How many of the player's referrals are in each status (integers), across all pages.\n * @category Referrals\n */\nexport interface ReferralTotals {\n /** In `registered`. */\n registered: number\n /** In `deposited`. */\n deposited: number\n /** In `in_hold`. */\n inHold: number\n /** In `paid`. */\n paid: number\n /** In `not_eligible`. */\n notEligible: number\n /** In `expired`. */\n expired: number\n /** In `cancelled`. */\n cancelled: number\n}\n\n/**\n * The player's referral code, the active program rules and the totals per status (`GET /referrals`).\n * @category Referrals\n */\nexport interface ReferralInfo {\n /**\n * `false` when the operator has no active referral campaign (and `rules` is `null`). Referrals already made keep\n * their windows open, so the totals and the history may still have rows.\n */\n enabled: boolean\n /** The player's referral code, from the profile; `null` when the gateway sends it empty. */\n code: string | null\n /**\n * Rules of the active campaign; `null` when there is none, and also when the gateway sends them without the\n * reward or the minimum real net loss (the program cannot be described without them).\n */\n rules: ReferralRules | null\n /** Totals per status. */\n totals: ReferralTotals\n}\n\n/**\n * The referred player's progress toward qualifying, in the campaign's currency.\n * @category Referrals\n */\nexport interface ReferralProgress {\n /** Whether the referred player already deposited. */\n depositDone: boolean\n /** Real net loss accumulated so far (`0` when the gateway sends none). */\n realNetLoss: ReferralMoney\n /** Real net loss required to qualify (the campaign's minimum). */\n target: ReferralMoney\n /** `max(0, target - realNetLoss)`; computed by the SDK when the gateway leaves it out. */\n remaining: ReferralMoney\n}\n\n/**\n * A referral of the history (`GET /referrals/history`): one row per referred player.\n * @category Referrals\n */\nexport interface Referral {\n /** Referral id. */\n id: string\n /**\n * The referred player's name, **already masked by the bonus service** (e.g. `\"Ma••• R.\"`): show it as it is,\n * never mask it again. `null` when empty.\n */\n refereeName: string | null\n /** Where the referred player stands (see {@link ReferralStatus}). */\n status: ReferralStatus\n /** Sign-up of the referred player (ISO 8601, UTC); `null` if the gateway does not send it. */\n createdAt: string | null\n /** End of the window to qualify (ISO 8601, UTC); `null` if the gateway does not send it. */\n deadlineAt: string | null\n /** Progress toward qualifying; `null` when the gateway sends no target. */\n progress: ReferralProgress | null\n}\n\n/**\n * Input of {@link ReferralsApi.listHistory}.\n * @category Referrals\n */\nexport interface ListReferralsInput {\n /** Page (starts at 1; integer ≥ 1). Gateway default: 1. */\n page?: number\n /** Items per page (integer from 1 to 100). Gateway default: 20. On the wire it goes as `limit`. */\n perPage?: number\n}\n\n/**\n * Page of the referral history, with the player's referral code.\n * @category Referrals\n */\nexport type ReferralHistory = Page<Referral> & {\n /** The player's referral code; `null` when the gateway sends it empty. */\n code: string | null\n}\n\n/**\n * The player's referrals. Both methods require login. A new player passes the code they were invited with in\n * the core's `auth.register({ referralCode })`: that is the only way to register a referral.\n * @category Referrals\n */\nexport interface ReferralsApi {\n /**\n * The player's referral code, the active program rules and the totals per status. Build the invitation\n * link in the app (your sign-up route with the code), so it always points at your site.\n * @example\n * const info = await igaming.referrals.get()\n * if (!info.enabled) showProgramUnavailable()\n * else showInvite(`${location.origin}/sign-up?ref=${info.code}`, info.rules)\n * @throws {EnginexError} `UNAUTHENTICATED` without a session; `UNAVAILABLE` when the bonus service does not\n * answer; `VALIDATION_ERROR`, also in `'warn'`, with money or currency outside the format.\n */\n get(params?: NoParams, options?: CallOptions): Promise<ReferralInfo>\n /**\n * Referral history, paginated, one row per referred player. Pagination comes inside `data` (not in the\n * envelope's `meta`): the SDK builds the `Page` and computes `totalPages` (`0` without items); a page beyond the\n * end returns `items: []`.\n * @example\n * const { items, totalPages } = await igaming.referrals.listHistory({ perPage: 20 })\n * items.forEach((r) => console.log(r.refereeName, r.status, r.progress?.remaining.amount))\n * @throws {EnginexError} `CONFIGURATION_ERROR` (without a request) for a `page` that is not an integer ≥ 1 or\n * a `perPage` outside 1–100 or not an integer; `UNAUTHENTICATED` without a session; `UNAVAILABLE` when the\n * bonus service does not answer; `VALIDATION_ERROR`, also in `'warn'`, with money or currency outside the\n * format.\n */\n listHistory(input?: ListReferralsInput, options?: CallOptions): Promise<ReferralHistory>\n}\n\nconst DEFAULT_PER_PAGE = 20\nconst HISTORY_PATH = '/referrals/history'\n\n// Gateway counter (integer >= 0), written explicitly by `encoding/json`; absent becomes 0 out of tolerance.\nconst count = () =>\n z._default(z.number().check(z.refine((value) => Number.isSafeInteger(value) && value >= 0, 'invalid counter')), 0)\n\n// `referralMoneyJSON`: `null` for an absent `common.Money`; the amount is int64 text (strict even in `'warn'`).\nconst money = () =>\n z.pipe(\n z.nullish(wire({ minor_units: minorUnits(), currency: z._default(currencyOrEmpty(), '') })),\n z.transform((value): ReferralMoney | null =>\n value == null ? null : { amount: value.minorUnits, currency: value.currency },\n ),\n )\n\nconst rulesSchema = () =>\n z.pipe(\n z.nullish(\n wire({\n reward: money(),\n minimum_real_net_loss: money(),\n referee_window_days: count(),\n hold_hours: count(),\n wagering_multiplier: z._default(z.string(), ''),\n maximum_conversion: money(),\n }),\n ),\n z.transform((rules): ReferralRules | null => {\n if (rules == null || rules.reward === null || rules.minimumRealNetLoss === null) return null\n return {\n reward: rules.reward,\n minimumRealNetLoss: rules.minimumRealNetLoss,\n refereeWindowDays: rules.refereeWindowDays,\n holdHours: rules.holdHours,\n wageringMultiplier: rules.wageringMultiplier,\n maximumConversion: rules.maximumConversion,\n }\n }),\n )\n\nconst infoSchema = /* @__PURE__ */ lazy(\n (): z.ZodMiniType<ReferralInfo> =>\n z.pipe(\n wire({\n enabled: z._default(z.boolean(), false),\n referral_code: optionalText(),\n rules: rulesSchema(),\n totals: z._default(\n wire({\n registered: count(),\n deposited: count(),\n in_hold: count(),\n paid: count(),\n not_eligible: count(),\n expired: count(),\n cancelled: count(),\n }),\n { registered: 0, deposited: 0, inHold: 0, paid: 0, notEligible: 0, expired: 0, cancelled: 0 },\n ),\n }),\n z.transform(\n ({ enabled, referralCode, rules, totals }): ReferralInfo => ({ enabled, code: referralCode, rules, totals }),\n ),\n ),\n)\n\n// `max(0, target - loss)` in BigInt, so a difference of two safe integers never rounds.\nfunction remainingOf(target: ReferralMoney, loss: ReferralMoney): ReferralMoney {\n const missing = BigInt(target.amount) - BigInt(loss.amount)\n return { amount: missing > 0n ? Number(missing) : 0, currency: target.currency }\n}\n\nconst progressSchema = () =>\n z.pipe(\n z.nullish(\n wire({\n deposit_done: z._default(z.boolean(), false),\n real_net_loss: money(),\n target: money(),\n remaining: money(),\n }),\n ),\n z.transform((progress): ReferralProgress | null => {\n if (progress == null || progress.target === null) return null\n const { target } = progress\n const realNetLoss = progress.realNetLoss ?? { amount: 0, currency: target.currency }\n return {\n depositDone: progress.depositDone,\n realNetLoss,\n target,\n remaining: progress.remaining ?? remainingOf(target, realNetLoss),\n }\n }),\n )\n\n// The legacy three-value `status` the older gateway sent alone; `player_status` replaces it.\nconst LEGACY_STATUS: Record<string, ReferralStatus> = { COMPLETED: 'paid', EXPIRED: 'expired', PENDING: 'registered' }\n\n/** `player_status` in lowercase; without it (an older gateway), derived from the legacy `status`. @internal */\nfunction statusOf(playerStatus: string | null, legacy: string | null): ReferralStatus {\n if (playerStatus !== null) return playerStatus.replace(/^CAMPAIGN_REFERRAL_STATUS_/, '').toLowerCase()\n return LEGACY_STATUS[(legacy ?? '').toUpperCase()] ?? 'registered'\n}\n\nconst referralSchema = () =>\n z.pipe(\n wire({\n id: z.string(),\n referee_name: optionalText(),\n status: optionalText(),\n player_status: optionalText(),\n created_at: optionalTimestamp(),\n deadline_at: optionalTimestamp(),\n progress: progressSchema(),\n }),\n z.transform(\n (r): Referral => ({\n id: r.id,\n refereeName: r.refereeName,\n status: statusOf(r.playerStatus, r.status),\n createdAt: r.createdAt,\n deadlineAt: r.deadlineAt,\n progress: r.progress,\n }),\n ),\n )\n\n// `ListReferrals`: pagination inside `data` (`page`, `limit`, `total_items`), no `meta`.\nconst historySchema = /* @__PURE__ */ lazy(() =>\n wire({\n referral_code: optionalText(),\n referrals: nullableList(referralSchema()),\n // A nil pointer (`null`) reads as absent, like an omitted pagination.\n pagination: z.pipe(\n z.nullish(wire({ page: count(), limit: count(), total_items: count() })),\n z.transform((value) => value ?? undefined),\n ),\n }),\n)\n\nconst positiveInt = (value: unknown, fallback: number): number =>\n typeof value === 'number' && Number.isSafeInteger(value) && value >= 1 ? value : fallback\n\n// Total reported by the gateway; in `warn` it may arrive raw (text, negative, absent): becomes 0.\nconst reportedTotal = (value: unknown): number =>\n typeof value === 'number' && Number.isSafeInteger(value) && value >= 0 ? value : 0\n\n/** Creates the `referrals` namespace. @internal */\nexport function createReferralsApi(transport: ExtensionTransport): ReferralsApi {\n return {\n get: (_params, options) =>\n transport.request({ method: 'GET', path: '/referrals', auth: 'required', schema: infoSchema(), options }),\n listHistory: (input, options) => {\n const problem = pageInputProblem('referrals.listHistory', input)\n if (problem !== undefined) return rejectInput(transport, problem, { method: 'GET', path: HISTORY_PATH })\n const requestedPage = input?.page\n const requestedPerPage = input?.perPage\n return transport\n .request({\n method: 'GET',\n path: HISTORY_PATH,\n query: { page: requestedPage, limit: requestedPerPage },\n auth: 'required',\n schema: historySchema(),\n options,\n })\n .then(({ referralCode, referrals, pagination }): ReferralHistory => {\n const items = Array.isArray(referrals) ? referrals : []\n const page = positiveInt(pagination?.page, requestedPage ?? 1)\n const perPage = positiveInt(pagination?.limit, requestedPerPage ?? DEFAULT_PER_PAGE)\n // A total smaller than the items already seen (or no pagination) must not turn into a `totalItems`\n // inconsistent with the delivered page.\n const seen = items.length > 0 ? (page - 1) * perPage + items.length : 0\n const totalItems = Math.max(reportedTotal(pagination?.totalItems), seen)\n return {\n items,\n page,\n perPage,\n totalItems,\n totalPages: totalItems > 0 ? Math.ceil(totalItems / perPage) : 0,\n code: referralCode,\n }\n })\n },\n }\n}\n","// Public types come from the core's main entry: the /extension `.d.ts` exposes Zod, and this package's\n// public API cannot depend on it (check-api).\nimport type { CallOptions, NoParams } from '@getenginex/sdk'\nimport { lazy, wire, type ExtensionTransport } from '@getenginex/sdk/extension'\nimport * as z from 'zod/mini'\n\n/**\n * FIRST sportsbook session created by {@link SportsbookApi.createSession}.\n *\n * **Sensitive:** `launchUrl` carries the player's operator token (`operatorToken`). Use it only to\n * open the sportsbook (iframe) and never log it to logs, analytics, error tracking.\n * @category Sportsbook\n */\nexport interface SportsbookSession {\n /**\n * FIRST sportsbook URL already with the operator token in the query — do not log it. Always\n * absolute (http/https); a response with anything else is `VALIDATION_ERROR`.\n */\n launchUrl: string\n /** Session validity from the response, in seconds (always greater than zero). */\n expiresInSeconds: number\n /**\n * Expiration instant in milliseconds since the epoch (like `Date.now()`): the client's clock at the\n * moment of the response plus `expiresInSeconds * 1000`. Reuse the session until `expiresAt - 30_000`.\n */\n expiresAt: number\n}\n\n/**\n * FIRST sportsbook (`GET /first/session`). The provider and the configuration come from\n * the core's `enginex.config.getSportsbook()`.\n * @category Sportsbook\n */\nexport interface SportsbookApi {\n /**\n * Creates the FIRST session for the logged-in player: returns the sportsbook URL (with the\n * operator token) to load in an iframe. Requires login. There is no cache in the SDK: each call generates a new\n * token; reuse the session until `expiresAt - 30_000` and call\n * `enginex.config.getSportsbook()` first to confirm `enabled && provider === 'first'`.\n *\n * **The returned URL carries the operator token.** The SDK delivers it only in the return value: no hook\n * (`onRequest`/`onResponse`/`onError`) nor `onValidationIssue` receives it, and the response is always\n * validated in strict mode. The separate token (`operator_token`) is never exposed. Do not log the URL\n * to logs, analytics or error tracking.\n * @example\n * const sb = await enginex.config.getSportsbook()\n * if (sb.enabled && sb.provider === 'first') {\n * const { launchUrl, expiresAt } = await igaming.sportsbook.createSession()\n * iframe.src = launchUrl\n * }\n * @throws {EnginexError} `UNAUTHENTICATED` without a session; the gateway envelope's code when FIRST\n * is not enabled for the operator (HTTP 400) and `UNAVAILABLE` (503) when the FIRST configuration is\n * incomplete, the session service is down or the bets service's sportsbook configuration\n * is not available; `VALIDATION_ERROR` if `launch_url` is not an\n * absolute http(s) URL or `expires_in_seconds` is not greater than zero.\n */\n createSession(params?: NoParams, options?: CallOptions): Promise<SportsbookSession>\n}\n\nconst HTTP_URL = 'Expected an absolute http(s) URL'\n\nconst sessionSchema = /* @__PURE__ */ lazy(\n (): z.ZodMiniType<SportsbookSession> =>\n z.pipe(\n wire({\n // The separate token only exists on the wire: the schema declares it (strict contract) and the output drops it.\n operator_token: z.string(),\n launch_url: z.string().check(\n z.refine(\n (value) => {\n try {\n const { protocol } = new URL(value)\n return protocol === 'https:' || protocol === 'http:'\n } catch {\n return false\n }\n },\n { message: HTTP_URL },\n ),\n ),\n expires_in_seconds: z.number().check(z.refine((n) => Number.isFinite(n) && n > 0, { message: 'Esperava > 0' })),\n }),\n // The clock is read when the response is interpreted (= moment of the response).\n z.transform(({ launchUrl, expiresInSeconds }) => ({\n launchUrl,\n expiresInSeconds,\n expiresAt: Date.now() + expiresInSeconds * 1000,\n })),\n ),\n)\n\n/** Creates the `sportsbook` namespace. @internal */\nexport function createSportsbookApi(transport: ExtensionTransport): SportsbookApi {\n return {\n createSession: (_params, options) =>\n transport.request({\n method: 'GET',\n path: '/first/session',\n auth: 'required',\n // The response carries the URL with the operator token: never through `warn` mode's recovery\n // (which would deliver a raw field and the response to `onValidationIssue`).\n validation: 'strict',\n schema: sessionSchema(),\n options,\n }),\n }\n}\n","import { EnginexError, type EnginexClient } from '@getenginex/sdk'\nimport * as extension from '@getenginex/sdk/extension'\nimport { createBetsApi, type BetsApi } from './modules/bets'\nimport { createBonusApi, type BonusApi } from './modules/bonus'\nimport { createCasinoApi, type CasinoApi } from './modules/casino'\nimport { createClubApi, type ClubApi } from './modules/club'\nimport { createLoyaltyApi, type LoyaltyApi } from './modules/loyalty'\nimport { createMissionsApi, type MissionsApi } from './modules/missions'\nimport { createReferralsApi, type ReferralsApi } from './modules/referrals'\nimport { LOCALE } from './internal/input'\nimport { createSportsbookApi, type SportsbookApi } from './modules/sportsbook'\n\n/**\n * iGaming namespaces of an SDK client, returned by {@link createIgaming}. Every request\n * goes through the app's client: same session, token renewal, tenant, locale, hooks, validation and\n * `dispose()`.\n * @category Client\n */\nexport interface IgamingClient {\n /** Catalog, game launch and casino history. */\n casino: CasinoApi\n /** Casino club: program, activities, missions with chests, coin store, history and tournaments. */\n club: ClubApi\n /** Bonus campaigns (offers, opt-in, redemption) and promo codes. */\n bonus: BonusApi\n /** Operator missions and the player's progress. */\n missions: MissionsApi\n /** Loyalty: points balance, tier, benefits and redemption. */\n loyalty: LoyaltyApi\n /** Referrals: code, program rules, totals per status and history with each referral's progress. */\n referrals: ReferralsApi\n /** FIRST sportsbook: session to open the sportsbook in an iframe. */\n sportsbook: SportsbookApi\n /** The player's sportsbook bets: history, details, cash-out offer and cash-out. */\n bets: BetsApi\n}\n\n/**\n * Creates the iGaming namespaces on top of a `@getenginex/sdk` client. It creates no session, tenant or\n * transport of its own and makes no request: call it once per client (in the browser, one per app;\n * on the server, one per request, together with the client).\n *\n * After `enginex.dispose()`, `createIgaming` still accepts the client, but every iGaming method\n * rejects with `CONFIGURATION_ERROR`, like the core methods.\n * @param client - The client returned by `createEnginexClient` (the object itself, not a copy).\n * @example\n * import { createEnginexClient } from '@getenginex/sdk'\n * import { createIgaming } from '@getenginex/sdk-igaming'\n *\n * export const enginex = createEnginexClient({ locale: 'pt-BR' })\n * export const igaming = createIgaming(enginex)\n * @throws {EnginexError} `CONFIGURATION_ERROR` if `client` is not a client created by\n * `createEnginexClient` (e.g. an arbitrary object or a `{ ...enginex }` copy), or if it was created\n * by an incompatible copy of `@getenginex/sdk` (install a single core version). Identify\n * with `isEnginexError(error, 'CONFIGURATION_ERROR')`.\n * @category Client\n */\nexport function createIgaming(client: EnginexClient): IgamingClient {\n // Validates the client right at creation (throws `CONFIGURATION_ERROR`); every namespace uses this\n // transport, the same as the app client's.\n const transport = extension.getExtensionTransport(client)\n const igaming: IgamingClient = {\n casino: createCasinoApi(transport),\n club: createClubApi(transport),\n bonus: createBonusApi(transport),\n missions: createMissionsApi(transport),\n loyalty: createLoyaltyApi(transport),\n referrals: createReferralsApi(transport),\n sportsbook: createSportsbookApi(transport),\n bets: createBetsApi(transport),\n }\n // Links the object to the app's client: `@getenginex/sdk-igaming/query` reaches the session (the `userId` of the\n // user keys) from the iGaming object alone. Requires core `>=0.5.0`.\n // Namespace import: with an old core (without the function) `import { registerProductClient }` would fail at\n // module load, before any useful message.\n if (typeof extension.registerProductClient !== 'function') {\n throw new EnginexError({\n code: 'CONFIGURATION_ERROR',\n status: 0,\n message: `createIgaming requires @getenginex/sdk >=0.5.0 <1.0.0 (peer): update the installed core.`,\n })\n }\n extension.registerProductClient(igaming, client)\n // The club's texts depend on the locale: `/query` reads it from here to put it in the club keys. Non-enumerable,\n // like the core's own links (a `{ ...igaming }` copy does not carry it).\n Object.defineProperty(igaming, LOCALE, {\n value: () => (typeof transport.getLocale === 'function' ? transport.getLocale() : undefined),\n })\n return igaming\n}\n"]}
|