@getenginex/sdk-igaming 0.5.0 → 0.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,122 +1,122 @@
1
1
  /**
2
- * Ponte tipada e com checagem de origem para os eventos `postMessage` do iframe do sportsbook FIRST.
2
+ * Typed bridge with origin checking for the `postMessage` events of the FIRST sportsbook iframe.
3
3
  *
4
- * Este entry não importa o core em runtime nem exige `lib.dom` nos tipos do consumidor. É o único
5
- * entry do pacote que toca o DOM, e só através dos objetos que o app passa (o iframe e a janela).
4
+ * This entry does not import the core at runtime nor require `lib.dom` in the consumer's types. It is the only
5
+ * entry of the package that touches the DOM, and only through the objects the app passes (the iframe and the window).
6
6
  * @module @getenginex/sdk-igaming/first-frame
7
7
  */
8
8
  /**
9
- * Mensagem `postMessage` como o helper a lê: só os campos que ele usa (um `MessageEvent` do DOM é
10
- * atribuível).
9
+ * `postMessage` message as the helper reads it: only the fields it uses (a DOM `MessageEvent` is
10
+ * assignable).
11
11
  * @category Sportsbook
12
12
  */
13
13
  interface FirstFrameMessageEvent {
14
- /** Conteúdo enviado pelo iframe: string JSON ou objeto. */
14
+ /** Content sent by the iframe: a JSON string or an object. */
15
15
  readonly data: unknown;
16
- /** Origem de quem enviou. */
16
+ /** Sender's origin. */
17
17
  readonly origin: string;
18
- /** Janela de quem enviou. */
18
+ /** Sender's window. */
19
19
  readonly source: unknown;
20
20
  }
21
21
  /**
22
- * Janela da página, no mínimo que o helper usa: um `Window` do DOM é atribuível. É a janela do app
23
- * (a que recebe as mensagens do iframe), não a do iframe.
22
+ * Page window, with the minimum the helper uses: a DOM `Window` is assignable. It is the app's window
23
+ * (the one that receives the iframe's messages), not the iframe's.
24
24
  * @category Sportsbook
25
25
  */
26
26
  interface FirstFrameWindow {
27
- /** Registra o listener de `message`. */
27
+ /** Registers the `message` listener. */
28
28
  addEventListener(type: 'message', listener: (event: FirstFrameMessageEvent) => void): void;
29
- /** Remove o listener de `message`. */
29
+ /** Removes the `message` listener. */
30
30
  removeEventListener(type: 'message', listener: (event: FirstFrameMessageEvent) => void): void;
31
31
  }
32
32
  /**
33
- * O iframe do FIRST, no mínimo que o helper usa: um `HTMLIFrameElement` é atribuível. A origem
34
- * esperada e o destino das mensagens saem de `src` (relido a cada mensagem).
33
+ * The FIRST iframe, with the minimum the helper uses: an `HTMLIFrameElement` is assignable. The expected
34
+ * origin and the destination of the messages come from `src` (re-read on every message).
35
35
  * @category Sportsbook
36
36
  */
37
37
  interface FirstFrameTarget {
38
- /** URL carregada no iframe (a `launchUrl` da sessão). Dela vem a origem confiável. */
38
+ /** URL loaded in the iframe (the session's `launchUrl`). The trusted origin comes from it. */
39
39
  readonly src: string;
40
- /** Janela do iframe; `null` enquanto ele não está no documento. */
40
+ /** The iframe's window; `null` while it is not in the document. */
41
41
  readonly contentWindow: {
42
- /** Envia uma mensagem para o iframe. */
42
+ /** Sends a message to the iframe. */
43
43
  postMessage(message: string, targetOrigin: string): void;
44
44
  } | null;
45
45
  }
46
46
  /**
47
- * Argumento de `onRedirect`: os campos de `eventData` (se for um objeto) mais o `link` do topo da
48
- * mensagem. O SDK só garante que `link`, quando presente, é texto (um `link` de outro tipo é
49
- * descartado); o conteúdo não é validado e `link` pode faltar.
47
+ * Argument of `onRedirect`: the fields of `eventData` (if it is an object) plus the top-level `link` of the
48
+ * message. The SDK only guarantees that `link`, when present, is text (a `link` of another type is
49
+ * dropped); the content is not validated and `link` may be missing.
50
50
  * @category Sportsbook
51
51
  */
52
52
  interface FirstFrameRedirect {
53
- /** Destino pedido pelo FIRST; opcional e não confiável (valide antes de abrir). */
53
+ /** Destination requested by FIRST; optional and untrusted (validate before opening). */
54
54
  link?: string;
55
- /** Demais campos de `eventData`, como o FIRST os enviou. */
55
+ /** Other `eventData` fields, as FIRST sent them. */
56
56
  [key: string]: unknown;
57
57
  }
58
58
  /**
59
- * Handlers dos eventos do iframe. Todos opcionais; um handler que lança (ou rejeita) é ignorado e
60
- * não impede os demais.
59
+ * Handlers for the iframe events. All optional; a handler that throws (or rejects) is ignored and
60
+ * does not prevent the others.
61
61
  * @category Sportsbook
62
62
  */
63
63
  interface FirstFrameHandlers {
64
- /** `APP_READY`: o sportsbook carregou e aceita `send`. */
64
+ /** `APP_READY`: the sportsbook has loaded and accepts `send`. */
65
65
  onReady?(): void;
66
- /** `BET_WAS_PLACED`: uma aposta foi feita (bom momento para reler o saldo). */
66
+ /** `BET_WAS_PLACED`: a bet was placed (a good moment to re-read the balance). */
67
67
  onBetPlaced?(data: unknown): void;
68
- /** `INSUFFICIENT_FUNDS`: saldo insuficiente para a aposta. */
68
+ /** `INSUFFICIENT_FUNDS`: insufficient balance for the bet. */
69
69
  onInsufficientFunds?(data: unknown): void;
70
- /** `depositClick`: o jogador pediu para depositar. */
70
+ /** `depositClick`: the player asked to deposit. */
71
71
  onDepositClick?(data: unknown): void;
72
- /** `PLACE_BET_CLICKED_NOT_LOGGED_IN` ou `OPEN_LOGIN_POPUP`: o jogador precisa entrar. */
72
+ /** `PLACE_BET_CLICKED_NOT_LOGGED_IN` or `OPEN_LOGIN_POPUP`: the player needs to log in. */
73
73
  onLoginRequired?(data: unknown): void;
74
- /** `on-page-height-change` / `ON_PAGE_HEIGHT_CHANGE`: nova altura (px, positiva) do conteúdo. */
74
+ /** `on-page-height-change` / `ON_PAGE_HEIGHT_CHANGE`: new content height (px, positive). */
75
75
  onHeightChange?(height: number): void;
76
76
  /**
77
- * `BUTTON_REDIRECT`: o FIRST pede para abrir um link. `data.link` vem no topo da mensagem (ou em
78
- * `eventData`) e **pode faltar ou não ser uma URL válida**. **Valide antes de abrir**: aceite só
79
- * http(s), sem credenciais.
77
+ * `BUTTON_REDIRECT`: FIRST asks to open a link. `data.link` comes at the top of the message (or in
78
+ * `eventData`) and **may be missing or not a valid URL**. **Validate before opening**: accept only
79
+ * http(s), without credentials.
80
80
  */
81
81
  onRedirect?(data: FirstFrameRedirect): void;
82
- /** `SCROLL_TO_TOP`: o FIRST pede para rolar a página ao topo. */
82
+ /** `SCROLL_TO_TOP`: FIRST asks to scroll the page to the top. */
83
83
  onScrollToTop?(): void;
84
- /** Todo evento aceito, inclusive os que também têm handler dedicado. */
84
+ /** Every accepted event, including those that also have a dedicated handler. */
85
85
  onEvent?(eventType: string, eventData: unknown): void;
86
86
  }
87
87
  /**
88
- * Conexão com o iframe do FIRST.
88
+ * Connection to the FIRST iframe.
89
89
  * @category Sportsbook
90
90
  */
91
91
  interface FirstFrame {
92
92
  /**
93
- * Envia um evento ao iframe: `postMessage(JSON.stringify({ eventType, eventData }), origem)`, com a
94
- * origem do `src` (nunca `'*'`). Espere `onReady` antes de enviar: o FIRST só ouve depois de
95
- * carregar. Eventos que o FIRST entende: `sportId`, `leagueId`, `eventId` (`{ value: id }`),
93
+ * Sends an event to the iframe: `postMessage(JSON.stringify({ eventType, eventData }), origin)`, with the
94
+ * origin of the `src` (never `'*'`). Wait for `onReady` before sending: FIRST only listens after
95
+ * loading. Events FIRST understands: `sportId`, `leagueId`, `eventId` (`{ value: id }`),
96
96
  * `liveBetting`, `home` (`{ value: true }`), `betting-history`, `open-bets`, `expand-bet-slip`
97
- * (`{ value: boolean }`), `bscode` (`{ value: código }`) e `shareBetslip` (`{ url }`).
97
+ * (`{ value: boolean }`), `bscode` (`{ value: code }`) and `shareBetslip` (`{ url }`).
98
98
  * @example
99
99
  * frame.send('sportId', { value: '66' })
100
- * @throws {EnginexError} `CONFIGURATION_ERROR` se o `src` não tem origem http(s) válida, se o
101
- * iframe não tem `contentWindow` ou depois de `dispose()`.
100
+ * @throws {EnginexError} `CONFIGURATION_ERROR` if the `src` has no valid http(s) origin, if the
101
+ * iframe has no `contentWindow` or after `dispose()`.
102
102
  */
103
103
  send(eventType: string, eventData?: unknown): void;
104
- /** Remove o listener. Idempotente; depois disso nada é entregue e `send` lança. */
104
+ /** Removes the listener. Idempotent; after that nothing is delivered and `send` throws. */
105
105
  dispose(): void;
106
106
  }
107
107
  /**
108
- * Opções de {@link connectFirstFrame}.
108
+ * Options of {@link connectFirstFrame}.
109
109
  * @category Sportsbook
110
110
  */
111
111
  interface ConnectFirstFrameOptions {
112
- /** Janela onde ouvir `message`. Padrão: `globalThis` (a janela da página que contém o iframe). */
112
+ /** Window to listen for `message` on. Default: `globalThis` (the window of the page that contains the iframe). */
113
113
  window?: FirstFrameWindow;
114
114
  }
115
115
  /**
116
- * Conecta ao iframe do sportsbook FIRST: recebe os eventos do FIRST em handlers tipados e envia
117
- * comandos com `send`. Só entrega mensagens cuja `origin` é a origem do `src` do iframe **e** cuja
118
- * `source` é o `contentWindow` do iframe; JSON inválido ou sem `eventType` é ignorado sem lançar.
119
- * O payload chega como o FIRST o enviou (`unknown`): valide antes de usar.
116
+ * Connects to the FIRST sportsbook iframe: receives FIRST's events in typed handlers and sends
117
+ * commands with `send`. It only delivers messages whose `origin` is the `src` origin of the iframe **and** whose
118
+ * `source` is the iframe's `contentWindow`; invalid JSON or JSON without `eventType` is ignored without throwing.
119
+ * The payload arrives as FIRST sent it (`unknown`): validate before using it.
120
120
  * @example
121
121
  * import { connectFirstFrame } from '@getenginex/sdk-igaming/first-frame'
122
122
  *
@@ -124,10 +124,10 @@ interface ConnectFirstFrameOptions {
124
124
  * onBetPlaced: () => void enginex.wallet.getBalance().then(showBalance),
125
125
  * onLoginRequired: () => openLogin(),
126
126
  * })
127
- * // ao desmontar o iframe:
127
+ * // when unmounting the iframe:
128
128
  * frame.dispose()
129
- * @throws {EnginexError} `CONFIGURATION_ERROR` se a janela (`options.window` ou `globalThis`) não
130
- * tem `addEventListener`/`removeEventListener`.
129
+ * @throws {EnginexError} `CONFIGURATION_ERROR` if the window (`options.window` or `globalThis`) has no
130
+ * `addEventListener`/`removeEventListener`.
131
131
  * @category Sportsbook
132
132
  */
133
133
  declare function connectFirstFrame(iframe: FirstFrameTarget, handlers: FirstFrameHandlers, options?: ConnectFirstFrameOptions): FirstFrame;
@@ -16,7 +16,7 @@ var FirstFrameConfigurationError = class extends Error {
16
16
  return { name: this.name, code: this.code, message: this.message, status: this.status };
17
17
  }
18
18
  };
19
- 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.";
19
+ var NO_ORIGIN = "The FIRST iframe src has no valid http(s) origin: set iframe.src to the launchUrl before using the frame.";
20
20
  function originOf(src) {
21
21
  try {
22
22
  const url = new URL(src);
@@ -97,7 +97,7 @@ function connectFirstFrame(iframe, handlers, options = {}) {
97
97
  const win = options.window ?? globalThis;
98
98
  if (typeof win.addEventListener !== "function" || typeof win.removeEventListener !== "function") {
99
99
  throw new FirstFrameConfigurationError(
100
- "connectFirstFrame precisa de uma janela com addEventListener: fora do browser, passe options.window."
100
+ "connectFirstFrame needs a window with addEventListener: outside the browser, pass options.window."
101
101
  );
102
102
  }
103
103
  let disposed = false;
@@ -112,12 +112,12 @@ function connectFirstFrame(iframe, handlers, options = {}) {
112
112
  win.addEventListener("message", listener);
113
113
  return {
114
114
  send(eventType, eventData) {
115
- if (disposed) throw new FirstFrameConfigurationError("O frame do FIRST j\xE1 foi encerrado (dispose).");
115
+ if (disposed) throw new FirstFrameConfigurationError("The FIRST frame has already been closed (dispose).");
116
116
  const origin = originOf(iframe.src);
117
117
  if (origin === null) throw new FirstFrameConfigurationError(NO_ORIGIN);
118
118
  const target = iframe.contentWindow;
119
119
  if (target === null) {
120
- throw new FirstFrameConfigurationError("O iframe do FIRST ainda n\xE3o tem contentWindow (n\xE3o est\xE1 no documento).");
120
+ throw new FirstFrameConfigurationError("The FIRST iframe has no contentWindow yet (it is not in the document).");
121
121
  }
122
122
  target.postMessage(JSON.stringify({ eventType, eventData }), origin);
123
123
  },
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/first-frame/index.ts"],"names":[],"mappings":";AA0HA,IAAM,KAAA,mBAAQ,MAAA,CAAO,GAAA,CAAI,kBAAkB,CAAA;AAM3C,IAAM,4BAAA,GAAN,cAA2C,KAAA,CAAM;AA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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.js","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"]}
1
+ {"version":3,"sources":["../../src/first-frame/index.ts"],"names":[],"mappings":";AA0HA,IAAM,KAAA,mBAAQ,MAAA,CAAO,GAAA,CAAI,kBAAkB,CAAA;AAM3C,IAAM,4BAAA,GAAN,cAA2C,KAAA,CAAM;AAAA,EAC7B,IAAA,GAAO,cAAA;AAAA,EAChB,IAAA,GAAO,qBAAA;AAAA,EACP,MAAA,GAAS,CAAA;AAAA,EACT,OAAA,GAAU,MAAA;AAAA,EACnB,YAAY,OAAA,EAAiB;AAC3B,IAAA,KAAA,CAAM,OAAO,CAAA;AACb,IAAA,MAAA,CAAO,eAAe,IAAA,EAAM,KAAA,EAAO,EAAE,KAAA,EAAO,MAAM,CAAA;AAAA,EACpD;AAAA,EAES,QAAA,GAAmB;AAC1B,IAAA,OAAO,CAAA,cAAA,EAAiB,IAAA,CAAK,IAAI,CAAA,GAAA,EAAM,KAAK,OAAO,CAAA,CAAA;AAAA,EACrD;AAAA,EAEA,MAAA,GAAS;AACP,IAAA,OAAO,EAAE,IAAA,EAAM,IAAA,CAAK,IAAA,EAAM,IAAA,EAAM,IAAA,CAAK,IAAA,EAAM,OAAA,EAAS,IAAA,CAAK,OAAA,EAAS,MAAA,EAAQ,IAAA,CAAK,MAAA,EAAO;AAAA,EACxF;AACF,CAAA;AAEA,IAAM,SAAA,GACJ,2GAAA;AAGF,SAAS,SAAS,GAAA,EAA4B;AAC5C,EAAA,IAAI;AACF,IAAA,MAAM,GAAA,GAAM,IAAI,GAAA,CAAI,GAAG,CAAA;AACvB,IAAA,OAAO,IAAI,QAAA,KAAa,QA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A,IACL,IAAA,CAAK,WAAW,SAAA,EAAW;AACzB,MAAA,IAAI,QAAA,EAAU,MAAM,IAAI,4BAAA,CAA6B,oDAAoD,CAAA;AACzG,MAAA,MAAM,MAAA,GAAS,QAAA,CAAS,MAAA,CAAO,GAAG,CAAA;AAClC,MAAA,IAAI,MAAA,KAAW,IAAA,EAAM,MAAM,IAAI,6BAA6B,SAAS,CAAA;AACrE,MAAA,MAAM,SAAS,MAAA,CAAO,aAAA;AACtB,MAAA,IAAI,WAAW,IAAA,EAAM;AACnB,QAAA,MAAM,IAAI,6BAA6B,wEAAwE,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.js","sourcesContent":["/**\n * Typed bridge with origin checking for the `postMessage` events of the FIRST sportsbook iframe.\n *\n * This entry does not import the core at runtime nor require `lib.dom` in the consumer's types. It is the only\n * entry of the package that touches the DOM, and only through the objects the app passes (the iframe and the window).\n * @module @getenginex/sdk-igaming/first-frame\n */\n\n/**\n * `postMessage` message as the helper reads it: only the fields it uses (a DOM `MessageEvent` is\n * assignable).\n * @category Sportsbook\n */\nexport interface FirstFrameMessageEvent {\n /** Content sent by the iframe: a JSON string or an object. */\n readonly data: unknown\n /** Sender's origin. */\n readonly origin: string\n /** Sender's window. */\n readonly source: unknown\n}\n\n/**\n * Page window, with the minimum the helper uses: a DOM `Window` is assignable. It is the app's window\n * (the one that receives the iframe's messages), not the iframe's.\n * @category Sportsbook\n */\nexport interface FirstFrameWindow {\n /** Registers the `message` listener. */\n addEventListener(type: 'message', listener: (event: FirstFrameMessageEvent) => void): void\n /** Removes the `message` listener. */\n removeEventListener(type: 'message', listener: (event: FirstFrameMessageEvent) => void): void\n}\n\n/**\n * The FIRST iframe, with the minimum the helper uses: an `HTMLIFrameElement` is assignable. The expected\n * origin and the destination of the messages come from `src` (re-read on every message).\n * @category Sportsbook\n */\nexport interface FirstFrameTarget {\n /** URL loaded in the iframe (the session's `launchUrl`). The trusted origin comes from it. */\n readonly src: string\n /** The iframe's window; `null` while it is not in the document. */\n readonly contentWindow: {\n /** Sends a message to the iframe. */\n postMessage(message: string, targetOrigin: string): void\n } | null\n}\n\n/**\n * Argument of `onRedirect`: the fields of `eventData` (if it is an object) plus the top-level `link` of the\n * message. The SDK only guarantees that `link`, when present, is text (a `link` of another type is\n * dropped); the content is not validated and `link` may be missing.\n * @category Sportsbook\n */\nexport interface FirstFrameRedirect {\n /** Destination requested by FIRST; optional and untrusted (validate before opening). */\n link?: string\n /** Other `eventData` fields, as FIRST sent them. */\n [key: string]: unknown\n}\n\n/**\n * Handlers for the iframe events. All optional; a handler that throws (or rejects) is ignored and\n * does not prevent the others.\n * @category Sportsbook\n */\nexport interface FirstFrameHandlers {\n /** `APP_READY`: the sportsbook has loaded and accepts `send`. */\n onReady?(): void\n /** `BET_WAS_PLACED`: a bet was placed (a good moment to re-read the balance). */\n onBetPlaced?(data: unknown): void\n /** `INSUFFICIENT_FUNDS`: insufficient balance for the bet. */\n onInsufficientFunds?(data: unknown): void\n /** `depositClick`: the player asked to deposit. */\n onDepositClick?(data: unknown): void\n /** `PLACE_BET_CLICKED_NOT_LOGGED_IN` or `OPEN_LOGIN_POPUP`: the player needs to log in. */\n onLoginRequired?(data: unknown): void\n /** `on-page-height-change` / `ON_PAGE_HEIGHT_CHANGE`: new content height (px, positive). */\n onHeightChange?(height: number): void\n /**\n * `BUTTON_REDIRECT`: FIRST asks to open a link. `data.link` comes at the top of the message (or in\n * `eventData`) and **may be missing or not a valid URL**. **Validate before opening**: accept only\n * http(s), without credentials.\n */\n onRedirect?(data: FirstFrameRedirect): void\n /** `SCROLL_TO_TOP`: FIRST asks to scroll the page to the top. */\n onScrollToTop?(): void\n /** Every accepted event, including those that also have a dedicated handler. */\n onEvent?(eventType: string, eventData: unknown): void\n}\n\n/**\n * Connection to the FIRST iframe.\n * @category Sportsbook\n */\nexport interface FirstFrame {\n /**\n * Sends an event to the iframe: `postMessage(JSON.stringify({ eventType, eventData }), origin)`, with the\n * origin of the `src` (never `'*'`). Wait for `onReady` before sending: FIRST only listens after\n * loading. Events FIRST understands: `sportId`, `leagueId`, `eventId` (`{ value: id }`),\n * `liveBetting`, `home` (`{ value: true }`), `betting-history`, `open-bets`, `expand-bet-slip`\n * (`{ value: boolean }`), `bscode` (`{ value: code }`) and `shareBetslip` (`{ url }`).\n * @example\n * frame.send('sportId', { value: '66' })\n * @throws {EnginexError} `CONFIGURATION_ERROR` if the `src` has no valid http(s) origin, if the\n * iframe has no `contentWindow` or after `dispose()`.\n */\n send(eventType: string, eventData?: unknown): void\n /** Removes the listener. Idempotent; after that nothing is delivered and `send` throws. */\n dispose(): void\n}\n\n/**\n * Options of {@link connectFirstFrame}.\n * @category Sportsbook\n */\nexport interface ConnectFirstFrameOptions {\n /** Window to listen for `message` on. Default: `globalThis` (the window of the page that contains the iframe). */\n window?: FirstFrameWindow\n}\n\nconst BRAND = Symbol.for('getenginex.error')\n\n// Error compatible with the core's `EnginexError` without importing it: the core cannot enter this entry\n// (importing `@getenginex/sdk`, even only for the error, would leave a runtime `import`). The core\n// recognizes errors by `instanceof Error` + the global mark `Symbol.for('getenginex.error')`, so\n// `isEnginexError(e, 'CONFIGURATION_ERROR')` answers `true` for this error.\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 'The FIRST iframe src has no valid http(s) origin: set iframe.src to the launchUrl before using the frame.'\n\n/** http(s) origin of `src`, or `null`. It never throws nor includes the `src` (it has a token) in messages. */\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` also adopts thenables and promises from another realm (not `instanceof Promise`).\n Promise.resolve(result).catch(() => {})\n } catch {\n // a faulty handler does not take down the listener nor the other 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` only reaches the handler if it is text (the top-level one in the message takes precedence): the public\n // type promises `link?: string`, and a number or object coming from the iframe would break whoever validates the 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 * Connects to the FIRST sportsbook iframe: receives FIRST's events in typed handlers and sends\n * commands with `send`. It only delivers messages whose `origin` is the `src` origin of the iframe **and** whose\n * `source` is the iframe's `contentWindow`; invalid JSON or JSON without `eventType` is ignored without throwing.\n * The payload arrives as FIRST sent it (`unknown`): validate before using it.\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 * // when unmounting the iframe:\n * frame.dispose()\n * @throws {EnginexError} `CONFIGURATION_ERROR` if the window (`options.window` or `globalThis`) has no\n * `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 needs a window with addEventListener: outside the browser, pass 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('The FIRST frame has already been closed (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('The FIRST iframe has no contentWindow yet (it is not in the document).')\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"]}