@clovnet/casino-sdk 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/config.ts","../src/core/cookies.ts","../src/core/errors.ts","../src/core/idempotency.ts","../src/core/http.ts","../src/core/session.ts","../src/modules/affiliate.ts","../src/modules/auth.ts","../src/core/money.ts","../src/modules/cashier.ts","../src/modules/wallet.ts","../src/modules/catalog.ts","../src/core/json-schema.ts","../src/core/env.ts","../src/modules/ext.ts","../src/modules/games.ts","../src/modules/kyc.ts","../src/modules/player.ts","../src/realtime/transport.ts","../src/realtime/client.ts","../src/modules/realtime.ts","../src/client.ts","../src/realtime/contract.ts","../src/index.ts"],"names":["isPlainObject","toIso","isRecord"],"mappings":";;;AAUO,IAAM,MAAA,GAAS;AAAA,EACpB,MAAA,EAAQ,kBAAA;AAAA,EACR,OAAA,EAAS,mBAAA;AAAA,EACT,IAAA,EAAM;AACR;AAGO,IAAM,MAAA,GAAS;AAAA,EACpB,MAAA,EAAQ,aAAA;AAAA,EACR,KAAA,EAAO,YAAA;AAAA,EACP,MAAA,EAAQ,UAAA;AAAA,EACR,IAAA,EAAM,cAAA;AAAA,EACN,WAAA,EAAa;AACf;AAmEO,SAAS,cAAc,MAAA,EAA4C;AACxE,EAAA,IAAI,CAAC,MAAA,CAAO,OAAA,EAAS,MAAM,IAAI,MAAM,2CAA2C,CAAA;AAChF,EAAA,IAAI,CAAC,MAAA,CAAO,QAAA,EAAU,MAAM,IAAI,MAAM,4CAA4C,CAAA;AAIlF,EAAA,MAAM,YAAY,MAAA,CAAO,KAAA,IAAU,UAAA,CAAW,KAAA,EAAO,KAAK,UAAU,CAAA;AACpE,EAAA,IAAI,CAAC,SAAA,EAAW;AACd,IAAA,MAAM,IAAI,KAAA;AAAA,MACR;AAAA,KACF;AAAA,EACF;AAEA,EAAA,OAAO;AAAA,IACL,OAAA,EAAS,kBAAA,CAAmB,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D;AAOO,IAAM,iBAAA,GAAoD;AAAA,EAC/D,gBAAA;AAAA,EACA,gBAAA;AAAA,EACA,mBAAA;AAAA,EACA,QAAA;AAAA,EACA,OAAA;AAAA,EACA;AACF;;;AC9BO,IAAM,mBAAA,GAAsB","file":"index.cjs","sourcesContent":["/**\n * Client configuration.\n */\nimport type { CasinoSdkError } from \"./core/errors.js\";\nimport type { CookieJar } from \"./core/cookies.js\";\n\n/** A `fetch`-compatible function. Defaults to the platform global. */\nexport type FetchLike = typeof fetch;\n\n/** Cookie names the runtime sets. Stable; surfaced for advanced use. */\nexport const COOKIE = {\n access: \"cwe_access_token\",\n refresh: \"cwe_refresh_token\",\n csrf: \"cwe_csrf\",\n} as const;\n\n/** Header names the SDK sends. */\nexport const HEADER = {\n tenant: \"x-tenant-id\",\n brand: \"x-brand-id\",\n region: \"x-region\",\n csrf: \"x-csrf-token\",\n idempotency: \"idempotency-key\",\n} as const;\n\nexport interface CasinoClientConfig {\n /** Base URL of the runtime HTTP API, e.g. `https://api.staging.example`. */\n baseUrl: string;\n /**\n * WebSocket URL of the realtime gateway, e.g. `wss://api.staging.example/realtime`.\n * Optional — only needed if you use `sdk.realtime`. Defaults to `baseUrl` with\n * the protocol swapped to ws(s) and `/realtime` appended.\n */\n wsUrl?: string;\n /**\n * Tenant id sent as `x-tenant-id` on every request — as *declared intent*,\n * not as the selector. Since the runtime's H1 trusted tenant resolution, the\n * tenant is determined by the request host (`baseUrl`'s origin → the\n * runtime's trusted host→tenant map, else its env base); an untrusted\n * `x-tenant-id` is ignored. The header is only honored when a trusted\n * internal proxy forwards it with `x-internal-tenant-token`. Point `baseUrl`\n * at the correct brand host; multi-brand apps need one client per brand\n * base URL.\n */\n tenantId: string;\n /** Optional brand id sent as `x-brand-id`. */\n brandId?: string;\n /** Optional region sent as `x-region`. */\n region?: string;\n /** Default fiat currency for wallet/cashier/launch calls (ISO 4217). Default `EUR`. */\n defaultCurrency?: string;\n /** Injected fetch (Node < 18, tests, custom agents). Defaults to global `fetch`. */\n fetch?: FetchLike;\n /**\n * Called when a request fails auth even after one refresh attempt. Use it to\n * route the user to login / clear app state. Receives the originating error.\n */\n onAuthError?: (error: CasinoSdkError) => void;\n /**\n * Disable the automatic 401 → refresh → retry behavior (default enabled).\n * Turn off if you manage refresh yourself.\n */\n autoRefresh?: boolean;\n /**\n * Node/SSR only: the cookie jar this client reads and writes (the browser manages\n * its own cookies). Defaults to a fresh private jar. On a server that handles many\n * users, never share one jar (or one module-scope client) across requests — use\n * `client.withCookies(new CookieJar())` per incoming request instead.\n */\n cookieJar?: CookieJar;\n /**\n * Default per-request timeout in milliseconds — a black-holed request rejects\n * with `NetworkError` (code `NETWORK_TIMEOUT`) instead of hanging forever, so\n * `deposit()`/`withdraw()`/`login()` always settle. Default 30 000; `0` disables.\n * Calls that legitimately run long expose a per-call override — e.g.\n * `kyc.uploadDocument(input, { timeoutMs })` for large files on slow uplinks.\n */\n timeoutMs?: number;\n}\n\n/** Internal, fully-resolved config with defaults applied. */\nexport interface ResolvedConfig extends Required<\n Omit<CasinoClientConfig, \"brandId\" | \"region\" | \"onAuthError\" | \"cookieJar\">\n> {\n brandId: string | undefined;\n region: string | undefined;\n onAuthError: ((error: CasinoSdkError) => void) | undefined;\n cookieJar: CookieJar | undefined;\n}\n\nexport function resolveConfig(config: CasinoClientConfig): ResolvedConfig {\n if (!config.baseUrl) throw new Error(\"createCasinoClient: `baseUrl` is required\");\n if (!config.tenantId) throw new Error(\"createCasinoClient: `tenantId` is required\");\n\n // Bind the global to `globalThis`: native browser `fetch` brand-checks its\n // receiver and throws `Illegal invocation` if invoked with any other `this`.\n const fetchImpl = config.fetch ?? (globalThis.fetch?.bind(globalThis) as FetchLike | undefined);\n if (!fetchImpl) {\n throw new Error(\n \"createCasinoClient: no global `fetch` found; pass `fetch` in config (Node < 18).\",\n );\n }\n\n return {\n baseUrl: stripTrailingSlash(config.baseUrl),\n wsUrl: config.wsUrl ?? deriveWsUrl(config.baseUrl),\n tenantId: config.tenantId,\n brandId: config.brandId,\n region: config.region,\n defaultCurrency: (config.defaultCurrency ?? \"EUR\").toUpperCase(),\n fetch: fetchImpl,\n onAuthError: config.onAuthError,\n autoRefresh: config.autoRefresh ?? true,\n cookieJar: config.cookieJar,\n timeoutMs: config.timeoutMs ?? 30_000,\n };\n}\n\nfunction stripTrailingSlash(url: string): string {\n return url.replace(/\\/+$/, \"\");\n}\n\nfunction deriveWsUrl(baseUrl: string): string {\n return `${stripTrailingSlash(baseUrl).replace(/^http/, \"ws\")}/realtime`;\n}\n","/**\n * Cookie handling.\n *\n * In the browser, the platform manages cookies and `credentials: \"include\"` sends\n * them automatically — the SDK only needs to *read* the JS-readable `cwe_csrf`\n * cookie via `document.cookie`.\n *\n * Outside the browser (Node / SSR / contract tests) there is no cookie store, so\n * the SDK keeps its own {@link CookieJar}: it captures `set-cookie` from responses\n * and replays a `Cookie` header on subsequent requests. This is what lets a\n * server-side `login()` establish a session that later calls reuse.\n */\n\nconst isBrowser = (): boolean =>\n typeof document !== \"undefined\" && typeof document.cookie === \"string\";\n\n/** Minimal cookie store used when no browser cookie jar exists. */\nexport class CookieJar {\n private readonly store = new Map<string, string>();\n\n /** Read a cookie value by name, or undefined. */\n get(name: string): string | undefined {\n return this.store.get(name);\n }\n\n /** Serialize all cookies into a `Cookie` request-header value. */\n header(): string | undefined {\n if (this.store.size === 0) return undefined;\n return [...this.store.entries()].map(([k, v]) => `${k}=${v}`).join(\"; \");\n }\n\n /** Clear the jar (e.g. on logout). */\n clear(): void {\n this.store.clear();\n }\n\n /**\n * Ingest `set-cookie` header(s) from a response. Only the `name=value` pair is\n * retained (attributes like Path/HttpOnly are ignored — this jar is a dev/SSR\n * convenience, not a spec-complete cookie store). A `Max-Age<=0` or an `Expires`\n * in the past deletes the cookie; `Max-Age` wins when both are present.\n */\n ingest(setCookie: string | string[] | null | undefined): void {\n if (!setCookie) return;\n const lines = Array.isArray(setCookie) ? setCookie : splitSetCookie(setCookie);\n for (const line of lines) {\n const [pair, ...attrs] = line.split(\";\");\n if (!pair) continue;\n const eq = pair.indexOf(\"=\");\n if (eq < 0) continue;\n const name = pair.slice(0, eq).trim();\n const value = pair.slice(eq + 1).trim();\n if (!name) continue;\n if (isExpired(attrs)) this.store.delete(name);\n else this.store.set(name, value);\n }\n }\n}\n\nfunction isExpired(attrs: string[]): boolean {\n let expires: string | undefined;\n for (const attr of attrs) {\n const eq = attr.indexOf(\"=\");\n const key = (eq === -1 ? attr : attr.slice(0, eq)).trim().toLowerCase();\n const value = eq === -1 ? undefined : attr.slice(eq + 1).trim();\n // Max-Age takes precedence over Expires when both are present (RFC 6265 §4.1.2.2).\n if (key === \"max-age\" && value !== undefined) return Number(value) <= 0;\n if (key === \"expires\" && value !== undefined) expires = value;\n }\n if (expires !== undefined) {\n const time = Date.parse(expires);\n if (!Number.isNaN(time)) return time <= Date.now();\n }\n return false;\n}\n\n/**\n * Split a folded `set-cookie` header (multiple cookies joined by commas) into\n * individual cookie strings without breaking the comma inside `Expires=...`.\n */\nfunction splitSetCookie(header: string): string[] {\n const out: string[] = [];\n let start = 0;\n for (let i = 0; i < header.length; i++) {\n if (header[i] === \",\") {\n const ahead = header.slice(i + 1, i + 12).toLowerCase();\n // A comma that is part of an Expires date is preceded by a weekday token.\n const before = header.slice(start, i);\n if (/expires=\\w{3}$/i.test(before.trim()) || /^\\s*\\d{1,2}-\\w{3}/.test(ahead)) {\n continue;\n }\n out.push(header.slice(start, i).trim());\n start = i + 1;\n }\n }\n out.push(header.slice(start).trim());\n return out.filter(Boolean);\n}\n\n/**\n * Read a cookie value, preferring the browser's `document.cookie`, falling back\n * to the provided {@link CookieJar} (Node/SSR).\n */\nexport function readCookie(name: string, jar?: CookieJar): string | undefined {\n if (isBrowser()) {\n const match = document.cookie\n .split(\";\")\n .map((c) => c.trim())\n .find((c) => c.startsWith(`${name}=`));\n if (match) return decodeURIComponent(match.slice(name.length + 1));\n }\n return jar?.get(name);\n}\n\nexport { isBrowser };\n","/**\n * Error model.\n *\n * The runtime returns a single envelope shape on failure:\n *\n * ```json\n * { \"error\": { \"code\": \"INSUFFICIENT_FUNDS\", \"message\": \"...\", \"details\": { } } }\n * ```\n *\n * `mapEnvelope` turns that (plus the HTTP status) into a typed {@link CasinoSdkError}\n * subclass so app code can `instanceof`-branch instead of string-matching codes.\n */\nimport type { ExtPluginClient } from \"../types/ext.js\";\n\n/** The runtime's `AppError` envelope, as seen on the wire. */\nexport interface AppErrorEnvelope {\n error: {\n code: string;\n message: string;\n details?: unknown;\n };\n}\n\n/** Type guard for the runtime error envelope. */\nexport function isAppErrorEnvelope(value: unknown): value is AppErrorEnvelope {\n if (typeof value !== \"object\" || value === null) return false;\n const err = (value as { error?: unknown }).error;\n return (\n typeof err === \"object\" &&\n err !== null &&\n typeof (err as { code?: unknown }).code === \"string\" &&\n typeof (err as { message?: unknown }).message === \"string\"\n );\n}\n\n/**\n * Base class for every error the SDK throws. Carries the stable machine-readable\n * `code`, the HTTP `status` (0 for transport/client-side failures), and the\n * runtime's `details` payload when present.\n */\nexport class CasinoSdkError extends Error {\n readonly code: string;\n readonly status: number;\n readonly details?: unknown;\n\n constructor(code: string, message: string, status = 0, details?: unknown) {\n super(message);\n this.name = new.target.name;\n this.code = code;\n this.status = status;\n if (details !== undefined) this.details = details;\n // Restore prototype chain for transpiled targets.\n Object.setPrototypeOf(this, new.target.prototype);\n }\n}\n\n/** 401 — session missing/invalid/expired. Often triggers an auto-refresh + retry. */\nexport class AuthError extends CasinoSdkError {}\n/**\n * 403 — authenticated but not allowed. This includes CSRF double-submit failures:\n * the runtime throws them as a plain `FORBIDDEN` (see `packages/core/src/csrf.ts`\n * in the runtime), so there is deliberately no separate CSRF error class here.\n */\nexport class ForbiddenError extends CasinoSdkError {}\n/** 400 — request failed validation. `details.issues` lists the per-field problems. */\nexport class ValidationError extends CasinoSdkError {}\n/** 404 — resource not found. */\nexport class NotFoundError extends CasinoSdkError {}\n/** 409 — conflict or invalid state transition. */\nexport class ConflictError extends CasinoSdkError {}\n/** 422 — wallet balance too low for the requested debit (`INSUFFICIENT_FUNDS`). */\nexport class InsufficientFundsError extends CasinoSdkError {}\n/**\n * 422 — the request was semantically rejected and no more-specific domain code\n * matched. The neutral fallback for unknown 422s: a future non-money 422 must not\n * `instanceof`-match app branches written for insufficient funds.\n */\nexport class UnprocessableError extends CasinoSdkError {}\n/**\n * 422 — a cashier gate plugin denied the operation (`DEPOSIT_DENIED`,\n * `WITHDRAWAL_DENIED`, `DEPOSIT_LIMIT_EXCEEDED`, `WITHDRAWAL_LIMIT_EXCEEDED`).\n * `details.pluginId` names the deciding plugin.\n */\nexport class OperationDeniedError extends CasinoSdkError {}\n/**\n * 429 — rate limited. On verification-request cooldowns `details.resendIn`\n * gives the seconds to wait before retrying.\n */\nexport class RateLimitError extends CasinoSdkError {}\n/**\n * 409 `FLOW_DELEGATED` — this tenant delegates the flow (signup/deposit/\n * withdrawal/KYC) to a plugin; drive the plugin's actions via `sdk.ext`\n * instead. `details: { flow, pluginKey }`.\n */\nexport class FlowDelegatedError extends ConflictError {\n /** The plugin that owns the delegated flow (from `details.pluginKey`). */\n readonly pluginKey: string;\n /** The delegated flow kind (from `details.flow`), e.g. `\"deposit\"`. */\n readonly flow: string | undefined;\n /**\n * Set (best-effort, by the SDK) when the ext catalog shows an action named\n * after the flow — `sdk.ext(pluginKey).call(continueWith.actionKey, …)` is\n * then the way to continue. Left `undefined` when the catalog lookup fails;\n * the original error is never masked.\n */\n continueWith?: { actionKey: string };\n\n constructor(code: string, message: string, status = 0, details?: unknown) {\n super(code, message, status, details);\n const d = (typeof details === \"object\" && details !== null ? details : {}) as {\n pluginKey?: unknown;\n flow?: unknown;\n };\n this.pluginKey = typeof d.pluginKey === \"string\" ? d.pluginKey : \"\";\n this.flow = typeof d.flow === \"string\" ? d.flow : undefined;\n }\n\n /** Sugar for `sdk.ext(this.pluginKey)` — the plugin client to continue the flow with. */\n resolve(sdk: { ext: (pluginKey: string) => ExtPluginClient }): ExtPluginClient {\n if (!this.pluginKey) {\n throw new Error(\"FlowDelegatedError.resolve(): the error carried no details.pluginKey.\");\n }\n return sdk.ext(this.pluginKey);\n }\n}\n/**\n * 409 `RG_BLOCKED` — a responsible-gaming state blocks the operation.\n * `details: { reason: \"cool_off\" | \"self_excluded\", until: string | null }`.\n */\nexport class RgBlockedError extends CasinoSdkError {}\n/**\n * 409 `LIMIT_EXCEEDED` — a responsible-gaming limit blocks the operation.\n * `details: { kind, period, remainingMinor, resetsAt }`.\n */\nexport class LimitExceededError extends CasinoSdkError {}\n/** 5xx — the runtime failed internally. */\nexport class ServerError extends CasinoSdkError {}\n/** No HTTP response (DNS/offline/abort/CORS). `status` is 0. */\nexport class NetworkError extends CasinoSdkError {}\n/**\n * A capability the SDK exposes for surface-completeness, but the runtime does not\n * implement yet. See the roadmap in `docs/SDK_BIBLE.md`.\n */\nexport class NotImplementedError extends CasinoSdkError {\n constructor(message: string) {\n super(\"NOT_IMPLEMENTED\", message, 0);\n }\n}\n\n// ── Plugin actions (`sdk.ext`) ───────────────────────────────────────────────────\n\n/**\n * The plugin is not installed/enabled for this tenant — either a 404 from an\n * `/api/ext/*` route (the runtime makes disabled and not-installed\n * indistinguishable) or the plugin is absent from a fresh catalog (then thrown\n * client-side with `status` 0 and code `PLUGIN_NOT_ENABLED`, no network call).\n */\nexport class PluginNotEnabledError extends NotFoundError {\n readonly pluginKey: string;\n\n constructor(\n pluginKey: string,\n options?: { code?: string; message?: string; status?: number; details?: unknown },\n ) {\n super(\n options?.code ?? \"PLUGIN_NOT_ENABLED\",\n options?.message ?? `Plugin \"${pluginKey}\" is not enabled for this tenant.`,\n options?.status ?? 0,\n options?.details,\n );\n this.pluginKey = pluginKey;\n }\n}\n\n/**\n * The action key is not among the plugin's catalog descriptors. Thrown\n * client-side (status 0) without a network call when the catalog is fresh.\n */\nexport class PluginActionNotFoundError extends NotFoundError {\n readonly pluginKey: string;\n readonly actionKey: string;\n\n constructor(pluginKey: string, actionKey: string) {\n super(\n \"PLUGIN_ACTION_NOT_FOUND\",\n `Plugin \"${pluginKey}\" declares no action \"${actionKey}\" in its catalog.`,\n 0,\n );\n this.pluginKey = pluginKey;\n this.actionKey = actionKey;\n }\n}\n\n/**\n * The plugin handler timed out or crashed — a 504 from an `/api/ext/*` route or\n * the envelope code `PLUGIN_ROUTE_ERROR` (also the legacy `PLUGIN_ROUTE_TIMEOUT`).\n */\nexport class PluginUnavailableError extends ServerError {}\n\n/**\n * A generated plugin client's expected major version does not match the\n * installed plugin's version in the catalog. Thrown client-side by\n * `assertPluginVersion` (status 0).\n */\nexport class PluginVersionMismatchError extends ConflictError {\n readonly pluginKey: string;\n readonly expectedRange: string;\n readonly actualVersion: string;\n\n constructor(pluginKey: string, expectedRange: string, actualVersion: string) {\n super(\n \"PLUGIN_VERSION_MISMATCH\",\n `Plugin \"${pluginKey}\" is installed at ${actualVersion}, but this client expects ${expectedRange}.`,\n 0,\n { pluginKey, expectedRange, actualVersion },\n );\n this.pluginKey = pluginKey;\n this.expectedRange = expectedRange;\n this.actualVersion = actualVersion;\n }\n}\n\nconst CODE_TO_CLASS: Record<\n string,\n new (...a: ConstructorParameters<typeof CasinoSdkError>) => CasinoSdkError\n> = {\n VALIDATION_ERROR: ValidationError,\n TENANT_CONTEXT_ERROR: ValidationError,\n UNAUTHORIZED: AuthError,\n REALTIME_UNAUTHORIZED: AuthError,\n REALTIME_AUTH: AuthError,\n FORBIDDEN: ForbiddenError,\n NOT_FOUND: NotFoundError,\n CONFLICT: ConflictError,\n INVALID_STATE_TRANSITION: ConflictError,\n INVALID_WITHDRAWAL_STATE: ConflictError,\n INSUFFICIENT_FUNDS: InsufficientFundsError,\n DEPOSIT_DENIED: OperationDeniedError,\n WITHDRAWAL_DENIED: OperationDeniedError,\n DEPOSIT_LIMIT_EXCEEDED: OperationDeniedError,\n WITHDRAWAL_LIMIT_EXCEEDED: OperationDeniedError,\n RATE_LIMITED: RateLimitError,\n FLOW_DELEGATED: FlowDelegatedError,\n // Plugin handler timed out / crashed (plugin actions & ext routes).\n PLUGIN_ROUTE_ERROR: PluginUnavailableError,\n PLUGIN_ROUTE_TIMEOUT: PluginUnavailableError,\n RG_BLOCKED: RgBlockedError,\n LIMIT_EXCEEDED: LimitExceededError,\n // 422 — a KYC document upload was rejected (bad format/size/expiry). Mapped to\n // ValidationError (not the status-422 InsufficientFundsError fallback).\n KYC_DOCUMENT_INVALID: ValidationError,\n // 409 conflict-family domain codes.\n KYC_REQUEST_STATE: ConflictError,\n PROFILE_FIELD_LOCKED: ConflictError,\n BALANCE_REMAINING: ConflictError,\n WITHDRAWAL_PENDING: ConflictError,\n};\n\n/** Choose the right error subclass from an envelope + HTTP status. */\nexport function mapEnvelope(status: number, body: unknown): CasinoSdkError {\n if (isAppErrorEnvelope(body)) {\n const { code, message, details } = body.error;\n const ByCode = CODE_TO_CLASS[code];\n if (ByCode) return new ByCode(code, message, status, details);\n return mapByStatus(status, code, message, details);\n }\n return mapByStatus(status, statusCodeName(status), `HTTP ${status}`, body);\n}\n\nfunction mapByStatus(\n status: number,\n code: string,\n message: string,\n details?: unknown,\n): CasinoSdkError {\n if (status === 401) return new AuthError(code, message, status, details);\n if (status === 403) return new ForbiddenError(code, message, status, details);\n if (status === 404) return new NotFoundError(code, message, status, details);\n if (status === 409) return new ConflictError(code, message, status, details);\n if (status === 422) return new UnprocessableError(code, message, status, details);\n if (status === 429) return new RateLimitError(code, message, status, details);\n if (status >= 500) return new ServerError(code, message, status, details);\n return new CasinoSdkError(code, message, status, details);\n}\n\nfunction statusCodeName(status: number): string {\n if (status === 400) return \"VALIDATION_ERROR\";\n if (status === 401) return \"UNAUTHORIZED\";\n if (status === 403) return \"FORBIDDEN\";\n if (status === 404) return \"NOT_FOUND\";\n if (status === 409) return \"CONFLICT\";\n if (status === 422) return \"UNPROCESSABLE\";\n if (status === 429) return \"RATE_LIMITED\";\n if (status >= 500) return \"INTERNAL_ERROR\";\n return \"REQUEST_ERROR\";\n}\n","/**\n * Idempotency key generation.\n *\n * Money operations on the runtime require a key (8–128 chars) sent both as the\n * body field `idempotencyKey` and the `idempotency-key` header. Replays return\n * the original result with `idempotent: true`. The SDK auto-generates one per\n * money call unless the caller supplies their own.\n */\n\n/** A reasonably-unique, URL-safe key. Prefers `crypto.randomUUID` when available. */\nexport function generateIdempotencyKey(prefix = \"idem\"): string {\n const uuid = randomUuid();\n return `${prefix}-${uuid}`;\n}\n\nfunction randomUuid(): string {\n const c = (globalThis as { crypto?: Crypto }).crypto;\n if (c?.randomUUID) return c.randomUUID();\n // Fallback for very old runtimes: random hex from getRandomValues, else Math.random.\n if (c?.getRandomValues) {\n const bytes = new Uint8Array(16);\n c.getRandomValues(bytes);\n return [...bytes].map((b) => b.toString(16).padStart(2, \"0\")).join(\"\");\n }\n let out = \"\";\n for (let i = 0; i < 32; i++) out += Math.floor(Math.random() * 16).toString(16);\n return out;\n}\n","/**\n * The isomorphic HTTP layer every module calls through.\n *\n * Responsibilities (so modules and app code never deal with them):\n * - inject `x-tenant-id` (+ optional brand/region) from config — declared intent\n * only: the runtime resolves the tenant from the request host (H1) and ignores\n * untrusted `x-tenant-*` headers,\n * - `credentials: \"include\"` for the cookie session; in Node, replay/ingest a\n * {@link CookieJar},\n * - double-submit CSRF: read `cwe_csrf`, send `x-csrf-token` on mutations,\n * - auto idempotency keys for money ops (body field + header),\n * - decode the `AppError` envelope into a typed {@link CasinoSdkError},\n * - on 401, attempt a single refresh + retry, then fire `onAuthError` — the refresh\n * is single-flight across concurrent 401s and never refreshes itself,\n * - apply the default request timeout (`timeoutMs`, 30s) → `NETWORK_TIMEOUT`.\n */\nimport { HEADER, COOKIE, type ResolvedConfig } from \"../config.js\";\nimport { CookieJar, readCookie, isBrowser } from \"./cookies.js\";\nimport type { CasinoSdkError } from \"./errors.js\";\nimport { mapEnvelope, NetworkError } from \"./errors.js\";\nimport { generateIdempotencyKey } from \"./idempotency.js\";\n\ntype Method = \"GET\" | \"POST\" | \"PUT\" | \"PATCH\" | \"DELETE\";\n\nexport interface RequestOptions {\n /** Query params; `undefined`/`null` are dropped, arrays repeat the key. */\n query?: Record<string, string | number | boolean | undefined | null | readonly string[]>;\n /**\n * Request body. A plain value is JSON-encoded; a `FormData` is sent as\n * multipart (content-type left to fetch so the boundary is set) — used by\n * KYC document uploads.\n */\n body?: unknown;\n /**\n * Mark this a money operation: the SDK injects an idempotency key into both the\n * body (`idempotencyKey`) and the `idempotency-key` header.\n */\n idempotent?: boolean;\n /** Provide your own idempotency key instead of an auto-generated one. */\n idempotencyKey?: string;\n /**\n * With `idempotent`, send the key as the `idempotency-key` header only and leave\n * the body untouched. Plugin ext routes validate bodies `.strict()` and read the\n * key from the header, so an injected body field would be rejected.\n */\n idempotencyHeaderOnly?: boolean;\n /** Force-enable/disable the CSRF header (defaults: on for mutations). */\n csrf?: boolean;\n /** Extra request headers, merged after the SDK's own (advanced; e.g. `if-none-match`). */\n headers?: Record<string, string>;\n /** Abort signal. */\n signal?: AbortSignal;\n /** Per-request timeout in ms, overriding `config.timeoutMs` (`0` disables). */\n timeoutMs?: number;\n /** Internal: prevents infinite refresh recursion. */\n _isRetry?: boolean;\n /**\n * Internal: this request must never enter the 401 → refresh → retry path, and a\n * 401 on it does not fire `onAuthError` itself. Set on the refresh POST: when\n * refresh 401s (fully logged out), the *originating* request reports the auth\n * failure exactly once instead of the refresh request recursing into itself.\n */\n _noRefresh?: boolean;\n /**\n * Internal: skip the error enricher for this request. Set on the ext catalog\n * reads the enricher itself performs, so an erroring catalog can never\n * re-enter its own error path.\n */\n _noEnrich?: boolean;\n}\n\n/** Result of a {@link HttpClient.conditionalGet} (ETag revalidation). */\nexport interface ConditionalGetResult<T> {\n /** True when the server answered `304 Not Modified` — keep your cached copy. */\n notModified: boolean;\n /** The parsed body (present on 2xx, absent on 304). */\n data?: T;\n /** The response `ETag`, to send back as `etag` on the next call. */\n etag?: string;\n /** Parsed `Cache-Control: max-age=N`, in seconds. */\n maxAgeSeconds?: number;\n}\n\nexport class HttpClient {\n readonly jar: CookieJar;\n private refresh: (() => Promise<void>) | null = null;\n private refreshInflight: Promise<void> | null = null;\n private enrich: ((error: CasinoSdkError) => Promise<void> | void) | null = null;\n\n constructor(private readonly config: ResolvedConfig) {\n this.jar = config.cookieJar ?? new CookieJar();\n }\n\n /** Wired by the client after the auth module exists (avoids a circular import). */\n setRefreshHandler(fn: () => Promise<void>): void {\n this.refresh = fn;\n }\n\n /**\n * Wired by the client: a best-effort pass over every decoded error before it is\n * thrown (e.g. populating `FlowDelegatedError.continueWith` from the ext\n * catalog). Whatever it does or throws, the original error is what propagates.\n */\n setErrorEnricher(fn: (error: CasinoSdkError) => Promise<void> | void): void {\n this.enrich = fn;\n }\n\n get<T>(path: string, options?: Omit<RequestOptions, \"body\">): Promise<T> {\n return this.request<T>(\"GET\", path, options);\n }\n\n post<T>(path: string, options?: RequestOptions): Promise<T> {\n return this.request<T>(\"POST\", path, options);\n }\n\n put<T>(path: string, options?: RequestOptions): Promise<T> {\n return this.request<T>(\"PUT\", path, options);\n }\n\n patch<T>(path: string, options?: RequestOptions): Promise<T> {\n return this.request<T>(\"PATCH\", path, options);\n }\n\n delete<T>(path: string, options?: RequestOptions): Promise<T> {\n return this.request<T>(\"DELETE\", path, options);\n }\n\n async request<T>(method: Method, path: string, options: RequestOptions = {}): Promise<T> {\n const response = await this.performFetch(method, path, options);\n\n if (!response.ok) {\n const err = await this.toError(response, options);\n if (response.status === 401 && !options._noRefresh) this.config.onAuthError?.(err);\n throw err;\n }\n\n return this.parseBody<T>(response);\n }\n\n /**\n * GET with ETag revalidation: sends `If-None-Match` when `etag` is given and\n * treats `304 Not Modified` as success (empty `data`). Used for endpoints that\n * declare HTTP caching, e.g. the ext plugin catalog.\n */\n async conditionalGet<T>(\n path: string,\n options: { etag?: string; signal?: AbortSignal; _noEnrich?: boolean } = {},\n ): Promise<ConditionalGetResult<T>> {\n const requestOptions: RequestOptions = {\n ...(options.etag !== undefined ? { headers: { \"if-none-match\": options.etag } } : {}),\n ...(options.signal ? { signal: options.signal } : {}),\n ...(options._noEnrich !== undefined ? { _noEnrich: options._noEnrich } : {}),\n };\n const response = await this.performFetch(\"GET\", path, requestOptions);\n\n if (response.status === 304) {\n return { notModified: true, ...readCacheMeta(response) };\n }\n if (!response.ok) {\n const err = await this.toError(response, requestOptions);\n if (response.status === 401) this.config.onAuthError?.(err);\n throw err;\n }\n const data = await this.parseBody<T>(response);\n return {\n notModified: false,\n ...(data !== undefined ? { data } : {}),\n ...readCacheMeta(response),\n };\n }\n\n /** The shared pipeline: headers, CSRF, idempotency, cookies, fetch, 401→refresh→retry. */\n private async performFetch(\n method: Method,\n path: string,\n options: RequestOptions = {},\n ): Promise<Response> {\n const url = this.buildUrl(path, options.query);\n const isMutation = method !== \"GET\";\n\n const headers = new Headers();\n headers.set(HEADER.tenant, this.config.tenantId);\n if (this.config.brandId) headers.set(HEADER.brand, this.config.brandId);\n if (this.config.region) headers.set(HEADER.region, this.config.region);\n headers.set(\"accept\", \"application/json\");\n\n // CSRF double-submit on mutations (unless explicitly disabled).\n const wantCsrf = options.csrf ?? isMutation;\n if (wantCsrf) {\n const token = readCookie(COOKIE.csrf, this.jar);\n if (token) headers.set(HEADER.csrf, token);\n }\n\n // Money ops: auto idempotency key (header + body field).\n let body = options.body;\n if (options.idempotent) {\n const key = options.idempotencyKey ?? generateIdempotencyKey();\n headers.set(HEADER.idempotency, key);\n if (!options.idempotencyHeaderOnly) {\n if (isPlainObject(body)) body = { ...body, idempotencyKey: key };\n else if (body === undefined) body = { idempotencyKey: key };\n }\n }\n\n let serialized: string | FormData | undefined;\n if (isFormData(body)) {\n serialized = body;\n } else if (body !== undefined) {\n headers.set(\"content-type\", \"application/json\");\n serialized = JSON.stringify(body);\n }\n\n if (options.headers) {\n for (const [name, value] of Object.entries(options.headers)) headers.set(name, value);\n }\n\n // Node cookie jar replay (no-op in the browser, which sends cookies itself).\n if (!isBrowser()) {\n const cookie = this.jar.header();\n if (cookie) headers.set(\"cookie\", cookie);\n }\n\n const timeoutMs = options.timeoutMs ?? this.config.timeoutMs;\n const signal = withTimeout(options.signal, timeoutMs);\n\n let response: Response;\n try {\n // Call through a bare reference, not `this.config.fetch(...)`: invoking it\n // as a method sets `this` to `this.config`, and browsers brand-check native\n // `fetch` and throw `TypeError: Illegal invocation` for any non-global\n // receiver. (Node's undici doesn't enforce this, hence green tests/SSR.)\n const doFetch = this.config.fetch;\n response = await doFetch(url, {\n method,\n headers,\n credentials: \"include\",\n ...(serialized !== undefined ? { body: serialized } : {}),\n ...(signal ? { signal } : {}),\n });\n } catch (cause) {\n if ((cause as Error)?.name === \"TimeoutError\") {\n throw new NetworkError(\n \"NETWORK_TIMEOUT\",\n `Request to ${method} ${path} timed out after ${timeoutMs}ms`,\n 0,\n cause,\n );\n }\n throw new NetworkError(\n \"NETWORK_ERROR\",\n `Request to ${method} ${path} failed: ${(cause as Error)?.message ?? \"unknown\"}`,\n 0,\n cause,\n );\n }\n\n if (!isBrowser()) {\n const setCookie = readSetCookie(response.headers);\n warnOnAuthIdentitySwitch(this.jar, setCookie);\n this.jar.ingest(setCookie);\n }\n\n const refresh = this.refresh;\n if (\n response.status === 401 &&\n this.config.autoRefresh &&\n refresh &&\n !options._isRetry &&\n !options._noRefresh\n ) {\n try {\n await this.runRefresh(refresh);\n return this.performFetch(method, path, { ...options, _isRetry: true });\n } catch {\n const err = await this.toError(response, options);\n this.config.onAuthError?.(err);\n throw err;\n }\n }\n\n return response;\n }\n\n /**\n * Run the wired refresh handler with single-flight dedupe (same pattern as the\n * ext catalog): concurrent 401s all await ONE in-flight `POST /auth/player/refresh`.\n * With rotating refresh tokens, parallel refreshes would present an already-rotated\n * token and get the whole session revoked.\n */\n private runRefresh(refresh: () => Promise<void>): Promise<void> {\n if (this.refreshInflight) return this.refreshInflight;\n const running = Promise.resolve()\n .then(refresh)\n .finally(() => {\n if (this.refreshInflight === running) this.refreshInflight = null;\n });\n this.refreshInflight = running;\n return running;\n }\n\n private async parseBody<T>(response: Response): Promise<T> {\n if (response.status === 204) return undefined as T;\n const text = await response.text();\n if (!text) return undefined as T;\n try {\n return JSON.parse(text) as T;\n } catch {\n return text as unknown as T;\n }\n }\n\n private async toError(response: Response, options?: RequestOptions): Promise<CasinoSdkError> {\n let parsed: unknown;\n try {\n parsed = JSON.parse(await response.text());\n } catch {\n parsed = undefined;\n }\n const err = mapEnvelope(response.status, parsed);\n if (this.enrich && !options?._noEnrich) {\n try {\n await this.enrich(err);\n } catch {\n // Best-effort only — never mask the original error.\n }\n }\n return err;\n }\n\n private buildUrl(path: string, query?: RequestOptions[\"query\"]): string {\n const url = new URL(`${this.config.baseUrl}${path.startsWith(\"/\") ? path : `/${path}`}`);\n if (query) {\n for (const [key, value] of Object.entries(query)) {\n if (value === undefined || value === null) continue;\n if (Array.isArray(value)) for (const v of value) url.searchParams.append(key, v);\n else url.searchParams.set(key, String(value));\n }\n }\n return url.toString();\n }\n}\n\n/**\n * Combine the caller's abort signal with the default request timeout. A timeout\n * abort carries name `TimeoutError`, which the fetch catch maps to a\n * `NETWORK_TIMEOUT` NetworkError. On platforms without `AbortSignal.timeout`/`any`\n * (very old runtimes) the caller's signal wins and no default timeout applies.\n */\nfunction withTimeout(caller: AbortSignal | undefined, timeoutMs: number): AbortSignal | undefined {\n if (\n !timeoutMs ||\n timeoutMs <= 0 ||\n typeof AbortSignal === \"undefined\" ||\n typeof AbortSignal.timeout !== \"function\"\n ) {\n return caller;\n }\n const timeout = AbortSignal.timeout(timeoutMs);\n if (!caller) return timeout;\n if (typeof AbortSignal.any === \"function\") return AbortSignal.any([caller, timeout]);\n return caller;\n}\n\nfunction isPlainObject(value: unknown): value is Record<string, unknown> {\n return typeof value === \"object\" && value !== null && !Array.isArray(value) && !isFormData(value);\n}\n\n/** Guarded so SSR/edge targets without a FormData global don't throw. */\nfunction isFormData(value: unknown): value is FormData {\n return typeof FormData !== \"undefined\" && value instanceof FormData;\n}\n\n/** Extract ETag + `Cache-Control: max-age` for {@link HttpClient.conditionalGet}. */\nfunction readCacheMeta(response: Response): { etag?: string; maxAgeSeconds?: number } {\n const etag = response.headers.get(\"etag\");\n const cacheControl = response.headers.get(\"cache-control\");\n const match = cacheControl ? /(?:^|[,\\s])max-age=(\\d+)/i.exec(cacheControl) : null;\n const maxAge = match?.[1] !== undefined ? Number(match[1]) : undefined;\n return {\n ...(etag !== null ? { etag } : {}),\n ...(maxAge !== undefined && Number.isFinite(maxAge) ? { maxAgeSeconds: maxAge } : {}),\n };\n}\n\n/**\n * Dev-mode cross-user bleed detector (server only). When a response is about to\n * write an access token whose `sub` (playerId) differs from the one already in the\n * jar, this jar is being reused across users — the exact Next.js/SSR misuse where a\n * module-scope client replays user A's cookies on user B's request. Rotation of the\n * same user's token keeps `sub` stable, so this never fires on refresh.\n */\nfunction warnOnAuthIdentitySwitch(jar: CookieJar, setCookie: string | string[] | null): void {\n if (typeof process !== \"undefined\" && process.env[\"NODE_ENV\"] === \"production\") return;\n if (!setCookie) return;\n const previous = jar.get(COOKIE.access);\n if (!previous) return;\n const previousSub = jwtSub(previous);\n if (previousSub === undefined) return;\n\n const accessCookie = new RegExp(`(?:^|,\\\\s*)${COOKIE.access}=([^;,\\\\s]+)`);\n const lines = Array.isArray(setCookie) ? setCookie : [setCookie];\n for (const line of lines) {\n const match = accessCookie.exec(line);\n if (!match?.[1]) continue;\n const incomingSub = jwtSub(match[1]);\n if (incomingSub !== undefined && incomingSub !== previousSub) {\n console.warn(\n \"[casino-sdk] SECURITY: this client's cookie jar already holds a session for \" +\n \"another player, and a response just switched it to a different identity. \" +\n \"On the server, never share one client (or one CookieJar) across users' \" +\n \"requests — module-scope clients are browser-only. Scope one per request \" +\n \"with `client.withCookies(new CookieJar())`. See docs/guides/react.md.\",\n );\n return;\n }\n }\n}\n\n/** Best-effort decode of a JWT's `sub` claim (no verification — display/guard only). */\nfunction jwtSub(token: string): string | undefined {\n const payload = token.split(\".\")[1];\n if (!payload) return undefined;\n try {\n const base64 = payload.replace(/-/g, \"+\").replace(/_/g, \"/\");\n const padded = base64 + \"=\".repeat((4 - (base64.length % 4)) % 4);\n const decoded =\n typeof atob === \"function\" ? atob(padded) : Buffer.from(padded, \"base64\").toString(\"binary\");\n const claims = JSON.parse(decoded) as { sub?: unknown };\n return typeof claims.sub === \"string\" ? claims.sub : undefined;\n } catch {\n return undefined;\n }\n}\n\n/** Read `set-cookie` across fetch implementations (undici exposes `getSetCookie`). */\nfunction readSetCookie(headers: Headers): string | string[] | null {\n const getter = (headers as Headers & { getSetCookie?: () => string[] }).getSetCookie;\n if (typeof getter === \"function\") {\n const all = getter.call(headers);\n if (all.length) return all;\n }\n return headers.get(\"set-cookie\");\n}\n","/**\n * Session state held client-side.\n *\n * Several runtime endpoints need the player's id and/or currency that the SDK can\n * supply automatically once the player has authenticated:\n *\n * - cashier `deposits`/`withdrawals` take `playerId` in the body,\n * - `GET /wallet/balance` and `/wallet/transactions` take `playerId` + `currency`,\n * - provider game sessions (`providerSession`) take `playerId` + `currency`.\n *\n * Auth responses (`signup`/`login`/`me`) populate this cache so callers don't have\n * to thread `playerId` through every call. Every method still accepts an explicit\n * override.\n */\nimport type { Player, PlayerProfile } from \"../types/http.js\";\n\nexport interface SessionSnapshot {\n player: Player | null;\n profile: PlayerProfile | null;\n /** Default currency: profile currency, else the client's configured default. */\n currency: string;\n}\n\nexport class Session {\n private player: Player | null = null;\n private profile: PlayerProfile | null = null;\n private readonly fallbackCurrency: string;\n\n constructor(fallbackCurrency: string) {\n this.fallbackCurrency = fallbackCurrency;\n }\n\n setPlayer(player: Player | null, profile?: PlayerProfile | null): void {\n this.player = player;\n if (profile !== undefined) this.profile = profile;\n if (player === null) this.profile = null;\n }\n\n clear(): void {\n this.player = null;\n this.profile = null;\n }\n\n get playerId(): string | undefined {\n return this.player?.id;\n }\n\n /** Resolve a playerId, preferring an explicit override; throws if neither exists. */\n requirePlayerId(override?: string): string {\n const id = override ?? this.player?.id;\n if (!id) {\n throw new Error(\n \"No authenticated player. Call `auth.login()`/`auth.me()` first, or pass an explicit playerId.\",\n );\n }\n return id;\n }\n\n /** Resolve a currency: override → profile → configured default. */\n resolveCurrency(override?: string): string {\n return (override ?? this.profile?.currency ?? this.fallbackCurrency).toUpperCase();\n }\n\n snapshot(): SessionSnapshot {\n return {\n player: this.player,\n profile: this.profile,\n currency: this.resolveCurrency(),\n };\n }\n}\n","/**\n * `sdk.affiliate` — affiliate click tracking.\n *\n * Maps to the runtime's one public affiliate endpoint, `POST /affiliate/track/click`.\n * Call it on the landing page; anything not captured at click time (gclid/fbclid/…)\n * is unrecoverable. The endpoint is rate-limited per IP (`RateLimitError` on 429).\n */\nimport type { HttpClient } from \"../core/http.js\";\nimport type { TrackClickInput, TrackClickResult } from \"../types/http.js\";\n\nexport class AffiliateModule {\n constructor(private readonly http: HttpClient) {}\n\n /**\n * Record an affiliate click. Returns the `clickId` join key — persist it\n * (cookie/localStorage) and carry it into signup so the registration can be\n * attributed to the click.\n */\n trackClick(input: TrackClickInput): Promise<TrackClickResult> {\n return this.http.post<TrackClickResult>(\"/affiliate/track/click\", { body: input });\n }\n}\n","/**\n * `sdk.auth` — signup, login, logout, refresh, me, social OAuth, and sessions\n * (\"your devices\").\n *\n * Maps to the runtime's `/auth/player/*` routes. Auth is cookie-based: the runtime\n * sets `cwe_access_token` / `cwe_refresh_token` (HttpOnly) and `cwe_csrf` (readable);\n * the SDK's HTTP layer carries the session and CSRF automatically. After a\n * successful auth call the {@link Session} cache is populated so wallet/cashier/launch\n * calls can auto-fill `playerId` + `currency`.\n */\nimport type { HttpClient } from \"../core/http.js\";\nimport type { Session } from \"../core/session.js\";\nimport type {\n AuthSession,\n LoginHistoryPage,\n LoginInput,\n MeResponse,\n SafeSession,\n SessionHistoryPage,\n SessionHistoryQuery,\n SignupInput,\n SocialAccount,\n SocialProvider,\n VerificationRequestResult,\n} from \"../types/http.js\";\n\nexport interface SocialStartOptions {\n /**\n * Where the runtime should send the player back after the provider flow.\n * Use `https:` URLs only — a non-https `redirectUri` (or worse, a scheme like\n * `javascript:`) must never reach a browser navigation. The runtime validates\n * it against the tenant's allowlist; keep your allowlist https-only too.\n */\n redirectUri?: string;\n}\n\nexport class AuthModule {\n constructor(\n private readonly http: HttpClient,\n private readonly session: Session,\n private readonly baseUrl: string,\n ) {}\n\n /** Create an account and start a session. */\n async signup(input: SignupInput): Promise<AuthSession> {\n const res = await this.http.post<AuthSession>(\"/auth/player/signup\", { body: input });\n this.session.setPlayer(res.player);\n return res;\n }\n\n /** Log in with email + password and start a session. */\n async login(input: LoginInput): Promise<AuthSession> {\n const res = await this.http.post<AuthSession>(\"/auth/player/login\", { body: input });\n this.session.setPlayer(res.player);\n return res;\n }\n\n /** End the session and clear the cached player. */\n async logout(): Promise<void> {\n try {\n await this.http.post<{ success: true }>(\"/auth/player/logout\");\n } finally {\n this.session.clear();\n this.http.jar.clear();\n }\n }\n\n /**\n * Rotate the session using the refresh cookie. Called automatically by the HTTP\n * layer on a 401; you rarely call it directly.\n *\n * The request is marked `_noRefresh`: a 401 here (fully logged out) must throw\n * immediately instead of re-entering the 401 → refresh path it is part of.\n */\n async refresh(): Promise<AuthSession> {\n const res = await this.http.post<AuthSession>(\"/auth/player/refresh\", { _noRefresh: true });\n this.session.setPlayer(res.player);\n return res;\n }\n\n /** Current player + profile. Refreshes the session cache (incl. default currency). */\n async me(): Promise<MeResponse> {\n const res = await this.http.get<MeResponse>(\"/auth/player/me\");\n this.session.setPlayer(res.player, res.profile);\n return res;\n }\n\n readonly social = {\n /**\n * Build the URL that begins a social login. Send the browser here (full\n * navigation, not fetch) so the runtime can redirect to the provider.\n */\n startUrl: (provider: SocialProvider, options?: SocialStartOptions): string => {\n const url = new URL(`${this.baseUrl}/auth/player/social/${provider}/start`);\n if (options?.redirectUri) url.searchParams.set(\"redirect_uri\", options.redirectUri);\n return url.toString();\n },\n\n /**\n * Complete the OAuth callback (provider → your app) by exchanging `code`+`state`.\n * Use this if your app handles the callback route itself; otherwise the runtime\n * handles `/auth/player/social/:provider/callback` directly.\n */\n callback: async (\n provider: SocialProvider,\n params: { code?: string; state?: string; hash?: string },\n ): Promise<AuthSession> => {\n const res = await this.http.get<AuthSession>(`/auth/player/social/${provider}/callback`, {\n query: params,\n csrf: false,\n });\n this.session.setPlayer(res.player);\n return res;\n },\n\n /** Link a social account to the logged-in player. */\n link: (provider: SocialProvider, code: string): Promise<{ account: SocialAccount }> =>\n this.http.post(`/auth/player/social/${provider}/link`, { body: { code } }),\n\n /** Unlink a previously-linked social account. */\n unlink: (provider: SocialProvider, socialAccountId: string): Promise<{ success: true }> =>\n this.http.delete(`/auth/player/social/${provider}/${socialAccountId}`),\n };\n\n /**\n * Session management — the \"your devices\" surface. The runtime scopes every call\n * to the authenticated player (the id comes from the verified principal, never a\n * path), so a player can only see and revoke their own sessions.\n */\n readonly sessions = {\n /** Active sessions — the player's currently signed-in devices. */\n list: async (): Promise<SafeSession[]> => {\n const res = await this.http.get<{ sessions: SafeSession[] }>(\"/auth/player/sessions\");\n return res.sessions;\n },\n\n /**\n * Full session history — active plus revoked/expired, newest first. Paginated:\n * `limit` 1–100 (default 50), `offset` ≥ 0; `pagination.hasMore` says whether\n * another page exists.\n */\n history: async (query: SessionHistoryQuery = {}): Promise<SessionHistoryPage> =>\n this.http.get<SessionHistoryPage>(\"/auth/player/sessions/history\", {\n query: { limit: query.limit, offset: query.offset },\n }),\n\n /** Disconnect (revoke) one of the player's own sessions. */\n revoke: (sessionId: string): Promise<{ success: true }> =>\n this.http.delete(`/auth/player/sessions/${encodeURIComponent(sessionId)}`),\n\n /**\n * Revoke every session. By default the current one survives (\"sign out\n * everywhere else\"); pass `{ exceptCurrent: false }` to revoke this device\n * too (the runtime then also clears the auth cookies).\n */\n revokeAll: (options?: { exceptCurrent?: boolean }): Promise<{ revoked: number }> =>\n // The runtime parses this with `z.coerce.boolean()`, where ANY non-empty\n // string (including \"false\") coerces to true — only the empty string\n // reads as false. Omit for the default (true), send \"\" for false.\n this.http.delete(\"/auth/player/sessions\", {\n query: { exceptCurrent: options?.exceptCurrent === false ? \"\" : undefined },\n }),\n };\n\n /**\n * Login history (successful and failed attempts, newest first). Paginated:\n * `limit` 1–100 (default 50), `offset` ≥ 0.\n */\n loginHistory(query: SessionHistoryQuery = {}): Promise<LoginHistoryPage> {\n return this.http.get<LoginHistoryPage>(\"/auth/player/login-history\", {\n query: { limit: query.limit, offset: query.offset },\n });\n }\n\n /** Password management. The reset flow is anonymous; `change` needs a session. */\n readonly password = {\n /**\n * Change the password (requires the current one). The runtime revokes every\n * OTHER session; this one survives. Rate-limited 10/h per player.\n */\n change: (input: { currentPassword: string; newPassword: string }): Promise<{ success: true }> =>\n this.http.post(\"/auth/player/password/change\", { body: input }),\n\n /**\n * Request a password-reset email. Always resolves `{ success: true }`\n * (anti-enumeration) — even for unknown emails or while rate-limited.\n */\n requestReset: (email: string): Promise<{ success: true }> =>\n this.http.post(\"/auth/player/password/reset/request\", { body: { email } }),\n\n /**\n * Complete a reset with the emailed token. Revokes ALL sessions — the\n * player must log in again.\n */\n confirmReset: (input: { token: string; newPassword: string }): Promise<{ success: true }> =>\n this.http.post(\"/auth/player/password/reset/confirm\", { body: input }),\n };\n\n /**\n * Email/phone verification. `request` sends the token/OTP (429 with\n * `details.resendIn` inside the cooldown); `confirm` verifies it.\n */\n readonly verification = {\n email: {\n request: (): Promise<VerificationRequestResult> =>\n this.http.post(\"/auth/player/email/verification/request\"),\n\n /** Confirm with the emailed link `token` XOR the 6-digit `code` (code needs a session). */\n confirm: (input: { token?: string; code?: string }): Promise<{ verified: true }> =>\n this.http.post(\"/auth/player/email/verification/confirm\", { body: input }),\n },\n phone: {\n /** Pass `phone` to verify a NEW number (applied on confirm). */\n request: (phone?: string): Promise<VerificationRequestResult> =>\n this.http.post(\"/auth/player/phone/verification/request\", {\n body: phone !== undefined ? { phone } : {},\n }),\n\n confirm: (code: string): Promise<{ verified: true }> =>\n this.http.post(\"/auth/player/phone/verification/confirm\", { body: { code } }),\n },\n };\n}\n","/**\n * Money.\n *\n * The runtime keeps money to **4 decimal places** (`@cwe/shared/money.ts`, `SCALE=4`).\n * Three encodings appear on the wire and the SDK reconciles them to ONE:\n *\n * - REST **responses** carry 4-dp **decimal strings** — `\"12.5000\"`.\n * - REST **request bodies** take plain JSON **numbers** in major units — `12.5`\n * (the runtime's Zod schemas are `z.number()`; it normalizes to 4-dp internally).\n * - Realtime carries the same value as a **scale-4 integer** — `125000`.\n *\n * The SDK's public surface always uses {@link MinorUnits} (the scale-4 integer),\n * matching `docs/realtime-sdk-contract.ts`. Convert at the REST boundary with\n * {@link decimalToMinor} (read) / {@link minorToAmount} (write), and display with\n * {@link formatMoney}. Never do money math beyond display.\n */\n\n/** Integer minor units at scale 4 (i.e. major × 10_000). `125000` ⇒ `12.5000`. */\nexport type MinorUnits = number;\n\n/** Decimal places the runtime stores. Do not change without the runtime changing. */\nexport const MONEY_SCALE = 4;\nconst FACTOR = 10 ** MONEY_SCALE;\n\n/**\n * Convert a runtime decimal string (or number) to scale-4 minor units.\n * `\"12.5000\"` ⇒ `125000`. Throws on non-numeric input.\n */\nexport function decimalToMinor(value: string | number): MinorUnits {\n const n = typeof value === \"number\" ? value : Number(value);\n if (!Number.isFinite(n)) {\n throw new TypeError(`decimalToMinor: not a finite number: ${String(value)}`);\n }\n return Math.round(n * FACTOR);\n}\n\n/**\n * Parse a runtime **minor-unit integer string** (`\"1000000\"` ⇒ `1000000`) — the\n * encoding the player history surfaces (`/player/cashier/*`, `/player/bets`,\n * `/player/game-sessions`, `/player/limits`) use, unlike the 4-dp decimal\n * strings elsewhere (use {@link decimalToMinor} for those).\n *\n * Strict by design: only canonical digit strings (`/^-?\\d+$/`) within the safe\n * integer range are accepted. A 4-dp decimal that happens to be integral\n * (`\"50.0000\"`) is a WRONG-SURFACE value — accepting it would misread €50.00 as\n * 50 minor units (a 10 000× error) — and an over-`MAX_SAFE_INTEGER` string would\n * silently lose minor units. Both throw so contract drift is loud.\n */\nexport function minorStringToMinor(value: string): MinorUnits {\n if (!/^-?\\d+$/.test(value)) {\n throw new TypeError(`minorStringToMinor: not a minor-unit integer string: ${String(value)}`);\n }\n const n = Number(value);\n if (!Number.isSafeInteger(n)) {\n throw new TypeError(\n `minorStringToMinor: value exceeds the safe integer range: ${String(value)}`,\n );\n }\n return n;\n}\n\n/**\n * Convert scale-4 minor units to the plain major-unit **number** the runtime's\n * write schemas expect (`amount: z.number()`). `125000` ⇒ `12.5`. Safe for the\n * 4-dp range: a scale-4 integer divided by 10⁴ round-trips exactly through JSON.\n */\nexport function minorToAmount(minor: MinorUnits): number {\n if (!Number.isInteger(minor)) {\n throw new TypeError(`minorToAmount: expected an integer, got ${String(minor)}`);\n }\n return minor / FACTOR;\n}\n\n/**\n * Convert scale-4 minor units back to a canonical 4-dp decimal string\n * (`125000` ⇒ `\"12.5000\"`) — the format REST **responses** use. Kept public for\n * symmetry/display; note the runtime's write paths take numbers, not strings\n * (use {@link minorToAmount} there).\n */\nexport function minorToDecimal(minor: MinorUnits): string {\n if (!Number.isInteger(minor)) {\n throw new TypeError(`minorToDecimal: expected an integer, got ${String(minor)}`);\n }\n const negative = minor < 0;\n const abs = Math.abs(minor);\n const whole = Math.trunc(abs / FACTOR);\n const frac = String(abs % FACTOR).padStart(MONEY_SCALE, \"0\");\n return `${negative ? \"-\" : \"\"}${whole}.${frac}`;\n}\n\n/**\n * Format minor units for display in the currency's natural precision.\n * `formatMoney(125000, \"EUR\")` ⇒ `\"€12.50\"` (en locale). Uses `Intl.NumberFormat`;\n * pass `locale` to localize, or `{ minimumFractionDigits }` to show all 4 dp.\n */\nexport function formatMoney(\n minor: MinorUnits,\n currency: string,\n options?: { locale?: string; minimumFractionDigits?: number; maximumFractionDigits?: number },\n): string {\n const major = minor / FACTOR;\n return new Intl.NumberFormat(options?.locale, {\n style: \"currency\",\n currency,\n ...(options?.minimumFractionDigits !== undefined\n ? { minimumFractionDigits: options.minimumFractionDigits }\n : {}),\n ...(options?.maximumFractionDigits !== undefined\n ? { maximumFractionDigits: options.maximumFractionDigits }\n : {}),\n }).format(major);\n}\n","/**\n * `sdk.cashier` — deposits & withdrawals.\n *\n * Maps to `POST /cashier/deposits` and `POST /cashier/withdrawals`. These are money\n * operations: the HTTP layer auto-generates an idempotency key (body + header), and\n * the SDK auto-fills `playerId` + `currency` from the session. Amounts are passed in\n * minor units and converted to the plain major-unit number the runtime's write\n * schemas require; any `balances` in the response (4-dp decimal strings) are\n * converted back to minor units.\n */\nimport type { HttpClient } from \"../core/http.js\";\nimport type { Session } from \"../core/session.js\";\nimport { decimalToMinor, minorStringToMinor, minorToAmount } from \"../core/money.js\";\nimport type {\n DepositDetail,\n DepositHistoryPage,\n DepositHistoryQuery,\n DepositInput,\n DepositResult,\n DepositSummary,\n PaymentMethod,\n WalletBuckets,\n WithdrawalDetail,\n WithdrawalHistoryPage,\n WithdrawalHistoryQuery,\n WithdrawalInput,\n WithdrawalResult,\n WithdrawalSummary,\n} from \"../types/http.js\";\n\ntype RawBuckets = { cash: string; bonus: string; locked: string };\ntype RawDepositResult = Omit<DepositResult, \"balances\"> & { balances?: RawBuckets };\ntype RawWithdrawalResult = Omit<WithdrawalResult, \"balances\"> & { balances?: RawBuckets };\n\n/** Raw history shapes (minor-unit integer strings) before conversion. */\ntype RawDepositSummary = Omit<DepositSummary, \"amount\"> & { amountMinor: string };\ntype RawDepositDetail = Omit<DepositDetail, \"amount\"> & { amountMinor: string };\ntype RawWithdrawalSummary = Omit<WithdrawalSummary, \"amount\"> & { amountMinor: string };\ntype RawWithdrawalDetail = Omit<WithdrawalDetail, \"amount\"> & { amountMinor: string };\ntype RawPaymentMethod = Omit<PaymentMethod, \"limits\"> & {\n limits: { minMinor: string; maxMinor: string; currency: string };\n};\n\nexport class CashierModule {\n constructor(\n private readonly http: HttpClient,\n private readonly session: Session,\n ) {}\n\n /**\n * Initiate a deposit. Follow `result.nextAction` for any PSP redirect/3DS step;\n * a `result.challenge` means a gate plugin requires a step-up (e.g. KYC) first.\n */\n async deposit(input: DepositInput): Promise<DepositResult> {\n const playerId = this.session.requirePlayerId(input.playerId);\n const currency = this.session.resolveCurrency(input.currency);\n const raw = await this.http.post<RawDepositResult>(\"/cashier/deposits\", {\n idempotent: true,\n ...(input.idempotencyKey ? { idempotencyKey: input.idempotencyKey } : {}),\n body: {\n playerId,\n currency,\n amount: minorToAmount(input.amount),\n providerKey: input.providerKey,\n methodKey: input.methodKey,\n instrumentId: input.instrumentId,\n baseCurrency: input.baseCurrency,\n returnUrl: input.returnUrl,\n metadata: input.metadata,\n },\n });\n return withBuckets(raw);\n }\n\n /** Request a withdrawal. May land in `pending_review` depending on risk rules. */\n async withdraw(input: WithdrawalInput): Promise<WithdrawalResult> {\n const playerId = this.session.requirePlayerId(input.playerId);\n const currency = this.session.resolveCurrency(input.currency);\n const raw = await this.http.post<RawWithdrawalResult>(\"/cashier/withdrawals\", {\n idempotent: true,\n ...(input.idempotencyKey ? { idempotencyKey: input.idempotencyKey } : {}),\n body: {\n playerId,\n currency,\n amount: minorToAmount(input.amount),\n providerKey: input.providerKey,\n methodKey: input.methodKey,\n instrumentId: input.instrumentId,\n baseCurrency: input.baseCurrency,\n metadata: input.metadata,\n },\n });\n return withBuckets(raw);\n }\n\n /**\n * The payment methods available to the player (`GET /player/cashier/methods`),\n * sorted for display; `limits` in minor units. Cached 60s server-side.\n */\n async listMethods(options: { currency?: string } = {}): Promise<PaymentMethod[]> {\n const res = await this.http.get<{ methods: RawPaymentMethod[] }>(\"/player/cashier/methods\", {\n query: { currency: options.currency },\n });\n return res.methods.map(toMethod);\n }\n\n /** Deposit history, newest first, amounts in minor units. */\n async deposits(query: DepositHistoryQuery = {}): Promise<DepositHistoryPage> {\n const res = await this.http.get<{\n deposits: RawDepositSummary[];\n pagination: DepositHistoryPage[\"pagination\"];\n }>(\"/player/cashier/deposits\", {\n query: {\n status: query.status,\n providerKey: query.providerKey,\n ...rangeQuery(query),\n },\n });\n return { deposits: res.deposits.map(toDeposit), pagination: res.pagination };\n }\n\n /**\n * One deposit with its wallet linkage and any pending `nextAction`\n * (`GET /player/cashier/deposits/:id`). Realtime `wallet.deposit` remains the\n * push channel; this is the authoritative re-read.\n */\n async depositStatus(depositId: string): Promise<DepositDetail> {\n const raw = await this.http.get<RawDepositDetail>(\n `/player/cashier/deposits/${encodeURIComponent(depositId)}`,\n );\n return toDeposit(raw);\n }\n\n /** Withdrawal history, newest first, amounts in minor units. */\n async withdrawals(query: WithdrawalHistoryQuery = {}): Promise<WithdrawalHistoryPage> {\n const res = await this.http.get<{\n withdrawals: RawWithdrawalSummary[];\n pagination: WithdrawalHistoryPage[\"pagination\"];\n }>(\"/player/cashier/withdrawals\", {\n query: { status: query.status, ...rangeQuery(query) },\n });\n return { withdrawals: res.withdrawals.map(toWithdrawal), pagination: res.pagination };\n }\n\n /** One withdrawal with its reserve/settle/release wallet-transaction legs. */\n async withdrawalStatus(withdrawalId: string): Promise<WithdrawalDetail> {\n const raw = await this.http.get<RawWithdrawalDetail>(\n `/player/cashier/withdrawals/${encodeURIComponent(withdrawalId)}`,\n );\n return toWithdrawal(raw);\n }\n\n /**\n * Cancel a withdrawal that hasn't been picked up yet (`requested`/\n * `pending_review` only — anything later is a `ConflictError` with code\n * `INVALID_WITHDRAWAL_STATE`). Releases the reserved funds; idempotent\n * (a replay returns `idempotent: true` without balances).\n */\n async cancelWithdrawal(withdrawalId: string): Promise<WithdrawalResult> {\n const raw = await this.http.post<RawWithdrawalResult>(\n `/player/cashier/withdrawals/${encodeURIComponent(withdrawalId)}/cancel`,\n );\n return withBuckets(raw);\n }\n}\n\nfunction rangeQuery(query: {\n from?: string | Date;\n to?: string | Date;\n limit?: number;\n offset?: number;\n}): Record<string, string | number | undefined> {\n return {\n from: toIso(query.from),\n to: toIso(query.to),\n limit: query.limit,\n offset: query.offset,\n };\n}\n\nfunction toIso(value: string | Date | undefined): string | undefined {\n return value instanceof Date ? value.toISOString() : value;\n}\n\nfunction toDeposit<T extends { amountMinor: string }>(\n raw: T,\n): Omit<T, \"amountMinor\"> & { amount: number } {\n const { amountMinor, ...rest } = raw;\n return { ...rest, amount: minorStringToMinor(amountMinor) };\n}\n\nconst toWithdrawal = toDeposit;\n\nfunction toMethod(raw: RawPaymentMethod): PaymentMethod {\n const { limits, ...rest } = raw;\n return {\n ...rest,\n limits: {\n min: minorStringToMinor(limits.minMinor),\n max: minorStringToMinor(limits.maxMinor),\n currency: limits.currency,\n },\n };\n}\n\nfunction toBuckets(raw: RawBuckets): WalletBuckets {\n return {\n cash: decimalToMinor(raw.cash),\n bonus: decimalToMinor(raw.bonus),\n locked: decimalToMinor(raw.locked),\n };\n}\n\nfunction withBuckets<T extends { balances?: RawBuckets }>(\n raw: T,\n): Omit<T, \"balances\"> & { balances?: WalletBuckets } {\n const { balances, ...rest } = raw;\n return balances ? { ...rest, balances: toBuckets(balances) } : { ...rest };\n}\n","/**\n * `sdk.wallet` — balance buckets, transaction history, and the append-only ledger.\n *\n * Maps to `GET /wallet/balance`, `GET /wallet/transactions`, and `GET /wallet/ledger`.\n * All take the player's id (auto-filled from the session); balance also takes a\n * currency (defaults to the profile/config currency). All money is converted to\n * scale-4 minor units here.\n */\nimport type { HttpClient } from \"../core/http.js\";\nimport type { Session } from \"../core/session.js\";\nimport { decimalToMinor } from \"../core/money.js\";\nimport { NotImplementedError } from \"../core/errors.js\";\nimport type {\n BalanceResponse,\n LedgerEntry,\n LedgerQuery,\n Paginated,\n TransactionsQuery,\n WalletTransaction,\n} from \"../types/http.js\";\n\n/** Raw runtime shapes (decimal strings) before minor-unit conversion. */\ninterface RawBalance {\n playerId: string;\n currency: string;\n cashBalance: string;\n bonusBalance: string;\n lockedBalance: string;\n total: string;\n status: \"active\" | \"frozen\" | \"closed\";\n walletId: string | null;\n}\n\ninterface RawTransaction {\n id: string;\n walletId: string;\n playerId: string;\n externalTransactionId: string | null;\n type: WalletTransaction[\"type\"];\n amount: string;\n currency: string;\n source: string;\n gameId: string | null;\n idempotencyKey: string;\n metadata: Record<string, unknown> | null;\n status: WalletTransaction[\"status\"];\n createdAt: string;\n updatedAt: string;\n}\n\ninterface RawLedgerEntry {\n id: string;\n walletId: string;\n transactionId: string;\n playerId: string;\n walletType: LedgerEntry[\"walletType\"];\n direction: LedgerEntry[\"direction\"];\n amount: string;\n currency: string;\n balanceBefore: string;\n balanceAfter: string;\n createdAt: string;\n}\n\nexport class WalletModule {\n constructor(\n private readonly http: HttpClient,\n private readonly session: Session,\n ) {}\n\n /** Current balance across the cash/bonus/locked buckets, in minor units. */\n async getBalance(options?: { playerId?: string; currency?: string }): Promise<BalanceResponse> {\n const playerId = this.session.requirePlayerId(options?.playerId);\n const currency = this.session.resolveCurrency(options?.currency);\n const raw = await this.http.get<RawBalance>(\"/wallet/balance\", {\n query: { playerId, currency },\n });\n return {\n playerId: raw.playerId,\n currency: raw.currency,\n cash: decimalToMinor(raw.cashBalance),\n bonus: decimalToMinor(raw.bonusBalance),\n locked: decimalToMinor(raw.lockedBalance),\n total: decimalToMinor(raw.total),\n status: raw.status,\n walletId: raw.walletId,\n };\n }\n\n /** Paginated transaction history (newest first), amounts in minor units. */\n async transactions(query: TransactionsQuery = {}): Promise<Paginated<WalletTransaction>> {\n const playerId = this.session.requirePlayerId(query.playerId);\n const raw = await this.http.get<Paginated<RawTransaction>>(\"/wallet/transactions\", {\n query: {\n playerId,\n walletId: query.walletId,\n type: query.type,\n status: query.status,\n currency: query.currency,\n limit: query.limit,\n offset: query.offset,\n },\n });\n return { ...raw, rows: raw.rows.map(toTransaction) };\n }\n\n /**\n * Paginated append-only ledger (newest first) — one row per bucket movement,\n * with before/after balance snapshots, amounts in minor units. Filter by\n * `transactionId` to see the legs of a single transaction.\n */\n async ledger(query: LedgerQuery = {}): Promise<Paginated<LedgerEntry>> {\n const playerId = this.session.requirePlayerId(query.playerId);\n const raw = await this.http.get<Paginated<RawLedgerEntry>>(\"/wallet/ledger\", {\n query: {\n playerId,\n walletId: query.walletId,\n walletType: query.walletType,\n transactionId: query.transactionId,\n limit: query.limit,\n offset: query.offset,\n },\n });\n return { ...raw, rows: raw.rows.map(toLedgerEntry) };\n }\n\n /**\n * Fetch a single transaction by id.\n *\n * @remarks Not available to players yet — the runtime route\n * `GET /wallet/transactions/:id` requires staff permission. Tracked on the\n * roadmap; use {@link transactions} to page history in the meantime.\n */\n getTransaction(_id: string): Promise<WalletTransaction> {\n return Promise.reject(\n new NotImplementedError(\n \"wallet.getTransaction: runtime exposes single-transaction reads to staff only. \" +\n \"Use wallet.transactions() until a player-facing endpoint ships.\",\n ),\n );\n }\n}\n\nfunction toTransaction(raw: RawTransaction): WalletTransaction {\n return { ...raw, amount: decimalToMinor(raw.amount) };\n}\n\nfunction toLedgerEntry(raw: RawLedgerEntry): LedgerEntry {\n return {\n ...raw,\n amount: decimalToMinor(raw.amount),\n balanceBefore: decimalToMinor(raw.balanceBefore),\n balanceAfter: decimalToMinor(raw.balanceAfter),\n };\n}\n","/**\n * `sdk.catalog` — lobby, search, categories tree, providers, game detail,\n * suggested, and trending. All endpoints are public and geo/currency-aware via\n * query params (`country`, `currency`, `locale`, `device`).\n *\n * Maps to the runtime's `/catalog/*` routes.\n */\nimport type { HttpClient } from \"../core/http.js\";\nimport type {\n CategoryNode,\n Game,\n GamePage,\n GeoQuery,\n LobbyQuery,\n Provider,\n SearchQuery,\n} from \"../types/http.js\";\n\nexport class CatalogModule {\n constructor(private readonly http: HttpClient) {}\n\n /** The default lobby, filtered by geo/currency/device. */\n lobby(query: LobbyQuery = {}): Promise<GamePage> {\n return this.http.get<GamePage>(\"/catalog/lobby\", { query: { ...query } });\n }\n\n /** Search/filter games by text, provider, category, and feature flags. */\n searchGames(query: SearchQuery = {}): Promise<GamePage> {\n return this.http.get<GamePage>(\"/catalog/games\", {\n query: {\n country: query.country,\n subdivision: query.subdivision,\n currency: query.currency,\n locale: query.locale,\n device: query.device,\n limit: query.limit,\n offset: query.offset,\n q: query.q,\n provider: query.provider,\n category: query.category,\n hasDemo: boolParam(query.hasDemo),\n isVirtual: boolParam(query.isVirtual),\n bonusBuy: boolParam(query.bonusBuy),\n megaways: boolParam(query.megaways),\n },\n });\n }\n\n /** Trending games over a window (`\"all\"` by default), most popular first. */\n async trending(query: GeoQuery & { window?: string; limit?: number } = {}): Promise<Game[]> {\n const res = await this.http.get<{ games: Game[] }>(\"/catalog/trending\", {\n query: { ...query },\n });\n return res.games;\n }\n\n /** The localized category tree (recursive `children`). */\n async categories(options?: { locale?: string }): Promise<CategoryNode[]> {\n const res = await this.http.get<{ categories: CategoryNode[] }>(\"/catalog/categories\", {\n query: { locale: options?.locale },\n });\n return res.categories;\n }\n\n /** All enabled providers for this brand/region. */\n async providers(query: GeoQuery = {}): Promise<Provider[]> {\n const res = await this.http.get<{ providers: Provider[] }>(\"/catalog/providers\", {\n query: { ...query },\n });\n return res.providers;\n }\n\n /** A single game by internal id or slug. */\n game(idOrSlug: string, query: GeoQuery = {}): Promise<Game> {\n return this.http.get<Game>(`/catalog/games/${encodeURIComponent(idOrSlug)}`, {\n query: { ...query },\n });\n }\n\n /**\n * Games suggested alongside the given game. Takes the internal game **id** only\n * (an unknown id — including a slug — yields an empty list, not a 404).\n */\n async suggested(gameId: string, query: GeoQuery & { limit?: number } = {}): Promise<Game[]> {\n const res = await this.http.get<{ games: Game[] }>(\n `/catalog/games/${encodeURIComponent(gameId)}/suggested`,\n { query: { ...query } },\n );\n return res.games;\n }\n}\n\n/** The runtime reads feature flags as `\"1\"`/`\"0\"` strings. */\nfunction boolParam(value: boolean | undefined): string | undefined {\n if (value === undefined) return undefined;\n return value ? \"1\" : \"0\";\n}\n","/**\n * Minimal JSON Schema (draft-07 subset) checker: `type`, `required`, `enum` —\n * nothing more, by design. The SDK uses it for **dev-mode advisory warnings**\n * on plugin-action inputs; the server's Zod validation stays authoritative and\n * the SDK never rejects client-side on a schema mismatch. The playground reuses\n * it to derive form field types.\n */\n\n/** One advisory mismatch found by {@link checkJsonSchema}. */\nexport interface JsonSchemaProblem {\n /** JSON-pointer-ish location, `\"\"` for the root value. */\n path: string;\n message: string;\n}\n\ninterface SchemaNode {\n type?: string | string[];\n required?: string[];\n enum?: unknown[];\n properties?: Record<string, unknown>;\n items?: unknown;\n}\n\n/**\n * Best-effort check of `value` against `schema`. Returns problems (empty when the\n * value passes or the schema is not an object). Only `type`, `required`, and\n * `enum` are enforced, recursing through `properties` and single-schema `items`.\n */\nexport function checkJsonSchema(value: unknown, schema: unknown, path = \"\"): JsonSchemaProblem[] {\n if (typeof schema !== \"object\" || schema === null) return [];\n const node = schema as SchemaNode;\n const problems: JsonSchemaProblem[] = [];\n\n if (node.type !== undefined) {\n const allowed = Array.isArray(node.type) ? node.type : [node.type];\n if (!allowed.some((t) => matchesType(value, t))) {\n problems.push({ path, message: `expected ${allowed.join(\" | \")}, got ${typeName(value)}` });\n return problems; // wrong shape — deeper checks would only be noise\n }\n }\n\n if (node.enum !== undefined && !node.enum.some((candidate) => sameJson(candidate, value))) {\n problems.push({ path, message: `expected one of ${JSON.stringify(node.enum)}` });\n }\n\n if (isRecord(value)) {\n for (const key of node.required ?? []) {\n if (!(key in value) || value[key] === undefined) {\n problems.push({ path: joinPath(path, key), message: \"required property is missing\" });\n }\n }\n if (node.properties) {\n for (const [key, propSchema] of Object.entries(node.properties)) {\n if (key in value && value[key] !== undefined) {\n problems.push(...checkJsonSchema(value[key], propSchema, joinPath(path, key)));\n }\n }\n }\n }\n\n if (Array.isArray(value) && node.items !== undefined && !Array.isArray(node.items)) {\n value.forEach((item, i) => {\n problems.push(...checkJsonSchema(item, node.items, `${path}[${i}]`));\n });\n }\n\n return problems;\n}\n\nfunction matchesType(value: unknown, type: string): boolean {\n switch (type) {\n case \"object\":\n return isRecord(value);\n case \"array\":\n return Array.isArray(value);\n case \"string\":\n return typeof value === \"string\";\n case \"number\":\n return typeof value === \"number\" && Number.isFinite(value);\n case \"integer\":\n return typeof value === \"number\" && Number.isInteger(value);\n case \"boolean\":\n return typeof value === \"boolean\";\n case \"null\":\n return value === null;\n default:\n return true; // unknown type keyword — not ours to judge\n }\n}\n\nfunction sameJson(a: unknown, b: unknown): boolean {\n if (Object.is(a, b)) return true;\n if (typeof a !== \"object\" || typeof b !== \"object\" || a === null || b === null) return false;\n try {\n return JSON.stringify(a) === JSON.stringify(b);\n } catch {\n return false;\n }\n}\n\nfunction typeName(value: unknown): string {\n if (value === null) return \"null\";\n if (Array.isArray(value)) return \"array\";\n return typeof value;\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\nfunction joinPath(path: string, key: string): string {\n return path ? `${path}.${key}` : key;\n}\n","/**\n * Build-environment detection for dev-only diagnostics (schema warnings,\n * deprecation notices, hook misuse guards).\n */\n\n/**\n * True outside production builds (`process.env.NODE_ENV !== \"production\"`).\n * Bundlers statically replace the env read; where no `process` global exists we\n * err on the dev side, matching React's convention.\n */\nexport function isDevEnvironment(): boolean {\n try {\n return typeof process === \"undefined\" || process.env.NODE_ENV !== \"production\";\n } catch {\n return true;\n }\n}\n","/**\n * `sdk.ext` — plugin actions: player-facing features that tenant-enabled plugins\n * expose on the casino API.\n *\n * ```ts\n * // Discovery\n * const catalog = await sdk.ext.catalog();\n * const cashback = await sdk.ext.plugin(\"cashback\");\n *\n * // Generic — works for any enabled plugin, no build-time knowledge:\n * const summary = await sdk.ext(\"cashback\").call(\"getSummary\");\n * await sdk.ext(\"cashback\").call(\"claim\", { periodId });\n *\n * // Typed — when the plugin's generated client package is installed, the\n * // ExtRegistry augmentation narrows call() keys/input/result (see types/ext.ts).\n * ```\n *\n * `call()` resolves the action descriptor from the cached catalog\n * (`GET /api/ext/_catalog`, ETag-revalidated, `Cache-Control: max-age` honored),\n * routes input per the action's method (GET/DELETE ⇒ query, POST/PUT ⇒ JSON body,\n * `:name` path params substituted from matching top-level input keys), and\n * auto-generates an `Idempotency-Key` for idempotent mutations. The key travels\n * as a header only — plugin bodies validate `.strict()`.\n *\n * Dev-mode only: input is best-effort checked against the action's JSON schema\n * (`console.warn`, never a client-side throw — the server's Zod is\n * authoritative), and `deprecated` actions warn once per action per client.\n *\n * Money note: plugin payloads are opaque to the SDK, so no minor-unit conversion\n * happens here — consult the plugin's own docs for its money shapes.\n */\nimport type { HttpClient, RequestOptions } from \"../core/http.js\";\nimport { generateIdempotencyKey } from \"../core/idempotency.js\";\nimport { checkJsonSchema } from \"../core/json-schema.js\";\nimport { isDevEnvironment } from \"../core/env.js\";\nimport {\n NotFoundError,\n PluginActionNotFoundError,\n PluginNotEnabledError,\n PluginUnavailableError,\n PluginVersionMismatchError,\n ServerError,\n CasinoSdkError,\n} from \"../core/errors.js\";\nimport type {\n ExtCatalog,\n ExtCatalogPlugin,\n ExtCallOpts,\n ExtMethod,\n ExtPluginClient,\n ExtRegistry,\n ExtRequestInit,\n PluginActionDescriptor,\n TypedExtPluginClient,\n} from \"../types/ext.js\";\n\nexport interface ExtCatalogOptions {\n /** Bypass the cache and refetch unconditionally. */\n force?: boolean;\n}\n\n/**\n * The `sdk.ext` surface: callable for a per-plugin handle, plus catalog\n * discovery. Fully lazy — nothing is fetched until an action is called or the\n * catalog is requested, and a broken catalog endpoint never affects non-ext SDK\n * usage.\n */\nexport interface ExtModule {\n /** Typed handle — `pluginKey` is registered in {@link ExtRegistry} (generated client installed). */\n <K extends keyof ExtRegistry & string>(pluginKey: K): TypedExtPluginClient<ExtRegistry[K]>;\n /** Generic handle for any enabled plugin; no build-time knowledge needed. */\n (pluginKey: string): ExtPluginClient;\n /**\n * The tenant's plugin catalog. Cached in-memory per `Cache-Control: max-age`\n * (default 60s) and revalidated via ETag once stale; `{ force: true }`\n * refetches unconditionally. Concurrent callers share one in-flight fetch.\n */\n catalog(opts?: ExtCatalogOptions): Promise<ExtCatalog>;\n /**\n * One plugin's catalog entry, straight from\n * `GET /api/ext/_catalog/:pluginKey`. Rejects with\n * {@link PluginNotEnabledError} when the plugin is not enabled (404).\n */\n plugin(pluginKey: string): Promise<ExtCatalogPlugin>;\n}\n\nconst CATALOG_PATH = \"/api/ext/_catalog\";\n/** The runtime declares `Cache-Control: max-age=60` on the catalog; fallback if absent. */\nconst DEFAULT_CATALOG_MAX_AGE_S = 60;\n\ninterface CatalogCache {\n catalog: ExtCatalog;\n etag: string | undefined;\n expiresAt: number;\n}\n\nexport function createExtModule(http: HttpClient): ExtModule {\n let cache: CatalogCache | null = null;\n let inflight: Promise<ExtCatalog> | null = null;\n const clients = new Map<string, ExtPluginClient>();\n const warnedDeprecated = new Set<string>();\n\n function cacheUntil(maxAgeSeconds: number | undefined): number {\n return Date.now() + (maxAgeSeconds ?? DEFAULT_CATALOG_MAX_AGE_S) * 1000;\n }\n\n async function fetchCatalog(force: boolean): Promise<ExtCatalog> {\n const etag = !force && cache ? cache.etag : undefined;\n const res = await http.conditionalGet<ExtCatalog>(CATALOG_PATH, {\n ...(etag !== undefined ? { etag } : {}),\n _noEnrich: true,\n });\n if (res.notModified && cache) {\n cache = { ...cache, expiresAt: cacheUntil(res.maxAgeSeconds) };\n return cache.catalog;\n }\n if (res.data === undefined) {\n throw new ServerError(\n \"EXT_CATALOG_EMPTY\",\n \"The plugin catalog endpoint returned no body.\",\n 0,\n );\n }\n cache = { catalog: res.data, etag: res.etag, expiresAt: cacheUntil(res.maxAgeSeconds) };\n return res.data;\n }\n\n function catalog(opts: ExtCatalogOptions = {}): Promise<ExtCatalog> {\n if (!opts.force) {\n if (cache && Date.now() < cache.expiresAt) return Promise.resolve(cache.catalog);\n if (inflight) return inflight;\n }\n const fetching = fetchCatalog(opts.force ?? false).finally(() => {\n if (inflight === fetching) inflight = null;\n });\n inflight = fetching;\n return fetching;\n }\n\n async function plugin(pluginKey: string): Promise<ExtCatalogPlugin> {\n try {\n return await http.get<ExtCatalogPlugin>(`${CATALOG_PATH}/${encodeURIComponent(pluginKey)}`, {\n _noEnrich: true,\n });\n } catch (err) {\n throw remapExtError(err, pluginKey);\n }\n }\n\n async function resolveDescriptor(\n pluginKey: string,\n actionKey: string,\n ): Promise<PluginActionDescriptor> {\n const cat = await catalog();\n const entry = cat.plugins.find((p) => p.pluginKey === pluginKey);\n if (!entry) throw new PluginNotEnabledError(pluginKey);\n const action = entry.actions.find((a) => a.key === actionKey);\n if (!action) throw new PluginActionNotFoundError(pluginKey, actionKey);\n return action;\n }\n\n async function callAction<T>(\n pluginKey: string,\n actionKey: string,\n input?: unknown,\n opts: ExtCallOpts = {},\n ): Promise<T> {\n const action = await resolveDescriptor(pluginKey, actionKey);\n\n if (isDevEnvironment()) {\n if (action.deprecated !== undefined) {\n const key = `${pluginKey}.${actionKey}`;\n if (!warnedDeprecated.has(key)) {\n warnedDeprecated.add(key);\n console.warn(`[casino-sdk] ext action \"${key}\" is deprecated: ${action.deprecated}`);\n }\n }\n warnOnSchemaMismatch(pluginKey, action, input);\n }\n\n const routed = routeInput(action, input);\n const autoIdempotent = action.kind === \"mutation\" && action.idempotent === true;\n const idempotencyKey =\n opts.idempotencyKey ?? (autoIdempotent ? generateIdempotencyKey() : undefined);\n\n try {\n return await http.request<T>(action.method, routed.path, {\n ...(routed.query !== undefined ? { query: routed.query } : {}),\n ...(routed.body !== undefined ? { body: routed.body } : {}),\n ...(idempotencyKey !== undefined\n ? { idempotent: true, idempotencyHeaderOnly: true, idempotencyKey }\n : {}),\n ...(opts.signal ? { signal: opts.signal } : {}),\n });\n } catch (err) {\n throw remapExtError(err, pluginKey);\n }\n }\n\n async function rawRequest<T>(\n pluginKey: string,\n method: ExtMethod,\n path: string,\n init: ExtRequestInit = {},\n ): Promise<T> {\n const sub = path.startsWith(\"/\") ? path : `/${path}`;\n try {\n return await http.request<T>(method, `/api/ext/${encodeURIComponent(pluginKey)}${sub}`, {\n ...(init.query !== undefined ? { query: toQuery(init.query) } : {}),\n ...(init.body !== undefined ? { body: init.body } : {}),\n ...(init.idempotencyKey !== undefined\n ? { idempotent: true, idempotencyHeaderOnly: true, idempotencyKey: init.idempotencyKey }\n : {}),\n ...(init.signal ? { signal: init.signal } : {}),\n });\n } catch (err) {\n throw remapExtError(err, pluginKey);\n }\n }\n\n function pluginClient(pluginKey: string): ExtPluginClient {\n const existing = clients.get(pluginKey);\n if (existing) return existing;\n const client: ExtPluginClient = {\n pluginKey,\n call: <T>(actionKey: string, input?: unknown, opts?: ExtCallOpts) =>\n callAction<T>(pluginKey, actionKey, input, opts),\n request: <T>(method: ExtMethod, path: string, init?: ExtRequestInit) =>\n rawRequest<T>(pluginKey, method, path, init),\n };\n clients.set(pluginKey, client);\n return client;\n }\n\n return Object.assign(pluginClient, { catalog, plugin }) as ExtModule;\n}\n\n// ── Input routing ────────────────────────────────────────────────────────────────\n\ninterface RoutedInput {\n path: string;\n query?: RequestOptions[\"query\"];\n body?: unknown;\n}\n\n/**\n * Route `input` per the descriptor: substitute `:name` path params from matching\n * top-level input keys, then send the rest as query (GET/DELETE) or JSON body\n * (POST/PUT).\n */\nfunction routeInput(action: PluginActionDescriptor, input: unknown): RoutedInput {\n let path = action.path;\n const isObjectInput = isPlainObject(input);\n const rest: Record<string, unknown> | undefined = isObjectInput ? { ...input } : undefined;\n\n if (rest && path.includes(\":\")) {\n path = path.replace(/:([A-Za-z0-9_]+)/g, (segment, name: string) => {\n if (!(name in rest)) return segment; // leave it — the server 404s authoritatively\n const value = rest[name];\n // Treat a null/undefined value like a missing key: leave the `:name`\n // placeholder (the server 404s authoritatively) rather than stringifying\n // it into the path as the literal \"undefined\"/\"null\". Still drop it from\n // `rest` so it can't leak into the query/body either.\n if (value === undefined || value === null) {\n delete rest[name];\n return segment;\n }\n delete rest[name];\n return encodeURIComponent(String(value));\n });\n }\n\n if (action.method === \"GET\" || action.method === \"DELETE\") {\n if (input !== undefined && !isObjectInput && isDevEnvironment()) {\n console.warn(\n `[casino-sdk] ext action \"${action.key}\": ${action.method} input must be a flat object; ignoring ${describeValue(input)}.`,\n );\n }\n return {\n path,\n ...(rest && Object.keys(rest).length > 0 ? { query: toQuery(rest) } : {}),\n };\n }\n\n // POST / PUT — remaining keys (or the raw non-object input) become the JSON body.\n if (rest) return { path, body: rest };\n return { path, ...(input !== undefined ? { body: input } : {}) };\n}\n\n/** Flatten a record into the HTTP layer's query shape. Query schemas are flat: nested objects are unsupported and dropped (dev warn). */\nfunction toQuery(record: Record<string, unknown>): NonNullable<RequestOptions[\"query\"]> {\n const query: Record<string, string | number | boolean | readonly string[]> = {};\n for (const [key, value] of Object.entries(record)) {\n if (value === undefined || value === null) continue;\n if (Array.isArray(value)) {\n query[key] = value.map((v) => String(v));\n } else if (typeof value === \"object\") {\n if (isDevEnvironment()) {\n console.warn(\n `[casino-sdk] ext query param \"${key}\" is an object; query schemas are flat — dropping it.`,\n );\n }\n } else {\n query[key] = value as string | number | boolean;\n }\n }\n return query;\n}\n\nfunction warnOnSchemaMismatch(\n pluginKey: string,\n action: PluginActionDescriptor,\n input: unknown,\n): void {\n if (action.input === undefined) return;\n // Omitted input is fine for an object schema without required keys — check `{}`\n // so only genuinely missing required fields warn. Non-object schemas can't be\n // judged without a value.\n const value = input === undefined ? (schemaExpectsObject(action.input) ? {} : undefined) : input;\n if (value === undefined) return;\n const problems = checkJsonSchema(value, action.input);\n if (problems.length > 0) {\n console.warn(\n `[casino-sdk] input for ext action \"${pluginKey}.${action.key}\" does not match its declared schema (the server stays authoritative): ` +\n problems.map((p) => `${p.path || \"$\"}: ${p.message}`).join(\"; \"),\n );\n }\n}\n\nfunction schemaExpectsObject(schema: unknown): boolean {\n if (typeof schema !== \"object\" || schema === null) return false;\n const node = schema as { type?: string | string[]; properties?: unknown };\n if (node.type === \"object\") return true;\n if (Array.isArray(node.type) && node.type.includes(\"object\")) return true;\n return node.type === undefined && node.properties !== undefined;\n}\n\nfunction isPlainObject(value: unknown): value is Record<string, unknown> {\n return typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\nfunction describeValue(value: unknown): string {\n return Array.isArray(value) ? \"an array\" : `a ${typeof value}`;\n}\n\n// ── Error remapping (§4 of the plugin-actions contract) ─────────────────────────\n\n/**\n * Sharpen transport errors from `/api/ext/*` routes: a 404 means the plugin is\n * not enabled (indistinguishable from not-installed), a 504 means the plugin\n * handler timed out or crashed. Everything else passes through untouched.\n */\nfunction remapExtError(err: unknown, pluginKey: string): unknown {\n if (!(err instanceof CasinoSdkError)) return err;\n if (\n err instanceof NotFoundError &&\n !(err instanceof PluginNotEnabledError) &&\n !(err instanceof PluginActionNotFoundError)\n ) {\n return new PluginNotEnabledError(pluginKey, {\n code: err.code,\n message: err.message,\n status: err.status,\n details: err.details,\n });\n }\n if (\n err instanceof ServerError &&\n err.status === 504 &&\n !(err instanceof PluginUnavailableError)\n ) {\n return new PluginUnavailableError(err.code, err.message, err.status, err.details);\n }\n return err;\n}\n\n// ── Generated-client version guard ──────────────────────────────────────────────\n\n/**\n * Runtime guard for generated plugin clients: throws\n * {@link PluginVersionMismatchError} when the installed plugin's **major**\n * version differs from the expected range's major. `expectedRange` accepts the\n * common single-major forms a generator emits: `\"1\"`, `\"1.x\"`, `\"1.2.3\"`,\n * `\"^1.2.3\"`, `\"~1.2\"`, `\"=1.0.0\"`, `\"v1\"`.\n */\nexport function assertPluginVersion(catalogEntry: ExtCatalogPlugin, expectedRange: string): void {\n const expected = parseMajor(expectedRange);\n if (expected === null) {\n throw new TypeError(\n `assertPluginVersion: cannot parse a major version out of expected range \"${expectedRange}\".`,\n );\n }\n const actual = parseMajor(catalogEntry.version);\n if (actual === null || actual !== expected) {\n throw new PluginVersionMismatchError(\n catalogEntry.pluginKey,\n expectedRange,\n catalogEntry.version,\n );\n }\n}\n\nfunction parseMajor(version: string): number | null {\n const match = /^\\s*[\\^~=v]*\\s*(\\d+)/.exec(version);\n return match?.[1] !== undefined ? Number(match[1]) : null;\n}\n","/**\n * `sdk.games` — launch a game session.\n *\n * `providerSession` maps to the generic `POST /providers/:provider/session` and\n * returns a fully-formed `launchUrl` to render in the game iframe plus a\n * `sessionId`. Provider adapters are registered per tenant in the runtime\n * (built-in `\"fake\"` for dev, or plugin-contributed adapters). The SDK never\n * sees provider secrets; all money flows server-side through the provider →\n * wallet (and pushes back over the realtime `wallet.balance` channel).\n *\n * `launch` is a stub: the runtime removed its route (`POST\n * /plugins/slotserv/launch`) together with the baked-in SlotServ plugin\n * (runtime `16d4e5d`); it throws `NotImplementedError` until an aggregation\n * plugin ships a launch surface again.\n */\nimport type { HttpClient } from \"../core/http.js\";\nimport type { Session } from \"../core/session.js\";\nimport { NotImplementedError, ValidationError } from \"../core/errors.js\";\nimport { minorStringToMinor } from \"../core/money.js\";\nimport type {\n Bet,\n BetDetail,\n BetsPage,\n BetsQuery,\n GameSession,\n GameSessionsPage,\n LaunchInput,\n LaunchResult,\n} from \"../types/http.js\";\n\n/** Raw runtime shapes (minor-unit integer strings) before conversion. */\ntype RawBet = Omit<Bet, \"betAmount\" | \"winAmount\"> & {\n betAmountMinor: string;\n winAmountMinor: string | null;\n};\ntype RawBetDetail = RawBet & Pick<BetDetail, \"walletTransactions\">;\ntype RawGameSession = Omit<GameSession, \"betTotal\" | \"winTotal\"> & {\n betTotalMinor: string;\n winTotalMinor: string;\n};\n\n/**\n * Assert a game `launchUrl` is safe to render in an iframe: `https:` only\n * (`http:` tolerated for loopback hosts so local dev runtimes keep working).\n * `javascript:`, `data:`, and every other scheme are rejected — a compromised or\n * misconfigured provider must not be able to hand the frontend a script URL.\n *\n * The SDK applies this to every launch result; it is exported so app code can\n * re-validate URLs it stored or received elsewhere. Also render the iframe with\n * `sandbox=\"allow-scripts allow-same-origin allow-forms\"` (see the games guide).\n *\n * @returns the URL, unchanged, for fluent use.\n * @throws ValidationError (`LAUNCH_URL_INVALID`, status 0) when the URL is unsafe.\n */\nexport function assertLaunchUrl(url: string): string {\n let parsed: URL;\n try {\n parsed = new URL(url);\n } catch {\n throw new ValidationError(\"LAUNCH_URL_INVALID\", `launchUrl is not a valid URL: ${url}`, 0);\n }\n const loopback =\n parsed.hostname === \"localhost\" ||\n parsed.hostname === \"127.0.0.1\" ||\n parsed.hostname === \"[::1]\" ||\n parsed.hostname === \"::1\";\n if (parsed.protocol === \"https:\" || (parsed.protocol === \"http:\" && loopback)) return url;\n throw new ValidationError(\n \"LAUNCH_URL_INVALID\",\n `launchUrl must be https: (got \"${parsed.protocol}\"). Refusing to expose it to the game iframe.`,\n 0,\n { url },\n );\n}\n\nexport class GamesModule {\n constructor(\n private readonly http: HttpClient,\n private readonly session: Session,\n ) {}\n\n /**\n * @deprecated The runtime removed the SlotServ aggregation route\n * (`POST /plugins/slotserv/launch`) along with its baked-in plugins\n * (runtime `16d4e5d`, 2026-07-10) — this now always throws\n * {@link NotImplementedError}. Launch through a tenant-registered provider\n * adapter instead: {@link providerSession}. It returns the same\n * `{ launchUrl, sessionId }` shape.\n */\n async launch(gameId: string, _input: LaunchInput = {}): Promise<LaunchResult> {\n throw new NotImplementedError(\n `games.launch(\"${gameId}\"): the runtime no longer serves POST /plugins/slotserv/launch ` +\n \"(the SlotServ aggregation plugin was removed). Use games.providerSession(provider, \" +\n 'gameId) — provider adapters are registered per tenant (built-in \"fake\" for dev, or ' +\n \"plugin-contributed).\",\n );\n }\n\n /**\n * Open a game session with a specific provider adapter via the generic\n * `POST /providers/:provider/session` route (provider-agnostic counterpart of\n * {@link launch}). Currency defaults from the session.\n */\n async providerSession(\n provider: string,\n gameId: string,\n options: { playerId?: string; currency?: string } = {},\n ): Promise<LaunchResult> {\n const playerId = this.session.requirePlayerId(options.playerId);\n const currency = this.session.resolveCurrency(options.currency);\n const result = await this.http.post<LaunchResult>(\n `/providers/${encodeURIComponent(provider)}/session`,\n { body: { playerId, gameId, currency } },\n );\n assertLaunchUrl(result.launchUrl);\n return result;\n }\n\n /** Bet history (`GET /player/bets`), newest first, amounts in minor units. */\n async bets(query: BetsQuery = {}): Promise<BetsPage> {\n const res = await this.http.get<{ bets: RawBet[]; pagination: BetsPage[\"pagination\"] }>(\n \"/player/bets\",\n {\n query: {\n gameId: query.gameId,\n providerKey: query.providerKey,\n status: query.status,\n from: toIso(query.from),\n to: toIso(query.to),\n limit: query.limit,\n offset: query.offset,\n },\n },\n );\n return { bets: res.bets.map(toBet), pagination: res.pagination };\n }\n\n /** One bet plus its round-linked wallet transactions (`GET /player/bets/:betId`). */\n async bet(betId: string): Promise<BetDetail> {\n const raw = await this.http.get<RawBetDetail>(`/player/bets/${encodeURIComponent(betId)}`);\n return { ...toBet(raw), walletTransactions: raw.walletTransactions };\n }\n\n /** Game-session history with per-session bet/win totals in minor units. */\n async gameSessions(\n query: { from?: string | Date; to?: string | Date; limit?: number; offset?: number } = {},\n ): Promise<GameSessionsPage> {\n const res = await this.http.get<{\n sessions: RawGameSession[];\n pagination: GameSessionsPage[\"pagination\"];\n }>(\"/player/game-sessions\", {\n query: {\n from: toIso(query.from),\n to: toIso(query.to),\n limit: query.limit,\n offset: query.offset,\n },\n });\n return { sessions: res.sessions.map(toGameSession), pagination: res.pagination };\n }\n}\n\nfunction toIso(value: string | Date | undefined): string | undefined {\n return value instanceof Date ? value.toISOString() : value;\n}\n\nfunction toBet(raw: RawBet): Bet {\n const { betAmountMinor, winAmountMinor, ...rest } = raw;\n return {\n ...rest,\n betAmount: minorStringToMinor(betAmountMinor),\n winAmount: winAmountMinor === null ? null : minorStringToMinor(winAmountMinor),\n };\n}\n\nfunction toGameSession(raw: RawGameSession): GameSession {\n const { betTotalMinor, winTotalMinor, ...rest } = raw;\n return {\n ...rest,\n betTotal: minorStringToMinor(betTotalMinor),\n winTotal: minorStringToMinor(winTotalMinor),\n };\n}\n","/**\n * `sdk.kyc` — the player-side KYC surface (`/player/kyc/*`).\n *\n * Flow: {@link status} says where the player stands and whether the withdrawal\n * gate is met; {@link requirements} lists the open requests with their document\n * checklists; {@link uploadDocument} sends files (multipart; JPEG/PNG/PDF,\n * sniffed server-side); {@link submit} hands a completed request to review.\n * Players can never download their documents — item `document` objects are\n * metadata only. Live status pushes arrive on the realtime `player` channel\n * (`kyc_status_changed` / `kyc_documents_requested`).\n *\n * If the tenant delegates the KYC flow to a plugin, mutations throw\n * {@link FlowDelegatedError} — drive the plugin's `/api/ext` routes via\n * `sdk.ext` instead.\n */\nimport type { HttpClient } from \"../core/http.js\";\nimport type {\n KycHistoryPage,\n KycRequest,\n KycStatusResponse,\n KycUploadInput,\n KycUploadResult,\n} from \"../types/http.js\";\n\nexport class KycModule {\n constructor(private readonly http: HttpClient) {}\n\n /** Verification level, per-gate requirements, and email/phone verification flags. */\n status(): Promise<KycStatusResponse> {\n return this.http.get<KycStatusResponse>(\"/player/kyc/status\");\n }\n\n /** Open KYC requests (draft/submitted/in_review/needs_more) with their checklists. */\n async requirements(): Promise<KycRequest[]> {\n const res = await this.http.get<{ requests: KycRequest[] }>(\"/player/kyc/requirements\");\n return res.requests;\n }\n\n /** All requests, newest first. `limit` 1–100 (default 50). */\n history(query: { limit?: number; offset?: number } = {}): Promise<KycHistoryPage> {\n return this.http.get<KycHistoryPage>(\"/player/kyc/history\", {\n query: { limit: query.limit, offset: query.offset },\n });\n }\n\n /**\n * Upload a document. With `requestId` it attaches to that request (which must\n * be `draft`/`needs_more`); without, it is a proactive re-verification\n * upload. Rejections are `ValidationError` with code `KYC_DOCUMENT_INVALID`\n * (format/size/expiry — see `details`).\n *\n * Large files on slow uplinks can outlive the client's default request\n * timeout (30s) — raise or disable it per call via `options.timeoutMs`\n * (`0` disables).\n */\n uploadDocument(\n input: KycUploadInput,\n options: { timeoutMs?: number; signal?: AbortSignal } = {},\n ): Promise<KycUploadResult> {\n const form = new FormData();\n // Text fields must precede the file part — the runtime reads fields\n // collected up to the first file.\n form.append(\"documentTypeKey\", input.documentTypeKey);\n if (input.expiryDate !== undefined) form.append(\"expiryDate\", input.expiryDate);\n const fileName =\n input.fileName ??\n (typeof File !== \"undefined\" && input.file instanceof File ? input.file.name : \"document\");\n form.append(\"file\", input.file, fileName);\n\n const path =\n input.requestId !== undefined\n ? `/player/kyc/requests/${encodeURIComponent(input.requestId)}/documents`\n : \"/player/kyc/documents\";\n return this.http.post<KycUploadResult>(path, {\n body: form,\n ...(options.timeoutMs !== undefined ? { timeoutMs: options.timeoutMs } : {}),\n ...(options.signal ? { signal: options.signal } : {}),\n });\n }\n\n /**\n * Submit a request for review. Every `required` checklist item needs an\n * uploaded/approved document first — otherwise `ValidationError` with\n * `details.missing` listing the absent `documentTypeKey`s.\n */\n submit(requestId: string): Promise<{ status: \"submitted\" }> {\n return this.http.post(`/player/kyc/requests/${encodeURIComponent(requestId)}/submit`);\n }\n}\n","/**\n * `sdk.player` — profile, preferences, consents, responsible-gaming limits, and\n * account lifecycle (close / GDPR export).\n *\n * Maps to the runtime's `/player/*` account surface. Responsible-gaming limit\n * values ride the wire as scale-4 minor-unit integer *strings* (minutes for\n * `session_time`); the SDK converts them to `MinorUnits` numbers at the\n * boundary. KYC lives at `sdk.kyc`.\n */\nimport type { HttpClient } from \"../core/http.js\";\nimport type { AuthModule } from \"./auth.js\";\nimport { minorStringToMinor } from \"../core/money.js\";\nimport type {\n ConsentsPage,\n CoolOffPeriod,\n DataExportStatus,\n MeResponse,\n PlayerLimit,\n PlayerPreferences,\n ProfileResponse,\n SelfExclusionPeriod,\n SetLimitInput,\n SetPreferencesInput,\n UpdateProfileInput,\n UpdateProfileResult,\n} from \"../types/http.js\";\n\n/** Raw runtime limit view (minor-unit digit strings) before conversion. */\ninterface RawPlayerLimit {\n kind: PlayerLimit[\"kind\"];\n period: PlayerLimit[\"period\"];\n value: string;\n currency: string | null;\n activeFrom: string;\n pending: { value: string | null; removal: boolean; activeAt: string } | null;\n}\n\nexport class PlayerModule {\n constructor(\n private readonly http: HttpClient,\n private readonly auth: AuthModule,\n ) {}\n\n /** The logged-in player's identity + profile (via `/auth/player/me`). */\n getProfile(): Promise<MeResponse> {\n return this.auth.me();\n }\n\n /**\n * The full profile row plus which identity fields are KYC-locked\n * (`GET /player/profile`). `profile` is null until one exists.\n */\n profile(): Promise<ProfileResponse> {\n return this.http.get<ProfileResponse>(\"/player/profile\");\n }\n\n /**\n * Patch the profile (`PATCH /player/profile`). At least one field; `null`\n * clears. Identity fields (`firstName`/`lastName`/`birthDate`/`country`)\n * throw `ConflictError` (`PROFILE_FIELD_LOCKED`) after KYC approval.\n */\n updateProfile(patch: UpdateProfileInput): Promise<UpdateProfileResult> {\n return this.http.patch<UpdateProfileResult>(\"/player/profile\", { body: patch });\n }\n\n /** Preferences (locale, display currency, marketing consents, reality check). */\n getPreferences(): Promise<PlayerPreferences> {\n return this.http.get<PlayerPreferences>(\"/player/preferences\");\n }\n\n /**\n * Update preferences (`PUT /player/preferences`, partial — at least one\n * field). Marketing changes are recorded on the consent trail; set\n * `realityCheckMinutes: null` to disable the reality check.\n */\n setPreferences(patch: SetPreferencesInput): Promise<PlayerPreferences> {\n return this.http.put<PlayerPreferences>(\"/player/preferences\", { body: patch });\n }\n\n /** The append-only marketing-consent trail, newest first. */\n consents(query: { limit?: number; offset?: number } = {}): Promise<ConsentsPage> {\n return this.http.get<ConsentsPage>(\"/player/consents\", {\n query: { limit: query.limit, offset: query.offset },\n });\n }\n\n /**\n * Active responsible-gaming limits, values in minor units (minutes for\n * `session_time`). `pending` carries a ratcheted increase/removal and when it\n * applies.\n */\n async getLimits(): Promise<PlayerLimit[]> {\n const res = await this.http.get<{ limits: RawPlayerLimit[] }>(\"/player/limits\");\n return res.limits.map(toLimit);\n }\n\n /**\n * Set/remove limits (`PUT /player/limits`). `value` in minor units (minutes\n * for `session_time`); `null` removes. New limits and decreases apply\n * immediately; increases/removals apply after the 24h ratchet cooldown\n * (returned in `pending`).\n */\n async setLimits(limits: SetLimitInput[]): Promise<PlayerLimit[]> {\n const res = await this.http.put<{ limits: RawPlayerLimit[] }>(\"/player/limits\", {\n body: {\n limits: limits.map((l) => ({\n kind: l.kind,\n period: l.period,\n value: l.value === null ? null : toLimitString(l.value),\n currency: l.currency,\n })),\n },\n });\n return res.limits.map(toLimit);\n }\n\n /** Responsible-gaming actions beyond limits. */\n readonly rg = {\n /**\n * Start a cooling-off period (blocks gameplay + deposits; login and\n * withdrawals stay). Extend-only — a shorter period than the active one is\n * a `ConflictError`.\n */\n coolOff: (period: CoolOffPeriod): Promise<{ success: true; until: string }> =>\n this.http.post(\"/player/rg/cool-off\", { body: { period } }),\n\n /**\n * Self-exclude. Irreversible player-side; revokes every session (including\n * this one). `until` is null for `\"permanent\"`.\n */\n selfExclude: (period: SelfExclusionPeriod): Promise<{ success: true; until: string | null }> =>\n this.http.post(\"/player/rg/self-exclude\", { body: { period } }),\n\n /** Acknowledge a reality-check prompt (audit trail only). */\n acknowledgeRealityCheck: (gameSessionId?: string): Promise<{ success: true }> =>\n this.http.post(\"/player/rg/reality-check/ack\", {\n body: gameSessionId !== undefined ? { gameSessionId } : {},\n }),\n };\n\n /** Presence signals. */\n readonly presence = {\n /**\n * Tell the runtime this player is still here (`POST\n * /player/presence/heartbeat`, 204). Any authenticated request already\n * refreshes presence server-side — call this only for clients that idle\n * while \"in play\" (e.g. a game iframe generates provider callbacks, not\n * player API traffic). Best-effort on the server: a storage blip never\n * fails the request; presence decays via TTL and heals on the next call.\n */\n heartbeat: (): Promise<void> => this.http.post<void>(\"/player/presence/heartbeat\"),\n };\n\n /** Account lifecycle. */\n readonly account = {\n /**\n * Close the account (idempotent). Requires zero balances and no pending\n * withdrawal — otherwise `ConflictError` with code `BALANCE_REMAINING` or\n * `WITHDRAWAL_PENDING`. Revokes every session.\n */\n close: (reason?: string): Promise<{ success: true }> =>\n this.http.post(\"/player/account/close\", {\n body: reason !== undefined ? { reason } : {},\n }),\n\n /**\n * Request a GDPR data export (202; one active at a time — a second request\n * while pending/processing is a `ConflictError`). The download link is\n * delivered out-of-band.\n */\n requestDataExport: (): Promise<DataExportStatus> => this.http.post(\"/player/account/export\"),\n\n /** Latest export request, or `{ status: \"none\" }` if never requested. */\n dataExportStatus: (): Promise<DataExportStatus> => this.http.get(\"/player/account/export\"),\n };\n}\n\nfunction toLimit(raw: RawPlayerLimit): PlayerLimit {\n return {\n kind: raw.kind,\n period: raw.period,\n value: minorStringToMinor(raw.value),\n currency: raw.currency,\n activeFrom: raw.activeFrom,\n pending: raw.pending\n ? {\n value: raw.pending.value === null ? null : minorStringToMinor(raw.pending.value),\n removal: raw.pending.removal,\n activeAt: raw.pending.activeAt,\n }\n : null,\n };\n}\n\nfunction toLimitString(value: number): string {\n // Safe-integer, not just integer: an over-MAX_SAFE_INTEGER value survives the\n // runtime's digit-string schema but then permanently bricks getLimits(), whose\n // strict read parser rejects unsafe magnitudes.\n if (!Number.isSafeInteger(value) || value <= 0) {\n throw new TypeError(\n `player.setLimits: value must be a positive safe integer (minor units, or minutes for session_time), got ${String(value)}`,\n );\n }\n return String(value);\n}\n","/**\n * WebSocket transport resolution.\n *\n * The realtime client is isomorphic: in the browser it uses the global\n * `WebSocket`; in Node it uses an injected `ws` implementation (peer dependency).\n * It never imports `ws` statically so the core stays dependency-free and\n * tree-shakeable.\n */\nimport type { WebSocketImpl } from \"./contract.js\";\n\n/** Resolve a WebSocket constructor: explicit injection → browser global. */\nexport function resolveWebSocket(injected?: WebSocketImpl): WebSocketImpl {\n if (injected) return injected;\n const g = globalThis as { WebSocket?: WebSocketImpl };\n if (g.WebSocket) return g.WebSocket;\n throw new Error(\n \"No WebSocket implementation available. In Node, pass `WebSocketImpl` \" +\n \"(e.g. `import WebSocket from 'ws'`) in the realtime options.\",\n );\n}\n\n/** Standard ready-state constants (browser + `ws` agree on these values). */\nexport const WS_OPEN = 1;\n","/**\n * The realtime client: a single socket per player that hides the wire protocol,\n * reconnection, heartbeat, eventId dedupe, and post-reconnect re-sync.\n *\n * Wire protocol (mirrors `packages/realtime/src/protocol.ts` in the runtime):\n * - client → server: `auth`, `subscribe`, `unsubscribe`, `ping`\n * - server → client: `ready`, `subscribed`, `unsubscribed`, `event`, `error`,\n * `reconnect`, `pong`\n *\n * Push-only: this client never moves money. Correctness comes from `resync()`,\n * which re-reads authoritative state over REST after every (re)connect.\n */\nimport { resolveWebSocket, WS_OPEN } from \"./transport.js\";\nimport type {\n ChannelEventMap,\n ConnectionState,\n RealtimeChannel,\n RealtimeClient,\n RealtimeClientOptions,\n RealtimeError,\n Unsubscribe,\n WebSocketLike,\n} from \"./contract.js\";\n\n// ── Server frame shapes (decode side) ──────────────────────────────────────────\n\ninterface ReadyFrame {\n type: \"ready\";\n connectionId: string;\n heartbeatMs: number;\n resumeToken: string;\n}\ninterface EventFrame {\n type: \"event\";\n channel: RealtimeChannel;\n event: string;\n eventId: string;\n v: number;\n occurredAt: string;\n tenantId: string;\n data: unknown;\n}\ninterface ErrorFrame {\n type: \"error\";\n code: string;\n message: string;\n details?: unknown;\n id?: string;\n}\ninterface ReconnectFrame {\n type: \"reconnect\";\n reason: \"draining\" | \"slow_consumer\" | \"auth_expired\";\n}\ntype ServerFrame =\n | ReadyFrame\n | EventFrame\n | ErrorFrame\n | ReconnectFrame\n | { type: \"subscribed\" | \"unsubscribed\"; id?: string; channels: RealtimeChannel[] }\n | { type: \"pong\" };\n\ntype Handler = (event: ChannelEventMap[RealtimeChannel]) => void;\n\nconst DEFAULTS = { baseMs: 500, maxMs: 15_000, factor: 2, dedupeWindow: 512, heartbeatMs: 25_000 };\n\n/**\n * A caller awaiting `connect()` is rejected after this many failed connection\n * cycles. Background reconnection keeps going (with capped backoff) — observe\n * `onStateChange` for a later recovery.\n */\nconst MAX_PENDING_CONNECT_ATTEMPTS = 5;\n\n/** Close the socket when no `pong` arrives within this many heartbeat intervals. */\nconst PONG_DEADLINE_INTERVALS = 2;\n\n/**\n * A socket that upgrades but never delivers the `ready` frame (dropped auth\n * ticket, WS-speaking non-gateway proxy, hung gateway) is closed after this long\n * so the cycle fails, retries, and the pending `connect()` stays bounded — the\n * pong deadline can't reap it because the heartbeat only starts on `ready`.\n * `options.heartbeatMs` (documented test-only) overrides it in tests.\n */\nconst READY_DEADLINE_MS = 10_000;\n\nexport function createRealtimeClient(options: RealtimeClientOptions): RealtimeClient {\n return new RealtimeClientImpl(options);\n}\n\nclass RealtimeClientImpl implements RealtimeClient {\n state: ConnectionState = \"idle\";\n\n private socket: WebSocketLike | null = null;\n\n private readonly handlers = new Map<RealtimeChannel, Set<Handler>>();\n private readonly active = new Set<RealtimeChannel>();\n /**\n * Channels the app declared via `subscribe()` (as opposed to interest implied by\n * an `on()` handler). A channel is torn down only when BOTH interests are gone:\n * `unsubscribe()` must not kill a channel that still has a handler, and removing\n * the last handler must not kill a channel the app explicitly subscribed.\n */\n private readonly explicit = new Set<RealtimeChannel>();\n private readonly seen: SeenSet;\n\n private readonly stateListeners = new Set<(s: ConnectionState) => void>();\n private readonly errorListeners = new Set<(e: RealtimeError) => void>();\n\n private attempt = 0;\n private lastPongAt = 0;\n private heartbeatTimer: ReturnType<typeof setInterval> | null = null;\n private reconnectTimer: ReturnType<typeof setTimeout> | null = null;\n private readyDeadlineTimer: ReturnType<typeof setTimeout> | null = null;\n private intentionalClose = false;\n /**\n * Teardown epoch. `disconnect()` bumps it; an `open()` that suspended (awaiting\n * the auth credential) before the bump must abandon its cycle when it resumes —\n * otherwise it resurrects an authenticated \"zombie\" socket after logout.\n */\n private epoch = 0;\n private lastOccurredAt: string | undefined;\n private idCounter = 0;\n private connectResolve: (() => void) | null = null;\n private connectReject: ((err: Error) => void) | null = null;\n private connectPromise: Promise<void> | null = null;\n\n constructor(private readonly options: RealtimeClientOptions) {\n this.seen = new SeenSet(options.dedupeWindow ?? DEFAULTS.dedupeWindow);\n }\n\n connect(): Promise<void> {\n if (this.state === \"ready\") return Promise.resolve();\n // Single-flight: while a connect/reconnect cycle is pending, every caller gets\n // the SAME promise — a second connect() (React StrictMode's double mount) must\n // not open a second socket or clobber the pending resolve/reject pair.\n if (this.connectPromise) return this.connectPromise;\n this.intentionalClose = false;\n const pending = new Promise<void>((resolve, reject) => {\n this.connectResolve = resolve;\n this.connectReject = reject;\n });\n const tracked: Promise<void> = pending.finally(() => {\n if (this.connectPromise === tracked) this.connectPromise = null;\n });\n this.connectPromise = tracked;\n // While auto-reconnect is already cycling (timer pending or open() in flight),\n // don't open a competing socket — the cycle settles this promise instead.\n if (this.state !== \"reconnecting\") void this.open();\n return tracked;\n }\n\n async disconnect(): Promise<void> {\n this.intentionalClose = true;\n this.epoch++; // any open() suspended mid-await must abandon its cycle\n this.clearTimers();\n // A caller still awaiting connect() settles now — it will never become ready.\n this.failConnect(new Error(\"realtime: disconnect() before the connection became ready\"));\n if (this.socket) {\n try {\n this.socket.close(1000, \"client disconnect\");\n } catch {\n /* ignore */\n }\n this.socket = null;\n }\n this.setState(\"closed\");\n }\n\n on<C extends RealtimeChannel>(\n channel: C,\n handler: (event: ChannelEventMap[C]) => void,\n ): Unsubscribe {\n let set = this.handlers.get(channel);\n if (!set) {\n set = new Set();\n this.handlers.set(channel, set);\n }\n set.add(handler as Handler);\n // Mark active now so the channel is (re)subscribed on the next `ready` frame —\n // whether we're connected yet or not (subscribe-before-connect is the norm).\n // Handler interest does NOT mark the channel `explicit`.\n if (!this.active.has(channel)) this.markActive([channel]);\n\n return () => {\n const handlers = this.handlers.get(channel);\n handlers?.delete(handler as Handler);\n if (handlers && handlers.size === 0) {\n this.handlers.delete(channel);\n if (!this.explicit.has(channel)) this.teardown([channel]);\n }\n };\n }\n\n async subscribe(channels: readonly RealtimeChannel[]): Promise<void> {\n for (const c of channels) this.explicit.add(c);\n this.markActive(channels);\n }\n\n async unsubscribe(channels: readonly RealtimeChannel[]): Promise<void> {\n for (const c of channels) this.explicit.delete(c);\n // Keep any channel a live on() handler still needs (L-SDK6).\n this.teardown(channels.filter((c) => !this.handlers.get(c)?.size));\n }\n\n async withSubscription<T>(\n channels: readonly RealtimeChannel[],\n scope: () => Promise<T>,\n ): Promise<T> {\n await this.subscribe(channels);\n try {\n return await scope();\n } finally {\n await this.unsubscribe(channels);\n }\n }\n\n activeChannels(): readonly RealtimeChannel[] {\n return [...this.active];\n }\n\n /** Register interest and subscribe on the wire when connected. */\n private markActive(channels: readonly RealtimeChannel[]): void {\n for (const c of channels) this.active.add(c);\n if (this.state === \"ready\") {\n this.send({ type: \"subscribe\", channels: [...channels], id: this.nextId() });\n }\n }\n\n /** Drop interest and unsubscribe on the wire when connected. */\n private teardown(channels: readonly RealtimeChannel[]): void {\n if (channels.length === 0) return;\n for (const c of channels) this.active.delete(c);\n if (this.state === \"ready\") {\n this.send({ type: \"unsubscribe\", channels: [...channels], id: this.nextId() });\n }\n }\n\n onStateChange(handler: (state: ConnectionState) => void): Unsubscribe {\n this.stateListeners.add(handler);\n return () => this.stateListeners.delete(handler);\n }\n\n onError(handler: (error: RealtimeError) => void): Unsubscribe {\n this.errorListeners.add(handler);\n return () => this.errorListeners.delete(handler);\n }\n\n // ── internals ────────────────────────────────────────────────────────────────\n\n private async open(): Promise<void> {\n const epoch = this.epoch;\n this.setState(this.attempt === 0 ? \"connecting\" : \"reconnecting\");\n let ticket: string | undefined;\n try {\n const cred = await this.options.getAuthCredential?.();\n if (cred && \"ticket\" in cred) ticket = cred.ticket;\n } catch (err) {\n if (epoch !== this.epoch) return; // torn down while fetching the credential\n this.emitError({ code: \"REALTIME_AUTH\", message: (err as Error).message });\n // Auth failures are deterministic (usually: not logged in) — settle the\n // pending connect() now instead of hanging it across the retry loop.\n this.failConnect(err instanceof Error ? err : new Error(String(err)));\n this.scheduleReconnect();\n return;\n }\n // disconnect() ran while we awaited the ticket: the pending connect() is\n // already settled and state is \"closed\" — do NOT resurrect a socket for the\n // dead cycle (it would come up authenticated as the logged-out user).\n if (epoch !== this.epoch) return;\n\n let socket: WebSocketLike;\n try {\n // resolveWebSocket inside the try: a missing WebSocket implementation must\n // reject the pending connect(), not escape `void this.open()` as an\n // unhandled rejection while connect() hangs forever.\n const WebSocketImpl = resolveWebSocket(this.options.WebSocketImpl);\n socket = new WebSocketImpl(this.options.url);\n } catch (err) {\n this.failConnect(err as Error);\n this.scheduleReconnect();\n return;\n }\n this.socket = socket;\n this.armReadyDeadline(socket);\n\n // Every handler is tagged to ITS socket: events from a socket that is no longer\n // `this.socket` (replaced during a reconnect race) must not touch live state —\n // a stale onclose used to null the current socket, orphaning it mid-heartbeat.\n socket.onopen = () => {\n if (socket !== this.socket) return;\n // Ticket path: authenticate in-band. Cookie path: the upgrade already carried it.\n if (ticket) this.send({ type: \"auth\", token: ticket });\n };\n socket.onmessage = (ev) => {\n if (socket !== this.socket) return;\n this.onMessage(ev.data);\n };\n socket.onerror = () => {\n if (socket !== this.socket) return;\n this.emitError({ code: \"REALTIME_SOCKET\", message: \"socket error\" });\n };\n socket.onclose = (ev) => this.onClose(socket, ev?.code);\n }\n\n private onMessage(raw: unknown): void {\n if (typeof raw !== \"string\") return;\n let frame: ServerFrame;\n try {\n frame = JSON.parse(raw) as ServerFrame;\n } catch {\n return;\n }\n\n switch (frame.type) {\n case \"ready\":\n this.onReady(frame);\n break;\n case \"event\":\n this.onEvent(frame);\n break;\n case \"error\":\n this.emitError({\n code: frame.code,\n message: frame.message,\n ...(isRecord(frame.details) ? { details: frame.details } : {}),\n });\n break;\n case \"reconnect\":\n // Server asked us to cycle; close and let auto-reconnect take over.\n try {\n this.socket?.close(1000, frame.reason);\n } catch {\n /* ignore */\n }\n break;\n case \"pong\":\n this.lastPongAt = Date.now();\n break;\n case \"subscribed\":\n case \"unsubscribed\":\n break;\n }\n }\n\n private onReady(frame: ReadyFrame): void {\n this.attempt = 0;\n this.clearReadyDeadline();\n this.setState(\"ready\");\n this.startHeartbeat(frame.heartbeatMs || this.options.heartbeatMs || DEFAULTS.heartbeatMs);\n\n // Replay the currently-active channels (subscribe-once-and-forget).\n if (this.active.size > 0) {\n this.send({ type: \"subscribe\", channels: [...this.active], id: this.nextId() });\n }\n\n // Reconcile any state missed while disconnected. REST is the source of truth.\n const ctx = this.lastOccurredAt !== undefined ? { since: this.lastOccurredAt } : {};\n void Promise.resolve(this.options.resync?.(ctx)).catch(() => {\n /* app-supplied; swallow */\n });\n\n this.connectResolve?.();\n this.connectResolve = null;\n this.connectReject = null;\n }\n\n private onEvent(frame: EventFrame): void {\n if (this.seen.has(frame.eventId)) return; // dedupe across reconnect/resume overlap\n this.seen.add(frame.eventId);\n this.lastOccurredAt = frame.occurredAt;\n\n const handlers = this.handlers.get(frame.channel);\n if (!handlers) return;\n const event = frame as unknown as ChannelEventMap[RealtimeChannel];\n for (const handler of handlers) {\n try {\n handler(event);\n } catch (err) {\n this.emitError({ code: \"REALTIME_HANDLER\", message: (err as Error).message });\n }\n }\n }\n\n private onClose(socket: WebSocketLike, code?: number): void {\n // A close from a socket we already replaced is stale — ignoring it keeps the\n // live socket's heartbeat and reconnect schedule intact.\n if (socket !== this.socket) return;\n this.clearTimers();\n this.socket = null;\n if (this.intentionalClose) {\n this.setState(\"closed\");\n return;\n }\n // 4401 = unauthorized: getAuthCredential() will refresh on the next open().\n this.scheduleReconnect(code);\n }\n\n private scheduleReconnect(_code?: number): void {\n if (this.intentionalClose) return;\n this.setState(\"reconnecting\");\n // Bounded wait for callers: after enough failed cycles, reject the pending\n // connect() promise. Reconnection itself keeps cycling in the background.\n if (this.connectReject && this.attempt + 1 >= MAX_PENDING_CONNECT_ATTEMPTS) {\n this.failConnect(\n new Error(\n `realtime: connection not ready after ${MAX_PENDING_CONNECT_ATTEMPTS} attempts (still retrying in the background)`,\n ),\n );\n }\n const delay = this.backoffDelay(this.attempt++);\n this.reconnectTimer = setTimeout(() => void this.open(), delay);\n }\n\n private backoffDelay(attempt: number): number {\n const { baseMs, maxMs, factor } = {\n baseMs: this.options.backoff?.baseMs ?? DEFAULTS.baseMs,\n maxMs: this.options.backoff?.maxMs ?? DEFAULTS.maxMs,\n factor: this.options.backoff?.factor ?? DEFAULTS.factor,\n };\n const ceiling = Math.min(maxMs, baseMs * factor ** attempt);\n return Math.floor(Math.random() * ceiling); // full jitter\n }\n\n private startHeartbeat(intervalMs: number): void {\n this.clearHeartbeat();\n this.lastPongAt = Date.now();\n this.heartbeatTimer = setInterval(() => {\n const socket = this.socket;\n if (!socket || socket.readyState !== WS_OPEN) return;\n if (Date.now() - this.lastPongAt >= intervalMs * PONG_DEADLINE_INTERVALS) {\n // No pong across the deadline: the connection is dead (half-open TCP after\n // a network change, say) and would otherwise show stale state for minutes.\n // Close and run the close path NOW — reconnect + REST resync — rather than\n // waiting for a close event a dead socket may never fire.\n try {\n socket.close(4000, \"pong deadline\");\n } catch {\n /* ignore */\n }\n this.onClose(socket);\n return;\n }\n this.send({ type: \"ping\" });\n }, intervalMs);\n }\n\n private clearHeartbeat(): void {\n if (this.heartbeatTimer) {\n clearInterval(this.heartbeatTimer);\n this.heartbeatTimer = null;\n }\n }\n\n /** Reap a socket that upgrades but never becomes `ready` (see READY_DEADLINE_MS). */\n private armReadyDeadline(socket: WebSocketLike): void {\n this.clearReadyDeadline();\n const deadlineMs = this.options.heartbeatMs ?? READY_DEADLINE_MS;\n this.readyDeadlineTimer = setTimeout(() => {\n if (socket !== this.socket || this.state === \"ready\") return;\n try {\n socket.close(4000, \"ready deadline\");\n } catch {\n /* ignore */\n }\n this.onClose(socket); // idempotent via the socket tag\n }, deadlineMs);\n }\n\n private clearReadyDeadline(): void {\n if (this.readyDeadlineTimer) {\n clearTimeout(this.readyDeadlineTimer);\n this.readyDeadlineTimer = null;\n }\n }\n\n private clearTimers(): void {\n this.clearHeartbeat();\n this.clearReadyDeadline();\n if (this.reconnectTimer) {\n clearTimeout(this.reconnectTimer);\n this.reconnectTimer = null;\n }\n }\n\n private send(frame: Record<string, unknown>): void {\n if (!this.socket || this.socket.readyState !== WS_OPEN) return;\n try {\n this.socket.send(JSON.stringify(frame));\n } catch (err) {\n this.emitError({ code: \"REALTIME_SEND\", message: (err as Error).message });\n }\n }\n\n private setState(state: ConnectionState): void {\n if (this.state === state) return;\n this.state = state;\n // Listener guards mirror onEvent's: an app listener throwing must not abort\n // the lifecycle transition that invoked it (e.g. wedge a reconnect cycle).\n for (const l of this.stateListeners) {\n try {\n l(state);\n } catch {\n /* app-supplied; swallow */\n }\n }\n }\n\n private emitError(error: RealtimeError): void {\n for (const l of this.errorListeners) {\n try {\n l(error);\n } catch {\n /* app-supplied; swallow */\n }\n }\n }\n\n private failConnect(err: Error): void {\n this.connectReject?.(err);\n this.connectResolve = null;\n this.connectReject = null;\n // Clear synchronously (not just in the tracked promise's finally microtask):\n // a connect() issued in the same tick as disconnect() must start a fresh\n // cycle, not adopt the already-rejected promise.\n this.connectPromise = null;\n }\n\n private nextId(): string {\n return `c${++this.idCounter}`;\n }\n}\n\n/** Bounded insertion-ordered set for eventId dedupe (LRU-ish via FIFO eviction). */\nclass SeenSet {\n private readonly set = new Set<string>();\n constructor(private readonly max: number) {}\n has(id: string): boolean {\n return this.set.has(id);\n }\n add(id: string): void {\n this.set.add(id);\n if (this.set.size > this.max) {\n const oldest = this.set.values().next().value;\n if (oldest !== undefined) this.set.delete(oldest);\n }\n }\n}\n\nfunction isRecord(v: unknown): v is Record<string, unknown> {\n return typeof v === \"object\" && v !== null;\n}\n","/**\n * `sdk.realtime` — the realtime gateway, pre-wired with the ticket handshake.\n *\n * Flow: `POST /realtime/ticket` (cookie-authenticated, via the HTTP layer) →\n * `{ ticket }` → open the WS → send `{ type: \"auth\", token }`. In the browser the\n * same-site HttpOnly cookie can authenticate the upgrade directly; the ticket path\n * is used everywhere for portability and to survive access-token expiry.\n *\n * This is a thin delegate over the standalone {@link createRealtimeClient} so it\n * shares the SDK's session/config and you don't pass `url`/`getAuthCredential`.\n */\nimport type { HttpClient } from \"../core/http.js\";\nimport { createRealtimeClient } from \"../realtime/client.js\";\nimport type {\n ChannelEventMap,\n ConnectionState,\n RealtimeChannel,\n RealtimeClient,\n RealtimeError,\n Unsubscribe,\n WebSocketImpl,\n} from \"../realtime/contract.js\";\n\n/** Realtime options you can pass to `createCasinoClient({ realtime })`. */\nexport interface RealtimeOptions {\n /** Reconcile missed state after every (re)connect; the SDK calls this for you. */\n resync?: (ctx: { since?: string }) => Promise<void>;\n backoff?: { baseMs?: number; maxMs?: number; factor?: number };\n heartbeatMs?: number;\n dedupeWindow?: number;\n /** Node only: pass `ws` (`import WebSocket from \"ws\"`). */\n WebSocketImpl?: WebSocketImpl;\n}\n\nexport class RealtimeModule {\n private client: RealtimeClient | null = null;\n\n constructor(\n private readonly http: HttpClient,\n private readonly wsUrl: string,\n private readonly options: RealtimeOptions = {},\n ) {}\n\n /** Fetch a single-use socket ticket from the gateway. */\n ticket(): Promise<{ ticket: string; expiresIn: number }> {\n return this.http.post<{ ticket: string; expiresIn: number }>(\"/realtime/ticket\");\n }\n\n private ensure(): RealtimeClient {\n if (this.client) return this.client;\n this.client = createRealtimeClient({\n url: this.wsUrl,\n getAuthCredential: async () => {\n const { ticket } = await this.ticket();\n return { ticket };\n },\n ...(this.options.resync ? { resync: this.options.resync } : {}),\n ...(this.options.backoff ? { backoff: this.options.backoff } : {}),\n ...(this.options.heartbeatMs !== undefined ? { heartbeatMs: this.options.heartbeatMs } : {}),\n ...(this.options.dedupeWindow !== undefined\n ? { dedupeWindow: this.options.dedupeWindow }\n : {}),\n ...(this.options.WebSocketImpl ? { WebSocketImpl: this.options.WebSocketImpl } : {}),\n });\n return this.client;\n }\n\n get state(): ConnectionState {\n return this.client?.state ?? \"idle\";\n }\n\n /** Open the socket and authenticate. Call once after login. */\n connect(): Promise<void> {\n return this.ensure().connect();\n }\n\n /** Close intentionally (call on logout). Stops auto-reconnect. */\n async disconnect(): Promise<void> {\n if (this.client) await this.client.disconnect();\n }\n\n /** Subscribe to a channel with a typed handler. Returns an unsubscribe fn. */\n on<C extends RealtimeChannel>(\n channel: C,\n handler: (event: ChannelEventMap[C]) => void,\n ): Unsubscribe {\n return this.ensure().on(channel, handler);\n }\n\n subscribe(channels: readonly RealtimeChannel[]): Promise<void> {\n return this.ensure().subscribe(channels);\n }\n\n unsubscribe(channels: readonly RealtimeChannel[]): Promise<void> {\n return this.ensure().unsubscribe(channels);\n }\n\n withSubscription<T>(channels: readonly RealtimeChannel[], scope: () => Promise<T>): Promise<T> {\n return this.ensure().withSubscription(channels, scope);\n }\n\n activeChannels(): readonly RealtimeChannel[] {\n return this.client?.activeChannels() ?? [];\n }\n\n onStateChange(handler: (state: ConnectionState) => void): Unsubscribe {\n return this.ensure().onStateChange(handler);\n }\n\n onError(handler: (error: RealtimeError) => void): Unsubscribe {\n return this.ensure().onError(handler);\n }\n}\n","/**\n * `createCasinoClient` — the framework-agnostic entry point.\n *\n * Composes the HTTP layer + session cache + every module into one object:\n * `{ auth, cashier, wallet, catalog, games, player, realtime, ... }`. Construct it\n * once and share it (e.g. via the React `CasinoProvider`).\n */\nimport { resolveConfig, type CasinoClientConfig } from \"./config.js\";\nimport { HttpClient } from \"./core/http.js\";\nimport type { CookieJar } from \"./core/cookies.js\";\nimport { FlowDelegatedError } from \"./core/errors.js\";\nimport { Session } from \"./core/session.js\";\nimport { AffiliateModule } from \"./modules/affiliate.js\";\nimport { AuthModule } from \"./modules/auth.js\";\nimport { CashierModule } from \"./modules/cashier.js\";\nimport { WalletModule } from \"./modules/wallet.js\";\nimport { CatalogModule } from \"./modules/catalog.js\";\nimport { createExtModule, type ExtModule } from \"./modules/ext.js\";\nimport { GamesModule } from \"./modules/games.js\";\nimport { KycModule } from \"./modules/kyc.js\";\nimport { PlayerModule } from \"./modules/player.js\";\nimport { RealtimeModule, type RealtimeOptions } from \"./modules/realtime.js\";\nimport type { SessionSnapshot } from \"./core/session.js\";\n\nexport interface CreateCasinoClientConfig extends CasinoClientConfig {\n /** Options for `sdk.realtime` (resync hook, backoff, Node WebSocket, …). */\n realtime?: RealtimeOptions;\n}\n\nexport interface CasinoClient {\n readonly affiliate: AffiliateModule;\n readonly auth: AuthModule;\n readonly cashier: CashierModule;\n readonly wallet: WalletModule;\n readonly catalog: CatalogModule;\n /**\n * Plugin actions: `sdk.ext(pluginKey).call(actionKey, input)` plus catalog\n * discovery (`sdk.ext.catalog()` / `sdk.ext.plugin(key)`).\n */\n readonly ext: ExtModule;\n readonly games: GamesModule;\n /** Player-side KYC: status, requirements, document upload, submit. */\n readonly kyc: KycModule;\n readonly player: PlayerModule;\n readonly realtime: RealtimeModule;\n /** A snapshot of the cached player/profile/currency (no network call). */\n getSession(): SessionSnapshot;\n /**\n * A fully isolated scope of this client bound to `jar`: same configuration, fresh\n * HTTP pipeline, fresh session cache — nothing (cookies, CSRF, cached player) is\n * shared with this client or any other scope.\n *\n * THE way to use the SDK server-side (Next.js route handlers, RSC, API routes):\n * a module-scope client is safe in the browser (one user per tab) but on a server\n * it is shared across every user's requests, so its jar would replay user A's\n * auth cookies on user B's request. Create one scope per incoming request:\n *\n * ```ts\n * const scoped = client.withCookies(new CookieJar());\n * await scoped.auth.login(credentials); // cookies stay inside this scope\n * ```\n */\n withCookies(jar: CookieJar): CasinoClient;\n}\n\nexport function createCasinoClient(config: CreateCasinoClientConfig): CasinoClient {\n const resolved = resolveConfig(config);\n const http = new HttpClient(resolved);\n const session = new Session(resolved.defaultCurrency);\n\n const auth = new AuthModule(http, session, resolved.baseUrl);\n // Wire 401 → refresh → retry now that the auth module exists.\n http.setRefreshHandler(async () => {\n await auth.refresh();\n });\n\n const ext = createExtModule(http);\n // Complete the FLOW_DELEGATED loop: when a core flow is delegated to a plugin,\n // point at the continuation action if the ext catalog declares one named after\n // the flow. Best-effort — a failed catalog lookup leaves `continueWith`\n // undefined and never masks the original error.\n http.setErrorEnricher(async (error) => {\n if (!(error instanceof FlowDelegatedError) || !error.pluginKey || error.flow === undefined) {\n return;\n }\n const cat = await ext.catalog();\n const entry = cat.plugins.find((p) => p.pluginKey === error.pluginKey);\n const action = entry?.actions.find((a) => a.key === error.flow);\n if (action) error.continueWith = { actionKey: action.key };\n });\n\n return {\n affiliate: new AffiliateModule(http),\n auth,\n cashier: new CashierModule(http, session),\n wallet: new WalletModule(http, session),\n catalog: new CatalogModule(http),\n ext,\n games: new GamesModule(http, session),\n kyc: new KycModule(http),\n player: new PlayerModule(http, auth),\n realtime: new RealtimeModule(http, resolved.wsUrl, config.realtime ?? {}),\n getSession: () => session.snapshot(),\n withCookies: (jar) => createCasinoClient({ ...config, cookieJar: jar }),\n };\n}\n","/**\n * Canonical realtime surface, aligned with the runtime's\n * `docs/realtime-sdk-contract.ts` (the agreed contract; verbatim copy kept in\n * `contract.vendored.ts` for diffing — `pnpm sync:contract` refreshes it). We\n * ALIGN with that file — do not fork it. Naming note: the runtime doc calls the\n * core-channel union `RealtimeChannel` and the core+ext union\n * `AnyRealtimeChannel`; here they are {@link CoreRealtimeChannel} and\n * {@link RealtimeChannel} respectively. The plugin `ext.*` channel family\n * ({@link ExtChannel}, {@link ExtPluginEvent}) is part of the runtime contract.\n * SDK-local additions: {@link WebSocketImpl}, `dedupeWindow`,\n * {@link REALTIME_CHANNELS}, {@link isExtChannel}.\n *\n * Money amounts are scale-4 integer minor units (see `core/money.ts`).\n */\n\n/** Statically-known core channels. Strings are stable, versioned, and authz-checked server-side. */\nexport type CoreRealtimeChannel =\n \"wallet.balance\" | \"wallet.deposit\" | \"wallet.withdrawal\" | \"gaming\" | \"bonus\" | \"player\";\n\n/**\n * Channel family published by tenant-enabled plugins, e.g. `\"ext.cashback\"`.\n * Which ones exist comes from the ext catalog (`ExtCatalogPlugin.channels`);\n * subscribing for a non-enabled plugin is rejected by the gateway exactly like\n * an unknown channel.\n */\nexport type ExtChannel = `ext.${string}`;\n\n/** Logical channels: the static core set plus the dynamic plugin family. */\nexport type RealtimeChannel = CoreRealtimeChannel | ExtChannel;\n\n/**\n * Narrow a plain string (e.g. an entry of `ExtCatalogPlugin.channels`, which the\n * wire contract types as `string[]`) to a subscribable {@link ExtChannel}.\n */\nexport function isExtChannel(value: string): value is ExtChannel {\n return value.startsWith(\"ext.\") && value.length > 4;\n}\n\n/**\n * All statically-known subscribable channels, for runtime validation/iteration.\n * Plugin `ext.*` channels are dynamic (discovered via the ext catalog) and\n * intentionally not listed.\n */\nexport const REALTIME_CHANNELS: readonly CoreRealtimeChannel[] = [\n \"wallet.balance\",\n \"wallet.deposit\",\n \"wallet.withdrawal\",\n \"gaming\",\n \"bonus\",\n \"player\",\n];\n\nexport type WalletBucket = \"cash\" | \"bonus\" | \"locked\";\n\n/** Minor units (scale-4 integer). Never do money math on the client beyond display. */\nexport type MinorUnits = number;\n\n/** Common envelope present on every server → client business event. */\nexport interface RealtimeEventMeta {\n readonly event: string;\n readonly eventId: string;\n readonly v: number;\n readonly occurredAt: string;\n readonly tenantId: string;\n}\n\nexport interface WalletBalanceEvent extends RealtimeEventMeta {\n readonly channel: \"wallet.balance\";\n readonly data: {\n readonly currency: string;\n readonly balances: Readonly<Record<WalletBucket, MinorUnits>>;\n readonly change: {\n readonly bucket: WalletBucket;\n readonly direction: \"credit\" | \"debit\";\n readonly amount: MinorUnits;\n readonly reason: string;\n };\n };\n}\n\nexport type DepositStatus = \"pending\" | \"processing\" | \"completed\" | \"failed\" | \"cancelled\";\n\nexport interface WalletDepositEvent extends RealtimeEventMeta {\n readonly channel: \"wallet.deposit\";\n readonly data: {\n readonly depositId: string;\n readonly status: DepositStatus;\n readonly amount: MinorUnits;\n readonly currency: string;\n };\n}\n\nexport type WithdrawalStatus =\n \"requested\" | \"approved\" | \"rejected\" | \"processing\" | \"completed\" | \"reversed\" | \"cancelled\";\n\nexport interface WalletWithdrawalEvent extends RealtimeEventMeta {\n readonly channel: \"wallet.withdrawal\";\n readonly data: {\n readonly withdrawalId: string;\n readonly status: WithdrawalStatus;\n readonly amount: MinorUnits;\n readonly currency: string;\n };\n}\n\nexport interface GamingEvent extends RealtimeEventMeta {\n readonly channel: \"gaming\";\n readonly data: {\n readonly roundId: string;\n readonly betId?: string;\n readonly status: \"placed\" | \"settled\" | \"rolled_back\" | \"round_closed\";\n /** Internal catalog game id — map to a display name from your catalog. */\n readonly gameId?: string;\n /** Provider key that produced the round (e.g. `\"slotserv\"`). */\n readonly provider?: string;\n /** Wager amount, present on `placed`. */\n readonly betAmount?: MinorUnits;\n /** Payout, present on `settled`. */\n readonly winAmount?: MinorUnits;\n readonly currency?: string;\n };\n}\n\nexport interface BonusEvent extends RealtimeEventMeta {\n readonly channel: \"bonus\";\n readonly data: {\n readonly bonusId: string;\n readonly status: \"granted\" | \"revoked\";\n readonly amount?: MinorUnits;\n readonly currency?: string;\n readonly reason?: string;\n };\n}\n\nexport interface PlayerEvent extends RealtimeEventMeta {\n readonly channel: \"player\";\n // Client-safe account-change hints: never emails/IPs/hashes — a coarse `change`\n // kind plus explicitly-safe scalars in `data` for changes that carry context.\n readonly data: {\n readonly change:\n | \"password_changed\"\n | \"social_linked\"\n | \"social_unlinked\"\n | \"account_locked\"\n | \"email_verified\"\n | \"phone_verified\"\n | \"session_revoked\"\n | \"kyc_status_changed\"\n | \"kyc_documents_requested\"\n | \"limit_changed\"\n | \"self_excluded\"\n | \"reality_check\";\n readonly data?: Readonly<Record<string, string | number | boolean | null>>;\n };\n}\n\n/**\n * An event published by a plugin on its `ext.<pluginKey>` channel. The standard\n * realtime envelope applies (incl. `eventId` dedupe); `data.type` is the\n * plugin-defined event type (e.g. `\"cashback.claimed\"`) and `data.payload` is\n * opaque to the SDK.\n */\nexport interface ExtPluginEvent extends RealtimeEventMeta {\n readonly channel: ExtChannel;\n readonly data: {\n readonly type: string;\n readonly payload: unknown;\n };\n}\n\n/** Maps a channel name to its event payload type, for type-safe `on(...)`. */\nexport interface ChannelEventMap {\n \"wallet.balance\": WalletBalanceEvent;\n \"wallet.deposit\": WalletDepositEvent;\n \"wallet.withdrawal\": WalletWithdrawalEvent;\n gaming: GamingEvent;\n bonus: BonusEvent;\n player: PlayerEvent;\n [channel: `ext.${string}`]: ExtPluginEvent;\n}\n\nexport type ConnectionState = \"idle\" | \"connecting\" | \"ready\" | \"reconnecting\" | \"closed\";\n\nexport interface RealtimeError {\n readonly code: string;\n readonly message: string;\n readonly details?: Record<string, unknown>;\n}\n\nexport interface RealtimeClientOptions {\n /** wss URL of the gateway, e.g. `wss://grandbet.example/realtime`. */\n readonly url: string;\n /**\n * How the SDK obtains a handshake credential. Return `{ ticket }` (fetched from\n * `POST /realtime/ticket`) or nothing to rely on a same-site HttpOnly cookie.\n * Called again on every reconnect so an expiring credential never drops the socket.\n */\n readonly getAuthCredential?: () => Promise<{ ticket: string } | void>;\n /**\n * Snapshot read run after every (re)connect to reconcile missed state. The socket\n * accelerates; REST is the truth. The SDK calls this; the app supplies the reads.\n */\n readonly resync?: (ctx: { since?: string }) => Promise<void>;\n /** Reconnect backoff. Defaults: base 500ms, factor 2, max 15s, full jitter. */\n readonly backoff?: {\n readonly baseMs?: number;\n readonly maxMs?: number;\n readonly factor?: number;\n };\n /** Override only for testing; the server dictates heartbeat in the `ready` frame. */\n readonly heartbeatMs?: number;\n /** Inject a WebSocket implementation (Node `ws`); defaults to the platform global. */\n readonly WebSocketImpl?: WebSocketImpl;\n /** Max remembered eventIds for dedupe. Default 512. */\n readonly dedupeWindow?: number;\n}\n\nexport type Unsubscribe = () => void;\n\nexport interface RealtimeClient {\n readonly state: ConnectionState;\n connect(): Promise<void>;\n disconnect(): Promise<void>;\n on<C extends RealtimeChannel>(\n channel: C,\n handler: (event: ChannelEventMap[C]) => void,\n ): Unsubscribe;\n subscribe(channels: readonly RealtimeChannel[]): Promise<void>;\n unsubscribe(channels: readonly RealtimeChannel[]): Promise<void>;\n withSubscription<T>(channels: readonly RealtimeChannel[], scope: () => Promise<T>): Promise<T>;\n activeChannels(): readonly RealtimeChannel[];\n onStateChange(handler: (state: ConnectionState) => void): Unsubscribe;\n onError(handler: (error: RealtimeError) => void): Unsubscribe;\n}\n\nexport type CreateRealtimeClient = (options: RealtimeClientOptions) => RealtimeClient;\n\n// ── Minimal structural WebSocket type (browser global or Node `ws`) ─────────────\n\nexport interface WebSocketLike {\n send(data: string): void;\n close(code?: number, reason?: string): void;\n readonly readyState: number;\n onopen: ((ev: unknown) => void) | null;\n onclose: ((ev: { code?: number; reason?: string }) => void) | null;\n onerror: ((ev: unknown) => void) | null;\n onmessage: ((ev: { data: unknown }) => void) | null;\n}\n\nexport type WebSocketImpl = new (url: string) => WebSocketLike;\n","/**\n * `@clovnet/casino-sdk` — player / casino frontend SDK for the CasinoWebEngine Runtime\n * Core. Framework-agnostic core; React bindings live at `@clovnet/casino-sdk/react`,\n * the standalone realtime client at `@clovnet/casino-sdk/realtime`.\n *\n * @example\n * import { createCasinoClient, formatMoney } from \"@clovnet/casino-sdk\";\n *\n * const sdk = createCasinoClient({\n * baseUrl: \"https://api.staging.example\",\n * wsUrl: \"wss://api.staging.example/realtime\",\n * tenantId: \"grandbet\",\n * });\n *\n * await sdk.auth.login({ email, password });\n * const balance = await sdk.wallet.getBalance();\n * formatMoney(balance.cash, balance.currency); // \"€12.50\"\n */\n\n/** The runtime API contract version this SDK release targets. */\nexport const RUNTIME_API_VERSION = \"2026-07-27\" as const;\n\nexport { createCasinoClient } from \"./client.js\";\nexport type { CasinoClient, CreateCasinoClientConfig } from \"./client.js\";\nexport type { CasinoClientConfig, FetchLike } from \"./config.js\";\nexport { COOKIE, HEADER } from \"./config.js\";\nexport type { SessionSnapshot } from \"./core/session.js\";\nexport type { RealtimeOptions } from \"./modules/realtime.js\";\nexport type { SocialStartOptions } from \"./modules/auth.js\";\n\n// Plugin actions (`sdk.ext`)\nexport { assertPluginVersion } from \"./modules/ext.js\";\nexport { assertLaunchUrl } from \"./modules/games.js\";\nexport type { ExtModule, ExtCatalogOptions } from \"./modules/ext.js\";\nexport type {\n ExtCatalog,\n ExtCatalogPlugin,\n PluginActionDescriptor,\n PluginFrontendDecl,\n ExtMethod,\n ExtCallOpts,\n ExtRequestInit,\n ExtPluginClient,\n ExtRegistry,\n ExtActionShape,\n ExtActionInput,\n ExtActionOutput,\n ExtCallArgs,\n TypedExtPluginClient,\n} from \"./types/ext.js\";\n\n// Minimal JSON-schema checker (dev-mode input warnings; reused by the playground)\nexport { checkJsonSchema, type JsonSchemaProblem } from \"./core/json-schema.js\";\n\n// Server-side cookie scoping: one jar per incoming request (`client.withCookies`)\nexport { CookieJar } from \"./core/cookies.js\";\n\n// Money helpers\nexport {\n formatMoney,\n decimalToMinor,\n minorStringToMinor,\n minorToDecimal,\n minorToAmount,\n MONEY_SCALE,\n type MinorUnits,\n} from \"./core/money.js\";\n\n// Idempotency (advanced — keys are auto-generated by default)\nexport { generateIdempotencyKey } from \"./core/idempotency.js\";\n\n// Error model\nexport {\n CasinoSdkError,\n AuthError,\n ForbiddenError,\n ValidationError,\n NotFoundError,\n ConflictError,\n InsufficientFundsError,\n UnprocessableError,\n OperationDeniedError,\n FlowDelegatedError,\n RgBlockedError,\n LimitExceededError,\n RateLimitError,\n ServerError,\n NetworkError,\n NotImplementedError,\n PluginNotEnabledError,\n PluginActionNotFoundError,\n PluginUnavailableError,\n PluginVersionMismatchError,\n isAppErrorEnvelope,\n type AppErrorEnvelope,\n} from \"./core/errors.js\";\n\n// Transport types (the player HTTP contract)\nexport type * from \"./types/http.js\";\n\n// Realtime contract types (channels, event payloads, client interface)\nexport type {\n RealtimeChannel,\n CoreRealtimeChannel,\n ExtChannel,\n ChannelEventMap,\n WalletBalanceEvent,\n WalletDepositEvent,\n WalletWithdrawalEvent,\n GamingEvent,\n BonusEvent,\n PlayerEvent,\n ExtPluginEvent,\n ConnectionState,\n RealtimeError,\n WalletBucket,\n} from \"./realtime/contract.js\";\nexport { REALTIME_CHANNELS, isExtChannel } from \"./realtime/contract.js\";\n"]}