@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.
- package/CHANGELOG.md +155 -0
- package/LICENSE +202 -0
- package/README.md +122 -2
- package/dist/first-frame/index.cjs +136 -0
- package/dist/first-frame/index.cjs.map +1 -0
- package/dist/first-frame/index.d.cts +135 -0
- package/dist/first-frame/index.d.ts +135 -0
- package/dist/first-frame/index.js +134 -0
- package/dist/first-frame/index.js.map +1 -0
- package/dist/index.cjs +1035 -0
- package/dist/index.cjs.map +1 -0
- package/dist/index.d.cts +1554 -0
- package/dist/index.d.ts +1554 -0
- package/dist/index.js +1014 -0
- package/dist/index.js.map +1 -0
- package/dist/query/index.cjs +84 -0
- package/dist/query/index.cjs.map +1 -0
- package/dist/query/index.d.cts +103 -0
- package/dist/query/index.d.ts +103 -0
- package/dist/query/index.js +81 -0
- package/dist/query/index.js.map +1 -0
- package/dist/testing/index.cjs +737 -0
- package/dist/testing/index.cjs.map +1 -0
- package/dist/testing/index.d.cts +75 -0
- package/dist/testing/index.d.ts +75 -0
- package/dist/testing/index.js +734 -0
- package/dist/testing/index.js.map +1 -0
- package/first-frame/package.json +5 -0
- package/package.json +159 -3
- package/query/package.json +5 -0
- package/testing/package.json +5 -0
package/CHANGELOG.md
ADDED
|
@@ -0,0 +1,155 @@
|
|
|
1
|
+
# @getenginex/sdk-igaming
|
|
2
|
+
|
|
3
|
+
## 0.5.0
|
|
4
|
+
|
|
5
|
+
### Minor Changes
|
|
6
|
+
|
|
7
|
+
- af441d0: **Breaking (antes do 1.0).** Exige `@getenginex/sdk >=0.6.0 <1.0.0`.
|
|
8
|
+
|
|
9
|
+
- Dinheiro estrito nas respostas: valores monetários (inteiro seguro, em número ou texto), moeda (`/^[A-Z]{3}$/`) e casas decimais (0-8) inválidos rejeitam a resposta inteira com `VALIDATION_ERROR`, também em `validation: 'warn'` (campanhas de bônus, totais do cassino, resgate de fidelidade e indicações). **Como migrar:** nada no app; um gateway fora do contrato passa a aparecer como erro.
|
|
10
|
+
- Indicações (`referrals`): um valor monetário inválido agora rejeita a lista inteira (antes, o item era descartado em silêncio). **Como migrar:** trate o erro da listagem; não há mais itens sumindo.
|
|
11
|
+
- Decisão registrada (desvio do rascunho, que exigia moeda sempre preenchida): a moeda vazia (`''`) é aceita só nos valores de campanha do bônus e no `currency` do resgate de fidelidade, porque o gateway omite a moeda no protojson quando o valor é 0; aceitar o vazio evita derrubar a listagem de campanhas. Em qualquer outro campo, moeda vazia rejeita a resposta. Pontos de fidelidade e progresso de missões não são dinheiro.
|
|
12
|
+
- Idempotência: as mutations (`bonus.optIn/claim/redeemPromoCode`, `loyalty.redeem`) reaproveitam a `Idempotency-Key` só depois de falha ambígua, para a mesma entrada e na mesma mutation; `ABORTED` libera a chave. **Como migrar:** "tentar de novo" com `mutate({ ...mesmos valores })` já reaproveita a chave; para repetir depois de recarregar a página, passe `idempotencyKey`.
|
|
13
|
+
|
|
14
|
+
## 0.4.0
|
|
15
|
+
|
|
16
|
+
### Minor Changes
|
|
17
|
+
|
|
18
|
+
- ddc9d2c: Novo entry `@getenginex/sdk-igaming/query`: `createIgamingQueries(igaming)` e
|
|
19
|
+
`createIgamingMutations(igaming)` devolvem uma fábrica por método de leitura (`{ queryKey, queryFn }`) e
|
|
20
|
+
uma mutation por método de escrita (`{ mutationKey, mutationFn, invalidates }`), com os mesmos nomes e
|
|
21
|
+
entradas dos namespaces (`casino`, `bonus`, `missions`, `loyalty`, `referrals`, `sportsbook`) e as mesmas
|
|
22
|
+
convenções de chave do `@getenginex/sdk/query`, compatíveis com `useQuery`/`useMutation`/`prefetchQuery`
|
|
23
|
+
do TanStack Query v5 sem depender dele. Catálogo do cassino e ofertas públicas de bônus usam chave
|
|
24
|
+
`public`; o resto das leituras usa a chave do usuário (`userId` da sessão, `'anonymous'` e
|
|
25
|
+
`UNAUTHENTICATED` sem request quando não há sessão). `bonus.optIn/claim/redeemPromoCode` e
|
|
26
|
+
`loyalty.redeem` mandam uma `Idempotency-Key` por objeto de entrada (o retry não duplica a operação) e
|
|
27
|
+
aceitam `{ idempotencyKey }` na fábrica; `loyalty.redeem` e `bonus.optIn/claim/redeemPromoCode` invalidam o namespace e o saldo
|
|
28
|
+
do core (`wallet`), `referrals.register` invalida `referrals` e `casino.launchGame`
|
|
29
|
+
`casino.listSessions`. `bonus.resolvePromoCode`, `bonus.redeemPromoCode`, `casino.launchGame` e
|
|
30
|
+
`sportsbook.createSession` trazem `gcTime: 0` (código promocional, URL do jogo e token do sportsbook).
|
|
31
|
+
`createIgaming` passa a registrar o objeto do produto no cliente do core
|
|
32
|
+
(`registerProductClient`, do core 0.5.0), por isso o peer `@getenginex/sdk` sobe de `>=0.2.0 <1.0.0`
|
|
33
|
+
para `>=0.5.0 <1.0.0`.
|
|
34
|
+
|
|
35
|
+
## 0.3.0
|
|
36
|
+
|
|
37
|
+
### Minor Changes
|
|
38
|
+
|
|
39
|
+
- bfd181d: Novo namespace `igaming.missions` (missões): `list({ page?, perPage? })` devolve `Page<Mission>` (envia
|
|
40
|
+
`page` e `limit`; o `Page` sai do `meta` do envelope do gateway) e `listMine()` devolve `UserMission[]`
|
|
41
|
+
(o progresso do jogador, lido de `data.missions`). `Mission` é `{ id, name, description, missionType,
|
|
42
|
+
objectiveType, targetValue, targetGameCategory, targetGames, rewardType, rewardValue, validFrom,
|
|
43
|
+
validTo }`; `UserMission` é `{ id, missionId, missionName, currentProgress, targetValue,
|
|
44
|
+
progressPercentage, status, rewardType, rewardValue, periodEnd, completedAt }`. `targetGames` nulo vira
|
|
45
|
+
`[]`; categoria vazia, data epoch (`1970-01-01T00:00:00Z`) e `period_end`/`completed_at` ausentes viram
|
|
46
|
+
`null`; `targetValue`/`rewardValue` são inteiros e `progressPercentage` é número. `missionType`
|
|
47
|
+
(`daily`, `weekly`, `event`, `permanent`), `objectiveType` (`wager`, `bet_count`, `win_amount`,
|
|
48
|
+
`play_game`, `deposit`), `rewardType` (`bonus`, `free_spins`, `points`, `free_bet`) e `status`
|
|
49
|
+
(`in_progress`, `completed`, `expired`, `claimed`) são uniões abertas em minúsculas: valor desconhecido
|
|
50
|
+
chega cru e vai para `onValidationIssue` em `validation: 'warn'`; em `'strict'`, `VALIDATION_ERROR`.
|
|
51
|
+
`page` que não é inteiro ≥ 1 e `perPage` fora de 1–100 rejeitam com `CONFIGURATION_ERROR` sem request.
|
|
52
|
+
Os dois métodos exigem login. Não há `claim()` (o gateway não tem rota de resgate). `withIgamingRoutes`
|
|
53
|
+
(`@getenginex/sdk-igaming/testing`) responde as duas rotas. Nova página "Missões" nos docs. O peer do core
|
|
54
|
+
continua `>=0.2.0 <1.0.0`.
|
|
55
|
+
|
|
56
|
+
Novo namespace `igaming.loyalty` (fidelidade): `get()` devolve `LoyaltyStatus` (`totalPointsEarned`,
|
|
57
|
+
`currentPoints`, `pointsRedeemed`, `currentTier`, `tierPoints`, `lifetimeWagered`, `lifetimeDeposited`,
|
|
58
|
+
`tierBenefits`, `tierExpiresAt`) e `redeem({ points, redemptionType })` devolve `{ redeemedPoints, value,
|
|
59
|
+
currency, bonusId }`. `tierBenefits` é o `tier_benefits_json` já convertido em objeto: texto vazio ou
|
|
60
|
+
ausente vira `null` sem aviso; JSON inválido ou que não é um objeto vira `null` e vai para
|
|
61
|
+
`onValidationIssue` (sem o texto no issue; em `'strict'`, `VALIDATION_ERROR`). `tierExpiresAt`, `value`,
|
|
62
|
+
`currency`, `bonusId` e `currentTier` vazios ou ausentes viram `null`. `redemptionType` é uma união aberta (`bonus`, `cash`,
|
|
63
|
+
`free_bet`); `points` não inteiro ou ≤ 0 e `redemptionType` vazio rejeitam com `CONFIGURATION_ERROR` sem
|
|
64
|
+
request. `redeem` manda `Idempotency-Key` (gerada, ou a de `options.idempotencyKey`, mantida no retry após
|
|
65
|
+
401), mas o gateway ainda não aplica o middleware de idempotência nesta rota: trave o botão, um duplo
|
|
66
|
+
clique pode resgatar duas vezes. Um 200 sem confirmação (`success` diferente de `true`) rejeita com
|
|
67
|
+
`UNKNOWN` (`status` 200) e a mensagem do gateway quando vem, senão a do SDK: releia `get()` antes de
|
|
68
|
+
tentar de novo. `withIgamingRoutes` responde `GET /loyalty` e `POST /loyalty/redeem`.
|
|
69
|
+
Nova página "Fidelidade" nos docs. O peer do core continua `>=0.2.0 <1.0.0`.
|
|
70
|
+
|
|
71
|
+
Novo namespace `igaming.referrals` (indicações): `get()` devolve `ReferralInfo` (`code`, `link`,
|
|
72
|
+
`totalReferrals`, `completedReferrals`, `pendingReferrals`, `totalEarned`, `bonusPerReferral`,
|
|
73
|
+
`minDeposit`); `listHistory({ page?, perPage? })` devolve `Page<Referral>` mais `completedCount` e
|
|
74
|
+
`totalEarned` (o gateway manda a paginação dentro do `data`: o SDK monta o `Page`, calcula `totalPages` e
|
|
75
|
+
não deixa `totalItems` ficar abaixo dos itens já vistos); `register({ code })` devolve `{ id, code, status,
|
|
76
|
+
refereeBonus, createdAt }` (HTTP 201). O gateway escreve o dinheiro como float na unidade maior; o SDK
|
|
77
|
+
converte para unidades menores com `Math.round(valor * 100)`, metades para longe do zero (`19.99` → `1999`,
|
|
78
|
+
`0.1 + 0.2` → `30`, `1e-7` → `0`, negativos mantêm o sinal), e valor não finito rejeita com
|
|
79
|
+
`VALIDATION_ERROR` em `strict`. `Referral` traz `refereeName` e `refereeEmailMasked`
|
|
80
|
+
(`ana@exemplo.com` → `a**@exemplo.com`; vazio ou inválido vira `null`); o e-mail cru e o `referee_id`
|
|
81
|
+
nunca são expostos (nem no resultado, nem nos issues, nem nos erros), também em `validation: 'warn'`
|
|
82
|
+
quando um item falha inteiro e o core devolve a lista crua: o SDK refaz cada indicação (máscara, status,
|
|
83
|
+
dinheiro em unidades menores) e descarta o que não é objeto ou cujo dinheiro não vira unidades menores.
|
|
84
|
+
Um `total_items` fora do formato em `'warn'` vale 0 (nunca `NaN`). `status` (`pending`, `qualified`,
|
|
85
|
+
`completed`, `expired`) é uma união aberta; `completedAt`, `expiresAt` e `createdAt` ausentes ou epoch
|
|
86
|
+
viram `null`. `page` e `perPage` inválidos e `code` vazio rejeitam com `CONFIGURATION_ERROR` sem request.
|
|
87
|
+
Quem está se cadastrando usa `auth.register({ referralCode })` do core. `withIgamingRoutes` responde as
|
|
88
|
+
três rotas. Nova página "Indicações" nos docs. O peer do core continua `>=0.2.0 <1.0.0`.
|
|
89
|
+
|
|
90
|
+
## 0.2.0
|
|
91
|
+
|
|
92
|
+
### Minor Changes
|
|
93
|
+
|
|
94
|
+
- f91eacb: Novo namespace `igaming.sportsbook` com `createSession(params?, options?)` (`GET /first/session`, exige
|
|
95
|
+
login): devolve `{ launchUrl, expiresInSeconds, expiresAt }` para abrir o sportsbook FIRST num iframe.
|
|
96
|
+
`expiresAt` (ms) é calculado no cliente (relógio na resposta + `expiresInSeconds * 1000`); o
|
|
97
|
+
`operator_token` não entra no tipo público. `launchUrl` carrega o token de operador: a resposta é
|
|
98
|
+
sempre validada em modo estrito (`launch_url` http(s) absoluta e `expires_in_seconds` > 0, senão
|
|
99
|
+
`VALIDATION_ERROR`) e nenhum hook nem `onValidationIssue` a recebe. `createIgamingRoutes` /
|
|
100
|
+
`withIgamingRoutes` ganham a rota mock de `/first/session`. Sem cache no SDK: reutilize a sessão até
|
|
101
|
+
`expiresAt - 30 s` e cheque `enginex.config.getSportsbook()` antes.
|
|
102
|
+
|
|
103
|
+
Novo entry opcional `@getenginex/sdk-igaming/first-frame` com `connectFirstFrame(iframe, handlers,
|
|
104
|
+
options?)`: ponte tipada para os eventos `postMessage` do iframe do FIRST (`onReady`, `onBetPlaced`,
|
|
105
|
+
`onInsufficientFunds`, `onDepositClick`, `onLoginRequired`, `onHeightChange`, `onRedirect`,
|
|
106
|
+
`onScrollToTop` e `onEvent` genérico) e `send(eventType, eventData)` para comandos. Em `onRedirect`,
|
|
107
|
+
`link` só chega se for texto (um `link` de outro tipo é descartado). Só entrega mensagens
|
|
108
|
+
com `event.source === iframe.contentWindow` e `event.origin` igual à origem do `src`; `send` posta
|
|
109
|
+
sempre para essa origem (nunca `'*'`). Não importa o core em runtime nem exige `lib.dom`
|
|
110
|
+
(`FirstFrameTarget`/`FirstFrameWindow` são estruturais); os erros de configuração são
|
|
111
|
+
`CONFIGURATION_ERROR` reconhecidos por `isEnginexError`. Fora do entry principal: quem importa só
|
|
112
|
+
`createIgaming` não o leva no bundle.
|
|
113
|
+
|
|
114
|
+
## 0.1.0
|
|
115
|
+
|
|
116
|
+
### Minor Changes
|
|
117
|
+
|
|
118
|
+
- 7be46cc: Namespace `bonus` em `createIgaming(enginex)`: `listPublicOffers` (vitrine pública, sem mandar a
|
|
119
|
+
sessão), `listOffers`, `getOffer`, `listParticipations` e `getParticipation` (paginação por cursor:
|
|
120
|
+
`CursorPage`/`CursorPageInput` do core), `optIn`, `claim` e `redeemPromoCode` (idempotentes: mandam
|
|
121
|
+
`Idempotency-Key`, a do chamador em `options.idempotencyKey` ou uma gerada, reusada no retry após
|
|
122
|
+
401; respostas validadas sempre em modo estrito) e `resolvePromoCode`. As campanhas chegam do formato
|
|
123
|
+
protojson do gateway em camelCase, com enums sem prefixo e em minúsculas, dinheiro em `number`
|
|
124
|
+
(unidades menores), durações em segundos e o estado da participação em `status` (+ `qualifiedAt`,
|
|
125
|
+
`completedAt`, `expiredAt`). `/testing` ganha as rotas mock de bônus (três campanhas, promo code
|
|
126
|
+
`BEMVINDO`, opt-in/claim/resgate com estado e replay por `Idempotency-Key`).
|
|
127
|
+
- 6397a2f: Namespace `casino` em `createIgaming(enginex)`: `listGames` (filtros por categoria, provedor, busca,
|
|
128
|
+
`ids` e ordenação, paginado), `listCategories`, `listProviders` e `getGame` (públicos, sem mandar a
|
|
129
|
+
sessão), `launchGame` (exige login; devolve `sessionId` e `gameUrl`, com o idioma vindo do `locale` do
|
|
130
|
+
cliente via `Accept-Language`), `listSessions`, `getHistory` (paginados) e `getBiggestWinners`. A URL
|
|
131
|
+
do jogo carrega o token da sessão de jogo: volta só no resultado — nunca nos hooks nem no
|
|
132
|
+
`onValidationIssue` — e a resposta do launch é validada sempre em modo estrito. Valores do histórico e
|
|
133
|
+
do ranking (int64 em texto no fio) chegam como `number` em unidades menores. `/testing` ganha as rotas
|
|
134
|
+
mock do cassino (catálogo fixo, launch com URL fictícia e sessões em memória).
|
|
135
|
+
- eb5d851: Novo pacote `@getenginex/sdk-igaming`: `createIgaming(enginex)` monta os namespaces de iGaming sobre o
|
|
136
|
+
cliente de `@getenginex/sdk` (peer dependency), sem sessão, tenant nem transporte próprios — tudo
|
|
137
|
+
passa pelo contrato `@getenginex/sdk/extension` do core. Um valor que não é um cliente criado por
|
|
138
|
+
`createEnginexClient` é rejeitado com `CONFIGURATION_ERROR`. `@getenginex/sdk-igaming/testing` traz
|
|
139
|
+
`createIgamingRoutes()` e `withIgamingRoutes(options)` para somar as rotas mock de iGaming ao
|
|
140
|
+
`createMockFetch` do core. Cassino e bônus chegam nas próximas versões.
|
|
141
|
+
- eb3921a: O core é declarado como peer `@getenginex/sdk@>=0.2.0 <1.0.0` (a primeira versão com o entry
|
|
142
|
+
`@getenginex/sdk/extension`); em tempo de execução, um cliente de uma cópia do core com contrato de
|
|
143
|
+
transporte incompatível faz `createIgaming` lançar `CONFIGURATION_ERROR`.
|
|
144
|
+
|
|
145
|
+
### Patch Changes
|
|
146
|
+
|
|
147
|
+
- Updated dependencies [ffc0bd1]
|
|
148
|
+
- Updated dependencies [a043c79]
|
|
149
|
+
- Updated dependencies [d4ebcf2]
|
|
150
|
+
- Updated dependencies [cbf1a39]
|
|
151
|
+
- Updated dependencies [826a4d8]
|
|
152
|
+
- Updated dependencies [126ff24]
|
|
153
|
+
- Updated dependencies [eb3921a]
|
|
154
|
+
- Updated dependencies [7144ada]
|
|
155
|
+
- @getenginex/sdk@0.2.0
|
package/LICENSE
ADDED
|
@@ -0,0 +1,202 @@
|
|
|
1
|
+
|
|
2
|
+
Apache License
|
|
3
|
+
Version 2.0, January 2004
|
|
4
|
+
http://www.apache.org/licenses/
|
|
5
|
+
|
|
6
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
7
|
+
|
|
8
|
+
1. Definitions.
|
|
9
|
+
|
|
10
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
11
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
12
|
+
|
|
13
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
14
|
+
the copyright owner that is granting the License.
|
|
15
|
+
|
|
16
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
17
|
+
other entities that control, are controlled by, or are under common
|
|
18
|
+
control with that entity. For the purposes of this definition,
|
|
19
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
20
|
+
direction or management of such entity, whether by contract or
|
|
21
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
22
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
23
|
+
|
|
24
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
25
|
+
exercising permissions granted by this License.
|
|
26
|
+
|
|
27
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
28
|
+
including but not limited to software source code, documentation
|
|
29
|
+
source, and configuration files.
|
|
30
|
+
|
|
31
|
+
"Object" form shall mean any form resulting from mechanical
|
|
32
|
+
transformation or translation of a Source form, including but
|
|
33
|
+
not limited to compiled object code, generated documentation,
|
|
34
|
+
and conversions to other media types.
|
|
35
|
+
|
|
36
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
37
|
+
Object form, made available under the License, as indicated by a
|
|
38
|
+
copyright notice that is included in or attached to the work
|
|
39
|
+
(an example is provided in the Appendix below).
|
|
40
|
+
|
|
41
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
42
|
+
form, that is based on (or derived from) the Work and for which the
|
|
43
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
44
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
45
|
+
of this License, Derivative Works shall not include works that remain
|
|
46
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
47
|
+
the Work and Derivative Works thereof.
|
|
48
|
+
|
|
49
|
+
"Contribution" shall mean any work of authorship, including
|
|
50
|
+
the original version of the Work and any modifications or additions
|
|
51
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
52
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
53
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
54
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
55
|
+
means any form of electronic, verbal, or written communication sent
|
|
56
|
+
to the Licensor or its representatives, including but not limited to
|
|
57
|
+
communication on electronic mailing lists, source code control systems,
|
|
58
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
59
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
60
|
+
excluding communication that is conspicuously marked or otherwise
|
|
61
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
62
|
+
|
|
63
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
64
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
65
|
+
subsequently incorporated within the Work.
|
|
66
|
+
|
|
67
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
68
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
69
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
70
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
71
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
72
|
+
Work and such Derivative Works in Source or Object form.
|
|
73
|
+
|
|
74
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
75
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
76
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
77
|
+
(except as stated in this section) patent license to make, have made,
|
|
78
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
79
|
+
where such license applies only to those patent claims licensable
|
|
80
|
+
by such Contributor that are necessarily infringed by their
|
|
81
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
82
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
83
|
+
institute patent litigation against any entity (including a
|
|
84
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
85
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
86
|
+
or contributory patent infringement, then any patent licenses
|
|
87
|
+
granted to You under this License for that Work shall terminate
|
|
88
|
+
as of the date such litigation is filed.
|
|
89
|
+
|
|
90
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
91
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
92
|
+
modifications, and in Source or Object form, provided that You
|
|
93
|
+
meet the following conditions:
|
|
94
|
+
|
|
95
|
+
(a) You must give any other recipients of the Work or
|
|
96
|
+
Derivative Works a copy of this License; and
|
|
97
|
+
|
|
98
|
+
(b) You must cause any modified files to carry prominent notices
|
|
99
|
+
stating that You changed the files; and
|
|
100
|
+
|
|
101
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
102
|
+
that You distribute, all copyright, patent, trademark, and
|
|
103
|
+
attribution notices from the Source form of the Work,
|
|
104
|
+
excluding those notices that do not pertain to any part of
|
|
105
|
+
the Derivative Works; and
|
|
106
|
+
|
|
107
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
108
|
+
distribution, then any Derivative Works that You distribute must
|
|
109
|
+
include a readable copy of the attribution notices contained
|
|
110
|
+
within such NOTICE file, excluding those notices that do not
|
|
111
|
+
pertain to any part of the Derivative Works, in at least one
|
|
112
|
+
of the following places: within a NOTICE text file distributed
|
|
113
|
+
as part of the Derivative Works; within the Source form or
|
|
114
|
+
documentation, if provided along with the Derivative Works; or,
|
|
115
|
+
within a display generated by the Derivative Works, if and
|
|
116
|
+
wherever such third-party notices normally appear. The contents
|
|
117
|
+
of the NOTICE file are for informational purposes only and
|
|
118
|
+
do not modify the License. You may add Your own attribution
|
|
119
|
+
notices within Derivative Works that You distribute, alongside
|
|
120
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
121
|
+
that such additional attribution notices cannot be construed
|
|
122
|
+
as modifying the License.
|
|
123
|
+
|
|
124
|
+
You may add Your own copyright statement to Your modifications and
|
|
125
|
+
may provide additional or different license terms and conditions
|
|
126
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
127
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
128
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
129
|
+
the conditions stated in this License.
|
|
130
|
+
|
|
131
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
132
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
133
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
134
|
+
this License, without any additional terms or conditions.
|
|
135
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
136
|
+
the terms of any separate license agreement you may have executed
|
|
137
|
+
with Licensor regarding such Contributions.
|
|
138
|
+
|
|
139
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
140
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
141
|
+
except as required for reasonable and customary use in describing the
|
|
142
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
143
|
+
|
|
144
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
145
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
146
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
147
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
148
|
+
implied, including, without limitation, any warranties or conditions
|
|
149
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
150
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
151
|
+
appropriateness of using or redistributing the Work and assume any
|
|
152
|
+
risks associated with Your exercise of permissions under this License.
|
|
153
|
+
|
|
154
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
155
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
156
|
+
unless required by applicable law (such as deliberate and grossly
|
|
157
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
158
|
+
liable to You for damages, including any direct, indirect, special,
|
|
159
|
+
incidental, or consequential damages of any character arising as a
|
|
160
|
+
result of this License or out of the use or inability to use the
|
|
161
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
162
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
163
|
+
other commercial damages or losses), even if such Contributor
|
|
164
|
+
has been advised of the possibility of such damages.
|
|
165
|
+
|
|
166
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
167
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
168
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
169
|
+
or other liability obligations and/or rights consistent with this
|
|
170
|
+
License. However, in accepting such obligations, You may act only
|
|
171
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
172
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
173
|
+
defend, and hold each Contributor harmless for any liability
|
|
174
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
175
|
+
of your accepting any such warranty or additional liability.
|
|
176
|
+
|
|
177
|
+
END OF TERMS AND CONDITIONS
|
|
178
|
+
|
|
179
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
180
|
+
|
|
181
|
+
To apply the Apache License to your work, attach the following
|
|
182
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
183
|
+
replaced with your own identifying information. (Don't include
|
|
184
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
185
|
+
comment syntax for the file format. We also recommend that a
|
|
186
|
+
file or class name and description of purpose be included on the
|
|
187
|
+
same "printed page" as the copyright notice for easier
|
|
188
|
+
identification within third-party archives.
|
|
189
|
+
|
|
190
|
+
Copyright [yyyy] [name of copyright owner]
|
|
191
|
+
|
|
192
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
193
|
+
you may not use this file except in compliance with the License.
|
|
194
|
+
You may obtain a copy of the License at
|
|
195
|
+
|
|
196
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
197
|
+
|
|
198
|
+
Unless required by applicable law or agreed to in writing, software
|
|
199
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
200
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
201
|
+
See the License for the specific language governing permissions and
|
|
202
|
+
limitations under the License.
|
package/README.md
CHANGED
|
@@ -1,3 +1,123 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @getenginex/sdk-igaming
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
📖 [game-engine-io.github.io/enginex-frontend-sdk](https://game-engine-io.github.io/enginex-frontend-sdk/igaming/)
|
|
4
|
+
|
|
5
|
+
Cassino, bônus, engajamento e sportsbook FIRST do EngineX, montados sobre o cliente de
|
|
6
|
+
[`@getenginex/sdk`](https://www.npmjs.com/package/@getenginex/sdk): `casino` (catálogo, abrir jogo,
|
|
7
|
+
sessões, histórico e ranking de ganhadores), `bonus` (campanhas de bônus, opt-in, resgate e promo
|
|
8
|
+
codes), `missions` (missões e progresso), `loyalty` (pontos, tier e resgate), `referrals` (código,
|
|
9
|
+
histórico e registro de indicação) e `sportsbook` (sessão do FIRST para o iframe).
|
|
10
|
+
|
|
11
|
+
## Instalação
|
|
12
|
+
|
|
13
|
+
Instale junto com o core — ele é _peer dependency_, então existe uma única cópia do core no app (a
|
|
14
|
+
mesma sessão, tenant, hooks e validação para tudo):
|
|
15
|
+
|
|
16
|
+
```bash
|
|
17
|
+
npm i @getenginex/sdk @getenginex/sdk-igaming
|
|
18
|
+
```
|
|
19
|
+
|
|
20
|
+
Core compatível: `>=0.6.0 <1.0.0` (peer). Em tempo de execução, um cliente criado por uma cópia do
|
|
21
|
+
core com contrato de transporte incompatível faz `createIgaming` lançar `CONFIGURATION_ERROR`. O `zod`
|
|
22
|
+
(4.x) é dependência comum do core e deste pacote: mantenha um único `zod` 4 no projeto para não
|
|
23
|
+
duplicá-lo no bundle.
|
|
24
|
+
|
|
25
|
+
## Uso
|
|
26
|
+
|
|
27
|
+
```ts
|
|
28
|
+
import { createEnginexClient } from '@getenginex/sdk'
|
|
29
|
+
import { createIgaming } from '@getenginex/sdk-igaming'
|
|
30
|
+
|
|
31
|
+
export const enginex = createEnginexClient({ locale: 'pt-BR' })
|
|
32
|
+
export const igaming = createIgaming(enginex)
|
|
33
|
+
|
|
34
|
+
const games = await igaming.casino.listGames({ category: 'slots', perPage: 24 })
|
|
35
|
+
const { gameUrl } = await igaming.casino.launchGame({ gameId: games.items[0].id }) // exige login
|
|
36
|
+
|
|
37
|
+
const offers = await igaming.bonus.listOffers() // exige login
|
|
38
|
+
await igaming.bonus.redeemPromoCode({ code: 'BEMVINDO' }, { idempotencyKey: crypto.randomUUID() })
|
|
39
|
+
|
|
40
|
+
const missions = await igaming.missions.list() // exige login
|
|
41
|
+
const loyalty = await igaming.loyalty.get() // exige login
|
|
42
|
+
const referral = await igaming.referrals.get() // exige login
|
|
43
|
+
```
|
|
44
|
+
|
|
45
|
+
`gameUrl` carrega o token da sessão de jogo: o SDK a devolve só no retorno (nunca nos hooks) — não a
|
|
46
|
+
registre em logs.
|
|
47
|
+
|
|
48
|
+
`createIgaming` não cria sessão, tenant nem transporte próprios e não faz nenhum request: todo método
|
|
49
|
+
de iGaming passa pelo cliente do app (renovação de tokens, `X-Original-Host`, `Accept-Language`,
|
|
50
|
+
`hooks`, `validation` e `dispose()`). Crie um por cliente: no browser, um por app; no servidor, um
|
|
51
|
+
por request, junto com o cliente. Um valor que não é um cliente criado por `createEnginexClient` (ex.:
|
|
52
|
+
uma cópia `{ ...enginex }`) é rejeitado com `CONFIGURATION_ERROR`.
|
|
53
|
+
|
|
54
|
+
## Queries e mutations
|
|
55
|
+
|
|
56
|
+
`@getenginex/sdk-igaming/query` traz as fábricas de query e mutation dos namespaces, no mesmo formato do
|
|
57
|
+
`@getenginex/sdk/query` (compatível com `useQuery`, `useMutation` e `prefetchQuery` do TanStack Query v5,
|
|
58
|
+
sem depender dele):
|
|
59
|
+
|
|
60
|
+
```ts
|
|
61
|
+
import { createIgaming } from '@getenginex/sdk-igaming'
|
|
62
|
+
import { createIgamingMutations, createIgamingQueries } from '@getenginex/sdk-igaming/query'
|
|
63
|
+
|
|
64
|
+
const igaming = createIgaming(enginex)
|
|
65
|
+
const q = createIgamingQueries(igaming)
|
|
66
|
+
const m = createIgamingMutations(igaming)
|
|
67
|
+
|
|
68
|
+
q.casino.listGames({ page: 1 }) // { queryKey: ['enginex', 'public', 'casino', 'listGames', { page: 1 }], queryFn }
|
|
69
|
+
q.loyalty.get() // { queryKey: ['enginex', 'user', <userId>, 'loyalty', 'get'], queryFn }
|
|
70
|
+
m.loyalty.redeem() // { mutationKey, mutationFn, invalidates }: loyalty e o saldo do core (wallet)
|
|
71
|
+
```
|
|
72
|
+
|
|
73
|
+
Catálogo do cassino e ofertas públicas de bônus usam chave `public`; as demais leituras, a chave do
|
|
74
|
+
usuário. `bonus.optIn/claim/redeemPromoCode` e `loyalty.redeem` mandam uma `Idempotency-Key` que só é
|
|
75
|
+
reaproveitada depois de falha ambígua (rede, timeout, 5xx, `KEY_IN_USE` ou `VALIDATION_ERROR` depois de 2xx), com a mesma entrada e na mesma mutation, e aceitam `m.loyalty.redeem({ idempotencyKey })`. O entry exige `@getenginex/sdk >=0.6.0` e não
|
|
76
|
+
entra no bundle de quem importa só `@getenginex/sdk-igaming`.
|
|
77
|
+
|
|
78
|
+
## Eventos do iframe do FIRST
|
|
79
|
+
|
|
80
|
+
`@getenginex/sdk-igaming/first-frame` (opcional, fora do bundle principal) recebe os eventos
|
|
81
|
+
`postMessage` do iframe do sportsbook com checagem de origem e janela, e envia comandos:
|
|
82
|
+
|
|
83
|
+
```ts
|
|
84
|
+
import { connectFirstFrame } from '@getenginex/sdk-igaming/first-frame'
|
|
85
|
+
|
|
86
|
+
const frame = connectFirstFrame(iframe, {
|
|
87
|
+
onBetPlaced: () => void enginex.wallet.getBalance().then(showBalance),
|
|
88
|
+
onLoginRequired: () => openLoginModal(),
|
|
89
|
+
})
|
|
90
|
+
frame.dispose() // ao desmontar
|
|
91
|
+
```
|
|
92
|
+
|
|
93
|
+
Detalhes na [documentação](https://game-engine-io.github.io/enginex-frontend-sdk/igaming/sportsbook).
|
|
94
|
+
|
|
95
|
+
## Testes
|
|
96
|
+
|
|
97
|
+
`@getenginex/sdk-igaming/testing` soma as rotas mock de iGaming ao `createMockFetch` do core:
|
|
98
|
+
|
|
99
|
+
```ts
|
|
100
|
+
import { createEnginexClient } from '@getenginex/sdk'
|
|
101
|
+
import { createMockFetch } from '@getenginex/sdk/testing'
|
|
102
|
+
import { createIgaming } from '@getenginex/sdk-igaming'
|
|
103
|
+
import { withIgamingRoutes } from '@getenginex/sdk-igaming/testing'
|
|
104
|
+
|
|
105
|
+
const enginex = createEnginexClient({
|
|
106
|
+
baseUrl: 'https://gateway.test', // em Node: baseUrl absoluto + tenantHost (no browser, opcionais)
|
|
107
|
+
tenantHost: 'casino.test',
|
|
108
|
+
fetch: createMockFetch(withIgamingRoutes({ withdrawalOtp: true })),
|
|
109
|
+
})
|
|
110
|
+
const igaming = createIgaming(enginex)
|
|
111
|
+
```
|
|
112
|
+
|
|
113
|
+
As rotas do core continuam valendo e as de `options.routes` vencem as de iGaming. Para montar o
|
|
114
|
+
objeto de rotas à mão, use `createIgamingRoutes()`.
|
|
115
|
+
|
|
116
|
+
## Runtimes suportados
|
|
117
|
+
|
|
118
|
+
Os mesmos do core: browsers com `fetch` e `AbortController`, Node 20+, Edge runtimes e Bun. ESM e
|
|
119
|
+
CommonJS; os tipos não dependem de `lib: DOM`.
|
|
120
|
+
|
|
121
|
+
## Licença
|
|
122
|
+
|
|
123
|
+
[Apache License 2.0](LICENSE).
|
|
@@ -0,0 +1,136 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
// src/first-frame/index.ts
|
|
4
|
+
var BRAND = /* @__PURE__ */ Symbol.for("getenginex.error");
|
|
5
|
+
var FirstFrameConfigurationError = class extends Error {
|
|
6
|
+
name = "EnginexError";
|
|
7
|
+
code = "CONFIGURATION_ERROR";
|
|
8
|
+
status = 0;
|
|
9
|
+
details = void 0;
|
|
10
|
+
constructor(message) {
|
|
11
|
+
super(message);
|
|
12
|
+
Object.defineProperty(this, BRAND, { value: true });
|
|
13
|
+
}
|
|
14
|
+
toString() {
|
|
15
|
+
return `EnginexError [${this.code}]: ${this.message}`;
|
|
16
|
+
}
|
|
17
|
+
toJSON() {
|
|
18
|
+
return { name: this.name, code: this.code, message: this.message, status: this.status };
|
|
19
|
+
}
|
|
20
|
+
};
|
|
21
|
+
var NO_ORIGIN = "O src do iframe do FIRST n\xE3o tem uma origem http(s) v\xE1lida: defina iframe.src com a launchUrl antes de usar o frame.";
|
|
22
|
+
function originOf(src) {
|
|
23
|
+
try {
|
|
24
|
+
const url = new URL(src);
|
|
25
|
+
return url.protocol === "https:" || url.protocol === "http:" ? url.origin : null;
|
|
26
|
+
} catch {
|
|
27
|
+
return null;
|
|
28
|
+
}
|
|
29
|
+
}
|
|
30
|
+
function isRecord(value) {
|
|
31
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
32
|
+
}
|
|
33
|
+
function parse(data) {
|
|
34
|
+
let value = data;
|
|
35
|
+
if (typeof value === "string") {
|
|
36
|
+
try {
|
|
37
|
+
value = JSON.parse(value);
|
|
38
|
+
} catch {
|
|
39
|
+
return void 0;
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
return isRecord(value) ? value : void 0;
|
|
43
|
+
}
|
|
44
|
+
function call(fn) {
|
|
45
|
+
if (!fn) return;
|
|
46
|
+
try {
|
|
47
|
+
const result = fn();
|
|
48
|
+
Promise.resolve(result).catch(() => {
|
|
49
|
+
});
|
|
50
|
+
} catch {
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
function positiveNumber(value) {
|
|
54
|
+
return typeof value === "number" && Number.isFinite(value) && value > 0 ? value : void 0;
|
|
55
|
+
}
|
|
56
|
+
function dispatch(message, handlers) {
|
|
57
|
+
const rawType = message.eventType || message.type;
|
|
58
|
+
if (typeof rawType !== "string" || rawType === "") return;
|
|
59
|
+
const eventType = rawType;
|
|
60
|
+
const eventData = message.eventData;
|
|
61
|
+
const on = (handler, ...args) => call(handler && (() => handler.apply(handlers, args)));
|
|
62
|
+
switch (eventType) {
|
|
63
|
+
case "APP_READY":
|
|
64
|
+
on(handlers.onReady);
|
|
65
|
+
break;
|
|
66
|
+
case "BET_WAS_PLACED":
|
|
67
|
+
on(handlers.onBetPlaced, eventData);
|
|
68
|
+
break;
|
|
69
|
+
case "INSUFFICIENT_FUNDS":
|
|
70
|
+
on(handlers.onInsufficientFunds, eventData);
|
|
71
|
+
break;
|
|
72
|
+
case "depositClick":
|
|
73
|
+
on(handlers.onDepositClick, eventData);
|
|
74
|
+
break;
|
|
75
|
+
case "PLACE_BET_CLICKED_NOT_LOGGED_IN":
|
|
76
|
+
case "OPEN_LOGIN_POPUP":
|
|
77
|
+
on(handlers.onLoginRequired, eventData);
|
|
78
|
+
break;
|
|
79
|
+
case "on-page-height-change":
|
|
80
|
+
case "ON_PAGE_HEIGHT_CHANGE": {
|
|
81
|
+
const height = positiveNumber(isRecord(eventData) ? eventData.height : void 0) ?? positiveNumber(message.height);
|
|
82
|
+
if (height !== void 0) on(handlers.onHeightChange, height);
|
|
83
|
+
break;
|
|
84
|
+
}
|
|
85
|
+
case "BUTTON_REDIRECT": {
|
|
86
|
+
const data = { ...isRecord(eventData) ? eventData : {} };
|
|
87
|
+
if (typeof message.link === "string") data.link = message.link;
|
|
88
|
+
else if (typeof data.link !== "string") delete data.link;
|
|
89
|
+
on(handlers.onRedirect, data);
|
|
90
|
+
break;
|
|
91
|
+
}
|
|
92
|
+
case "SCROLL_TO_TOP":
|
|
93
|
+
on(handlers.onScrollToTop);
|
|
94
|
+
break;
|
|
95
|
+
}
|
|
96
|
+
on(handlers.onEvent, eventType, eventData);
|
|
97
|
+
}
|
|
98
|
+
function connectFirstFrame(iframe, handlers, options = {}) {
|
|
99
|
+
const win = options.window ?? globalThis;
|
|
100
|
+
if (typeof win.addEventListener !== "function" || typeof win.removeEventListener !== "function") {
|
|
101
|
+
throw new FirstFrameConfigurationError(
|
|
102
|
+
"connectFirstFrame precisa de uma janela com addEventListener: fora do browser, passe options.window."
|
|
103
|
+
);
|
|
104
|
+
}
|
|
105
|
+
let disposed = false;
|
|
106
|
+
const listener = (event) => {
|
|
107
|
+
if (disposed) return;
|
|
108
|
+
const target = iframe.contentWindow;
|
|
109
|
+
const origin = originOf(iframe.src);
|
|
110
|
+
if (target === null || origin === null || event.source !== target || event.origin !== origin) return;
|
|
111
|
+
const message = parse(event.data);
|
|
112
|
+
if (message) dispatch(message, handlers);
|
|
113
|
+
};
|
|
114
|
+
win.addEventListener("message", listener);
|
|
115
|
+
return {
|
|
116
|
+
send(eventType, eventData) {
|
|
117
|
+
if (disposed) throw new FirstFrameConfigurationError("O frame do FIRST j\xE1 foi encerrado (dispose).");
|
|
118
|
+
const origin = originOf(iframe.src);
|
|
119
|
+
if (origin === null) throw new FirstFrameConfigurationError(NO_ORIGIN);
|
|
120
|
+
const target = iframe.contentWindow;
|
|
121
|
+
if (target === null) {
|
|
122
|
+
throw new FirstFrameConfigurationError("O iframe do FIRST ainda n\xE3o tem contentWindow (n\xE3o est\xE1 no documento).");
|
|
123
|
+
}
|
|
124
|
+
target.postMessage(JSON.stringify({ eventType, eventData }), origin);
|
|
125
|
+
},
|
|
126
|
+
dispose() {
|
|
127
|
+
if (disposed) return;
|
|
128
|
+
disposed = true;
|
|
129
|
+
win.removeEventListener?.("message", listener);
|
|
130
|
+
}
|
|
131
|
+
};
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
exports.connectFirstFrame = connectFirstFrame;
|
|
135
|
+
//# sourceMappingURL=index.cjs.map
|
|
136
|
+
//# sourceMappingURL=index.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../src/first-frame/index.ts"],"names":[],"mappings":";;;AA0HA,IAAM,KAAA,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;AACnB,QAAA,MAAM,IAAI,6BAA6B,iFAAwE,CAAA;AAAA,MACjH;AACA,MAAA,MAAA,CAAO,WAAA,CAAY,KAAK,SAAA,CAAU,EAAE,WAAW,SAAA,EAAW,GAAG,MAAM,CAAA;AAAA,IACrE,CAAA;AAAA,IACA,OAAA,GAAU;AACR,MAAA,IAAI,QAAA,EAAU;AACd,MAAA,QAAA,GAAW,IAAA;AACX,MAAA,GAAA,CAAI,mBAAA,GAAsB,WAAW,QAAQ,CAAA;AAAA,IAC/C;AAAA,GACF;AACF","file":"index.cjs","sourcesContent":["/**\n * Ponte tipada e com checagem de origem para os eventos `postMessage` do iframe do sportsbook FIRST.\n *\n * Este entry não importa o core em runtime nem exige `lib.dom` nos tipos do consumidor. É o único\n * entry do pacote que toca o DOM, e só através dos objetos que o app passa (o iframe e a janela).\n * @module @getenginex/sdk-igaming/first-frame\n */\n\n/**\n * Mensagem `postMessage` como o helper a lê: só os campos que ele usa (um `MessageEvent` do DOM é\n * atribuível).\n * @category Sportsbook\n */\nexport interface FirstFrameMessageEvent {\n /** Conteúdo enviado pelo iframe: string JSON ou objeto. */\n readonly data: unknown\n /** Origem de quem enviou. */\n readonly origin: string\n /** Janela de quem enviou. */\n readonly source: unknown\n}\n\n/**\n * Janela da página, no mínimo que o helper usa: um `Window` do DOM é atribuível. É a janela do app\n * (a que recebe as mensagens do iframe), não a do iframe.\n * @category Sportsbook\n */\nexport interface FirstFrameWindow {\n /** Registra o listener de `message`. */\n addEventListener(type: 'message', listener: (event: FirstFrameMessageEvent) => void): void\n /** Remove o listener de `message`. */\n removeEventListener(type: 'message', listener: (event: FirstFrameMessageEvent) => void): void\n}\n\n/**\n * O iframe do FIRST, no mínimo que o helper usa: um `HTMLIFrameElement` é atribuível. A origem\n * esperada e o destino das mensagens saem de `src` (relido a cada mensagem).\n * @category Sportsbook\n */\nexport interface FirstFrameTarget {\n /** URL carregada no iframe (a `launchUrl` da sessão). Dela vem a origem confiável. */\n readonly src: string\n /** Janela do iframe; `null` enquanto ele não está no documento. */\n readonly contentWindow: {\n /** Envia uma mensagem para o iframe. */\n postMessage(message: string, targetOrigin: string): void\n } | null\n}\n\n/**\n * Argumento de `onRedirect`: os campos de `eventData` (se for um objeto) mais o `link` do topo da\n * mensagem. O SDK só garante que `link`, quando presente, é texto (um `link` de outro tipo é\n * descartado); o conteúdo não é validado e `link` pode faltar.\n * @category Sportsbook\n */\nexport interface FirstFrameRedirect {\n /** Destino pedido pelo FIRST; opcional e não confiável (valide antes de abrir). */\n link?: string\n /** Demais campos de `eventData`, como o FIRST os enviou. */\n [key: string]: unknown\n}\n\n/**\n * Handlers dos eventos do iframe. Todos opcionais; um handler que lança (ou rejeita) é ignorado e\n * não impede os demais.\n * @category Sportsbook\n */\nexport interface FirstFrameHandlers {\n /** `APP_READY`: o sportsbook carregou e aceita `send`. */\n onReady?(): void\n /** `BET_WAS_PLACED`: uma aposta foi feita (bom momento para reler o saldo). */\n onBetPlaced?(data: unknown): void\n /** `INSUFFICIENT_FUNDS`: saldo insuficiente para a aposta. */\n onInsufficientFunds?(data: unknown): void\n /** `depositClick`: o jogador pediu para depositar. */\n onDepositClick?(data: unknown): void\n /** `PLACE_BET_CLICKED_NOT_LOGGED_IN` ou `OPEN_LOGIN_POPUP`: o jogador precisa entrar. */\n onLoginRequired?(data: unknown): void\n /** `on-page-height-change` / `ON_PAGE_HEIGHT_CHANGE`: nova altura (px, positiva) do conteúdo. */\n onHeightChange?(height: number): void\n /**\n * `BUTTON_REDIRECT`: o FIRST pede para abrir um link. `data.link` vem no topo da mensagem (ou em\n * `eventData`) e **pode faltar ou não ser uma URL válida**. **Valide antes de abrir**: aceite só\n * http(s), sem credenciais.\n */\n onRedirect?(data: FirstFrameRedirect): void\n /** `SCROLL_TO_TOP`: o FIRST pede para rolar a página ao topo. */\n onScrollToTop?(): void\n /** Todo evento aceito, inclusive os que também têm handler dedicado. */\n onEvent?(eventType: string, eventData: unknown): void\n}\n\n/**\n * Conexão com o iframe do FIRST.\n * @category Sportsbook\n */\nexport interface FirstFrame {\n /**\n * Envia um evento ao iframe: `postMessage(JSON.stringify({ eventType, eventData }), origem)`, com a\n * origem do `src` (nunca `'*'`). Espere `onReady` antes de enviar: o FIRST só ouve depois de\n * carregar. Eventos que o FIRST entende: `sportId`, `leagueId`, `eventId` (`{ value: id }`),\n * `liveBetting`, `home` (`{ value: true }`), `betting-history`, `open-bets`, `expand-bet-slip`\n * (`{ value: boolean }`), `bscode` (`{ value: código }`) e `shareBetslip` (`{ url }`).\n * @example\n * frame.send('sportId', { value: '66' })\n * @throws {EnginexError} `CONFIGURATION_ERROR` se o `src` não tem origem http(s) válida, se o\n * iframe não tem `contentWindow` ou depois de `dispose()`.\n */\n send(eventType: string, eventData?: unknown): void\n /** Remove o listener. Idempotente; depois disso nada é entregue e `send` lança. */\n dispose(): void\n}\n\n/**\n * Opções de {@link connectFirstFrame}.\n * @category Sportsbook\n */\nexport interface ConnectFirstFrameOptions {\n /** Janela onde ouvir `message`. Padrão: `globalThis` (a janela da página que contém o iframe). */\n window?: FirstFrameWindow\n}\n\nconst BRAND = Symbol.for('getenginex.error')\n\n// Erro compatível com o `EnginexError` do core sem importá-lo: o core não pode entrar neste entry\n// (importar `@getenginex/sdk`, mesmo só para o erro, deixaria um `import` em runtime). O core\n// reconhece erros por `instanceof Error` + a marca global `Symbol.for('getenginex.error')`, então\n// `isEnginexError(e, 'CONFIGURATION_ERROR')` responde `true` para este erro.\nclass FirstFrameConfigurationError extends Error {\n override readonly name = 'EnginexError'\n readonly code = 'CONFIGURATION_ERROR'\n readonly status = 0\n readonly details = undefined\n constructor(message: string) {\n super(message)\n Object.defineProperty(this, BRAND, { value: true })\n }\n\n override toString(): string {\n return `EnginexError [${this.code}]: ${this.message}`\n }\n\n toJSON() {\n return { name: this.name, code: this.code, message: this.message, status: this.status }\n }\n}\n\nconst NO_ORIGIN =\n 'O src do iframe do FIRST não tem uma origem http(s) válida: defina iframe.src com a launchUrl antes de usar o frame.'\n\n/** Origem http(s) de `src`, ou `null`. Nunca lança nem inclui o `src` (tem token) em mensagens. */\nfunction originOf(src: string): string | null {\n try {\n const url = new URL(src)\n return url.protocol === 'https:' || url.protocol === 'http:' ? url.origin : null\n } catch {\n return null\n }\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null && !Array.isArray(value)\n}\n\nfunction parse(data: unknown): Record<string, unknown> | undefined {\n let value = data\n if (typeof value === 'string') {\n try {\n value = JSON.parse(value)\n } catch {\n return undefined\n }\n }\n return isRecord(value) ? value : undefined\n}\n\nfunction call(fn: (() => unknown) | undefined): void {\n if (!fn) return\n try {\n const result = fn()\n // `Promise.resolve` adota também thenables e promises de outro realm (não `instanceof Promise`).\n Promise.resolve(result).catch(() => {})\n } catch {\n // um handler com defeito não derruba o listener nem os outros handlers\n }\n}\n\nfunction positiveNumber(value: unknown): number | undefined {\n return typeof value === 'number' && Number.isFinite(value) && value > 0 ? value : undefined\n}\n\nfunction dispatch(message: Record<string, unknown>, handlers: FirstFrameHandlers): void {\n const rawType = message.eventType || message.type\n if (typeof rawType !== 'string' || rawType === '') return\n const eventType = rawType\n const eventData = message.eventData\n const on = <A extends unknown[]>(handler: ((...args: A) => void) | undefined, ...args: A) =>\n call(handler && (() => handler.apply(handlers, args)))\n\n switch (eventType) {\n case 'APP_READY':\n on(handlers.onReady)\n break\n case 'BET_WAS_PLACED':\n on(handlers.onBetPlaced, eventData)\n break\n case 'INSUFFICIENT_FUNDS':\n on(handlers.onInsufficientFunds, eventData)\n break\n case 'depositClick':\n on(handlers.onDepositClick, eventData)\n break\n case 'PLACE_BET_CLICKED_NOT_LOGGED_IN':\n case 'OPEN_LOGIN_POPUP':\n on(handlers.onLoginRequired, eventData)\n break\n case 'on-page-height-change':\n case 'ON_PAGE_HEIGHT_CHANGE': {\n const height =\n positiveNumber(isRecord(eventData) ? eventData.height : undefined) ?? positiveNumber(message.height)\n if (height !== undefined) on(handlers.onHeightChange, height)\n break\n }\n case 'BUTTON_REDIRECT': {\n // `link` só chega ao handler se for texto (o do topo da mensagem tem precedência): o tipo\n // público promete `link?: string`, e um número ou objeto vindo do iframe quebraria quem valida a URL.\n const data: FirstFrameRedirect = { ...(isRecord(eventData) ? eventData : {}) }\n if (typeof message.link === 'string') data.link = message.link\n else if (typeof data.link !== 'string') delete data.link\n on(handlers.onRedirect, data)\n break\n }\n case 'SCROLL_TO_TOP':\n on(handlers.onScrollToTop)\n break\n default:\n break\n }\n on(handlers.onEvent, eventType, eventData)\n}\n\n/**\n * Conecta ao iframe do sportsbook FIRST: recebe os eventos do FIRST em handlers tipados e envia\n * comandos com `send`. Só entrega mensagens cuja `origin` é a origem do `src` do iframe **e** cuja\n * `source` é o `contentWindow` do iframe; JSON inválido ou sem `eventType` é ignorado sem lançar.\n * O payload chega como o FIRST o enviou (`unknown`): valide antes de usar.\n * @example\n * import { connectFirstFrame } from '@getenginex/sdk-igaming/first-frame'\n *\n * const frame = connectFirstFrame(iframe, {\n * onBetPlaced: () => void enginex.wallet.getBalance().then(showBalance),\n * onLoginRequired: () => openLogin(),\n * })\n * // ao desmontar o iframe:\n * frame.dispose()\n * @throws {EnginexError} `CONFIGURATION_ERROR` se a janela (`options.window` ou `globalThis`) não\n * tem `addEventListener`/`removeEventListener`.\n * @category Sportsbook\n */\nexport function connectFirstFrame(\n iframe: FirstFrameTarget,\n handlers: FirstFrameHandlers,\n options: ConnectFirstFrameOptions = {},\n): FirstFrame {\n const win = options.window ?? (globalThis as unknown as Partial<FirstFrameWindow>)\n if (typeof win.addEventListener !== 'function' || typeof win.removeEventListener !== 'function') {\n throw new FirstFrameConfigurationError(\n 'connectFirstFrame precisa de uma janela com addEventListener: fora do browser, passe options.window.',\n )\n }\n let disposed = false\n\n const listener = (event: FirstFrameMessageEvent): void => {\n if (disposed) return\n const target = iframe.contentWindow\n const origin = originOf(iframe.src)\n if (target === null || origin === null || event.source !== target || event.origin !== origin) return\n const message = parse(event.data)\n if (message) dispatch(message, handlers)\n }\n win.addEventListener('message', listener)\n\n return {\n send(eventType, eventData) {\n if (disposed) throw new FirstFrameConfigurationError('O frame do FIRST já foi encerrado (dispose).')\n const origin = originOf(iframe.src)\n if (origin === null) throw new FirstFrameConfigurationError(NO_ORIGIN)\n const target = iframe.contentWindow\n if (target === null) {\n throw new FirstFrameConfigurationError('O iframe do FIRST ainda não tem contentWindow (não está no documento).')\n }\n target.postMessage(JSON.stringify({ eventType, eventData }), origin)\n },\n dispose() {\n if (disposed) return\n disposed = true\n win.removeEventListener?.('message', listener)\n },\n }\n}\n"]}
|