@getenginex/sdk-igaming 0.10.1 → 0.12.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +61 -0
- package/README.md +4 -3
- package/dist/chunk-5ERRD3OA.js +648 -0
- package/dist/chunk-5ERRD3OA.js.map +1 -0
- package/dist/index.cjs +725 -54
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +895 -8
- package/dist/index.d.ts +895 -8
- package/dist/index.js +427 -397
- package/dist/index.js.map +1 -1
- package/dist/query/index.cjs +73 -7
- package/dist/query/index.cjs.map +1 -1
- package/dist/query/index.d.cts +24 -5
- package/dist/query/index.d.ts +24 -5
- package/dist/query/index.js +61 -8
- package/dist/query/index.js.map +1 -1
- package/dist/testing/index.cjs +499 -14
- package/dist/testing/index.cjs.map +1 -1
- package/dist/testing/index.d.cts +42 -4
- package/dist/testing/index.d.ts +42 -4
- package/dist/testing/index.js +499 -14
- package/dist/testing/index.js.map +1 -1
- package/package.json +7 -7
package/dist/query/index.js
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
|
+
import { keepsClubIdempotencyKey, LOCALE } from '../chunk-5ERRD3OA.js';
|
|
2
|
+
import { isEnginexError } from '@getenginex/sdk';
|
|
1
3
|
import { queryScope } from '@getenginex/sdk/query';
|
|
2
4
|
|
|
3
|
-
// src/query/index.ts
|
|
4
5
|
var methodOf = (igaming, namespace, method) => (input, options) => igaming[namespace][method].call(
|
|
5
6
|
igaming[namespace],
|
|
6
7
|
input,
|
|
@@ -12,23 +13,67 @@ var PUBLIC_READS = {
|
|
|
12
13
|
};
|
|
13
14
|
var USER_READS = {
|
|
14
15
|
casino: ["listSessions", "getHistory", "getBiggestWinners"],
|
|
16
|
+
club: ["getOverview", "listHistory", "listTournaments", "listRelatedTournaments", "getTournament", "getRanking"],
|
|
15
17
|
bonus: ["listOffers", "getOffer", "listParticipations", "getParticipation", "getOverview", "listPositions"],
|
|
16
|
-
missions: ["list", "listMine"],
|
|
18
|
+
missions: ["list", "listMine", "getMine"],
|
|
17
19
|
loyalty: ["get"],
|
|
18
20
|
referrals: ["get", "listHistory"],
|
|
19
21
|
bets: ["list", "get", "getCashoutOffer"]
|
|
20
22
|
};
|
|
23
|
+
var LOCALE_KEYED = /* @__PURE__ */ new Set(["club"]);
|
|
24
|
+
var NORMALIZE = {
|
|
25
|
+
"missions.getMine": (input) => {
|
|
26
|
+
if (input === void 0) return void 0;
|
|
27
|
+
if (typeof input !== "object" || input === null || Array.isArray(input)) return input;
|
|
28
|
+
const keys = Object.keys(input);
|
|
29
|
+
const flag = input.includeHistory;
|
|
30
|
+
if (keys.some((key) => key !== "includeHistory")) return input;
|
|
31
|
+
if (flag === void 0 || flag === false) return void 0;
|
|
32
|
+
return flag === true ? { includeHistory: true } : input;
|
|
33
|
+
}
|
|
34
|
+
};
|
|
35
|
+
function localeOf(igaming) {
|
|
36
|
+
const read = igaming[LOCALE];
|
|
37
|
+
return (typeof read === "function" ? read() : void 0) ?? null;
|
|
38
|
+
}
|
|
21
39
|
var userKeys = (...prefixes) => (scope) => prefixes.map(([namespace, method]) => scope.userPrefix(namespace, method));
|
|
22
40
|
var none = () => [];
|
|
41
|
+
var isConflict = (error) => isEnginexError(error) && error.status === 409;
|
|
42
|
+
var onConflict = (invalidates) => ({ when: isConflict, invalidates });
|
|
43
|
+
var leavesStateUnknown = (error) => isEnginexError(error) && (error.code === "NETWORK_ERROR" || error.code === "TIMEOUT" || error.code === "KEY_IN_USE" || error.status >= 500 || error.status >= 200 && error.status < 300 || error.code === "VALIDATION_ERROR" && error.status < 400);
|
|
44
|
+
var CLUB_WRITE = { idempotent: true, keepsKey: keepsClubIdempotencyKey };
|
|
45
|
+
var CLUB_MONEY = userKeys(["club", "getOverview"], ["club", "listHistory"], ["bonus"], ["wallet"]);
|
|
23
46
|
var WRITES = {
|
|
24
47
|
casino: { launchGame: { invalidates: userKeys(["casino", "listSessions"]), sensitive: true } },
|
|
48
|
+
club: {
|
|
49
|
+
setMembership: {
|
|
50
|
+
...CLUB_WRITE,
|
|
51
|
+
invalidates: userKeys(["club"]),
|
|
52
|
+
onError: onConflict(userKeys(["club", "getOverview"]))
|
|
53
|
+
},
|
|
54
|
+
// A play or a redemption moves coins, XP, the history and maybe a bonus or the balance; never the tournaments.
|
|
55
|
+
play: { ...CLUB_WRITE, invalidates: CLUB_MONEY, onError: onConflict(userKeys(["club", "getOverview"])) },
|
|
56
|
+
redeem: { ...CLUB_WRITE, invalidates: CLUB_MONEY, onError: onConflict(userKeys(["club", "getOverview"])) },
|
|
57
|
+
registerForTournament: {
|
|
58
|
+
...CLUB_WRITE,
|
|
59
|
+
invalidates: userKeys(["club"]),
|
|
60
|
+
onError: onConflict(userKeys(["club", "getOverview"], ["club", "listTournaments"], ["club", "getTournament"]))
|
|
61
|
+
}
|
|
62
|
+
},
|
|
25
63
|
bonus: {
|
|
26
64
|
resolvePromoCode: { invalidates: none, sensitive: true },
|
|
27
65
|
optIn: { invalidates: userKeys(["bonus"], ["wallet"]), idempotent: true },
|
|
28
66
|
claim: { invalidates: userKeys(["bonus"], ["wallet"]), idempotent: true },
|
|
29
67
|
redeemPromoCode: { invalidates: userKeys(["bonus"], ["wallet"]), idempotent: true, sensitive: true }
|
|
30
68
|
},
|
|
31
|
-
loyalty: {
|
|
69
|
+
loyalty: {
|
|
70
|
+
// An ambiguous failure may have redeemed the points: refetch them and the balance before a retry is offered.
|
|
71
|
+
redeem: {
|
|
72
|
+
invalidates: userKeys(["loyalty"], ["wallet"]),
|
|
73
|
+
idempotent: true,
|
|
74
|
+
onError: { when: leavesStateUnknown, invalidates: userKeys(["loyalty"], ["wallet"]) }
|
|
75
|
+
}
|
|
76
|
+
},
|
|
32
77
|
sportsbook: { createSession: { invalidates: none, sensitive: true } },
|
|
33
78
|
bets: { cashout: { invalidates: userKeys(["bets"], ["wallet"]), idempotent: true } }
|
|
34
79
|
};
|
|
@@ -45,10 +90,13 @@ function createIgamingQueries(igaming) {
|
|
|
45
90
|
PUBLIC_READS,
|
|
46
91
|
(namespace, method, input) => scope.publicQuery(namespace, method, methodOf(igaming, namespace, method), input)
|
|
47
92
|
);
|
|
48
|
-
add(
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
93
|
+
add(USER_READS, (namespace, method, raw) => {
|
|
94
|
+
const normalize = NORMALIZE[`${namespace}.${method}`];
|
|
95
|
+
const input = normalize ? normalize(raw) : raw;
|
|
96
|
+
const options = scope.userQuery(namespace, method, methodOf(igaming, namespace, method), input);
|
|
97
|
+
if (!LOCALE_KEYED.has(namespace)) return options;
|
|
98
|
+
return { ...options, queryKey: [...options.queryKey, { locale: localeOf(igaming) }] };
|
|
99
|
+
});
|
|
52
100
|
return out;
|
|
53
101
|
}
|
|
54
102
|
function createIgamingMutations(igaming) {
|
|
@@ -61,16 +109,21 @@ function createIgamingMutations(igaming) {
|
|
|
61
109
|
const scoped = {};
|
|
62
110
|
if (write.idempotent === true) {
|
|
63
111
|
scoped.idempotent = true;
|
|
112
|
+
if (write.keepsKey) scoped.keepsKey = write.keepsKey;
|
|
64
113
|
if (options?.idempotencyKey !== void 0) scoped.idempotencyKey = options.idempotencyKey;
|
|
65
114
|
}
|
|
66
115
|
if (write.sensitive === true) scoped.gcTime = 0;
|
|
67
|
-
|
|
116
|
+
const mutation = scope.mutation(
|
|
68
117
|
namespace,
|
|
69
118
|
method,
|
|
70
119
|
methodOf(igaming, namespace, method),
|
|
71
120
|
() => write.invalidates(scope),
|
|
72
121
|
scoped
|
|
73
122
|
);
|
|
123
|
+
const refresh = write.onError;
|
|
124
|
+
if (refresh)
|
|
125
|
+
mutation.invalidatesOnError = (_input, error) => refresh.when(error) ? refresh.invalidates(scope) : [];
|
|
126
|
+
return mutation;
|
|
74
127
|
};
|
|
75
128
|
}
|
|
76
129
|
}
|
package/dist/query/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/query/index.ts"],"names":[],"mappings":";;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AAA,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,UAAA,EAAY,SAAS,CAAA;AAAA,EACxC,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,YAAA,mBAAoD,IAAI,GAAA,CAAI,CAAC,MAAM,CAAC,CAAA;AAK1E,IAAM,SAAA,GAAyD;AAAA,EAC7D,kBAAA,EAAoB,CAAC,KAAA,KAAU;AAC7B,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CAAA;AAAA,UAC7B;AAAA,SACF;AACA,QAAA,MAAM,UAAU,KAAA,CAAM,OAAA;AAEtB,QAAA,IAAI,OAAA;AACF,UAAA,QAAA,CAAS,kBAAA,GAAqB,CAAC,MAAA,EAAQ,KAAA,KAAW,OAAA,CAAQ,IAAA,CAAK,KAAK,CAAA,GAAI,OAAA,CAAQ,WAAA,CAAY,KAAK,CAAA,GAAI,EAAC;AACxG,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 (with or without history). */\n readonly missions: QueriesOf<MissionsApi, 'list' | 'listMine' | 'getMine'>\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', 'getMine'],\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// Inputs that mean the same request share one cache entry: `getMine()`, `getMine({})` and\n// `getMine({ includeHistory: false })` all send no query string. Anything else (an invalid input included, so the\n// method still rejects it) is kept as it came.\nconst NORMALIZE: Record<string, (input: unknown) => unknown> = {\n 'missions.getMine': (input) => {\n if (input === undefined) return undefined\n if (typeof input !== 'object' || input === null || Array.isArray(input)) return input\n const keys = Object.keys(input)\n const flag = (input as { includeHistory?: unknown }).includeHistory\n if (keys.some((key) => key !== 'includeHistory')) return input\n if (flag === undefined || flag === false) return undefined\n return flag === true ? { includeHistory: true } : input\n },\n}\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 failure leaves stale (`invalidatesOnError`): `invalidates` when `when(error)` holds. */\n onError?: { when: (error: unknown) => boolean; invalidates: Invalidation }\n}\n\nconst isConflict = (error: unknown) => isEnginexError(error) && error.status === 409\nconst onConflict = (invalidates: Invalidation) => ({ when: isConflict, invalidates })\n\n// A failure after which the write may have happened: network, timeout, 5xx, `KEY_IN_USE`, or a 2xx the SDK could not\n// confirm (`UNKNOWN` with a 2xx status, `VALIDATION_ERROR` of a malformed answer). The same classes the core's\n// `isAmbiguousFailure` keeps the key for, plus the unconfirmed 2xx; written here so it holds with any core.\nconst leavesStateUnknown = (error: unknown) =>\n isEnginexError(error) &&\n (error.code === 'NETWORK_ERROR' ||\n error.code === 'TIMEOUT' ||\n error.code === 'KEY_IN_USE' ||\n error.status >= 500 ||\n (error.status >= 200 && error.status < 300) ||\n (error.code === 'VALIDATION_ERROR' && error.status < 400))\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: {\n ...CLUB_WRITE,\n invalidates: userKeys(['club']),\n onError: onConflict(userKeys(['club', 'getOverview'])),\n },\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, onError: onConflict(userKeys(['club', 'getOverview'])) },\n redeem: { ...CLUB_WRITE, invalidates: CLUB_MONEY, onError: onConflict(userKeys(['club', 'getOverview'])) },\n registerForTournament: {\n ...CLUB_WRITE,\n invalidates: userKeys(['club']),\n onError: onConflict(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: {\n // An ambiguous failure may have redeemed the points: refetch them and the balance before a retry is offered.\n redeem: {\n invalidates: userKeys(['loyalty'], ['wallet']),\n idempotent: true,\n onError: { when: leavesStateUnknown, invalidates: userKeys(['loyalty'], ['wallet']) },\n },\n },\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 * - `missions.getMine()`, `getMine({})` and `getMine({ includeHistory: false })` share one key (they send the same\n * request); `getMine({ includeHistory: true })` has its own.\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, raw) => {\n const normalize = NORMALIZE[`${namespace}.${method}`]\n const input = normalize ? normalize(raw) : raw\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`, also through `invalidatesOnError` after an ambiguous failure (network,\n * timeout, 5xx, `KEY_IN_USE`, or a 2xx it could not confirm: `UNKNOWN`/`VALIDATION_ERROR`), when the points may\n * have been redeemed;\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 refresh = write.onError\n // Set here (not through the scope) so it holds with any core; the adapters run it in `onError`.\n if (refresh)\n mutation.invalidatesOnError = (_input, error) => (refresh.when(error) ? refresh.invalidates(scope) : [])\n return mutation\n }\n }\n }\n return out as unknown as IgamingMutations\n}\n"]}
|