@getenginex/sdk-igaming 0.10.1 → 0.11.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/query/index.ts"],"names":[],"mappings":";;;AAsFA,IAAM,QAAA,GAAW,CAAC,OAAA,EAAiB,SAAA,EAAmB,MAAA,KAAmB,CAAC,KAAA,EAAgB,OAAA,KACtF,OAAA,CAAmD,SAAS,CAAA,CAAG,MAAM,CAAA,CAAa,IAAA;AAAA,EACjF,QAAoC,SAAS,CAAA;AAAA,EAC9C,KAAA;AAAA,EACA;AACF,CAAA;AAGF,IAAM,YAAA,GAAe;AAAA,EACnB,QAAQ,CAAC,WAAA,EAAa,kBAAkB,eAAA,EAAiB,SAAA,EAAW,gBAAgB,kBAAkB,CAAA;AAAA,EACtG,KAAA,EAAO,CAAC,kBAAkB;AAC5B,CAAA;AAGA,IAAM,UAAA,GAAa;AAAA,EACjB,MAAA,EAAQ,CAAC,cAAA,EAAgB,YAAA,EAAc,mBAAmB,CAAA;AAAA,EAC1D,OAAO,CAAC,YAAA,EAAc,YAAY,oBAAA,EAAsB,kBAAA,EAAoB,eAAe,eAAe,CAAA;AAAA,EAC1G,QAAA,EAAU,CAAC,MAAA,EAAQ,UAAU,CAAA;AAAA,EAC7B,OAAA,EAAS,CAAC,KAAK,CAAA;AAAA,EACf,SAAA,EAAW,CAAC,KAAA,EAAO,aAAa,CAAA;AAAA,EAChC,IAAA,EAAM,CAAC,MAAA,EAAQ,KAAA,EAAO,iBAAiB;AACzC,CAAA;AAGA,IAAM,WACJ,CAAA,GAAI,QAAA,KACJ,CAAC,KAAA,KACC,SAAS,GAAA,CAAI,CAAC,CAAC,SAAA,EAAW,MAAM,CAAA,KAAM,KAAA,CAAM,UAAA,CAAW,SAAA,EAAW,MAAM,CAAC,CAAA;AAC7E,IAAM,IAAA,GAAqB,MAAM,EAAC;AAWlC,IAAM,MAAA,GAAgD;AA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E,EAAC;AACpF,QAAA,IAAI,KAAA,CAAM,eAAe,IAAA,EAAM;AAC7B,UAAA,MAAA,CAAO,UAAA,GAAa,IAAA;AACpB,UAAA,IAAI,OAAA,EAAS,cAAA,KAAmB,MAAA,EAAW,MAAA,CAAO,iBAAiB,OAAA,CAAQ,cAAA;AAAA,QAC7E;AACA,QAAA,IAAI,KAAA,CAAM,SAAA,KAAc,IAAA,EAAM,MAAA,CAAO,MAAA,GAAS,CAAA;AAC9C,QAAA,OAAO,KAAA,CAAM,QAAA;AAAA,UACX,SAAA;AAAA,UACA,MAAA;AAAA,UACA,QAAA,CAAS,OAAA,EAAS,SAAA,EAAW,MAAM,CAAA;AAAA,UACnC,MAAM,KAAA,CAAM,WAAA,CAAY,KAAK,CAAA;AAAA,UAC7B;AAAA,SACF;AAAA,MACF,CAAA;AAAA,IACF;AAAA,EACF;AACA,EAAA,OAAO,GAAA;AACT","file":"index.js","sourcesContent":["/**\n * iGaming query and mutation factories, compatible with TanStack Query v5 (`useQuery`,\n * `useMutation`, `prefetchQuery`), without depending on it. Same key conventions as\n * `@getenginex/sdk/query`.\n * @module @getenginex/sdk-igaming/query\n */\n\nimport type { CallOptions } from '@getenginex/sdk'\nimport {\n queryScope,\n type IdempotentMutationsOf,\n type MutationsOf,\n type QueriesOf,\n type QueryScope,\n} from '@getenginex/sdk/query'\nimport type { IgamingClient } from '../client'\nimport type { BetsApi } from '../modules/bets'\nimport type { BonusApi } from '../modules/bonus'\nimport type { CasinoApi } from '../modules/casino'\nimport type { LoyaltyApi } from '../modules/loyalty'\nimport type { MissionsApi } from '../modules/missions'\nimport type { ReferralsApi } from '../modules/referrals'\nimport type { SportsbookApi } from '../modules/sportsbook'\n\n/**\n * iGaming query factories, one per read method: `q.<namespace>.<method>(input)` returns\n * `{ queryKey, queryFn }`. Obtained with {@link createIgamingQueries}.\n * @category Queries\n */\nexport interface IgamingQueries {\n /** Catalog and lobby jackpots (public) and, with login, sessions, history and biggest winners. */\n readonly casino: QueriesOf<\n CasinoApi,\n | 'listGames'\n | 'listCategories'\n | 'listProviders'\n | 'getGame'\n | 'listJackpots'\n | 'listJackpotGames'\n | 'listSessions'\n | 'getHistory'\n | 'getBiggestWinners'\n >\n /** Public offers (no login) and, with login, offers, participations, bonus overview and positions. */\n readonly bonus: QueriesOf<\n BonusApi,\n | 'listPublicOffers'\n | 'listOffers'\n | 'getOffer'\n | 'listParticipations'\n | 'getParticipation'\n | 'getOverview'\n | 'listPositions'\n >\n /** Operator missions and the player's own. */\n readonly missions: QueriesOf<MissionsApi, 'list' | 'listMine'>\n /** Points balance, tier and benefits. */\n readonly loyalty: QueriesOf<LoyaltyApi, 'get'>\n /** Referral code, program rules, totals and history. */\n readonly referrals: QueriesOf<ReferralsApi, 'get' | 'listHistory'>\n /** The player's bets, a bet's details and its cash-out offer. */\n readonly bets: QueriesOf<BetsApi, 'list' | 'get' | 'getCashoutOffer'>\n}\n\n/**\n * iGaming mutations, one per write method: `m.<namespace>.<method>()` returns\n * `{ mutationKey, mutationFn, invalidates }`. Obtained with {@link createIgamingMutations}.\n * @category Queries\n */\nexport interface IgamingMutations {\n /** Game launch (`launchGame`, with `gcTime: 0`: the game URL carries credentials). */\n readonly casino: MutationsOf<CasinoApi, 'launchGame'>\n /** Opt-in, redemption (idempotent: they accept `{ idempotencyKey }`) and promo code check. */\n readonly bonus: IdempotentMutationsOf<BonusApi, 'optIn' | 'claim' | 'redeemPromoCode'> &\n MutationsOf<BonusApi, 'resolvePromoCode'>\n /** Points redemption (idempotent: it accepts `{ idempotencyKey }`). */\n readonly loyalty: IdempotentMutationsOf<LoyaltyApi, 'redeem'>\n /** Sportsbook session (`gcTime: 0`: the URL carries the operator token). */\n readonly sportsbook: MutationsOf<SportsbookApi, 'createSession'>\n /** Bet cash-out (idempotent: it accepts `{ idempotencyKey }`). */\n readonly bets: IdempotentMutationsOf<BetsApi, 'cashout'>\n}\n\ntype Method = (input: unknown, options?: CallOptions) => Promise<unknown>\n\n// Calls `igaming[namespace][method]` at request time (not at creation), keeping `this`.\nconst methodOf = (igaming: object, namespace: string, method: string) => (input: unknown, options: CallOptions) =>\n ((igaming as Record<string, Record<string, Method>>)[namespace]![method] as Method).call(\n (igaming as Record<string, unknown>)[namespace],\n input,\n options,\n )\n\n// Reads without a session (the method sends no token): `public` key, no `staleTime`.\nconst PUBLIC_READS = {\n casino: ['listGames', 'listCategories', 'listProviders', 'getGame', 'listJackpots', 'listJackpotGames'],\n bonus: ['listPublicOffers'],\n} as const\n\n// Player reads: `user` key with the session's `userId`.\nconst USER_READS = {\n casino: ['listSessions', 'getHistory', 'getBiggestWinners'],\n bonus: ['listOffers', 'getOffer', 'listParticipations', 'getParticipation', 'getOverview', 'listPositions'],\n missions: ['list', 'listMine'],\n loyalty: ['get'],\n referrals: ['get', 'listHistory'],\n bets: ['list', 'get', 'getCashoutOffer'],\n} as const\n\ntype Invalidation = (scope: QueryScope) => readonly (readonly unknown[])[]\nconst userKeys =\n (...prefixes: [namespace: string, method?: string][]): Invalidation =>\n (scope) =>\n prefixes.map(([namespace, method]) => scope.userPrefix(namespace, method))\nconst none: Invalidation = () => []\n\ninterface Write {\n /** What the write leaves stale. The core's prefixes (`wallet`) come from `scope.userPrefix`. */\n invalidates: Invalidation\n /** Sends `Idempotency-Key` (accepts `{ idempotencyKey }`). */\n idempotent?: boolean\n /** Entry or result with a credential: `gcTime: 0`. */\n sensitive?: boolean\n}\n\nconst WRITES: Record<string, Record<string, Write>> = {\n casino: { launchGame: { invalidates: userKeys(['casino', 'listSessions']), sensitive: true } },\n bonus: {\n resolvePromoCode: { invalidates: none, sensitive: true },\n optIn: { invalidates: userKeys(['bonus'], ['wallet']), idempotent: true },\n claim: { invalidates: userKeys(['bonus'], ['wallet']), idempotent: true },\n redeemPromoCode: { invalidates: userKeys(['bonus'], ['wallet']), idempotent: true, sensitive: true },\n },\n loyalty: { redeem: { invalidates: userKeys(['loyalty'], ['wallet']), idempotent: true } },\n sportsbook: { createSession: { invalidates: none, sensitive: true } },\n bets: { cashout: { invalidates: userKeys(['bets'], ['wallet']), idempotent: true } },\n}\n\n/**\n * Creates the iGaming query factories: one per read method, with the same name and the same input\n * as the method (`q.casino.listGames({ page })`). Each call returns `{ queryKey, queryFn }`, compatible\n * with TanStack Query v5's `useQuery`/`prefetchQuery`/`fetchQuery`. It makes no request.\n *\n * - Reads without a session (`casino.listGames/listCategories/listProviders/getGame/listJackpots/listJackpotGames`,\n * `bonus.listPublicOffers`): key `['enginex', 'public', namespace, method, input?]`.\n * - Player reads (the others): key `['enginex', 'user', userId, namespace, method, input?]`,\n * with the session's `userId` when the factory is called; without a session, `'anonymous'` and the `queryFn`\n * rejects with `UNAUTHENTICATED` without a request (the same if the session switches user before the `fetch`).\n * - `queryFn` forwards the context's `signal`: canceling the query aborts the `fetch`.\n * - None carries `staleTime`.\n * @param igaming - The object returned by `createIgaming(enginex)` (the object itself, not a copy).\n * @example\n * import { useQuery } from '@tanstack/react-query'\n * import { createIgamingQueries } from '@getenginex/sdk-igaming/query'\n *\n * const q = createIgamingQueries(igaming)\n * const games = useQuery(q.casino.listGames({ category: 'slots' }))\n * @throws {EnginexError} `CONFIGURATION_ERROR` if `igaming` did not come from `createIgaming` (e.g. a\n * `{ ...igaming }` copy). Identify with `isEnginexError(error, 'CONFIGURATION_ERROR')`.\n * @category Queries\n */\nexport function createIgamingQueries(igaming: IgamingClient): IgamingQueries {\n const scope = queryScope(igaming)\n const out: Record<string, Record<string, (input?: unknown) => unknown>> = {}\n const add = (\n table: Record<string, readonly string[]>,\n build: (namespace: string, method: string, input: unknown) => unknown,\n ) => {\n for (const [namespace, methods] of Object.entries(table)) {\n const factories = (out[namespace] ??= {})\n for (const method of methods) factories[method] = (input) => build(namespace, method, input)\n }\n }\n add(PUBLIC_READS, (namespace, method, input) =>\n scope.publicQuery(namespace, method, methodOf(igaming, namespace, method), input),\n )\n add(USER_READS, (namespace, method, input) =>\n scope.userQuery(namespace, method, methodOf(igaming, namespace, method), input),\n )\n return out as unknown as IgamingQueries\n}\n\n/**\n * Creates the iGaming mutations: one per write method, with the same name as the method\n * (`m.loyalty.redeem()`). Each call returns `{ mutationKey, mutationFn, invalidates }`, compatible\n * with TanStack Query v5's `useMutation`; `invalidates(input, result)` lists the prefixes the write\n * leaves stale (with the session's `userId` at call time; call it only after success):\n *\n * - `bonus.optIn/claim/redeemPromoCode` → `bonus` and `wallet` (the core's balance);\n * - `loyalty.redeem` → `loyalty` and `wallet`;\n * - `bets.cashout` → `bets` and `wallet`;\n * - `casino.launchGame` → `casino.listSessions`; `bonus.resolvePromoCode` and\n * `sportsbook.createSession` → nothing.\n *\n * `mutationKey` is `['enginex', namespace, method]`, without the input. The ones that send `Idempotency-Key`\n * (`bonus.optIn/claim/redeemPromoCode`, `loyalty.redeem`, `bets.cashout`) reuse the key only after an ambiguous\n * failure (network, timeout, 5xx, `KEY_IN_USE` or `VALIDATION_ERROR` after a 2xx) with the same input,\n * on this options object (see the core's `createMutations`), and accept `{ idempotencyKey }` on the factory. The\n * ones that carry credentials in the input or the result (promo code, game URL, sportsbook\n * session) have `gcTime: 0`.\n * @param igaming - The object returned by `createIgaming(enginex)` (the object itself, not a copy).\n * @example\n * import { useMutation } from '@tanstack/react-query'\n * import { createIgamingMutations } from '@getenginex/sdk-igaming/query'\n *\n * const m = createIgamingMutations(igaming)\n * const redeem = m.loyalty.redeem()\n * const result = await redeem.mutationFn({ points: 500, redemptionType: 'bonus' })\n * for (const queryKey of redeem.invalidates({ points: 500, redemptionType: 'bonus' }, result)) {\n * await queryClient.invalidateQueries({ queryKey })\n * }\n * @throws {EnginexError} `CONFIGURATION_ERROR` if `igaming` did not come from `createIgaming`.\n * @category Queries\n */\nexport function createIgamingMutations(igaming: IgamingClient): IgamingMutations {\n const scope = queryScope(igaming)\n const out: Record<string, Record<string, (options?: { idempotencyKey?: string }) => unknown>> = {}\n for (const [namespace, methods] of Object.entries(WRITES)) {\n const factories = (out[namespace] ??= {})\n for (const [method, write] of Object.entries(methods)) {\n factories[method] = (options) => {\n const scoped: { idempotent?: boolean; idempotencyKey?: string; gcTime?: number } = {}\n if (write.idempotent === true) {\n scoped.idempotent = true\n if (options?.idempotencyKey !== undefined) scoped.idempotencyKey = options.idempotencyKey\n }\n if (write.sensitive === true) scoped.gcTime = 0\n return scope.mutation(\n namespace,\n method,\n methodOf(igaming, namespace, method),\n () => write.invalidates(scope),\n scoped,\n )\n }\n }\n }\n return out as unknown as IgamingMutations\n}\n"]}
1
+ {"version":3,"sources":["../../src/query/index.ts"],"names":[],"mappings":";;;;AA+FA,IAAM,QAAA,GAAW,CAAC,OAAA,EAAiB,SAAA,EAAmB,MAAA,KAAmB,CAAC,KAAA,EAAgB,OAAA,KACtF,OAAA,CAAmD,SAAS,CAAA,CAAG,MAAM,CAAA,CAAa,IAAA;AAAA,EACjF,QAAoC,SAAS,CAAA;AAAA,EAC9C,KAAA;AAAA,EACA;AACF,CAAA;AAGF,IAAM,YAAA,GAAe;AAAA,EACnB,QAAQ,CAAC,WAAA,EAAa,kBAAkB,eAAA,EAAiB,SAAA,EAAW,gBAAgB,kBAAkB,CAAA;AAAA,EACtG,KAAA,EAAO,CAAC,kBAAkB;AAC5B,CAAA;AAGA,IAAM,UAAA,GAAa;AAAA,EACjB,MAAA,EAAQ,CAAC,cAAA,EAAgB,YAAA,EAAc,mBAAmB,CAAA;AAAA,EAC1D,MAAM,CAAC,aAAA,EAAe,eAAe,iBAAA,EAAmB,wBAAA,EAA0B,iBAAiB,YAAY,CAAA;AAAA,EAC/G,OAAO,CAAC,YAAA,EAAc,YAAY,oBAAA,EAAsB,kBAAA,EAAoB,eAAe,eAAe,CAAA;AAAA,EAC1G,QAAA,EAAU,CAAC,MAAA,EAAQ,UAAU,CAAA;AAAA,EAC7B,OAAA,EAAS,CAAC,KAAK,CAAA;AAAA,EACf,SAAA,EAAW,CAAC,KAAA,EAAO,aAAa,CAAA;AAAA,EAChC,IAAA,EAAM,CAAC,MAAA,EAAQ,KAAA,EAAO,iBAAiB;A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AA,EAAU,QAAA,CAAS,kBAAA,GAAqB,CAAC,MAAA,EAAQ,KAAA,KAAW,UAAA,CAAW,KAAK,CAAA,GAAI,QAAA,CAAS,KAAK,CAAA,GAAI,EAAC;AACvG,QAAA,OAAO,QAAA;AAAA,MACT,CAAA;AAAA,IACF;AAAA,EACF;AACA,EAAA,OAAO,GAAA;AACT","file":"index.js","sourcesContent":["/**\n * iGaming query and mutation factories, compatible with TanStack Query v5 (`useQuery`,\n * `useMutation`, `prefetchQuery`), without depending on it. Same key conventions as\n * `@getenginex/sdk/query`.\n * @module @getenginex/sdk-igaming/query\n */\n\nimport { isEnginexError, type CallOptions } from '@getenginex/sdk'\nimport {\n queryScope,\n type IdempotentMutationsOf,\n type MutationsOf,\n type QueriesOf,\n type QueryScope,\n} from '@getenginex/sdk/query'\nimport type { IgamingClient } from '../client'\nimport { LOCALE } from '../internal/input'\nimport type { BetsApi } from '../modules/bets'\nimport type { BonusApi } from '../modules/bonus'\nimport type { CasinoApi } from '../modules/casino'\nimport { keepsClubIdempotencyKey, type ClubApi } from '../modules/club'\nimport type { LoyaltyApi } from '../modules/loyalty'\nimport type { MissionsApi } from '../modules/missions'\nimport type { ReferralsApi } from '../modules/referrals'\nimport type { SportsbookApi } from '../modules/sportsbook'\n\n/**\n * iGaming query factories, one per read method: `q.<namespace>.<method>(input)` returns\n * `{ queryKey, queryFn }`. Obtained with {@link createIgamingQueries}.\n * @category Queries\n */\nexport interface IgamingQueries {\n /** Catalog and lobby jackpots (public) and, with login, sessions, history and biggest winners. */\n readonly casino: QueriesOf<\n CasinoApi,\n | 'listGames'\n | 'listCategories'\n | 'listProviders'\n | 'getGame'\n | 'listJackpots'\n | 'listJackpotGames'\n | 'listSessions'\n | 'getHistory'\n | 'getBiggestWinners'\n >\n /** Casino club: overview, history, tournaments, related editions, a tournament and its ranking. */\n readonly club: QueriesOf<\n ClubApi,\n 'getOverview' | 'listHistory' | 'listTournaments' | 'listRelatedTournaments' | 'getTournament' | 'getRanking'\n >\n /** Public offers (no login) and, with login, offers, participations, bonus overview and positions. */\n readonly bonus: QueriesOf<\n BonusApi,\n | 'listPublicOffers'\n | 'listOffers'\n | 'getOffer'\n | 'listParticipations'\n | 'getParticipation'\n | 'getOverview'\n | 'listPositions'\n >\n /** Operator missions and the player's own. */\n readonly missions: QueriesOf<MissionsApi, 'list' | 'listMine'>\n /** Points balance, tier and benefits. */\n readonly loyalty: QueriesOf<LoyaltyApi, 'get'>\n /** Referral code, program rules, totals and history. */\n readonly referrals: QueriesOf<ReferralsApi, 'get' | 'listHistory'>\n /** The player's bets, a bet's details and its cash-out offer. */\n readonly bets: QueriesOf<BetsApi, 'list' | 'get' | 'getCashoutOffer'>\n}\n\n/**\n * iGaming mutations, one per write method: `m.<namespace>.<method>()` returns\n * `{ mutationKey, mutationFn, invalidates }`. Obtained with {@link createIgamingMutations}.\n * @category Queries\n */\nexport interface IgamingMutations {\n /** Game launch (`launchGame`, with `gcTime: 0`: the game URL carries credentials). */\n readonly casino: MutationsOf<CasinoApi, 'launchGame'>\n /** Club membership, plays, redemptions and tournament registration (idempotent: they accept `{ idempotencyKey }`). */\n readonly club: IdempotentMutationsOf<ClubApi, 'setMembership' | 'play' | 'redeem' | 'registerForTournament'>\n /** Opt-in, redemption (idempotent: they accept `{ idempotencyKey }`) and promo code check. */\n readonly bonus: IdempotentMutationsOf<BonusApi, 'optIn' | 'claim' | 'redeemPromoCode'> &\n MutationsOf<BonusApi, 'resolvePromoCode'>\n /** Points redemption (idempotent: it accepts `{ idempotencyKey }`). */\n readonly loyalty: IdempotentMutationsOf<LoyaltyApi, 'redeem'>\n /** Sportsbook session (`gcTime: 0`: the URL carries the operator token). */\n readonly sportsbook: MutationsOf<SportsbookApi, 'createSession'>\n /** Bet cash-out (idempotent: it accepts `{ idempotencyKey }`). */\n readonly bets: IdempotentMutationsOf<BetsApi, 'cashout'>\n}\n\ntype Method = (input: unknown, options?: CallOptions) => Promise<unknown>\n\n// Calls `igaming[namespace][method]` at request time (not at creation), keeping `this`.\nconst methodOf = (igaming: object, namespace: string, method: string) => (input: unknown, options: CallOptions) =>\n ((igaming as Record<string, Record<string, Method>>)[namespace]![method] as Method).call(\n (igaming as Record<string, unknown>)[namespace],\n input,\n options,\n )\n\n// Reads without a session (the method sends no token): `public` key, no `staleTime`.\nconst PUBLIC_READS = {\n casino: ['listGames', 'listCategories', 'listProviders', 'getGame', 'listJackpots', 'listJackpotGames'],\n bonus: ['listPublicOffers'],\n} as const\n\n// Player reads: `user` key with the session's `userId`.\nconst USER_READS = {\n casino: ['listSessions', 'getHistory', 'getBiggestWinners'],\n club: ['getOverview', 'listHistory', 'listTournaments', 'listRelatedTournaments', 'getTournament', 'getRanking'],\n bonus: ['listOffers', 'getOffer', 'listParticipations', 'getParticipation', 'getOverview', 'listPositions'],\n missions: ['list', 'listMine'],\n loyalty: ['get'],\n referrals: ['get', 'listHistory'],\n bets: ['list', 'get', 'getCashoutOffer'],\n} as const\n\n// Namespaces whose responses depend on the client's locale: their keys end with `{ locale }`.\nconst LOCALE_KEYED: ReadonlySet<string> = /* @__PURE__ */ new Set(['club'])\n\n/** The client's locale right now (`null` without one, or with a core older than 0.12.0). */\nfunction localeOf(igaming: object): string | null {\n const read = (igaming as Record<symbol, (() => string | undefined) | undefined>)[LOCALE]\n return (typeof read === 'function' ? read() : undefined) ?? null\n}\n\ntype Invalidation = (scope: QueryScope) => readonly (readonly unknown[])[]\nconst userKeys =\n (...prefixes: [namespace: string, method?: string][]): Invalidation =>\n (scope) =>\n prefixes.map(([namespace, method]) => scope.userPrefix(namespace, method))\nconst none: Invalidation = () => []\n\ninterface Write {\n /** What the write leaves stale. The core's prefixes (`wallet`) come from `scope.userPrefix`. */\n invalidates: Invalidation\n /** Sends `Idempotency-Key` (accepts `{ idempotencyKey }`). */\n idempotent?: boolean\n /** Entry or result with a credential: `gcTime: 0`. */\n sensitive?: boolean\n /** Extra failures that keep the key (core `>=0.12.0`; older cores ignore it). */\n keepsKey?: (error: unknown) => boolean\n /** What a 409 leaves stale (`invalidatesOnError`). */\n conflict?: Invalidation\n}\n\nconst isConflict = (error: unknown) => isEnginexError(error) && error.status === 409\n\n// The club writes keep the key after a 409 (an in-flight duplicate looks like any conflict) and, on a 409 (a stale\n// `versionId`, a wallet not confirmed), refresh what the retry must read again.\nconst CLUB_WRITE = { idempotent: true, keepsKey: keepsClubIdempotencyKey } as const\nconst CLUB_MONEY = userKeys(['club', 'getOverview'], ['club', 'listHistory'], ['bonus'], ['wallet'])\n\nconst WRITES: Record<string, Record<string, Write>> = {\n casino: { launchGame: { invalidates: userKeys(['casino', 'listSessions']), sensitive: true } },\n club: {\n setMembership: { ...CLUB_WRITE, invalidates: userKeys(['club']), conflict: userKeys(['club', 'getOverview']) },\n // A play or a redemption moves coins, XP, the history and maybe a bonus or the balance; never the tournaments.\n play: { ...CLUB_WRITE, invalidates: CLUB_MONEY, conflict: userKeys(['club', 'getOverview']) },\n redeem: { ...CLUB_WRITE, invalidates: CLUB_MONEY, conflict: userKeys(['club', 'getOverview']) },\n registerForTournament: {\n ...CLUB_WRITE,\n invalidates: userKeys(['club']),\n conflict: userKeys(['club', 'getOverview'], ['club', 'listTournaments'], ['club', 'getTournament']),\n },\n },\n bonus: {\n resolvePromoCode: { invalidates: none, sensitive: true },\n optIn: { invalidates: userKeys(['bonus'], ['wallet']), idempotent: true },\n claim: { invalidates: userKeys(['bonus'], ['wallet']), idempotent: true },\n redeemPromoCode: { invalidates: userKeys(['bonus'], ['wallet']), idempotent: true, sensitive: true },\n },\n loyalty: { redeem: { invalidates: userKeys(['loyalty'], ['wallet']), idempotent: true } },\n sportsbook: { createSession: { invalidates: none, sensitive: true } },\n bets: { cashout: { invalidates: userKeys(['bets'], ['wallet']), idempotent: true } },\n}\n\n/**\n * Creates the iGaming query factories: one per read method, with the same name and the same input\n * as the method (`q.casino.listGames({ page })`). Each call returns `{ queryKey, queryFn }`, compatible\n * with TanStack Query v5's `useQuery`/`prefetchQuery`/`fetchQuery`. It makes no request.\n *\n * - Reads without a session (`casino.listGames/listCategories/listProviders/getGame/listJackpots/listJackpotGames`,\n * `bonus.listPublicOffers`): key `['enginex', 'public', namespace, method, input?]`.\n * - The `club` reads also end with `{ locale }` (the client's locale, `null` without one): the club answers in that\n * locale, so after `setLocale` a factory called again returns a new key and the program (with its\n * `termsLocale`) is fetched again instead of a join recording consent under the old terms. Prefix invalidation\n * (`['enginex', 'user', userId, 'club']`) still matches every locale. Needs core `>=0.12.0` (older: `null`).\n * - Player reads (the others): key `['enginex', 'user', userId, namespace, method, input?]`,\n * with the session's `userId` when the factory is called; without a session, `'anonymous'` and the `queryFn`\n * rejects with `UNAUTHENTICATED` without a request (the same if the session switches user before the `fetch`).\n * - `queryFn` forwards the context's `signal`: canceling the query aborts the `fetch`.\n * - None carries `staleTime`.\n * @param igaming - The object returned by `createIgaming(enginex)` (the object itself, not a copy).\n * @example\n * import { useQuery } from '@tanstack/react-query'\n * import { createIgamingQueries } from '@getenginex/sdk-igaming/query'\n *\n * const q = createIgamingQueries(igaming)\n * const games = useQuery(q.casino.listGames({ category: 'slots' }))\n * @throws {EnginexError} `CONFIGURATION_ERROR` if `igaming` did not come from `createIgaming` (e.g. a\n * `{ ...igaming }` copy). Identify with `isEnginexError(error, 'CONFIGURATION_ERROR')`.\n * @category Queries\n */\nexport function createIgamingQueries(igaming: IgamingClient): IgamingQueries {\n const scope = queryScope(igaming)\n const out: Record<string, Record<string, (input?: unknown) => unknown>> = {}\n const add = (\n table: Record<string, readonly string[]>,\n build: (namespace: string, method: string, input: unknown) => unknown,\n ) => {\n for (const [namespace, methods] of Object.entries(table)) {\n const factories = (out[namespace] ??= {})\n for (const method of methods) factories[method] = (input) => build(namespace, method, input)\n }\n }\n add(PUBLIC_READS, (namespace, method, input) =>\n scope.publicQuery(namespace, method, methodOf(igaming, namespace, method), input),\n )\n add(USER_READS, (namespace, method, input) => {\n const options = scope.userQuery(namespace, method, methodOf(igaming, namespace, method), input)\n if (!LOCALE_KEYED.has(namespace)) return options\n // The club answers in the client's locale (texts, `termsLocale`): a `setLocale` must not reuse the cached\n // program, or a join would record consent under the terms of the old language.\n return { ...options, queryKey: [...options.queryKey, { locale: localeOf(igaming) }] }\n })\n return out as unknown as IgamingQueries\n}\n\n/**\n * Creates the iGaming mutations: one per write method, with the same name as the method\n * (`m.loyalty.redeem()`). Each call returns `{ mutationKey, mutationFn, invalidates }`, compatible\n * with TanStack Query v5's `useMutation`; `invalidates(input, result)` lists the prefixes the write\n * leaves stale (with the session's `userId` at call time; call it only after success):\n *\n * - `bonus.optIn/claim/redeemPromoCode` → `bonus` and `wallet` (the core's balance);\n * - `loyalty.redeem` → `loyalty` and `wallet`;\n * - `bets.cashout` → `bets` and `wallet`;\n * - `club.play/redeem` → `club.getOverview`, `club.listHistory`, `bonus` and `wallet` (a reward may credit a bonus or\n * the balance; the tournaments and rankings are not refetched); `club.setMembership/registerForTournament` →\n * `club`. The club writes also carry `invalidatesOnError`: on a 409 (a stale `versionId`) they refresh\n * `club.getOverview` (and, for `registerForTournament`, the tournaments), like the player did on settle;\n * `useEnginexMutation` runs it in `onError`, plain TanStack calls it in its own `onError`;\n * - `casino.launchGame` → `casino.listSessions`; `bonus.resolvePromoCode` and\n * `sportsbook.createSession` → nothing.\n *\n * `mutationKey` is `['enginex', namespace, method]`, without the input. The ones that send `Idempotency-Key`\n * (`bonus.optIn/claim/redeemPromoCode`, `loyalty.redeem`, `bets.cashout`, the four `club` writes) reuse the key only after an ambiguous\n * failure (network, timeout, 5xx, `KEY_IN_USE` or `VALIDATION_ERROR` after a 2xx) with the same input,\n * on this options object (see the core's `createMutations`), and accept `{ idempotencyKey }` on the factory. The\n * `club` writes also keep it after a 409 or 429 and release it only on 400/403/404/422 (see\n * `keepsClubIdempotencyKey`; needs core `>=0.12.0`). The\n * ones that carry credentials in the input or the result (promo code, game URL, sportsbook\n * session) have `gcTime: 0`.\n * @param igaming - The object returned by `createIgaming(enginex)` (the object itself, not a copy).\n * @example\n * import { useMutation } from '@tanstack/react-query'\n * import { createIgamingMutations } from '@getenginex/sdk-igaming/query'\n *\n * const m = createIgamingMutations(igaming)\n * const redeem = m.loyalty.redeem()\n * const result = await redeem.mutationFn({ points: 500, redemptionType: 'bonus' })\n * for (const queryKey of redeem.invalidates({ points: 500, redemptionType: 'bonus' }, result)) {\n * await queryClient.invalidateQueries({ queryKey })\n * }\n * @throws {EnginexError} `CONFIGURATION_ERROR` if `igaming` did not come from `createIgaming`.\n * @category Queries\n */\nexport function createIgamingMutations(igaming: IgamingClient): IgamingMutations {\n const scope = queryScope(igaming)\n const out: Record<string, Record<string, (options?: { idempotencyKey?: string }) => unknown>> = {}\n for (const [namespace, methods] of Object.entries(WRITES)) {\n const factories = (out[namespace] ??= {})\n for (const [method, write] of Object.entries(methods)) {\n factories[method] = (options) => {\n const scoped: {\n idempotent?: boolean\n idempotencyKey?: string\n gcTime?: number\n keepsKey?: (error: unknown) => boolean\n } = {}\n if (write.idempotent === true) {\n scoped.idempotent = true\n if (write.keepsKey) scoped.keepsKey = write.keepsKey\n if (options?.idempotencyKey !== undefined) scoped.idempotencyKey = options.idempotencyKey\n }\n if (write.sensitive === true) scoped.gcTime = 0\n const mutation = scope.mutation(\n namespace,\n method,\n methodOf(igaming, namespace, method),\n () => write.invalidates(scope),\n scoped,\n )\n const conflict = write.conflict\n // Set here (not through the scope) so it holds with any core; the adapters run it in `onError`.\n if (conflict) mutation.invalidatesOnError = (_input, error) => (isConflict(error) ? conflict(scope) : [])\n return mutation\n }\n }\n }\n return out as unknown as IgamingMutations\n}\n"]}
@@ -66,8 +66,8 @@ var SEED = [
66
66
  function pageOf(req, items) {
67
67
  const q = req.url.searchParams;
68
68
  const page = Math.max(1, Number.parseInt(q.get("page") ?? "", 10) || 1);
69
- const raw = Number.parseInt(q.get("limit") ?? "", 10);
70
- const limit = raw >= 1 && raw <= 100 ? raw : 20;
69
+ const raw2 = Number.parseInt(q.get("limit") ?? "", 10);
70
+ const limit = raw2 >= 1 && raw2 <= 100 ? raw2 : 20;
71
71
  return {
72
72
  items: items.slice((page - 1) * limit, page * limit),
73
73
  meta: { page, per_page: limit, total_pages: Math.ceil(items.length / limit), total_items: items.length }
@@ -602,8 +602,8 @@ function json(body, status = 200) {
602
602
  function pageOf2(req, items) {
603
603
  const q = req.url.searchParams;
604
604
  const page = Math.max(1, Number.parseInt(q.get("page") ?? "", 10) || 1);
605
- const raw = Number.parseInt(q.get("limit") ?? "", 10);
606
- const limit = raw >= 1 && raw <= 100 ? raw : 20;
605
+ const raw2 = Number.parseInt(q.get("limit") ?? "", 10);
606
+ const limit = raw2 >= 1 && raw2 <= 100 ? raw2 : 20;
607
607
  return {
608
608
  items: items.slice((page - 1) * limit, page * limit),
609
609
  meta: { page, per_page: limit, total_pages: Math.ceil(items.length / limit), total_items: items.length }
@@ -722,11 +722,447 @@ function createCasinoRoutes() {
722
722
  return testing.ok(items, meta);
723
723
  },
724
724
  "GET /api/v1/games/biggest-winners": (req) => {
725
- const raw = Number.parseInt(req.url.searchParams.get("limit") ?? "", 10);
726
- return testing.ok(WINNERS.slice(0, raw >= 1 ? raw : 10));
725
+ const raw2 = Number.parseInt(req.url.searchParams.get("limit") ?? "", 10);
726
+ return testing.ok(WINNERS.slice(0, raw2 >= 1 ? raw2 : 10));
727
727
  }
728
728
  };
729
729
  }
730
+ function raw(body, status = 200) {
731
+ return new Response(JSON.stringify(body), { status, headers: { "content-type": "application/json" } });
732
+ }
733
+ var VERSION = "club-v1";
734
+ var TOURNAMENT_VERSION = "tour-v1";
735
+ var OWN = "tour-own-1";
736
+ var EXTERNAL = "ext_tlt_weekly_1";
737
+ var RELATED = "ext_tlt_weekly_2";
738
+ var GO_ZERO = "0001-01-01T00:00:00Z";
739
+ var BRL = (amount) => ({ currency: "BRL", amountMinor: String(amount), decimalPlaces: 2 });
740
+ var pt = (text) => ({ "pt-BR": text });
741
+ var at = (offsetMs) => new Date(Date.UTC(2026, 10, 24, 12) + offsetMs).toISOString().replace(/\.\d{3}Z$/, "Z");
742
+ var reward = (id, kind, quantity, extra = {}) => ({
743
+ id,
744
+ label: pt(id),
745
+ kind,
746
+ quantity: String(quantity),
747
+ ttlSeconds: "0",
748
+ editionId: "",
749
+ ...extra
750
+ });
751
+ var SLICES = [
752
+ { id: "slice-coins", reward: reward("r-coins-50", "coins", 50) },
753
+ { id: "slice-spins", reward: reward("r-spins-10", "free_spins", 10, { campaign: { spins: "10", gameId: "" } }) },
754
+ { id: "slice-bonus", reward: reward("r-bonus-10", "bonus_balance", 1, { money: BRL(1e3) }) }
755
+ ];
756
+ var CHEST = [reward("chest-coins", "coins", 100), reward("chest-spins", "free_spins", 5)];
757
+ var ITEMS = [
758
+ {
759
+ id: "item-spins",
760
+ label: pt("20 giros"),
761
+ terms: {},
762
+ costCoins: "200",
763
+ reward: reward("r-item-spins", "free_spins", 20),
764
+ coverUrl: ""
765
+ },
766
+ {
767
+ id: "item-cash",
768
+ label: pt("R$ 50"),
769
+ terms: {},
770
+ costCoins: "5000",
771
+ reward: reward("r-item-cash", "real_balance", 1, { money: BRL(5e3) }),
772
+ coverUrl: ""
773
+ }
774
+ ];
775
+ function hash(text) {
776
+ let h = 0;
777
+ for (const char of text) h = h * 31 + char.charCodeAt(0) >>> 0;
778
+ return h;
779
+ }
780
+ function createClubRoutes(options = {}) {
781
+ const mode = options.program ?? "active";
782
+ const active = mode === "active";
783
+ const state = {
784
+ joined: mode === "paused",
785
+ xp: 1200,
786
+ coins: 500,
787
+ wheelPlayed: false,
788
+ chestReceipt: null,
789
+ registration: null
790
+ };
791
+ const receipts = [];
792
+ const movements = [
793
+ { id: "mv-1", kind: "coins", units: "500", sourceId: "welcome", occurredAt: at(-864e5) },
794
+ { id: "mv-2", kind: "xp", units: "1200", sourceId: "welcome", occurredAt: at(-864e5) }
795
+ ];
796
+ const replays = /* @__PURE__ */ new Map();
797
+ const seenInFlight = /* @__PURE__ */ new Set();
798
+ const lostOnce = /* @__PURE__ */ new Set();
799
+ let sequence = 0;
800
+ const program = () => mode === "disabled" ? {
801
+ enabled: false,
802
+ joined: false,
803
+ membershipRequired: false,
804
+ canJoin: false,
805
+ historyAvailable: false,
806
+ versionId: "",
807
+ locale: "",
808
+ termsLocale: "",
809
+ timeZone: "",
810
+ currency: "",
811
+ name: {},
812
+ terms: {},
813
+ coinName: {},
814
+ coverUrl: "",
815
+ levels: []
816
+ } : activeProgram();
817
+ const activeProgram = () => ({
818
+ enabled: active,
819
+ joined: state.joined,
820
+ membershipRequired: true,
821
+ canJoin: active && !state.joined,
822
+ historyAvailable: true,
823
+ versionId: VERSION,
824
+ locale: "pt-BR",
825
+ termsLocale: "pt-BR",
826
+ timeZone: "America/Sao_Paulo",
827
+ currency: "BRL",
828
+ name: pt("Clube"),
829
+ terms: pt("Termos do clube"),
830
+ coinName: pt("moedas"),
831
+ coverUrl: "",
832
+ levels: [
833
+ { id: "bronze", name: pt("Bronze"), minXp: "0", benefit: pt("Roleta di\xE1ria") },
834
+ { id: "silver", name: pt("Prata"), minXp: "5000", benefit: pt("Cashback semanal") }
835
+ ]
836
+ });
837
+ const pausedRewards = () => ({
838
+ xp: String(state.xp),
839
+ coins: String(state.coins),
840
+ levelId: "bronze",
841
+ activities: [],
842
+ storeItems: [],
843
+ missions: state.chestReceipt === null ? [
844
+ {
845
+ mission: {
846
+ id: "mission-login",
847
+ title: pt("Entre 3 dias"),
848
+ terms: {},
849
+ recurrence: "",
850
+ countBy: "",
851
+ target: "0",
852
+ coverUrl: ""
853
+ },
854
+ editionId: "",
855
+ progress: "0",
856
+ rightId: "right-1",
857
+ canClaim: false,
858
+ claimExpiresAt: at(6 * 864e5),
859
+ chestOptions: [],
860
+ rightVersionId: "club-v0",
861
+ stampedDays: []
862
+ }
863
+ ] : []
864
+ });
865
+ const rewards = () => {
866
+ if (mode === "paused") return pausedRewards();
867
+ const activity = {
868
+ activity: {
869
+ id: "wheel-daily",
870
+ kind: "wheel",
871
+ name: pt("Roleta di\xE1ria"),
872
+ terms: {},
873
+ coverUrl: "",
874
+ wheelTheme: "emerald",
875
+ playLabel: pt("Girar"),
876
+ slices: SLICES
877
+ },
878
+ canPlay: state.joined && !state.wheelPlayed,
879
+ unavailableReason: ""
880
+ };
881
+ if (state.wheelPlayed) {
882
+ activity.latestReceipt = receipts.find((r) => r.sourceKind === "activity");
883
+ activity.availableAt = at(864e5);
884
+ }
885
+ const chest = {
886
+ mission: {
887
+ id: "mission-login",
888
+ title: pt("Entre 3 dias"),
889
+ terms: {},
890
+ recurrence: "weekly",
891
+ countBy: "day",
892
+ target: "3",
893
+ coverUrl: ""
894
+ },
895
+ editionId: "2026-W48",
896
+ progress: "3",
897
+ rightId: "right-1",
898
+ rightVersionId: VERSION,
899
+ chestOptions: CHEST,
900
+ canClaim: state.joined && state.chestReceipt === null,
901
+ endsAt: at(5 * 864e5),
902
+ claimExpiresAt: at(6 * 864e5),
903
+ stampedDays: ["2026-11-22", "2026-11-23", "2026-11-24"]
904
+ };
905
+ if (state.chestReceipt) chest.receipt = state.chestReceipt;
906
+ return {
907
+ xp: String(state.xp),
908
+ coins: String(state.coins),
909
+ levelId: "bronze",
910
+ activities: [activity],
911
+ missions: [chest],
912
+ storeItems: ITEMS.map((item) => ({
913
+ item,
914
+ canRedeem: state.joined && state.coins >= Number(item.costCoins),
915
+ unavailableReason: state.coins >= Number(item.costCoins) ? "" : "insufficient_coins"
916
+ }))
917
+ };
918
+ };
919
+ const tournaments = () => {
920
+ const own = {
921
+ id: OWN,
922
+ source: "own",
923
+ versionId: TOURNAMENT_VERSION,
924
+ title: pt("Torneio da semana"),
925
+ terms: pt("Maior multiplicador vence"),
926
+ status: "live",
927
+ startsAt: at(-864e5),
928
+ endsAt: at(6 * 864e5),
929
+ updatedAt: at(0),
930
+ scoringRule: "round_multiplier",
931
+ tieBreak: "earliest",
932
+ currency: "BRL",
933
+ timeZone: "America/Sao_Paulo",
934
+ gameIds: [],
935
+ prizes: [
936
+ { fromRank: 1, toRank: 1, reward: reward("prize-1", "real_balance", 1, { money: BRL(5e4) }), terms: {} },
937
+ { fromRank: 2, toRank: 10, reward: reward("prize-2", "free_spins", 50), terms: {} }
938
+ ],
939
+ joinMode: "registration",
940
+ locale: "pt-BR",
941
+ rankingAvailable: true,
942
+ canRegister: state.joined && state.registration === null,
943
+ requiresTicket: false,
944
+ stale: false,
945
+ registrationStartsAt: at(-864e5),
946
+ registrationEndsAt: at(5 * 864e5),
947
+ coverUrl: ""
948
+ };
949
+ if (state.registration) own.registration = state.registration;
950
+ const external = {
951
+ id: EXTERNAL,
952
+ source: "external",
953
+ versionId: "",
954
+ title: pt("Torneio do provedor"),
955
+ terms: {},
956
+ status: "live",
957
+ startsAt: at(-36e5),
958
+ endsAt: at(864e5),
959
+ updatedAt: at(0),
960
+ scoringRule: "",
961
+ tieBreak: "",
962
+ currency: "BRL",
963
+ timeZone: "",
964
+ gameIds: [],
965
+ prizes: [{ fromRank: 1, toRank: 3, announcedAmount: BRL(1e5) }],
966
+ joinMode: "",
967
+ locale: "",
968
+ rankingAvailable: false,
969
+ canRegister: false,
970
+ requiresTicket: false,
971
+ stale: false,
972
+ coverUrl: ""
973
+ };
974
+ return [own, external];
975
+ };
976
+ function keyOf(req) {
977
+ const header = req.headers.get("idempotency-key") ?? "";
978
+ const body = req.body?.idempotencyKey;
979
+ const key = typeof body === "string" && body !== "" ? body : header;
980
+ if (key === "" || key.length > 128 || key !== key.trim() || header !== "" && header !== key) return void 0;
981
+ return key;
982
+ }
983
+ function once(req, scope, run) {
984
+ const key = keyOf(req);
985
+ if (key === void 0) return testing.fail(400, "INVALID_ARGUMENT", "invalid club request");
986
+ if (key.startsWith("inflight-") && !seenInFlight.has(`${scope}:${key}`)) {
987
+ seenInFlight.add(`${scope}:${key}`);
988
+ return testing.fail(
989
+ 409,
990
+ "ALREADY_EXISTS",
991
+ "club action conflicts with the current version, availability, or account state"
992
+ );
993
+ }
994
+ const body = req.body ?? {};
995
+ const { idempotencyKey, ...payload } = body;
996
+ const fingerprint = JSON.stringify([req.url.pathname, payload]);
997
+ const id = `${scope}:${key}`;
998
+ const replay = replays.get(id);
999
+ if (replay) {
1000
+ if (replay.fingerprint !== fingerprint)
1001
+ return testing.fail(
1002
+ 409,
1003
+ "ALREADY_EXISTS",
1004
+ "club action conflicts with the current version, availability, or account state"
1005
+ );
1006
+ return replay.status < 400 ? raw(replay.body, replay.status) : testing.fail(replay.status, "ALREADY_EXISTS", "club conflict");
1007
+ }
1008
+ const result = run(payload, key);
1009
+ if (result instanceof Response) return result;
1010
+ replays.set(id, { fingerprint, ...result });
1011
+ if (key.startsWith("lost-") && !lostOnce.has(id)) {
1012
+ lostOnce.add(id);
1013
+ return testing.fail(503, "UNAVAILABLE", "club service temporarily unavailable");
1014
+ }
1015
+ return result.status < 400 ? raw(result.body, result.status) : testing.fail(result.status, "ALREADY_EXISTS", "club conflict");
1016
+ }
1017
+ const conflict = { status: 409, body: null };
1018
+ const receipt = (fields) => {
1019
+ sequence += 1;
1020
+ const row = {
1021
+ id: `rcpt-${sequence}`,
1022
+ status: "delivered",
1023
+ costCoins: "0",
1024
+ acceptedAt: at(sequence * 1e3),
1025
+ deliveredAt: at(sequence * 1e3),
1026
+ ticketConsumed: false,
1027
+ ...fields
1028
+ };
1029
+ receipts.unshift(row);
1030
+ return row;
1031
+ };
1032
+ const credit = (kind, units, sourceId) => {
1033
+ if (kind !== "coins") return;
1034
+ state.coins += units;
1035
+ movements.unshift({
1036
+ id: `mv-${movements.length + 1}`,
1037
+ kind: "coins",
1038
+ units: String(units),
1039
+ sourceId,
1040
+ occurredAt: at(0)
1041
+ });
1042
+ };
1043
+ return {
1044
+ // Disabled without history: the gateway writes the program alone (protojson omits the unset `rewards`).
1045
+ "GET /api/v1/casino/club": () => raw(mode === "disabled" ? { program: program() } : { program: program(), rewards: rewards() }),
1046
+ "PUT /api/v1/casino/club/membership": (req) => {
1047
+ const body = req.body ?? {};
1048
+ if (typeof body.joined !== "boolean")
1049
+ return testing.fail(400, "INVALID_ARGUMENT", "club membership requires an explicit joined value");
1050
+ if (body.joined && !body.termsLocale)
1051
+ return testing.fail(400, "INVALID_ARGUMENT", "club membership requires the displayed terms locale");
1052
+ return once(req, "membership", (payload) => {
1053
+ if (!active || payload.versionId !== VERSION) return conflict;
1054
+ state.joined = payload.joined === true;
1055
+ return { status: 200, body: program() };
1056
+ });
1057
+ },
1058
+ "GET /api/v1/casino/club/history": (req) => {
1059
+ const q = req.url.searchParams;
1060
+ const limitText = q.get("limit");
1061
+ const limit = limitText === null ? 20 : Number(limitText);
1062
+ if (!Number.isInteger(limit) || limit < 1 || limit > 100)
1063
+ return testing.fail(400, "INVALID_ARGUMENT", "invalid club request");
1064
+ const cursor = q.get("cursor") ?? "";
1065
+ const start = cursor === "" ? 0 : Number(cursor.replace(/^c/, ""));
1066
+ if (!Number.isInteger(start) || start < 0) return testing.fail(400, "INVALID_ARGUMENT", "invalid club request");
1067
+ const page = receipts.slice(start, start + limit);
1068
+ const end = start + page.length;
1069
+ return raw({
1070
+ receipts: page,
1071
+ movements: start === 0 ? movements : [],
1072
+ nextCursor: end < receipts.length ? `c${end}` : ""
1073
+ });
1074
+ },
1075
+ "POST /api/v1/casino/club/activities/:activityId/plays": (req) => once(req, "play", (payload, key) => {
1076
+ const activityId = req.params?.activityId;
1077
+ const version = mode === "paused" && activityId === "right-1" ? "club-v0" : VERSION;
1078
+ if (mode === "disabled" || mode === "paused" && activityId !== "right-1") return conflict;
1079
+ if (!state.joined || payload.versionId !== version) return conflict;
1080
+ if (activityId === "wheel-daily") {
1081
+ if (state.wheelPlayed) return conflict;
1082
+ const slice = SLICES[hash(key) % SLICES.length];
1083
+ const won = slice.reward;
1084
+ state.wheelPlayed = true;
1085
+ credit(String(won.kind), Number(won.quantity), "wheel-daily");
1086
+ const row = receipt({ sourceKind: "activity", sourceId: "wheel-daily", sliceId: slice.id, reward: won });
1087
+ return { status: 200, body: { receipt: row, sliceId: slice.id, rewards: rewards() } };
1088
+ }
1089
+ if (activityId === "right-1") {
1090
+ const option = CHEST.find((o) => o.id === payload.optionId);
1091
+ if (state.chestReceipt || !option) return conflict;
1092
+ credit(String(option.kind), Number(option.quantity), "right-1");
1093
+ state.chestReceipt = receipt({ sourceKind: "chest", sourceId: "right-1", reward: option });
1094
+ return { status: 200, body: { receipt: state.chestReceipt, sliceId: "", rewards: rewards() } };
1095
+ }
1096
+ return testing.fail(404, "NOT_FOUND", "club resource not found");
1097
+ }),
1098
+ "POST /api/v1/casino/club/rewards/:rewardId/redemptions": (req) => once(req, "redeem", (payload) => {
1099
+ const item = ITEMS.find((i) => i.id === req.params?.rewardId);
1100
+ if (!item) return testing.fail(404, "NOT_FOUND", "club resource not found");
1101
+ const cost = Number(item.costCoins);
1102
+ if (!active || !state.joined || payload.versionId !== VERSION || state.coins < cost) return conflict;
1103
+ state.coins -= cost;
1104
+ movements.unshift({
1105
+ id: `mv-${movements.length + 1}`,
1106
+ kind: "coins",
1107
+ units: String(-cost),
1108
+ sourceId: item.id,
1109
+ occurredAt: at(0)
1110
+ });
1111
+ const row = receipt({ sourceKind: "store", sourceId: item.id, reward: item.reward, costCoins: item.costCoins });
1112
+ return { status: 200, body: row };
1113
+ }),
1114
+ "GET /api/v1/casino/club/tournaments": (req) => {
1115
+ if (!active) return testing.fail(404, "NOT_FOUND", "club resource not found");
1116
+ const related = req.url.searchParams.get("relatedTo");
1117
+ if (related !== null) {
1118
+ if (related !== EXTERNAL) return testing.fail(404, "NOT_FOUND", "club resource not found");
1119
+ return raw({
1120
+ relatedTo: EXTERNAL,
1121
+ items: [
1122
+ {
1123
+ id: RELATED,
1124
+ title: pt("Torneio do provedor"),
1125
+ status: "upcoming",
1126
+ startsAt: at(864e5),
1127
+ endsAt: at(2 * 864e5)
1128
+ },
1129
+ // A nil title map and zero `time.Time` values, as `encoding/json` writes them.
1130
+ { id: "ext_tlt_weekly_3", title: null, status: "upcoming", startsAt: GO_ZERO, endsAt: GO_ZERO }
1131
+ ],
1132
+ nextCursor: ""
1133
+ });
1134
+ }
1135
+ return raw({ items: tournaments(), externalAvailable: true, externalStale: false, nextCursor: "" });
1136
+ },
1137
+ "GET /api/v1/casino/club/tournaments/:editionId": (req) => {
1138
+ if (!active) return testing.fail(404, "NOT_FOUND", "club resource not found");
1139
+ const tournament = tournaments().find((t) => t.id === req.params?.editionId);
1140
+ return tournament ? raw(tournament) : testing.fail(404, "NOT_FOUND", "club resource not found");
1141
+ },
1142
+ "GET /api/v1/casino/club/tournaments/:editionId/ranking": (req) => {
1143
+ if (!active) return testing.fail(404, "NOT_FOUND", "club resource not found");
1144
+ const editionId = req.params?.editionId;
1145
+ if (editionId === EXTERNAL)
1146
+ return testing.fail(404, "CLUB_RANKING_UNAVAILABLE", "ranking is unavailable for this edition");
1147
+ if (editionId !== OWN) return testing.fail(404, "NOT_FOUND", "club resource not found");
1148
+ const entries = [
1149
+ { position: 1, displayName: "Ma\u2022\u2022\u2022 R.", score: "152.5" },
1150
+ { position: 2, displayName: "Jo\u2022\u2022\u2022 S.", score: "98" },
1151
+ { position: 3, displayName: "An\u2022\u2022\u2022 P.", score: "71.25" }
1152
+ ];
1153
+ const body = { entries, updatedAt: at(0), final: false };
1154
+ if (state.registration) body.personal = { position: 4, displayName: "Voc\xEA", score: "12" };
1155
+ return raw(body);
1156
+ },
1157
+ "POST /api/v1/casino/club/tournaments/:editionId/registrations": (req) => once(req, "register", (payload) => {
1158
+ if (!active) return conflict;
1159
+ if (req.params?.editionId !== OWN) return testing.fail(404, "NOT_FOUND", "club resource not found");
1160
+ if (!state.joined || payload.versionId !== TOURNAMENT_VERSION || state.registration) return conflict;
1161
+ state.registration = { id: "reg-1", editionId: OWN, versionId: TOURNAMENT_VERSION, joinedAt: at(0) };
1162
+ return { status: 200, body: state.registration };
1163
+ })
1164
+ };
1165
+ }
730
1166
  var POINT_VALUE_CENTS = 5;
731
1167
  function createLoyaltyRoutes() {
732
1168
  const state = { total: 5200, current: 1500, redeemed: 3700 };
@@ -837,8 +1273,8 @@ function json2(body) {
837
1273
  function listMissions(req) {
838
1274
  const q = req.url.searchParams;
839
1275
  const page = Math.max(1, Number.parseInt(q.get("page") ?? "", 10) || 1);
840
- const raw = Number.parseInt(q.get("limit") ?? "", 10);
841
- const limit = raw >= 1 && raw <= 100 ? raw : 20;
1276
+ const raw2 = Number.parseInt(q.get("limit") ?? "", 10);
1277
+ const limit = raw2 >= 1 && raw2 <= 100 ? raw2 : 20;
842
1278
  return json2({
843
1279
  success: true,
844
1280
  data: MISSIONS.slice((page - 1) * limit, page * limit),
@@ -893,8 +1329,8 @@ var CODE = "MOCK123";
893
1329
  function listHistory(req) {
894
1330
  const q = req.url.searchParams;
895
1331
  const page = Math.max(1, Number.parseInt(q.get("page") ?? "", 10) || 1);
896
- const raw = Number.parseInt(q.get("limit") ?? "", 10);
897
- const limit = raw >= 1 ? Math.min(raw, 100) : 20;
1332
+ const raw2 = Number.parseInt(q.get("limit") ?? "", 10);
1333
+ const limit = raw2 >= 1 ? Math.min(raw2, 100) : 20;
898
1334
  return testing.ok({
899
1335
  referral_code: CODE,
900
1336
  referrals: REFERRALS.slice((page - 1) * limit, page * limit),
@@ -927,9 +1363,10 @@ function createSportsbookRoutes() {
927
1363
  }
928
1364
 
929
1365
  // src/testing/index.ts
930
- function createIgamingRoutes() {
1366
+ function createIgamingRoutes(options = {}) {
931
1367
  return {
932
1368
  ...createCasinoRoutes(),
1369
+ ...createClubRoutes(options.club),
933
1370
  ...createBonusRoutes(),
934
1371
  ...createSportsbookRoutes(),
935
1372
  ...createMissionsRoutes(),
@@ -939,7 +1376,8 @@ function createIgamingRoutes() {
939
1376
  };
940
1377
  }
941
1378
  function withIgamingRoutes(options = {}) {
942
- return { ...options, routes: { ...createIgamingRoutes(), ...options.routes } };
1379
+ const { club, ...core } = options;
1380
+ return { ...core, routes: { ...createIgamingRoutes({ club }), ...core.routes } };
943
1381
  }
944
1382
 
945
1383
  exports.createIgamingRoutes = createIgamingRoutes;