import { ApiRequestParams } from '@lizuz/mini-app-types'; import { ApiResult } from '@lizuz/mini-app-types'; import { ApiSdkModule } from '@lizuz/mini-app-types'; import { AppearanceSdkModule } from '@lizuz/mini-app-types'; import { AppearanceState } from '@lizuz/mini-app-types'; import { AuthSdkModule } from '@lizuz/mini-app-types'; import { ChatMessage } from '@lizuz/mini-app-types'; import { ConfigSdkModule } from '@lizuz/mini-app-types'; import { DeviceBiometricOptions } from '@lizuz/mini-app-types'; import { DeviceBiometricResult } from '@lizuz/mini-app-types'; import { DeviceCameraResult } from '@lizuz/mini-app-types'; import { DeviceExtraOptions } from '@lizuz/mini-app-types'; import { DeviceFileOptions } from '@lizuz/mini-app-types'; import { DeviceFileResult } from '@lizuz/mini-app-types'; import { DeviceGalleryResult } from '@lizuz/mini-app-types'; import { DeviceInfoResult } from '@lizuz/mini-app-types'; import { DeviceLocationResult } from '@lizuz/mini-app-types'; import { DeviceNetworkResult } from '@lizuz/mini-app-types'; import { DeviceNotificationResult } from '@lizuz/mini-app-types'; import { DeviceNotificationsOptions } from '@lizuz/mini-app-types'; import { DevicePermissionBaseResponse } from '@lizuz/mini-app-types'; import { DevicePermissionStatus } from '@lizuz/mini-app-types'; import { DeviceSdkModule } from '@lizuz/mini-app-types'; import { Direction } from '@lizuz/mini-app-types'; import { EventHandler } from '@lizuz/mini-app-types'; import { FlagsSdkModule } from '@lizuz/mini-app-types'; import { HostDescriptor } from '@lizuz/mini-app-types'; import { HttpMethod } from '@lizuz/mini-app-types'; import { HttpSdkModule } from '@lizuz/mini-app-types'; import { LinksOpenedEvent } from '@lizuz/mini-app-types'; import { LinksOpenOptions } from '@lizuz/mini-app-types'; import { LinksSdkModule } from '@lizuz/mini-app-types'; import { LocaleState } from '@lizuz/mini-app-types'; import { ModelCompletionOptions } from '@lizuz/mini-app-types'; import { NavigationRouterResult } from '@lizuz/mini-app-types'; import { NavigationRouterSkdModule } from '@lizuz/mini-app-types'; import { NavigationSdkModule } from '@lizuz/mini-app-types'; import { NavigationState } from '@lizuz/mini-app-types'; import { NavigationTarget } from '@lizuz/mini-app-types'; import { NotificationOpenEvent } from '@lizuz/mini-app-types'; import { NotificationsRegisterOptions } from '@lizuz/mini-app-types'; import { NotificationsRegisterResult } from '@lizuz/mini-app-types'; import { NotificationsSdkModule } from '@lizuz/mini-app-types'; import { PermissionsSdkModule } from '@lizuz/mini-app-types'; import { PlatformSdkModule } from '@lizuz/mini-app-types'; import { PlatformTypeLiteral } from '@lizuz/mini-app-types'; import { PlatformUser } from '@lizuz/mini-app-types'; import { StorageSdkModule } from '@lizuz/mini-app-types'; import { StorageSetOptions } from '@lizuz/mini-app-types'; import { StreamChunk } from '@lizuz/mini-app-types'; import { StreamError } from '@lizuz/mini-app-types'; import { ThemeMode } from '@lizuz/mini-app-types'; import { ThemePreference } from '@lizuz/mini-app-types'; import { ThemeState } from '@lizuz/mini-app-types'; /** Aggregate stats for one namespace.action pair. */ export declare interface ActionMetrics { count: number; successes: number; failures: number; timeouts: number; retries: number; totalDurationMs: number; averageDurationMs: number; /** * Latency percentiles over the bounded, age-windowed set of recent * durations for this action. Unlike the counters (which are cumulative), * these reflect only recent traffic, so a p99 that spiked an hour ago * stops skewing the picture once it ages out of the window. */ percentiles: DurationPercentiles; } export { ApiRequestParams } export { ApiResult } export { ApiSdkModule } /** * Internal handle returned alongside the public `AppearanceSdkModule` so the * composition root (`MiniAppSdk`) can push host-published `appearance.*` * events into the store. */ export declare interface AppearanceModuleHandle { module: AppearanceSdkModule; setLocale(locale: LocaleState): void; setTheme(theme: ThemeState): void; /** * Seeds the store from the loose `{ theme, locale }` hint a host attaches * to its `platform.getType` reply. This is how the Flutter shell — which * doesn't implement the `appearance` namespace — gets its theme and locale * into `sdk.appearance`, so mini-app code reads the same surface on both * shells. */ applyHint(hint: AppearanceType): void; } export { AppearanceSdkModule } export { AppearanceState } /** * The appearance hint a host attaches to its `platform.getType` reply, so a * mini app knows which theme/locale to start in without a second round trip. * * Each field accepts two forms, and hosts pick whichever they can produce: * - a loose string (`'dark'`, `'en-LK'`) — for the Flutter shell, which has * no `appearance` namespace and only knows the raw values; * - the full `ThemeState`/`LocaleState` — for the web shell, whose * `ShellAppearanceService` already computes `direction`/`mode` properly. * * The SDK normalizes both into full `ThemeState`/`LocaleState` before they * reach `sdk.appearance`, so mini-app code never sees the difference. Prefer * the object form when the host has it: re-deriving `direction` from a * language subtag is a guess, whereas the host's answer is authoritative. */ export declare type AppearanceType = { /** `'light' | 'dark' | 'system'`, or a full `ThemeState`. */ theme?: string | ThemeState; /** BCP-47 tag (`en`, `en-LK`, `ar`), or a full `LocaleState`. */ locale?: string | LocaleState; }; export { AuthSdkModule } export { ChatMessage } /** * Small helpers for assembling a `ChatMessage[]` without hand-writing * literals. Only the roles the wire protocol supports (`user`, `system`) are * offered — assistant turns come back from the host model's stream, not from * a mini app assembling its own history. */ export declare const ChatMessages: { readonly user: (content: string) => ChatMessage; readonly system: (content: string) => ChatMessage; }; /** Per-call control knobs for `chat()`, currently just cancellation. */ export declare interface ChatRequestOptions { /** * When provided, aborting the signal cancels the stream (rejecting the * returned `StreamBuilder`) and notifies the host to stop generating. */ signal?: AbortSignal; } /** * The AI/chat module. `chat()` streams the host model's completion back * chunk-by-chunk rather than waiting for one monolithic response — the * returned `StreamBuilder` starts accumulating chunks immediately, and the * caller consumes them via `builder.iterate()` or awaits whole-stream * completion with `builder.waitUntilDone()`. */ export declare interface ChatSdkModule { chat(messages: ChatMessage[], options?: ModelCompletionOptions, requestOptions?: ChatRequestOptions): Promise; } export { ConfigSdkModule } /** * Connection-state events the SDK itself emits (as opposed to host-published * events). Mini apps subscribe with `sdk.on("connection.lost", …)` / * `sdk.on("connection.established", …)` to reconcile state — re-fetch config * or flags, re-subscribe to events — after a host restart or transport drop. * Emitted only when the heartbeat/reconnect feature is enabled. */ export declare const CONNECTION_EVENTS: { readonly LOST: "connection.lost"; readonly ESTABLISHED: "connection.established"; }; /** * The SDK's ready-to-use `Logger` implementation. Not wired in by default — * `MiniAppSdk` still defaults to `NoopLogger` so logging stays opt-in — but * this is what a mini app or host passes in when it wants to actually see * what the SDK is doing: * * ```ts * const sdk = new MiniAppSdk({ miniAppId: 'x' }, { * logger: new ConsoleLogger({ minLevel: 'debug', redact: new Set(['token']) }), * }); * ``` */ export declare class ConsoleLogger implements Logger { private readonly minLevel; private readonly prefix; private readonly redact; constructor(options?: ConsoleLoggerOptions); debug(message: string, context?: Record): void; info(message: string, context?: Record): void; warn(message: string, context?: Record): void; error(message: string, context?: Record): void; private write; private maybeRedact; } export declare interface ConsoleLoggerOptions { /** Minimum level that actually gets written. Anything below this is dropped. Defaults to 'info'. */ minLevel?: "debug" | "info" | "warn" | "error"; /** Prefix prepended to every message, useful for telling multiple SDK instances apart in one console. Defaults to '[MiniAppSdk]'. */ prefix?: string; /** * Masks sensitive fields in `context` before a line is written. Either a * `Set` of top-level keys to redact unconditionally, or a * predicate `(key, value) => boolean` for finer control. Redacted values * are written as `"[REDACTED]"`. Applies to top-level context keys only — * it is a fast safety net, not a full PII scrubber (nested objects are * not walked). */ redact?: Set | ((key: string, value: unknown) => boolean); } /** Constructs a `MiniAppSdk` without initializing it. Call `.initialize()` yourself. */ export declare function createMiniAppSdk(options: MiniAppSdkOptions): MiniAppSdk; /** * The device actions a mini app can feature-detect with `isSupported`. The * host protocol today is namespace-granular — every action lives under the * `device` namespace — so this union exists for typo-safety and future * per-action capability reporting, not because the host differentiates them. */ export declare type DeviceAction = "location" | "camera" | "gallery" | "files" | "download" | "contact" | "biometric" | "notifications" | "network" | "info"; export { DeviceBiometricOptions } export { DeviceBiometricResult } export { DeviceCameraResult } export { DeviceExtraOptions } export { DeviceFileOptions } export { DeviceFileResult } export { DeviceGalleryResult } export { DeviceInfoResult } export { DeviceLocationResult } export { DeviceNetworkResult } export { DeviceNotificationResult } export { DeviceNotificationsOptions } export { DevicePermissionBaseResponse } export { DevicePermissionStatus } export { DeviceSdkModule } /** * The device module, plus a `isSupported` feature-detect guard. Mini apps * branch on `sdk.device.isSupported("biometric")` instead of discovering a * missing capability at request-time via a `ProtocolError`. */ export declare interface DeviceSdkModuleWithGuards extends DeviceSdkModule { /** * Whether the host negotiated the `device` namespace during the handshake. * Returns `false` before `sdk.initialize()` resolves (capabilities aren't * known yet). Because the protocol advertises capabilities at namespace * granularity, a supported action means "the namespace exists", not that a * specific action is implemented — the host may still reject an individual * call. */ isSupported(action: DeviceAction): boolean; } export { Direction } /** * Latency percentiles computed from a bounded window of recent request * durations. `0` when no durations have been recorded yet. */ export declare interface DurationPercentiles { p50Ms: number; p95Ms: number; p99Ms: number; } export { EventHandler } declare type EventHandler_2 = (payload: TPayload) => void; export { FlagsSdkModule } /** Returns the instance created by the most recent `initMiniAppSdk()` call. */ export declare function getMiniAppSdk(): MiniAppSdk; declare type Headers_2 = Record; export { Headers_2 as Headers } /** * Tuning for the optional liveness check and automatic reconnection. Provide * `heartbeat` in `MiniAppSdkOptions` to enable it. */ export declare interface HeartbeatOptions { /** How often to send a `heartbeat.ping` to the host, in ms. Defaults to 30000. */ intervalMs?: number; /** How long to wait for the pong before counting a miss, in ms. Defaults to 5000. */ timeoutMs?: number; /** Consecutive missed pongs before the connection is declared lost. Defaults to 2. */ maxMissedPongs?: number; } export { HostDescriptor } /** * HTTP events on the wire. `UPLOAD_PROGRESS` (host → mini app) is how the * host reports bytes-sent for an in-flight upload; `HttpSdkModule` mirrors * it onto `HttpUploadOptions.onProgress`, and mini apps can also subscribe * directly with `sdk.on("http.uploadProgress", …)`. */ export declare const HTTP_EVENTS: { readonly UPLOAD_PROGRESS: "http.uploadProgress"; }; export declare interface HttpBodyRequest extends HttpRequestBase { body?: TBody; } /** * Raised when an HTTP request resolves but the host's response carries a 4xx * status. Distinct from `HttpServerError` so consumers can branch on the kind * of failure: 4xx is never retryable — the request itself was rejected, and * retrying it would only fail again. */ export declare class HttpClientError extends SdkError { /** The HTTP status code the host reported (e.g. 404, 422). */ readonly status: number; constructor(params: { status: number; message?: string; details?: Record; }); } export declare type HttpDeleteParams = HttpRequestBase; export declare type HttpGetParams = HttpQueryRequest; export { HttpMethod } export declare type HttpPatchParams = HttpBodyRequest; export declare type HttpPostParams = HttpBodyRequest; /** Progress reported during an upload, delivered via `HttpUploadOptions.onProgress`. */ export declare interface HttpProgress { uploadedBytes: number; /** The host-reported total size when it knows it up front. */ totalBytes?: number; } export declare type HttpPutParams = HttpBodyRequest; export declare interface HttpQueryRequest extends HttpRequestBase { query?: Query; } export declare interface HttpRequestBase { endpoint?: string; headers?: Headers_2; } export declare interface HttpResult { status: number; data: T; headers: Headers_2; } export { HttpSdkModule } /** * Raised when an HTTP request resolves but the host's response carries a 5xx * status. Marked `retryable: true` so the request participates in the RPC * retry machinery — a transient upstream failure is exactly the case the * backoff/retry policy was built for. */ export declare class HttpServerError extends SdkError { /** The HTTP status code the host reported (e.g. 500, 502, 503). */ readonly status: number; constructor(params: { status: number; message?: string; details?: Record; }); } /** Extra knobs for upload-carrying verbs (`post`/`put`/`patch`). */ export declare interface HttpUploadOptions { /** * Invoked as the host reports upload progress. The SDK mirrors the host's * `http.uploadProgress` event onto this callback; the host decides how * granular the updates are. No callback = no progress subscription. */ onProgress?: (progress: HttpProgress) => void; } /** Constructs, initializes, and registers a `MiniAppSdk` as the active instance. */ export declare function initMiniAppSdk(options: MiniAppSdkOptions): Promise; /** * Deep-link events on the wire (host → mini app): `OPENED` fires when the * host resolves an incoming deep link into the mini app. Subscribe via * `sdk.links.onOpen` or `sdk.on("links.opened", …)`. */ export declare const LINKS_EVENTS: { readonly OPENED: "links.opened"; }; export { LinksOpenedEvent } export { LinksOpenOptions } export { LinksSdkModule } export { LocaleState } /** * Minimal, framework-agnostic logging contract. The SDK never calls * `console.*` directly — every internal component that needs to log takes * a `Logger` via constructor injection and defaults to `NoopLogger`. * * This is intentionally small in Phase 1 (no log levels config, no * structured sinks, no transports-for-logs). It exists now purely as the * seam a future phase can build real observability behind, without * touching any call site that already logs through this interface. */ export declare interface Logger { debug(message: string, context?: Record): void; info(message: string, context?: Record): void; warn(message: string, context?: Record): void; error(message: string, context?: Record): void; } /** * Value written to `PlatformMessage.channel`. Used by hosts to distinguish * SDK protocol messages from unrelated `postMessage` traffic on the same * window. */ export declare const MESSAGE_CHANNEL = "gov-platform-sdk"; /** * The message kinds that can travel over the transport. `stream` is the * incremental delivery channel for long-running responses: a single * request is answered by a sequence of `stream` messages, each carrying * one ordered `streamIndex`, with the final one flagged `streamLast: true`. */ export declare type MessageType = "request" | "response" | "event" | "handshake" | "stream"; /** * The SDK's composition root. `MiniAppSdk`'s only responsibilities are: * 1. composing the `RpcClient`, the `ModuleRegistry`, and all domain * modules, * 2. owning instance lifecycle (`initialize` / `destroy`), * 3. exposing the public API surface (`MiniAppSdkInterface`). * * It contains no RPC logic (that's `RpcClient`), no transport wiring * (that's `Transport`/`DefaultTransport`), and no per-module business logic * (that's `modules/*`). If you're about to add a `namespace`/`action` * string or a `.request()` call directly in this file, it almost certainly * belongs in a module file instead. */ export declare class MiniAppSdk implements MiniAppSdkInterface { readonly miniAppId: string; readonly version = "1.0.0"; readonly traceId: string; readonly hostDescriptor: HostDescriptor | null; readonly auth: AuthSdkModule; readonly permissions: PermissionsSdkModule; readonly flags: FlagsSdkModule; readonly config: ConfigSdkModule; readonly navigation: NavigationSdkModule; readonly api: ApiSdkModule; readonly storage: StorageSdkModule; readonly platform: PlatformSdkModule; readonly device: DeviceSdkModuleWithGuards; readonly http: HttpSdkModule; readonly ai: ChatSdkModule; readonly appearance: AppearanceSdkModule; readonly notifications: NotificationsSdkModule; readonly links: LinksSdkModule; readonly debug: SdkDebug; private readonly rpc; private readonly logger; private readonly registry; private readonly applyPlatformResponse; private readonly appearanceHandle; private readonly appearanceUnsubscribers; private initialized; private destroyed; private initializePromise; constructor(options: MiniAppSdkOptions, dependencies?: MiniAppSdkDependencies); /** * Resolves whether dev-mode warnings/logging should be enabled. An explicit * `options.devMode` always wins; otherwise it's inferred from the bundle's * `NODE_ENV`, defaulting to off when the environment variable is absent. */ private static resolveDevMode; /** * Retrieves a module by namespace, throwing if it hasn't been registered. * Every module assigned in the constructor is registered just above this * helper's call sites, so reaching this code with a missing module is a * programmer error, not a runtime condition. */ private requireModule; /** * Namespaces the host confirmed support for during the handshake. Empty * until `initialize()` resolves. */ get capabilities(): readonly string[]; /** * Starts the transport, performs the handshake, and resolves the current * platform type. Idempotent and concurrency-safe: calling `initialize()` * multiple times (including while a prior call is still in flight) * returns the same underlying promise instead of re-running the sequence. */ initialize(): Promise; private runInitializeSequence; private subscribeToAppearanceEvents; /** * Fallback for hosts that implement the `appearance` namespace but don't * put the hint on `platform.getType` — i.e. any shell built against an * earlier SDK. Bounded budget: appearance is additive and must never block * first paint. If the host is slow or doesn't answer, initialize() still * resolves and the app falls back to the store defaults. */ private hydrateAppearance; /** * Tears down the transport and clears all pending state. Safe to call * more than once. After `destroy()`, this instance cannot be * re-initialized — construct a new `MiniAppSdk` instead. */ destroy(): void; /** * Subscribes to a host-emitted event. Returns an unsubscribe function. * Delegates entirely to `RpcClient`; the only value this method adds over * calling `rpc.onEvent` directly is that it's part of the stable public * surface consumers already depend on. Known events (see `SdkEventMap`) * get typed payloads; host-defined events outside the map remain usable * through the `string` overload. */ on(event: K, handler: (payload: SdkEventMap[K]) => void, options?: OnEventOptions): () => void; on(event: string, handler: EventHandler, options?: OnEventOptions): () => void; /** {@inheritdoc} */ request(namespace: string, action: string, payload?: unknown, options?: RpcRequestOptions): Promise; /** {@inheritdoc} */ emit(event: K, data: SdkEventMap[K]): void; emit(event: string, data?: unknown): void; /** * Registers a middleware that wraps every request made through any * module from this point forward — logging, auth-token refresh, request * shaping, custom metrics, whatever a host or vendor needs. See * `rpc/middleware.ts` for the execution model. */ use(middleware: RpcMiddleware): void; /** * A point-in-time snapshot of every request this instance has made: * totals plus a per-`namespace.action` breakdown of counts, timings, * failures, timeouts, and retries. */ getMetrics(): RpcMetricsSnapshot; /** * Adds a module beyond the built-in ones — for a host-specific capability * or a vendor's own namespace — without needing to fork the SDK. The * factory receives the same `RpcClient` every built-in module uses, so a * custom module gets retry, timeout, and middleware behavior for free. * Retrieve it later with `getModule()`. * * ```ts * sdk.registerModule('payments', (rpc) => ({ * charge: (amount: number) => rpc.request('payments', 'charge', { amount }), * })); * const payments = sdk.getModule<{ charge(amount: number): Promise }>('payments'); * ``` */ registerModule(name: string, factory: ModuleFactory): void; /** Retrieves a module registered via `registerModule()` (or any built-in module, by its namespace name). */ getModule(name: string): T | undefined; } /** * Extra, internal-only construction knobs. Deliberately **not** part of * `MiniAppSdkOptions` (the public, vendor-facing options type) — a vendor * mini-app developer configures `miniAppId`/`timeout`/`retryAttempts` the * same way they always have. `transport`, `logger`, `allowedOrigin`, and * `tracer` are for host SDKs and internal callers: `transport` to inject a * non-default delivery mechanism, `logger` to wire up real logging, * `allowedOrigin` to pin `DefaultTransport` to a known host origin from the * start instead of learning it from the first message (see * `transport/DefaultTransport.ts`), and `tracer` to bridge RPC spans into * a host's existing tracing setup (OpenTelemetry, ...). `allowedOrigin` is * ignored if a custom `transport` is also provided — origin handling is that * transport's own concern at that point. */ export declare interface MiniAppSdkDependencies { transport?: Transport; logger?: Logger; allowedOrigin?: string; tracer?: Tracer; } /** * The full public shape of a `MiniAppSdk` instance — this is the contract * vendor mini apps code against: the domain modules plus lifecycle, * event-subscription, and extensibility methods. */ export declare interface MiniAppSdkInterface { readonly miniAppId: string; readonly version: string; readonly traceId: string; /** Static host descriptor injected by the shell before mount, or null if running outside a GSA shell. */ readonly hostDescriptor: HostDescriptor | null; /** * Namespaces the host confirmed it supports, negotiated during the * handshake in `initialize()`. Empty until `initialize()` resolves. A * mini app can use this to feature-detect before calling a module the * host might not implement, instead of only discovering that at * request-time via a `ProtocolError`. */ readonly capabilities: readonly string[]; auth: AuthSdkModule; permissions: PermissionsSdkModule; flags: FlagsSdkModule; config: ConfigSdkModule; navigation: NavigationSdkModule; storage: StorageSdkModule; platform: PlatformSdkModule; device: DeviceSdkModuleWithGuards; api: ApiSdkModule; http: HttpSdkModule; ai: ChatSdkModule; /** Push notifications: permission/token registration plus tap events. */ notifications: NotificationsSdkModule; /** Deep links: open external URLs and subscribe to inbound link resolution. */ links: LinksSdkModule; /** Runtime introspection: `debug.snapshot()` returns a serializable view of this instance. */ readonly debug: SdkDebug; initialize(): Promise; destroy(): void; /** * Subscribes to a host-emitted event. Returns an unsubscribe function. * Known events get typed payloads via `SdkEventMap`; host-defined events * outside that map remain usable through the `string` overload. */ on(event: K, handler: (payload: SdkEventMap[K]) => void, options?: OnEventOptions): () => void; on(event: string, handler: EventHandler, options?: OnEventOptions): () => void; /** * Low-level escape hatch for host calls that don't have a dedicated module * method yet, or need per-call control. Identical semantics to any module * call (retry, timeout, middleware, metrics), plus optional per-request * options such as an `AbortSignal`. */ request(namespace: string, action: string, payload?: unknown, options?: RpcRequestOptions): Promise; /** * Publishes an event to the shell's internal event bus. Other shell * components may listen. Mini-apps cannot subscribe to each other * directly. Known events get typed payloads via `SdkEventMap`. */ emit(event: K, data: SdkEventMap[K]): void; emit(event: string, data?: unknown): void; /** Registers a middleware wrapping every request made from this point forward. See `rpc/middleware.ts`. */ use(middleware: RpcMiddleware): void; /** A point-in-time snapshot of request counts, timings, failures, timeouts, and retries. */ getMetrics(): RpcMetricsSnapshot; /** Adds a module beyond the nine built-in ones, backed by the same `RpcClient` every built-in module uses. */ registerModule(name: string, factory: (rpc: RpcClient) => T): void; /** Retrieves a module registered via `registerModule()`, or any built-in module by its namespace name. */ getModule(name: string): T | undefined; } /** * Constructor options for `MiniAppSdk`. `transport` is deliberately *not* * part of this type (see `client/MiniAppSdk.ts`) — transport injection is a * host-SDK concern, not something a vendor mini-app developer needs to * think about. */ export declare interface MiniAppSdkOptions { miniAppId: string; timeout?: number; retryAttempts?: number; retryDelayMs?: number; /** Ceiling for the exponential retry backoff, in milliseconds. Defaults to 8000. */ maxRetryDelayMs?: number; /** Origin to pin for postMessage. Mapped to `allowedOrigin` internally. */ targetOrigin?: string; /** * When true, the SDK warns once per `namespace.action` when a request goes * to a domain namespace the host did not negotiate, and enables a * `ConsoleLogger` if no logger was injected. Defaults to the value of * `process.env.NODE_ENV !== "production"` (auto-detect). */ devMode?: boolean; /** * Enables the built-in `ConsoleLogger` (when no `logger` is injected via * the constructor dependencies) at the given minimum level. Useful for * on-boarding a vendor onto logging without custom wiring — the * `ConsoleLogger` supports `redact` too, but a redaction set isn't * configurable from options (construct a `ConsoleLogger` for that). */ logLevel?: "debug" | "info" | "warn" | "error"; /** * Enables the optional heartbeat & reconnect: the SDK periodically pings * the host, and when `maxMissedPongs` go unanswered it emits * `connection.lost`, re-runs the handshake with backoff, then emits * `connection.established` on success. Off by default — the host must * answer `heartbeat.ping`. */ heartbeat?: HeartbeatOptions; /** * Tuning for the request metrics recorder: the duration window used for * latency percentiles, and an `onSnapshot` hook a host can use to persist * metrics instead of polling `sdk.getMetrics()`. */ metrics?: RpcMetricsOptions; } export { ModelCompletionOptions } export declare type ModuleFactory = (rpc: RpcClient) => T; /** * Navigation events on the wire, in both directions: * * - `BACK_REQUESTED` (host → mini app) is published when the user presses * the native back button. The host holds the container open until the * mini app answers with `navigation.router.back(consumed)`; `false` * means "I'm at my root, you take over". * - `ROUTE_CHANGED` (mini app → host) is what a mini app `emit()`s after * its own router moved, so the host can keep its back-button policy in * sync without polling `navigation.getCurrent()`. */ export declare const NAVIGATION_EVENTS: { readonly BACK_REQUESTED: "navigation.back.requested"; readonly ROUTE_CHANGED: "navigation.route.changed"; }; export { NavigationRouterResult } export { NavigationRouterSkdModule as NavigationRouterSdkModule } export { NavigationRouterSkdModule } export { NavigationSdkModule } export { NavigationState } export { NavigationTarget } /** * A `Logger` that discards everything. This is the SDK's default logger so * that omitting a logger has zero behavioral or performance cost — consumers * only pay for logging if they opt in by injecting a real implementation. */ export declare class NoopLogger implements Logger { debug(): void; info(): void; warn(): void; error(): void; } /** * Default `Span` used when no tracer is supplied: accepts every call and does * nothing. Kept so the `RpcClient` hot path never branches on whether tracing * is enabled. */ export declare class NoopSpan implements Span { readonly name: string; constructor(name: string); end(): void; setAttribute(): void; } /** * The default `Tracer`: starts `NoopSpan`s, so an SDK that isn't given a * tracer behaves exactly as it always has — no allocation of real spans, no * behavior change. */ export declare const noopTracer: Tracer; export { NotificationOpenEvent } /** * Notification events on the wire (host → mini app): `TOKEN` delivers the * device push token once the host has it, `OPENED` fires when the user taps * a push notification and the host resolves it into the mini app. Mini apps * subscribe via `sdk.notifications.onToken` / `sdk.notifications.onOpen`, or * directly with `sdk.on("notifications.token", …)`. */ export declare const NOTIFICATIONS_EVENTS: { readonly TOKEN: "notifications.token"; readonly OPENED: "notifications.opened"; }; export { NotificationsRegisterOptions } export { NotificationsRegisterResult } export { NotificationsSdkModule } /** Options for `MiniAppSdk.on()` / `RpcClient.onEvent()`. */ export declare interface OnEventOptions { /** * When true, the new handler is immediately invoked with the last few * payloads this SDK has already seen for that event (a small bounded * buffer, kept per event name). Handy for slow mounts that would otherwise * miss events pushed before they subscribed. Defaults to false. */ replay?: boolean; } /** A single request currently awaiting a host reply, for debug snapshots. */ export declare interface PendingRequestInfo { requestId: string; namespace: string; action: string; /** Milliseconds since the request was dispatched. */ elapsedMs: number; } export { PermissionsSdkModule } /** * Name of the `CustomEvent` a host may dispatch as a secondary inbound * channel (used by non-`postMessage` hosts, e.g. a Flutter WebView bridge * that cannot easily synthesize a `MessageEvent`). */ export declare const PLATFORM_EVENT_NAME = "gov-platform-event"; /** * Structured error shape carried inside a `response` message when the host * could not fulfil a request. This is the wire representation; the SDK * converts it into a typed `SdkError` subclass before handing it to * consumer code (see `errors/`). */ export declare interface PlatformError { code: string; message: string; retryable?: boolean; details?: Record; } /** * The single envelope shape every message — in either direction — must * conform to. Field names and meanings are frozen for the current * `PROTOCOL_VERSION`; do not change without a protocol version bump. */ export declare interface PlatformMessage { channel: string; requestId: string; type: MessageType; namespace: string; action: string; source: string; target: string; gsaProtocolVersion: string; payload?: TPayload; error?: PlatformError; traceId: string; timestamp: number; /** * Only present on `stream` messages. Zero-based position of this chunk * in the overall response, the total chunk count when the host knows it * up front, and a flag marking the final chunk. */ streamIndex?: number; streamTotal?: number; streamLast?: boolean; } export { PlatformSdkModule } export { PlatformTypeLiteral } /** * The reply shape of `platform.getType`. * * Hosts may answer in either of two forms and both are accepted: * - the legacy bare string — `"flutter"` / `"web"`; * - this object, which additionally carries the appearance hint. * * `type` and `types` are both honored so a host isn't broken by the spelling * it happened to ship with. */ export declare type PlatformTypeResponse = { type?: PlatformTypes; types?: PlatformTypes; appearance?: AppearanceType; }; /** Alias kept for hosts/consumers that spell the platform union as `PlatformTypes`. */ export declare type PlatformTypes = "flutter" | "web"; export { PlatformUser } /** * The protocol/wire version this SDK build speaks. * Bumped whenever the shape of `PlatformMessage` changes in a * backward-incompatible way. Phase 1 stamps every message with this value * but does not yet negotiate it against the host (see Phase 2). */ export declare const PROTOCOL_VERSION = "1.0.0"; export declare type Query = Record; /** * Raised when a caller aborts an in-flight request via its `AbortSignal` * before the host answers. Never retryable: a cancellation is the caller's * explicit choice, not a transient failure. */ export declare class RequestCancelledError extends SdkError { readonly namespace: string; readonly action: string; constructor(options: RequestCancelledErrorOptions); } export declare interface RequestCancelledErrorOptions { namespace: string; action: string; cause?: unknown; } /** * Owns everything about *RPC semantics* as opposed to *message delivery*: * correlation ids, the pending-request map, timeout enforcement, retry * policy, the handshake sequence (including protocol version and * capability negotiation), and event subscription. * * `RpcClient` depends only on the `Transport` interface — it has no * knowledge of `postMessage`, `window`, or any other delivery mechanism. * SDK modules (`AuthModule`, `HttpModule`, ...) depend on `RpcClient`, not * on `Transport` directly. */ declare class RpcClient { private readonly miniAppId; private readonly timeout; private readonly retryAttempts; private readonly retryDelayMs; private readonly maxRetryDelayMs; private readonly logger; private readonly devMode; private readonly transport; private readonly heartbeatOptions; private readonly pending; private readonly eventHandlers; private readonly streamConsumers; private readonly middlewares; private readonly metricsRecorder; private readonly tracer; private readonly warnedUnavailableCapabilities; private readonly traceId; private started; /** Set while a reconnect (re-run of the handshake) is in progress. */ private reconnectInProgress; private heartbeatInterval; private heartbeatMissedPongs; /** Heartbeat pings awaiting a pong, keyed by requestId. */ private readonly heartbeatPings; /** * Bounded per-event buffer of recent payloads, for `onEvent()` subscriptions * that pass the `replay` option. New subscribers receive the buffered values * immediately so a slow mount doesn't lose events that arrived before it * subscribed. */ private readonly eventReplayBuffer; /** * Namespaces the host confirmed support for during the handshake. `null` * until `handshake()` resolves. Populated to `SDK_CAPABILITIES` verbatim * when a host doesn't report its own capabilities at all (an * not-yet-upgraded host), since the safest assumption in that case is * "everything this SDK build knows how to ask for is fair game", which * is exactly today's behavior for such a host. */ private negotiatedCapabilities; constructor(transport: Transport, options: RpcClientOptions); /** Begin listening for inbound messages via the injected `Transport`. */ start(): void; /** * Stop listening and reject every in-flight request. Safe to call * multiple times and safe to call even if `start` was never called. */ stop(): void; /** * Performs the initial handshake with the host: sends this SDK build's * protocol version and capability list, and waits for the host's * acknowledgement. * * A host that doesn't yet send an acknowledgement payload (an * un-upgraded host that just echoes `{ status: 'ok' }`) completes the * handshake exactly as before — every field on the ack is optional, and * missing fields fall back to permissive defaults. A host that *does* * report an incompatible protocol version, or that explicitly rejects * the connection, causes this to reject with a `HandshakeError` instead * of silently proceeding with a connection that won't actually work. */ handshake(): Promise; private performHandshake; /** * Registers a middleware. Middlewares run in registration order (the * first registered is outermost) and wrap the entire request, including * its retry attempts — see `rpc/middleware.ts` for the execution model. * Safe to call after `start()`; a middleware registered mid-session * applies to every request made from that point on, not to ones already * in flight. */ use(middleware: RpcMiddleware): void; /** * Sends a request and resolves with the host's response payload. Passes * through any registered middleware, then through the retry loop * described on `executeWithRetry`. An optional `AbortSignal` in `options` * cancels the request (including any queued retries) with a * `RequestCancelledError` as soon as it fires. * * A span named `rpc.request` is started for the whole composed call (one * span per logical request, wrapping the retry loop — same granularity as * the middleware chain) and annotated with the namespace, action, and any * terminal error. */ request(namespace: string, action: string, payload?: unknown, options?: RpcRequestOptions): Promise; /** * Dev-mode helper: once the handshake has completed, warn once per * `namespace.action` when the namespace is a domain capability this SDK * advertises but the host did not negotiate. Protocol-level namespaces * (`event`, `handshake`) are excluded — hosts never negotiate them, so a * warning would be noise. A no-op when `devMode` is off. */ private warnOnUnavailableCapability; /** * The actual retry loop: retryable failures (currently just * `TimeoutError`) are retried up to `retryAttempts` times, waiting an * exponentially increasing, jittered delay between attempts (see * `utils/backoff.ts`) so a burst of mini apps recovering from the same * host hiccup doesn't retry in lockstep. Every attempt — success or * failure — is recorded into `metricsRecorder`. */ private executeWithRetry; /** * Delays while watching an `AbortSignal`: aborts reject early with a * `RequestCancelledError` instead of letting the caller wait out a backoff * that no longer matters. */ private abortAwareDelay; /** * Sends a request whose response the host streams back as a sequence of * `stream` messages. Resolves with a `StreamBuilder` immediately — the * first chunk may arrive before this promise settles — which callers * consume via `builder.iterate()` (per-chunk) or `builder.waitUntilDone()` * (whole-stream completion). See `stream/StreamBuilder.ts`. * * Streams deliberately bypass the middleware and retry machinery: a * stream may already have produced output by the time a failure would be * detected, so an automatic retry can't be spliced in safely. A timeout * still applies, matching every other request. * * An optional `AbortSignal` in `options` cancels the stream: the builder * rejects with a `RequestCancelledError` and the host is told to stop * producing. A mini app can also cancel directly via `builder.cancel()`, * which notifies the host the same way. */ sendStreamRequest(namespace: string, action: string, payload?: unknown, options?: RpcStreamOptions): Promise; /** * Explicitly cancels an active streamed request by its `requestId`, * rejecting its builder and notifying the host to stop producing. No-op if * the stream already settled. The RPC layer owns cancellation semantics — * the `StreamBuilder` itself stays transport-agnostic. */ cancelStream(requestId: string): void; /** * Rejects a stream's builder with the given error (defaulting to a * `StreamCancelledError`), also firing the builder's `onCancel` hook so the * host is told to stop. `onAbort` uses this for the signal path. */ private cancelStreamBuilder; /** * Fire-and-forget host notification that a stream is being cancelled, so * the host can stop generating chunks instead of streaming into the void. */ private notifyHostStreamCancelled; /** * Subscribes to a namespaced event. Returns an unsubscribe function. * * The first handler registered for a given event name triggers an * `event.subscribe` request to the host, telling it this mini app now * wants that event's data pushed to it — some hosts only start emitting * an event once they've received this. The subscribe call is * fire-and-forget: a host that doesn't require explicit subscription * simply ignores it. * * With `{ replay: true }`, the handler is immediately invoked with the * last few payloads this client has already seen for that event (a small * bounded buffer, kept per event name), so a handler registered after the * host started emitting still observes the most recent value rather than * only future changes. */ onEvent(event: string, handler: EventHandler_2, options?: OnEventOptions): () => void; /** * Records a payload into the bounded per-event replay buffer, dropping the * oldest entry once `EVENT_REPLAY_BUFFER_SIZE` is exceeded. */ private bufferEvent; getTraceId(): string; /** * Namespaces the host confirmed support for. Returns an empty array * before `handshake()` resolves — callers that need to feature-detect * before `initialize()` completes should just wait for `initialize()`. */ getCapabilities(): readonly string[]; /** * A point-in-time snapshot of every request this client has made: * totals plus a per-`namespace.action` breakdown of counts, timings, * failures, timeouts, and retries. Safe to call at any time, including * before `start()` (it just reports all zeros). */ getMetrics(): RpcMetricsSnapshot; /** * A read-only view of every request currently awaiting a host reply, for * `MiniAppSdk.debug.snapshot()`. */ getPendingRequests(): PendingRequestInfo[]; /** The SDK build version reported to the host during the handshake. */ getSdkVersion(): string; /** Debug-time view of the transport, for `MiniAppSdk.debug.snapshot()`. */ getTransportDebugInfo(): TransportDebugInfo; /** * Dispatches a local (SDK-originated) event to subscribers without going * through the transport or the host — used for connection-state * notifications that the host itself cannot deliver because the link is * down. Subscribers register exactly as they would for a host event: * `sdk.on("connection.lost", …)`. Matching the host-event routing, the * subscription fires as `event.subscribe` only when at least one handler * exists, so first registering a listener marks the connection "live". */ private emitLocalEvent; private startHeartbeat; private stopHeartbeat; private maybeSendHeartbeat; private handleLostConnection; private reconnect; private completeHandshake; private sendRequest; private sendOrFail; private handleIncomingMessage; } declare interface RpcClientOptions { miniAppId: string; timeout?: number; retryAttempts?: number; retryDelayMs?: number; maxRetryDelayMs?: number; logger?: Logger; /** * When true, warns once per `namespace.action` about requests to domain * namespaces the host did not negotiate during the handshake. No-op when * false (production). Defaults to false. */ devMode?: boolean; /** Enables the optional heartbeat & reconnect (see `HeartbeatOptions`). */ heartbeat?: HeartbeatOptions; /** Tuning for the request metrics recorder (percentile window, export hook). */ metrics?: RpcMetricsOptions; /** * Optional tracer for RPC observability. When omitted, a no-op tracer is * used and behavior is unchanged. See `observability/tracer.types.ts` for * the minimal `Tracer`/`Span` contract. */ tracer?: Tracer; } /** * Tuning for `MetricsRecorder`. All fields are optional — the defaults keep * the recorder bounded (the duration window never grows without limit), and * everything here is additive to the existing counters. */ export declare interface RpcMetricsOptions { /** * Maximum number of recent durations kept per `namespace.action` for * percentile computation. Bounds memory on long-running mini apps. * Defaults to 100. */ maxDurationEntries?: number; /** * When set, durations older than this (in ms) are excluded from * percentile computation, so the percentiles reflect a rolling recent * window rather than the whole lifetime. Defaults to no age cutoff. */ durationsWindowMs?: number; /** * Export hook: invoked with every computed snapshot. A host can persist * metrics here without maintaining its own polling loop — call * `sdk.getMetrics()` (or read any snapshot) and the hook fires. */ onSnapshot?: (snapshot: RpcMetricsSnapshot) => void; } /** A full snapshot of everything the SDK has recorded since it was constructed (or since the last `reset()`). */ export declare interface RpcMetricsSnapshot { totalRequests: number; totalSuccesses: number; totalFailures: number; totalTimeouts: number; totalRetries: number; averageDurationMs: number; /** Latency percentiles across all recorded durations (all actions combined). */ percentiles: DurationPercentiles; /** Keyed by `"namespace.action"`, e.g. `"auth.getUser"`. */ byAction: Record; } /** * A middleware wraps a request: it can inspect the context, run code before * and after, short-circuit by not calling `next()`, or transform the * result/error. Middleware compose like Express/Koa handlers — each one * decides whether and when to call `next()`. * * ```ts * const loggingMiddleware: RpcMiddleware = async (ctx, next) => { * const start = Date.now(); * try { * return await next(); * } finally { * console.log(`${ctx.namespace}.${ctx.action} took ${Date.now() - start}ms`); * } * }; * ``` */ export declare type RpcMiddleware = (context: RpcMiddlewareContext, next: RpcNext) => Promise; /** * Everything a middleware knows about the request it's wrapping. Deliberately * a plain, serializable-ish shape — a middleware shouldn't need to reach * into `RpcClient` internals to decide what to do with a call. */ export declare interface RpcMiddlewareContext { readonly namespace: string; readonly action: string; readonly payload: unknown; /** Which attempt this is, 0-indexed. Middleware wrapping the outer request only ever sees attempt 0 — see the module doc comment for why. */ readonly attempt: number; } /** Calls the next middleware in the chain (or the actual request, if this is the last one) and returns its result. */ export declare type RpcNext = () => Promise; /** Per-request control knobs passed to `request()`. */ export declare interface RpcRequestOptions { /** * When provided, aborting the signal rejects the in-flight request (and any * pending retries) with a `RequestCancelledError` — useful for unmounting * screens or navigating away without waiting for the timeout. */ signal?: AbortSignal; /** * Optional transformation applied to the host's response **inside** the * retry loop. Throwing from here — e.g. mapping an `HttpResult` carrying a * 5xx `status` onto an `HttpServerError` — rejects the request and, when * the thrown error is `retryable`, participates in the normal retry policy * exactly like any other request failure. */ mapPayload?: (payload: unknown) => unknown; } /** Per-stream control knobs passed to `sendStreamRequest()`. */ export declare interface RpcStreamOptions { /** * When provided, aborting the signal cancels the stream (rejecting the * `StreamBuilder` with a `RequestCancelledError`) and notifies the host to * stop producing. */ signal?: AbortSignal; } /** The `sdk.debug` surface: runtime introspection for support and tooling. */ export declare interface SdkDebug { /** * A one-shot, fully serializable snapshot of the instance's runtime * state — version, platform, capabilities, metrics, in-flight requests, * and registered modules. Paste-able into a support ticket or dev tools. */ snapshot(): SdkDebugSnapshot; } /** A one-shot, fully serializable view of an SDK instance's runtime state. */ export declare interface SdkDebugSnapshot { /** The SDK build version reported to the host during the handshake. */ sdkVersion: string; /** The wire protocol version this build speaks. */ protocolVersion: string; miniAppId: string; traceId: string; platformType: PlatformTypeLiteral; /** Namespaces the host confirmed support for; empty until `initialize()` resolves. */ capabilities: readonly string[]; status: SdkStatus; /** Debug-time view of the transport (origin pinning, started flag). */ transport: TransportDebugInfo; /** Request counts, timings, failures, timeouts, and retries. */ metrics: RpcMetricsSnapshot; /** Requests dispatched but not yet answered by the host. */ pendingRequests: PendingRequestInfo[]; /** Names of every module (built-in or registered) that has been built. */ registeredModules: string[]; } /** * Root of the SDK's error hierarchy. Every error the SDK throws is an * instance of `SdkError` (or one of its subclasses below), so consumers can * reliably `catch (err) { if (err instanceof SdkError) ... }` instead of * pattern-matching on message strings. */ export declare class SdkError extends Error { readonly code: string; readonly retryable: boolean; readonly details: Record | undefined; readonly cause: unknown; constructor(options: SdkErrorOptions); } /** * Exhaustive union of machine-readable error codes the SDK itself can * raise. Host-originated errors (returned inside a `response` message's * `error.code`) are host-defined strings and are preserved as-is on * `ProtocolError`/`SdkError.code` even if they don't appear in this union — * this union only constrains codes the SDK *generates*. */ export declare type SdkErrorCode = "TIMEOUT" | "TRANSPORT_NOT_STARTED" | "TRANSPORT_SEND_FAILED" | "HANDSHAKE_FAILED" | "HANDSHAKE_TIMEOUT" | "INVALID_MESSAGE" | "SDK_NOT_INITIALIZED" | "SDK_ALREADY_DESTROYED" | "REQUEST_CANCELLED" | "STREAM_CANCELLED" | "HTTP_CLIENT_ERROR" | "HTTP_SERVER_ERROR" | "HOST_ERROR"; export declare interface SdkErrorOptions { code: SdkErrorCode | (string & {}); message: string; retryable?: boolean; details?: Record; cause?: unknown; } /** * The events this SDK knows about, keyed by their full wire name. A * compile-time convenience for `sdk.on()` / `sdk.emit()` — not a runtime * filter: the `string` overloads remain, so host-defined events outside this * map keep working unchanged. Mirrors `APPEARANCE_EVENTS`, * `NAVIGATION_EVENTS`, and `CONNECTION_EVENTS`. */ export declare interface SdkEventMap { /** Payload is the raw host value: a locale tag or a full `LocaleState`. */ "appearance.locale.changed": string | LocaleState; /** Payload is the raw host value: a preference string or a full `ThemeState`. */ "appearance.theme.changed": string | ThemeState; /** The host is holding a native back press, waiting for the mini app to answer via `navigation.router.back(…)`. */ "navigation.back.requested": undefined; /** Mini app → host: how its internal router moved, so the host can keep its back-button policy in sync. */ "navigation.route.changed": { previous: string; current: string; canGoBack: boolean; }; /** Emitted when the heartbeat/reconnect detects the host went away. */ "connection.lost": { timestamp: number; }; /** Emitted after a successful reconnect handshake. */ "connection.established": { timestamp: number; }; /** Host → mini app: upload progress for an in-flight `http.post`/`put`/`patch`. */ "http.uploadProgress": HttpProgress; /** Host → mini app: the device push token was delivered or refreshed. */ "notifications.token": string; /** Host → mini app: the user tapped a push notification the host resolved into the mini app. */ "notifications.opened": NotificationOpenEvent; /** Host → mini app: a deep link was resolved into this mini app. */ "links.opened": LinksOpenedEvent; } /** Runtime status of the SDK instance, for debug snapshots. */ export declare type SdkStatus = "initializing" | "ready" | "destroyed"; /** * A single traced operation. The SDK starts one per interesting RPC phase * (handshake, request, stream) and annotates it as events happen; the tracer * implementation decides what `end()` means (submit to an OpenTelemetry * exporter, print, discard). */ export declare interface Span { readonly name: string; /** Marks the span as finished. The span is not usable afterwards. */ end(): void; /** Records a key/value attribute. Values are tracer-defined; keep them small and serializable. */ setAttribute(key: string, value: unknown): void; } export { StorageSdkModule } export { StorageSetOptions } /** * Accumulates the chunks of an in-flight streamed response and hands the * assembled result to consumers via a promise and an async iterator. * * Lifecycle: the `RpcClient` registers a `StreamBuilder` per streamed * request, feeds it one `StreamChunk` per inbound `stream` message, and the * builder resolves once the host flags the final chunk (`last: true`) or * rejects if the host reports an error / the stream times out. * * This class is intentionally transport-agnostic: it holds no reference to * `RpcClient`, `Transport`, or the wire format — chunks in, result out. * Cancellation follows the same rule: `cancel()` rejects the stream locally * and invokes the `onCancel` hook if one was set, but the hook — which is * what tells the host to stop producing — is the RPC layer's responsibility * to wire up. */ export declare class StreamBuilder { private readonly chunks; private resolved; private rejected; private receivedBytesCount; private receivedChunksCount; private totalCount; /** Hook the RPC layer sets to notify the host that this stream is being cancelled. */ private onCancelCallback; private readonly promise; private resolve?; private reject?; /** * A never-rejecting mirror of `promise`, so consumers that only want the * chunks produced before a failure (`iterate`) don't have to catch. */ private readonly settledPromise; /** Resolves when the stream completes, or rejects if it fails mid-stream. */ waitUntilDone(): Promise; /** Records one inbound chunk. Chunks are keyed by `index` (out-of-order delivery is safe). */ addChunk(chunk: StreamChunk): void; /** True once the final chunk has been received. */ get isDone(): boolean; /** True once the stream has been failed (via error chunk, transport, timeout, or cancellation). */ get isRejected(): boolean; /** Total number of distinct chunks received so far (deduplicated by index). */ get receivedChunks(): number; /** Total bytes received so far across all distinct chunks. */ get receivedBytes(): number; /** The stream's overall size as reported by the host via `streamTotal`, or 0 if it never sent one. */ get total(): number; /** * Yields every chunk received so far once the stream settles. After a * failure this yields nothing (the chunks already buffered before the * failure are considered untrustworthy — a mid-stream failure means the * response may be incomplete). */ iterate(): AsyncIterableIterator; /** Fails the stream. No further chunks are accepted. */ rejectChunk(err: Error): void; /** * Cancels the stream: rejects it with a `StreamCancelledError` (or the * provided error) and fires the `onCancel` hook the RPC layer installed, so * the host is told to stop producing. Safe to call more than once; only the * first call has any effect. */ cancel(error?: Error): void; /** * Internal hook used by the RPC layer: invoked when the mini app cancels the * stream via `cancel()`, giving the layer a chance to notify the host (e.g. * send an `ai.cancel` request) before the stream settles. Transport-agnostic * here — the hook's semantics belong entirely to whoever installs it. */ get onCancel(): (() => void) | null; set onCancel(callback: (() => void) | null); } /** * Raised when a streamed response is cancelled before it completes — either * explicitly via `StreamBuilder.cancel()` or because the mini app aborted the * owning `AbortSignal`. Never retryable: a cancellation is the caller's * explicit choice, not a transient failure. */ export declare class StreamCancelledError extends SdkError { constructor(message?: string); } export { StreamChunk } export { StreamError } export { ThemeMode } export { ThemePreference } export { ThemeState } /** * A minimal, SDK-shaped tracer interface. Deliberately tiny so an existing * tracer (OpenTelemetry, Datadog, ...) can be bridged with a thin adapter — * or so a host can implement one for its own backend without coupling the * SDK to a specific vendor. */ export declare interface Tracer { /** * Starts a span. `context` carries the request's `namespace`, `action`, * and the SDK instance's `traceId` so an adapter can connect spans to the * messages already stamped with that id on the wire. */ startSpan(name: string, context?: Record): Span; } /** * A `Transport` is a dumb pipe: it can start listening, stop listening, and * send a raw envelope. It knows nothing about requests, correlation ids, * timeouts, retries, or events — that behavior lives one layer up, in * `RpcClient` (see `rpc/RpcClient.ts`). * * Keeping `Transport` this narrow is what makes the SDK host-agnostic: a * new host environment (Electron IPC, a Web Worker, a React Native bridge) * only ever needs to implement these three methods. Nothing about * `RpcClient`, the modules, or `MiniAppSdk` needs to know or care. * * Vendor mini-app developers never construct a `Transport` themselves — a * host SDK provides one, or the SDK falls back to `DefaultTransport`. */ export declare interface Transport { /** * Begin listening for inbound messages. `onMessage` is invoked once per * inbound envelope; the transport does not need to validate or interpret * the envelope's contents — that is the caller's responsibility. */ start(onMessage: (message: PlatformMessage) => void): void; /** * Stop listening and release any resources (event listeners, timers, * sockets, etc.) acquired in `start`. Must be safe to call even if * `start` was never called, and safe to call more than once. */ stop(): void; /** * Send a single envelope to the host. Delivery is fire-and-forget from * the transport's point of view — request/response semantics, timeouts, * and retries are the caller's (`RpcClient`'s) responsibility, not the * transport's. */ send(message: PlatformMessage): void; /** * Optional introspection used by `MiniAppSdk.debug.snapshot()`. A * transport that has nothing to report (or doesn't want to) may omit it. */ getDebugInfo?(): TransportDebugInfo; } /** Debug-time view of a transport, for `MiniAppSdk.debug.snapshot()`. */ export declare interface TransportDebugInfo { /** Whether the transport is currently listening for inbound messages. */ started: boolean; /** The origin outbound messages are pinned to, when known. */ pinnedOrigin?: string | null; } export { }