@getenginex/sdk-igaming 0.0.0-stage → 0.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,103 @@
1
+ import { MutationsOf, IdempotentMutationsOf, QueriesOf } from '@getenginex/sdk/query';
2
+ import { CasinoApi, BonusApi, LoyaltyApi, ReferralsApi, SportsbookApi, MissionsApi, IgamingClient } from '../index.cjs';
3
+ import '@getenginex/sdk';
4
+
5
+ /**
6
+ * Fábricas de query e mutation de iGaming, compatíveis com o TanStack Query v5 (`useQuery`,
7
+ * `useMutation`, `prefetchQuery`), sem depender dele. Mesmas convenções de chave do
8
+ * `@getenginex/sdk/query`.
9
+ * @module @getenginex/sdk-igaming/query
10
+ */
11
+
12
+ /**
13
+ * Fábricas de query de iGaming, uma por método de leitura: `q.<namespace>.<método>(input)` devolve
14
+ * `{ queryKey, queryFn }`. Obtidas com {@link createIgamingQueries}.
15
+ * @category Queries
16
+ */
17
+ interface IgamingQueries {
18
+ /** Catálogo (público) e, com login, sessões, histórico e maiores ganhadores. */
19
+ readonly casino: QueriesOf<CasinoApi, 'listGames' | 'listCategories' | 'listProviders' | 'getGame' | 'listSessions' | 'getHistory' | 'getBiggestWinners'>;
20
+ /** Ofertas públicas (sem login) e, com login, ofertas e participações. */
21
+ readonly bonus: QueriesOf<BonusApi, 'listPublicOffers' | 'listOffers' | 'getOffer' | 'listParticipations' | 'getParticipation'>;
22
+ /** Missões do operador e as do jogador. */
23
+ readonly missions: QueriesOf<MissionsApi, 'list' | 'listMine'>;
24
+ /** Saldo de pontos, tier e benefícios. */
25
+ readonly loyalty: QueriesOf<LoyaltyApi, 'get'>;
26
+ /** Código, link e histórico de indicações. */
27
+ readonly referrals: QueriesOf<ReferralsApi, 'get' | 'listHistory'>;
28
+ }
29
+ /**
30
+ * Mutations de iGaming, uma por método de escrita: `m.<namespace>.<método>()` devolve
31
+ * `{ mutationKey, mutationFn, invalidates }`. Obtidas com {@link createIgamingMutations}.
32
+ * @category Queries
33
+ */
34
+ interface IgamingMutations {
35
+ /** Abertura de jogo (`launchGame`, com `gcTime: 0`: a URL do jogo carrega credenciais). */
36
+ readonly casino: MutationsOf<CasinoApi, 'launchGame'>;
37
+ /** Opt-in, resgate (idempotentes: aceitam `{ idempotencyKey }`) e conferência de promo code. */
38
+ readonly bonus: IdempotentMutationsOf<BonusApi, 'optIn' | 'claim' | 'redeemPromoCode'> & MutationsOf<BonusApi, 'resolvePromoCode'>;
39
+ /** Resgate de pontos (idempotente: aceita `{ idempotencyKey }`). */
40
+ readonly loyalty: IdempotentMutationsOf<LoyaltyApi, 'redeem'>;
41
+ /** Registro de código de indicação. */
42
+ readonly referrals: MutationsOf<ReferralsApi, 'register'>;
43
+ /** Sessão do sportsbook (`gcTime: 0`: a URL carrega o token de operador). */
44
+ readonly sportsbook: MutationsOf<SportsbookApi, 'createSession'>;
45
+ }
46
+ /**
47
+ * Cria as fábricas de query de iGaming: uma por método de leitura, com o mesmo nome e a mesma entrada
48
+ * do método (`q.casino.listGames({ page })`). Cada chamada devolve `{ queryKey, queryFn }`, compatível
49
+ * com `useQuery`/`prefetchQuery`/`fetchQuery` do TanStack Query v5. Não faz request.
50
+ *
51
+ * - Leituras sem sessão (`casino.listGames/listCategories/listProviders/getGame`,
52
+ * `bonus.listPublicOffers`): chave `['enginex', 'public', namespace, método, input?]`.
53
+ * - Leituras do jogador (as demais): chave `['enginex', 'user', userId, namespace, método, input?]`,
54
+ * com o `userId` da sessão quando a fábrica é chamada; sem sessão, `'anonymous'` e o `queryFn`
55
+ * rejeita com `UNAUTHENTICATED` sem request (o mesmo se a sessão mudar de usuário antes do `fetch`).
56
+ * - `queryFn` repassa o `signal` do contexto: cancelar a query aborta o `fetch`.
57
+ * - Nenhuma traz `staleTime`.
58
+ * @param igaming - O objeto devolvido por `createIgaming(enginex)` (o próprio, não uma cópia).
59
+ * @example
60
+ * import { useQuery } from '@tanstack/react-query'
61
+ * import { createIgamingQueries } from '@getenginex/sdk-igaming/query'
62
+ *
63
+ * const q = createIgamingQueries(igaming)
64
+ * const games = useQuery(q.casino.listGames({ category: 'slots' }))
65
+ * @throws {EnginexError} `CONFIGURATION_ERROR` se `igaming` não veio de `createIgaming` (ex.: uma
66
+ * cópia `{ ...igaming }`). Identifique com `isEnginexError(error, 'CONFIGURATION_ERROR')`.
67
+ * @category Queries
68
+ */
69
+ declare function createIgamingQueries(igaming: IgamingClient): IgamingQueries;
70
+ /**
71
+ * Cria as mutations de iGaming: uma por método de escrita, com o mesmo nome do método
72
+ * (`m.loyalty.redeem()`). Cada chamada devolve `{ mutationKey, mutationFn, invalidates }`, compatível
73
+ * com `useMutation` do TanStack Query v5; `invalidates(input, result)` lista os prefixos que a escrita
74
+ * deixa desatualizados (com o `userId` da sessão na hora da chamada; chame só depois do sucesso):
75
+ *
76
+ * - `bonus.optIn/claim/redeemPromoCode` → `bonus` e `wallet` (saldo do core);
77
+ * - `loyalty.redeem` → `loyalty` e `wallet`; `referrals.register` → `referrals`;
78
+ * - `casino.launchGame` → `casino.listSessions`; `bonus.resolvePromoCode` e
79
+ * `sportsbook.createSession` → nada.
80
+ *
81
+ * `mutationKey` é `['enginex', namespace, método]`, sem a entrada. As que mandam `Idempotency-Key`
82
+ * (`bonus.optIn/claim/redeemPromoCode`, `loyalty.redeem`) reusam a chave só depois de uma falha
83
+ * ambígua (rede, timeout, 5xx, `KEY_IN_USE` ou `VALIDATION_ERROR` depois de 2xx) com a mesma entrada,
84
+ * neste objeto de opções (veja `createMutations` do core), e aceitam `{ idempotencyKey }` na fábrica. As
85
+ * que levam credenciais na entrada ou no resultado (código promocional, URL do jogo, sessão do
86
+ * sportsbook) trazem `gcTime: 0`.
87
+ * @param igaming - O objeto devolvido por `createIgaming(enginex)` (o próprio, não uma cópia).
88
+ * @example
89
+ * import { useMutation } from '@tanstack/react-query'
90
+ * import { createIgamingMutations } from '@getenginex/sdk-igaming/query'
91
+ *
92
+ * const m = createIgamingMutations(igaming)
93
+ * const redeem = m.loyalty.redeem()
94
+ * const result = await redeem.mutationFn({ points: 500, redemptionType: 'bonus' })
95
+ * for (const queryKey of redeem.invalidates({ points: 500, redemptionType: 'bonus' }, result)) {
96
+ * await queryClient.invalidateQueries({ queryKey })
97
+ * }
98
+ * @throws {EnginexError} `CONFIGURATION_ERROR` se `igaming` não veio de `createIgaming`.
99
+ * @category Queries
100
+ */
101
+ declare function createIgamingMutations(igaming: IgamingClient): IgamingMutations;
102
+
103
+ export { type IgamingMutations, type IgamingQueries, createIgamingMutations, createIgamingQueries };
@@ -0,0 +1,103 @@
1
+ import { MutationsOf, IdempotentMutationsOf, QueriesOf } from '@getenginex/sdk/query';
2
+ import { CasinoApi, BonusApi, LoyaltyApi, ReferralsApi, SportsbookApi, MissionsApi, IgamingClient } from '../index.js';
3
+ import '@getenginex/sdk';
4
+
5
+ /**
6
+ * Fábricas de query e mutation de iGaming, compatíveis com o TanStack Query v5 (`useQuery`,
7
+ * `useMutation`, `prefetchQuery`), sem depender dele. Mesmas convenções de chave do
8
+ * `@getenginex/sdk/query`.
9
+ * @module @getenginex/sdk-igaming/query
10
+ */
11
+
12
+ /**
13
+ * Fábricas de query de iGaming, uma por método de leitura: `q.<namespace>.<método>(input)` devolve
14
+ * `{ queryKey, queryFn }`. Obtidas com {@link createIgamingQueries}.
15
+ * @category Queries
16
+ */
17
+ interface IgamingQueries {
18
+ /** Catálogo (público) e, com login, sessões, histórico e maiores ganhadores. */
19
+ readonly casino: QueriesOf<CasinoApi, 'listGames' | 'listCategories' | 'listProviders' | 'getGame' | 'listSessions' | 'getHistory' | 'getBiggestWinners'>;
20
+ /** Ofertas públicas (sem login) e, com login, ofertas e participações. */
21
+ readonly bonus: QueriesOf<BonusApi, 'listPublicOffers' | 'listOffers' | 'getOffer' | 'listParticipations' | 'getParticipation'>;
22
+ /** Missões do operador e as do jogador. */
23
+ readonly missions: QueriesOf<MissionsApi, 'list' | 'listMine'>;
24
+ /** Saldo de pontos, tier e benefícios. */
25
+ readonly loyalty: QueriesOf<LoyaltyApi, 'get'>;
26
+ /** Código, link e histórico de indicações. */
27
+ readonly referrals: QueriesOf<ReferralsApi, 'get' | 'listHistory'>;
28
+ }
29
+ /**
30
+ * Mutations de iGaming, uma por método de escrita: `m.<namespace>.<método>()` devolve
31
+ * `{ mutationKey, mutationFn, invalidates }`. Obtidas com {@link createIgamingMutations}.
32
+ * @category Queries
33
+ */
34
+ interface IgamingMutations {
35
+ /** Abertura de jogo (`launchGame`, com `gcTime: 0`: a URL do jogo carrega credenciais). */
36
+ readonly casino: MutationsOf<CasinoApi, 'launchGame'>;
37
+ /** Opt-in, resgate (idempotentes: aceitam `{ idempotencyKey }`) e conferência de promo code. */
38
+ readonly bonus: IdempotentMutationsOf<BonusApi, 'optIn' | 'claim' | 'redeemPromoCode'> & MutationsOf<BonusApi, 'resolvePromoCode'>;
39
+ /** Resgate de pontos (idempotente: aceita `{ idempotencyKey }`). */
40
+ readonly loyalty: IdempotentMutationsOf<LoyaltyApi, 'redeem'>;
41
+ /** Registro de código de indicação. */
42
+ readonly referrals: MutationsOf<ReferralsApi, 'register'>;
43
+ /** Sessão do sportsbook (`gcTime: 0`: a URL carrega o token de operador). */
44
+ readonly sportsbook: MutationsOf<SportsbookApi, 'createSession'>;
45
+ }
46
+ /**
47
+ * Cria as fábricas de query de iGaming: uma por método de leitura, com o mesmo nome e a mesma entrada
48
+ * do método (`q.casino.listGames({ page })`). Cada chamada devolve `{ queryKey, queryFn }`, compatível
49
+ * com `useQuery`/`prefetchQuery`/`fetchQuery` do TanStack Query v5. Não faz request.
50
+ *
51
+ * - Leituras sem sessão (`casino.listGames/listCategories/listProviders/getGame`,
52
+ * `bonus.listPublicOffers`): chave `['enginex', 'public', namespace, método, input?]`.
53
+ * - Leituras do jogador (as demais): chave `['enginex', 'user', userId, namespace, método, input?]`,
54
+ * com o `userId` da sessão quando a fábrica é chamada; sem sessão, `'anonymous'` e o `queryFn`
55
+ * rejeita com `UNAUTHENTICATED` sem request (o mesmo se a sessão mudar de usuário antes do `fetch`).
56
+ * - `queryFn` repassa o `signal` do contexto: cancelar a query aborta o `fetch`.
57
+ * - Nenhuma traz `staleTime`.
58
+ * @param igaming - O objeto devolvido por `createIgaming(enginex)` (o próprio, não uma cópia).
59
+ * @example
60
+ * import { useQuery } from '@tanstack/react-query'
61
+ * import { createIgamingQueries } from '@getenginex/sdk-igaming/query'
62
+ *
63
+ * const q = createIgamingQueries(igaming)
64
+ * const games = useQuery(q.casino.listGames({ category: 'slots' }))
65
+ * @throws {EnginexError} `CONFIGURATION_ERROR` se `igaming` não veio de `createIgaming` (ex.: uma
66
+ * cópia `{ ...igaming }`). Identifique com `isEnginexError(error, 'CONFIGURATION_ERROR')`.
67
+ * @category Queries
68
+ */
69
+ declare function createIgamingQueries(igaming: IgamingClient): IgamingQueries;
70
+ /**
71
+ * Cria as mutations de iGaming: uma por método de escrita, com o mesmo nome do método
72
+ * (`m.loyalty.redeem()`). Cada chamada devolve `{ mutationKey, mutationFn, invalidates }`, compatível
73
+ * com `useMutation` do TanStack Query v5; `invalidates(input, result)` lista os prefixos que a escrita
74
+ * deixa desatualizados (com o `userId` da sessão na hora da chamada; chame só depois do sucesso):
75
+ *
76
+ * - `bonus.optIn/claim/redeemPromoCode` → `bonus` e `wallet` (saldo do core);
77
+ * - `loyalty.redeem` → `loyalty` e `wallet`; `referrals.register` → `referrals`;
78
+ * - `casino.launchGame` → `casino.listSessions`; `bonus.resolvePromoCode` e
79
+ * `sportsbook.createSession` → nada.
80
+ *
81
+ * `mutationKey` é `['enginex', namespace, método]`, sem a entrada. As que mandam `Idempotency-Key`
82
+ * (`bonus.optIn/claim/redeemPromoCode`, `loyalty.redeem`) reusam a chave só depois de uma falha
83
+ * ambígua (rede, timeout, 5xx, `KEY_IN_USE` ou `VALIDATION_ERROR` depois de 2xx) com a mesma entrada,
84
+ * neste objeto de opções (veja `createMutations` do core), e aceitam `{ idempotencyKey }` na fábrica. As
85
+ * que levam credenciais na entrada ou no resultado (código promocional, URL do jogo, sessão do
86
+ * sportsbook) trazem `gcTime: 0`.
87
+ * @param igaming - O objeto devolvido por `createIgaming(enginex)` (o próprio, não uma cópia).
88
+ * @example
89
+ * import { useMutation } from '@tanstack/react-query'
90
+ * import { createIgamingMutations } from '@getenginex/sdk-igaming/query'
91
+ *
92
+ * const m = createIgamingMutations(igaming)
93
+ * const redeem = m.loyalty.redeem()
94
+ * const result = await redeem.mutationFn({ points: 500, redemptionType: 'bonus' })
95
+ * for (const queryKey of redeem.invalidates({ points: 500, redemptionType: 'bonus' }, result)) {
96
+ * await queryClient.invalidateQueries({ queryKey })
97
+ * }
98
+ * @throws {EnginexError} `CONFIGURATION_ERROR` se `igaming` não veio de `createIgaming`.
99
+ * @category Queries
100
+ */
101
+ declare function createIgamingMutations(igaming: IgamingClient): IgamingMutations;
102
+
103
+ export { type IgamingMutations, type IgamingQueries, createIgamingMutations, createIgamingQueries };
@@ -0,0 +1,81 @@
1
+ import { queryScope } from '@getenginex/sdk/query';
2
+
3
+ // src/query/index.ts
4
+ var methodOf = (igaming, namespace, method) => (input, options) => igaming[namespace][method].call(
5
+ igaming[namespace],
6
+ input,
7
+ options
8
+ );
9
+ var PUBLIC_READS = {
10
+ casino: ["listGames", "listCategories", "listProviders", "getGame"],
11
+ bonus: ["listPublicOffers"]
12
+ };
13
+ var USER_READS = {
14
+ casino: ["listSessions", "getHistory", "getBiggestWinners"],
15
+ bonus: ["listOffers", "getOffer", "listParticipations", "getParticipation"],
16
+ missions: ["list", "listMine"],
17
+ loyalty: ["get"],
18
+ referrals: ["get", "listHistory"]
19
+ };
20
+ var userKeys = (...prefixes) => (scope) => prefixes.map(([namespace, method]) => scope.userPrefix(namespace, method));
21
+ var none = () => [];
22
+ var WRITES = {
23
+ casino: { launchGame: { invalidates: userKeys(["casino", "listSessions"]), sensitive: true } },
24
+ bonus: {
25
+ resolvePromoCode: { invalidates: none, sensitive: true },
26
+ optIn: { invalidates: userKeys(["bonus"], ["wallet"]), idempotent: true },
27
+ claim: { invalidates: userKeys(["bonus"], ["wallet"]), idempotent: true },
28
+ redeemPromoCode: { invalidates: userKeys(["bonus"], ["wallet"]), idempotent: true, sensitive: true }
29
+ },
30
+ loyalty: { redeem: { invalidates: userKeys(["loyalty"], ["wallet"]), idempotent: true } },
31
+ referrals: { register: { invalidates: userKeys(["referrals"]) } },
32
+ sportsbook: { createSession: { invalidates: none, sensitive: true } }
33
+ };
34
+ function createIgamingQueries(igaming) {
35
+ const scope = queryScope(igaming);
36
+ const out = {};
37
+ const add = (table, build) => {
38
+ for (const [namespace, methods] of Object.entries(table)) {
39
+ const factories = out[namespace] ??= {};
40
+ for (const method of methods) factories[method] = (input) => build(namespace, method, input);
41
+ }
42
+ };
43
+ add(
44
+ PUBLIC_READS,
45
+ (namespace, method, input) => scope.publicQuery(namespace, method, methodOf(igaming, namespace, method), input)
46
+ );
47
+ add(
48
+ USER_READS,
49
+ (namespace, method, input) => scope.userQuery(namespace, method, methodOf(igaming, namespace, method), input)
50
+ );
51
+ return out;
52
+ }
53
+ function createIgamingMutations(igaming) {
54
+ const scope = queryScope(igaming);
55
+ const out = {};
56
+ for (const [namespace, methods] of Object.entries(WRITES)) {
57
+ const factories = out[namespace] ??= {};
58
+ for (const [method, write] of Object.entries(methods)) {
59
+ factories[method] = (options) => {
60
+ const scoped = {};
61
+ if (write.idempotent === true) {
62
+ scoped.idempotent = true;
63
+ if (options?.idempotencyKey !== void 0) scoped.idempotencyKey = options.idempotencyKey;
64
+ }
65
+ if (write.sensitive === true) scoped.gcTime = 0;
66
+ return scope.mutation(
67
+ namespace,
68
+ method,
69
+ methodOf(igaming, namespace, method),
70
+ () => write.invalidates(scope),
71
+ scoped
72
+ );
73
+ };
74
+ }
75
+ }
76
+ return out;
77
+ }
78
+
79
+ export { createIgamingMutations, createIgamingQueries };
80
+ //# sourceMappingURL=index.js.map
81
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../src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AC9C,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 * Fábricas de query e mutation de iGaming, compatíveis com o TanStack Query v5 (`useQuery`,\n * `useMutation`, `prefetchQuery`), sem depender dele. Mesmas convenções de chave do\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 { 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 * Fábricas de query de iGaming, uma por método de leitura: `q.<namespace>.<método>(input)` devolve\n * `{ queryKey, queryFn }`. Obtidas com {@link createIgamingQueries}.\n * @category Queries\n */\nexport interface IgamingQueries {\n /** Catálogo (público) e, com login, sessões, histórico e maiores ganhadores. */\n readonly casino: QueriesOf<\n CasinoApi,\n 'listGames' | 'listCategories' | 'listProviders' | 'getGame' | 'listSessions' | 'getHistory' | 'getBiggestWinners'\n >\n /** Ofertas públicas (sem login) e, com login, ofertas e participações. */\n readonly bonus: QueriesOf<\n BonusApi,\n 'listPublicOffers' | 'listOffers' | 'getOffer' | 'listParticipations' | 'getParticipation'\n >\n /** Missões do operador e as do jogador. */\n readonly missions: QueriesOf<MissionsApi, 'list' | 'listMine'>\n /** Saldo de pontos, tier e benefícios. */\n readonly loyalty: QueriesOf<LoyaltyApi, 'get'>\n /** Código, link e histórico de indicações. */\n readonly referrals: QueriesOf<ReferralsApi, 'get' | 'listHistory'>\n}\n\n/**\n * Mutations de iGaming, uma por método de escrita: `m.<namespace>.<método>()` devolve\n * `{ mutationKey, mutationFn, invalidates }`. Obtidas com {@link createIgamingMutations}.\n * @category Queries\n */\nexport interface IgamingMutations {\n /** Abertura de jogo (`launchGame`, com `gcTime: 0`: a URL do jogo carrega credenciais). */\n readonly casino: MutationsOf<CasinoApi, 'launchGame'>\n /** Opt-in, resgate (idempotentes: aceitam `{ idempotencyKey }`) e conferência de promo code. */\n readonly bonus: IdempotentMutationsOf<BonusApi, 'optIn' | 'claim' | 'redeemPromoCode'> &\n MutationsOf<BonusApi, 'resolvePromoCode'>\n /** Resgate de pontos (idempotente: aceita `{ idempotencyKey }`). */\n readonly loyalty: IdempotentMutationsOf<LoyaltyApi, 'redeem'>\n /** Registro de código de indicação. */\n readonly referrals: MutationsOf<ReferralsApi, 'register'>\n /** Sessão do sportsbook (`gcTime: 0`: a URL carrega o token de operador). */\n readonly sportsbook: MutationsOf<SportsbookApi, 'createSession'>\n}\n\ntype Method = (input: unknown, options?: CallOptions) => Promise<unknown>\n\n// Chama `igaming[namespace][método]` na hora do request (não na criação), mantendo o `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// Leituras sem sessão (o método não manda token): chave `public`, sem `staleTime`.\nconst PUBLIC_READS = {\n casino: ['listGames', 'listCategories', 'listProviders', 'getGame'],\n bonus: ['listPublicOffers'],\n} as const\n\n// Leituras do jogador: chave `user` com o `userId` da sessão.\nconst USER_READS = {\n casino: ['listSessions', 'getHistory', 'getBiggestWinners'],\n bonus: ['listOffers', 'getOffer', 'listParticipations', 'getParticipation'],\n missions: ['list', 'listMine'],\n loyalty: ['get'],\n referrals: ['get', 'listHistory'],\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 /** O que a escrita deixa desatualizado. Os prefixos do core (`wallet`) saem de `scope.userPrefix`. */\n invalidates: Invalidation\n /** Manda `Idempotency-Key` (aceita `{ idempotencyKey }`). */\n idempotent?: boolean\n /** Entrada ou resultado com credencial: `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 referrals: { register: { invalidates: userKeys(['referrals']) } },\n sportsbook: { createSession: { invalidates: none, sensitive: true } },\n}\n\n/**\n * Cria as fábricas de query de iGaming: uma por método de leitura, com o mesmo nome e a mesma entrada\n * do método (`q.casino.listGames({ page })`). Cada chamada devolve `{ queryKey, queryFn }`, compatível\n * com `useQuery`/`prefetchQuery`/`fetchQuery` do TanStack Query v5. Não faz request.\n *\n * - Leituras sem sessão (`casino.listGames/listCategories/listProviders/getGame`,\n * `bonus.listPublicOffers`): chave `['enginex', 'public', namespace, método, input?]`.\n * - Leituras do jogador (as demais): chave `['enginex', 'user', userId, namespace, método, input?]`,\n * com o `userId` da sessão quando a fábrica é chamada; sem sessão, `'anonymous'` e o `queryFn`\n * rejeita com `UNAUTHENTICATED` sem request (o mesmo se a sessão mudar de usuário antes do `fetch`).\n * - `queryFn` repassa o `signal` do contexto: cancelar a query aborta o `fetch`.\n * - Nenhuma traz `staleTime`.\n * @param igaming - O objeto devolvido por `createIgaming(enginex)` (o próprio, não uma cópia).\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` se `igaming` não veio de `createIgaming` (ex.: uma\n * cópia `{ ...igaming }`). Identifique com `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 * Cria as mutations de iGaming: uma por método de escrita, com o mesmo nome do método\n * (`m.loyalty.redeem()`). Cada chamada devolve `{ mutationKey, mutationFn, invalidates }`, compatível\n * com `useMutation` do TanStack Query v5; `invalidates(input, result)` lista os prefixos que a escrita\n * deixa desatualizados (com o `userId` da sessão na hora da chamada; chame só depois do sucesso):\n *\n * - `bonus.optIn/claim/redeemPromoCode` → `bonus` e `wallet` (saldo do core);\n * - `loyalty.redeem` → `loyalty` e `wallet`; `referrals.register` → `referrals`;\n * - `casino.launchGame` → `casino.listSessions`; `bonus.resolvePromoCode` e\n * `sportsbook.createSession` → nada.\n *\n * `mutationKey` é `['enginex', namespace, método]`, sem a entrada. As que mandam `Idempotency-Key`\n * (`bonus.optIn/claim/redeemPromoCode`, `loyalty.redeem`) reusam a chave só depois de uma falha\n * ambígua (rede, timeout, 5xx, `KEY_IN_USE` ou `VALIDATION_ERROR` depois de 2xx) com a mesma entrada,\n * neste objeto de opções (veja `createMutations` do core), e aceitam `{ idempotencyKey }` na fábrica. As\n * que levam credenciais na entrada ou no resultado (código promocional, URL do jogo, sessão do\n * sportsbook) trazem `gcTime: 0`.\n * @param igaming - O objeto devolvido por `createIgaming(enginex)` (o próprio, não uma cópia).\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` se `igaming` não veio de `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"]}