@getenginex/sdk-igaming 0.8.0 → 0.8.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/internal/schemas.ts","../src/modules/bonus.ts","../src/modules/casino.ts","../src/internal/input.ts","../src/internal/optional-values.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","moneyText","currencyCode","wire","lazy","money","decimalPlaces","text","count","sessionSchema","extension","EnginexError"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;AAaO,SAAS,UAAU,MAAA,EAAgB;AACxC,EAAA,OAAOA,MAAA,CAAE,IAAA;AAAA,IACPA,MAAA,CAAE,QAAA,CAASA,MAAA,CAAE,KAAA,CAAM,CAACA,MAAA,CAAE,MAAA,EAAO,EAAGA,MAAA,CAAE,MAAA,EAAQ,CAAC,CAAC,CAAA;AAAA,IAC5CA,MAAA,CAAE,SAAA,CAAU,CAAC,KAAA,KAAU;AACrB,MAAA,IAAI,KAAA,KAAU,MAAA,IAAa,KAAA,KAAU,CAAA,EAAG,OAAO,aAAA;AAC/C,MAAA,IAAI,OAAO,KAAA,KAAU,QAAA,EAAU,OAAO,OAAO,KAAK,CAAA;AAClD,MAAA,OAAA,CAAQ,KAAA,CAAM,UAAA,CAAW,MAAM,CAAA,GAAI,KAAA,CAAM,MAAM,MAAA,CAAO,MAAM,CAAA,GAAI,KAAA,EAAO,WAAA,EAAY;AAAA,IACrF,CAAC;AAAA,GACH;AACF;AAQO,SAAS,UAAA,GAAa;AAC3B,EAAA,OAAOC,mBAAA,EAAU;AACnB;AAOO,SAAS,eAAA,GAAyC;AACvD,EAAA,OAAOC,sBAAA,CAAa,EAAE,UAAA,EAAY,IAAA,EAAM,CAAA;AAC1C;AAEA,IAAM,YAAA,GAAe,qDAAA;AAOd,SAAS,WAAA,GAAc;A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B,SAAS,CAAA;AAAA,IACrC,OAAA,EAAS,iBAAiB,SAAS,CAAA;AAAA,IACnC,SAAA,EAAW,mBAAmB,SAAS,CAAA;AAAA,IACvC,UAAA,EAAY,oBAAoB,SAAS;AAAA,GAC3C;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;AAC/C,EAAA,OAAO,OAAA;AACT","file":"index.cjs","sourcesContent":["import { currencyCode, moneyText, strictValue } from '@getenginex/sdk/extension'\nimport { 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 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, CursorPage, CursorPageInput, NoParams } from '@getenginex/sdk'\nimport { lazy, wire, type ExtensionTransport } from '@getenginex/sdk/extension'\nimport { 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}\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 }),\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 { z } from 'zod/mini'\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 * 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 /** 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 * 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 * 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 * 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 an `availability` field next to the list,\n * which this SDK version does not expose yet. In those cases the list may come empty, without an error; show\n * a generic empty state.\n * @example\n * const page = await igaming.casino.listGames({ category: 'slots', sort: 'popular', perPage: 24 })\n * page.items.forEach((game) => renderCard(game.name, game.thumbnail))\n * @throws {EnginexError} `INVALID_ARGUMENT` (400) for `search` above 100 characters or more than\n * 100 `ids`; `UNAVAILABLE`/`PROVIDER_ERROR` (503) only when the call to the casino\n * service itself fails.\n */\n listGames(input?: ListGamesInput, options?: CallOptions): Promise<Page<Game>>\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\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/** Creates the `casino` namespace. @internal */\nexport function createCasinoApi(transport: ExtensionTransport): CasinoApi {\n return {\n listGames: (input, options) =>\n transport.requestPage({\n method: 'GET',\n path: '/games',\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 },\n page: input?.page,\n perPage: input?.perPage,\n perPageParam: 'limit',\n auth: 'none',\n item: gameSchema(),\n options,\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, language }, options) =>\n transport.request({\n method: 'POST',\n path: `/games/${encodeURIComponent(gameId)}/launch`,\n body: { is_demo: mode === 'demo', is_mobile: isMobile === true, return_url: returnUrl, language },\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 }\n}\n","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 { 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","// 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 { 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 * 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. The format is defined\n * by the operator (the contract only says \"benefits of the current tier\"): check before displaying. `null`\n * when it comes empty or absent, and also when it is not a valid JSON object (in this case\n * `onValidationIssue` is notified, without the content).\n */\n tierBenefits: Record<string, unknown> | 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 not a JSON object.\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 as text. Empty/absent is `null` without a warning; anything else that is not an object becomes a\n// `tier_benefits_json` divergence (without the text, which may hold operator data, in the message).\nconst tierBenefits = () =>\n z.pipe(\n z.nullish(z.string()),\n z.transform((text, ctx): Record<string, unknown> | 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 && !Array.isArray(parsed))\n return parsed as Record<string, unknown>\n ctx.issues.push({ code: 'custom', message: 'tier_benefits_json is not a JSON object', input: undefined })\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 =\n typeof tierBenefitsJson === 'object' && tierBenefitsJson !== null && !Array.isArray(tierBenefitsJson)\n ? tierBenefitsJson\n : 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 { 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 { 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 { 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 { 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 { 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}\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 }\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/schemas.ts","../src/modules/bonus.ts","../src/modules/casino.ts","../src/internal/input.ts","../src/internal/optional-values.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","moneyText","currencyCode","z2","wire","lazy","z3","money","decimalPlaces","z4","z5","text","z6","z7","count","z8","sessionSchema","z9","extension","EnginexError"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;AAaO,SAAS,UAAU,MAAA,EAAgB;AACxC,EAAA,OAASA,aAAA,CAAA,IAAA;AAAA,IACLA,aAAA,CAAA,QAAA,CAAWA,oBAAM,CAAGA,aAAA,CAAA,MAAA,IAAYA,aAAA,CAAA,MAAA,EAAQ,CAAC,CAAC,CAAA;AAAA,IAC1CA,aAAA,CAAA,SAAA,CAAU,CAAC,KAAA,KAAU;AACrB,MAAA,IAAI,KAAA,KAAU,MAAA,IAAa,KAAA,KAAU,CAAA,EAAG,OAAO,aAAA;AAC/C,MAAA,IAAI,OAAO,KAAA,KAAU,QAAA,EAAU,OAAO,OAAO,KAAK,CAAA;AAClD,MAAA,OAAA,CAAQ,KAAA,CAAM,UAAA,CAAW,MAAM,CAAA,GAAI,KAAA,CAAM,MAAM,MAAA,CAAO,MAAM,CAAA,GAAI,KAAA,EAAO,WAAA,EAAY;AAAA,IACrF,CAAC;AAAA,GACH;AACF;AAQO,SAAS,UAAA,GAAa;AAC3B,EAAA,OAAOC,mBAAA,EAAU;AACnB;AAOO,SAAS,eAAA,GAAyC;AACvD,EAAA,OAAOC,sBAAA,CAAa,EAAE,UAAA,EAAY,IAAA,EAAM,CAAA;AAC1C;AAEA,IAAM,YAAA,GAAe,qDAAA;AAOd,SAAS,WAAA,GAAc;AAC5B,EAAA,OAASF,aAAA,CAAA,IAAA;AAAA,IACLA,aAAA,CAAA,KAAA,CAAM;AAAA,MAEHA,sBAAO,CACP,KAAA;AAAA,QACGA,qBAAO,CAAC,KAAA,KAAU,SAA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AAA,KACV,CAAA;AAAA,EACH;AACA,EAAUD,oBAAA,CAAA,qBAAA,CAAsB,SAAS,MAAM,CAAA;AAC/C,EAAA,OAAO,OAAA;AACT","file":"index.cjs","sourcesContent":["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 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, 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}\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 }),\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 { 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 * 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 /** 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 * 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 * 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 * 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 an `availability` field next to the list,\n * which this SDK version does not expose yet. In those cases the list may come empty, without an error; show\n * a generic empty state.\n * @example\n * const page = await igaming.casino.listGames({ category: 'slots', sort: 'popular', perPage: 24 })\n * page.items.forEach((game) => renderCard(game.name, game.thumbnail))\n * @throws {EnginexError} `INVALID_ARGUMENT` (400) for `search` above 100 characters or more than\n * 100 `ids`; `UNAVAILABLE`/`PROVIDER_ERROR` (503) only when the call to the casino\n * service itself fails.\n */\n listGames(input?: ListGamesInput, options?: CallOptions): Promise<Page<Game>>\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\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/** Creates the `casino` namespace. @internal */\nexport function createCasinoApi(transport: ExtensionTransport): CasinoApi {\n return {\n listGames: (input, options) =>\n transport.requestPage({\n method: 'GET',\n path: '/games',\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 },\n page: input?.page,\n perPage: input?.perPage,\n perPageParam: 'limit',\n auth: 'none',\n item: gameSchema(),\n options,\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, language }, options) =>\n transport.request({\n method: 'POST',\n path: `/games/${encodeURIComponent(gameId)}/launch`,\n body: { is_demo: mode === 'demo', is_mobile: isMobile === true, return_url: returnUrl, language },\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 }\n}\n","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","// 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 * 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. The format is defined\n * by the operator (the contract only says \"benefits of the current tier\"): check before displaying. `null`\n * when it comes empty or absent, and also when it is not a valid JSON object (in this case\n * `onValidationIssue` is notified, without the content).\n */\n tierBenefits: Record<string, unknown> | 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 not a JSON object.\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 as text. Empty/absent is `null` without a warning; anything else that is not an object becomes a\n// `tier_benefits_json` divergence (without the text, which may hold operator data, in the message).\nconst tierBenefits = () =>\n z.pipe(\n z.nullish(z.string()),\n z.transform((text, ctx): Record<string, unknown> | 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 && !Array.isArray(parsed))\n return parsed as Record<string, unknown>\n ctx.issues.push({ code: 'custom', message: 'tier_benefits_json is not a JSON object', input: undefined })\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 =\n typeof tierBenefitsJson === 'object' && tierBenefitsJson !== null && !Array.isArray(tierBenefitsJson)\n ? tierBenefitsJson\n : 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 { 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}\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 }\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"]}