{"version":3,"file":"index.mjs","names":[],"sources":["../src/events/eventMap.ts","../src/plugins/EventGateway.ts","../src/plugins/PluginLoader.ts","../src/plugins/PluginHost.ts","../src/sessionmanager/index.ts","../src/transport/httpClient.ts","../src/transport/InjectionController.ts","../src/transport/ScriptLoader.ts","../src/transport/initPatchScripts.ts","../src/transport/runtimeListenerSurface.ts","../src/transport/browserConfig.ts","../src/transport/Transport.ts","../src/createClient.ts"],"sourcesContent":["import type { HyperEmitter } from '@open-wa/hyperemitter';\nimport type { Logger } from '@open-wa/logger';\nimport type { z } from 'zod';\n\nexport interface EventContext {\n  correlationId: string;\n  attempt?: number;\n  ts: number;\n}\n\nexport interface StepEvent<TDetails = Record<string, unknown>> extends EventContext {\n  step: string;\n  details?: TDetails;\n  error?: { name: string; message: string; stack?: string };\n  durationMs?: number;\n}\n\nexport interface OpenWAEventMeta {\n  internal: boolean;\n  sensitive: boolean;\n}\n\nexport type Message = unknown;\nexport type Ack = unknown;\nexport type Chat = unknown;\nexport type ChatState = unknown;\nexport type GroupParticipantChange = unknown;\nexport type BatteryStatus = unknown;\nexport type IncomingCall = unknown;\nexport type CallState = unknown;\nexport type PollVote = unknown;\nexport type Reaction = unknown;\nexport type MessagePreProcessor = unknown;\nexport type MediaProcessResult = unknown;\nexport type WebhookRegistration = unknown;\nexport type WebhookDeliveryAttempt = unknown;\nexport type WebhookDeliveryResult = unknown;\nexport type PersistenceArtifact = unknown;\n\nexport type STATE = 'STARTING' | 'AUTHENTICATING' | 'READY' | 'DISCONNECTED' | 'STOPPED';\n\nexport interface OpenWAEventMap {\n  'launch.create.start': StepEvent<{ configSummary?: Record<string, unknown> }>;\n  'launch.create.retry': StepEvent<{ reason: string; nextAttempt: number }>;\n  'launch.create.ready': StepEvent<{ state: STATE }>;\n  \n  'launch.config.setup.before': StepEvent;\n  'launch.config.setup.after': StepEvent;\n  'launch.logging.setup.before': StepEvent;\n  'launch.logging.setup.after': StepEvent;\n  \n  'launch.update.check.before': StepEvent<{ currentVersion?: string }>;\n  'launch.update.check.after': StepEvent<{ updateAvailable?: boolean; latestVersion?: string }>;\n  \n  'launch.browser.init.before': StepEvent<{ browserArgs?: string[]; headless?: boolean }>;\n  'launch.browser.init.after': StepEvent<{ pid?: number }>;\n  \n  'launch.page.init.before': StepEvent;\n  'launch.page.init.after': StepEvent<{ userAgent?: string; viewport?: { w: number; h: number } }>;\n  'launch.page.interception.before': StepEvent<{ enabled: boolean }>;\n  'launch.page.interception.after': StepEvent;\n  \n  'launch.navigation.gotoWaWeb.before': StepEvent<{ url: string }>;\n  'launch.navigation.gotoWaWeb.after': StepEvent<{ finalUrl?: string }>;\n  \n  'launch.modules.wait.before': StepEvent<{ timeoutMs?: number }>;\n  'launch.modules.wait.after': StepEvent<{ success: boolean }>;\n  \n  'launch.injection.earlyCheck.before': StepEvent;\n  'launch.injection.earlyCheck.after': StepEvent<{ canInjectPreAuth: boolean }>;\n  \n  'launch.auth.check.before': StepEvent<{ timeoutMs?: number }>;\n  'launch.auth.check.after': StepEvent<{ isAuthenticated: boolean; method?: 'race' | 'direct' | 'shell_probe' }>;\n  'launch.auth.nuke.detected': StepEvent<{ reason: string }>;\n  'launch.auth.timeout': StepEvent<{ timeoutMs: number; phoneOutOfReach?: boolean }>;\n  'launch.auth.phoneOutOfReach': StepEvent<{ reason?: string }>;\n  \n  'launch.auth.qr.requested': StepEvent<{ smartQr?: boolean }>;\n  'launch.auth.qr.generated': StepEvent<{ qr: string; ascii?: string; attemptInThisCycle?: number }>;\n  'launch.auth.qr.scanned': StepEvent;\n  'launch.auth.qr.expired': StepEvent;\n  'launch.auth.linkCode.requested': StepEvent;\n  'launch.auth.linkCode.generated': StepEvent<{ linkCode: string }>;\n  \n  'launch.auth.pairing': StepEvent;\n  'launch.auth.syncing': StepEvent;\n  \n  'launch.license.preload.before': StepEvent<{ source?: 'local' | 'remote' | 'cached' }>;\n  'launch.license.preload.after': StepEvent<{\n    success: boolean;\n    status?: 'valid' | 'metadata_only' | 'missing' | 'invalid' | 'expired';\n    source?: 'local' | 'remote' | 'cached' | 'none';\n    payloadSource?: 'server' | 'local_metadata';\n    detail?: string;\n    blockingFailure?: boolean;\n  }>;\n  \n  'launch.wapi.inject.before': StepEvent<{ injectPreApiScripts: boolean }>;\n  'launch.wapi.inject.after': StepEvent<{ success: boolean }>;\n  'launch.helper.pre_api.before': StepEvent<{ mode: 'noop' | 'scripts' }>;\n  'launch.helper.pre_api.after': StepEvent<{ mode: 'noop' | 'scripts'; success: boolean; requiredLegacyHelpers?: readonly string[] }>;\n  \n  'launch.session.validityCheck.before': StepEvent<{ phase: 'post_injection' | 'post_patch' | 'post_overlay' }>;\n  'launch.session.validityCheck.after': StepEvent<{\n    phase: 'post_injection' | 'post_patch' | 'post_overlay';\n    valid: boolean;\n    usable: boolean;\n    hasRuntime: boolean;\n    hasStore: boolean;\n    hasMsg: boolean;\n    sessionLoaded: boolean;\n    repairable: boolean;\n    repaired?: boolean;\n    bridgeReady?: boolean;\n    requiredMethods?: string[];\n    missingMethods?: string[];\n    failureReason?: 'runtime_missing' | 'store_missing' | 'session_not_loaded' | 'required_method_missing';\n  }>;\n  'launch.session.invalid.retry': StepEvent<{ reason: string }>;\n  \n  'launch.license.check.before': StepEvent<{ source?: 'local' | 'remote' | 'cached' }>;\n  'launch.license.check.after': StepEvent<{\n    status: 'valid' | 'metadata_only' | 'missing' | 'invalid' | 'expired';\n    detail?: string;\n    source?: 'local' | 'remote' | 'cached';\n    payloadSource?: 'server' | 'local_metadata';\n    blockingFailure?: boolean;\n  }>;\n  \n  'launch.patch.init.before': StepEvent<{ phase?: 'preload'; source?: 'builtin' | 'remote' | 'cached' | 'none' }>;\n  'launch.patch.init.after': StepEvent<{\n    phase?: 'preload';\n    applied: string[];\n    available?: string[];\n    outcome?: 'ready' | 'none' | 'failed';\n    source?: 'builtin' | 'remote' | 'cached' | 'none';\n    tag?: string | null;\n    blockingFailure?: boolean;\n  }>;\n  'launch.patch.integrity.before': StepEvent<{ phase: 'post_patch' }>;\n  'launch.patch.integrity.after': StepEvent<{\n    phase: 'post_patch';\n    valid: boolean;\n    usable: boolean;\n    failureReason?: 'runtime_missing' | 'store_missing' | 'session_not_loaded' | 'required_method_missing';\n  }>;\n  \n  'launch.client.finalize.before': StepEvent<{ validationStage: 'loaded_equivalent'; patchOutcome: string; licenseStatus: string }>;\n  'launch.client.finalize.after': StepEvent<{\n    state: STATE;\n    success: boolean;\n    outcome: 'ready' | 'failed';\n    detail?: string;\n  }>;\n\n  'internal_launch_progress': { value?: number; text?: string };\n  'critical_internal_message': { value?: string; text?: string };\n\n  'session.state.changed': StepEvent<{ prev: STATE; next: STATE; reason?: string }>;\n  'session.connection.disconnected': StepEvent<{ reason?: string; wasLoggedIn?: boolean }>;\n  'session.connection.reconnecting': StepEvent<{ reason?: string }>;\n  'session.connection.reconnected': StepEvent<{ downtimeMs?: number }>;\n  \n  'session.frame.navigated': StepEvent<{ url?: string; isMainFrame: boolean }>;\n  'session.reinject.detected': StepEvent<{ reason: 'wapi_missing' | 'stale_session' | 'reload' | string }>;\n  'session.reinject.before': StepEvent<{ reason: string }>;\n  'session.reinject.after': StepEvent<{ success: boolean }>;\n  'session.reinject.qr.waiting': StepEvent<{ reason?: string }>;\n  \n  'session.stale.detected': StepEvent<{ reason?: string }>;\n  'session.logout': StepEvent<{ reason?: string }>;\n\n  'message.received': { ctx: EventContext; message: Message };\n  'message.any': { ctx: EventContext; message: Message };\n  'interactive.response': { ctx: EventContext; response: unknown };\n  'message.deleted': { ctx: EventContext; messageId: string; chatId: string; by?: string };\n\n  'ack.changed': { ctx: EventContext; ack: Ack };\n\n  'group.addedToGroup': { ctx: EventContext; groupId: string; by?: string };\n  'group.removedFromGroup': { ctx: EventContext; groupId: string; by?: string };\n  'group.participants.changed.global': { ctx: EventContext; change: GroupParticipantChange };\n  'group.approval.request': { ctx: EventContext; groupId: string; requesterId: string };\n  'group.changed': { ctx: EventContext; groupId: string; changeType: string };\n\n  'chat.deleted': { ctx: EventContext; chatId: string };\n  'chat.opened': { ctx: EventContext; chat: Chat };\n  'chat.state': { ctx: EventContext; state: ChatState };\n\n  'device.battery': { ctx: EventContext; battery: BatteryStatus };\n  'device.plugged': { ctx: EventContext; plugged: boolean; battery?: number };\n\n  'call.incoming': { ctx: EventContext; call: IncomingCall };\n  'call.state': { ctx: EventContext; state: CallState };\n\n  'auth.logout': { ctx: EventContext; reason?: string };\n\n  'ui.button': { ctx: EventContext; messageId: string; buttonId: string; from: string };\n  'ui.poll.vote': { ctx: EventContext; vote: PollVote };\n\n  'broadcast.received': { ctx: EventContext; message: Message };\n  'label.changed': { ctx: EventContext; labelId: string; action: 'added' | 'removed' | 'renamed' };\n  'story.received': { ctx: EventContext; storyId: string; from: string; timestamp: number };\n  'commerce.order': { ctx: EventContext; orderId: string; from: string };\n  'commerce.product.new': { ctx: EventContext; productId: string; catalogId?: string };\n  'reaction.added': { ctx: EventContext; reaction: Reaction };\n\n  'media.preprocess.before': { ctx: EventContext; message: Message; processors: MessagePreProcessor[] };\n  'media.preprocess.after': { ctx: EventContext; message: Message; results: MediaProcessResult[] };\n\n  'webhook.registered': { ctx: EventContext; webhook: WebhookRegistration };\n  'webhook.unregistered': { ctx: EventContext; webhookId: string };\n  'webhook.trigger.before': { ctx: EventContext; webhookId: string; event: string; payload: unknown };\n  'webhook.trigger.after': { ctx: EventContext; webhookId: string; event: string; enqueued: boolean; reasonIfSkipped?: string };\n  'webhook.queue.enqueued': { ctx: EventContext; delivery: WebhookDeliveryAttempt };\n  'webhook.queue.dequeued': { ctx: EventContext; deliveryId: string; webhookId: string };\n  'webhook.deliver.before': { ctx: EventContext; attempt: WebhookDeliveryAttempt };\n  'webhook.deliver.after': { ctx: EventContext; result: WebhookDeliveryResult };\n\n  'persistence.session.save.before': StepEvent<{ target: 'disk' | 's3' | 'memory' }>;\n  'persistence.session.save.after': StepEvent<{ artifacts: PersistenceArtifact[] }>;\n  'persistence.compress.zstd.before': StepEvent<{ inputBytes?: number }>;\n  'persistence.compress.zstd.after': StepEvent<{ artifact: PersistenceArtifact }>;\n  'persistence.archive.zip.before': StepEvent<{ inputs: Array<{ path: string; sizeBytes?: number }> }>;\n  'persistence.archive.zip.after': StepEvent<{ artifact: PersistenceArtifact }>;\n  'persistence.upload.s3.before': StepEvent<{ bucket: string; key: string; kind: 'sessionData' | 'zstd' | 'zip' }>;\n  'persistence.upload.s3.after': StepEvent<{ bucket: string; key: string; etag?: string; sizeBytes?: number }>;\n\n  'patch.apply.before': StepEvent<{ patchId: string; description?: string; required?: boolean; source?: 'builtin' | 'remote' | 'cached' }>;\n  'patch.apply.after': StepEvent<{\n    patchId: string;\n    applied: boolean;\n    outcome?: 'applied' | 'not_applicable' | 'failed';\n    required?: boolean;\n    detail?: string;\n  }>;\n  'patch.init.before': StepEvent<{ phase?: 'apply'; patchIds?: string[]; preloadOutcome?: 'ready' | 'none' | 'failed' }>;\n  'patch.init.after': StepEvent<{\n    phase?: 'apply';\n    applied: string[];\n    outcome?: 'applied' | 'skipped' | 'failed';\n    blockingFailure?: boolean;\n    results?: Array<{\n      patchId: string;\n      description?: string;\n      required: boolean;\n      outcome: 'applied' | 'not_applicable' | 'failed';\n      detail?: string;\n    }>;\n  }>;\n\n  'license.check.before': StepEvent<{ source: 'local' | 'remote' | 'cached' }>;\n  'license.check.after': StepEvent<{\n    status: 'valid' | 'metadata_only' | 'missing' | 'invalid' | 'expired';\n    detail?: string;\n    source?: 'local' | 'remote' | 'cached';\n    payloadSource?: 'server' | 'local_metadata';\n    blockingFailure?: boolean;\n  }>;\n  'license.inject.before': StepEvent;\n  'license.inject.after': StepEvent<{\n    success: boolean;\n    status?: 'valid' | 'metadata_only' | 'missing' | 'invalid' | 'expired';\n    keyType?: string;\n    payloadSource?: 'server' | 'local_metadata';\n    detail?: string;\n  }>;\n\n  'cli.launched': { ctx: EventContext; argv: string[]; version?: string };\n  'server.start.before': StepEvent<{ host?: string; port?: number }>;\n  'server.start.after': StepEvent<{ host: string; port: number }>;\n  'server.port.live': { ctx: EventContext; url: string; host: string; port: number };\n\n  'error': { scope: string; error: Error; fatal?: boolean };\n  \n  'core.starting': { config: unknown };\n  'core.started': Record<string, never>;\n  'core.stopping': { reason?: string };\n  'core.stopped': Record<string, never>;\n  \n  'client.ready': { sessionId: string };\n}\n\nexport const OpenWAEventMetaMap: Record<keyof OpenWAEventMap, OpenWAEventMeta> = {\n  'launch.create.start': { internal: true, sensitive: false },\n  'launch.create.retry': { internal: true, sensitive: false },\n  'launch.create.ready': { internal: true, sensitive: false },\n  'launch.config.setup.before': { internal: true, sensitive: false },\n  'launch.config.setup.after': { internal: true, sensitive: false },\n  'launch.logging.setup.before': { internal: true, sensitive: false },\n  'launch.logging.setup.after': { internal: true, sensitive: false },\n  'launch.update.check.before': { internal: true, sensitive: false },\n  'launch.update.check.after': { internal: true, sensitive: false },\n  'launch.browser.init.before': { internal: true, sensitive: false },\n  'launch.browser.init.after': { internal: true, sensitive: false },\n  'launch.page.init.before': { internal: true, sensitive: false },\n  'launch.page.init.after': { internal: true, sensitive: false },\n  'launch.page.interception.before': { internal: true, sensitive: false },\n  'launch.page.interception.after': { internal: true, sensitive: false },\n  'launch.navigation.gotoWaWeb.before': { internal: true, sensitive: false },\n  'launch.navigation.gotoWaWeb.after': { internal: true, sensitive: false },\n  'launch.modules.wait.before': { internal: true, sensitive: false },\n  'launch.modules.wait.after': { internal: true, sensitive: false },\n  'launch.injection.earlyCheck.before': { internal: true, sensitive: false },\n  'launch.injection.earlyCheck.after': { internal: true, sensitive: false },\n  'launch.auth.check.before': { internal: true, sensitive: false },\n  'launch.auth.check.after': { internal: true, sensitive: false },\n  'launch.auth.nuke.detected': { internal: true, sensitive: false },\n  'launch.auth.timeout': { internal: true, sensitive: false },\n  'launch.auth.phoneOutOfReach': { internal: true, sensitive: false },\n  'launch.auth.qr.requested': { internal: true, sensitive: false },\n  'launch.auth.qr.generated': { internal: true, sensitive: true },\n  'launch.auth.qr.scanned': { internal: true, sensitive: false },\n  'launch.auth.qr.expired': { internal: true, sensitive: false },\n  'launch.auth.linkCode.requested': { internal: true, sensitive: false },\n  'launch.auth.linkCode.generated': { internal: true, sensitive: true },\n  'launch.auth.pairing': { internal: true, sensitive: false },\n  'launch.auth.syncing': { internal: true, sensitive: false },\n  'launch.license.preload.before': { internal: true, sensitive: false },\n  'launch.license.preload.after': { internal: true, sensitive: false },\n  'launch.wapi.inject.before': { internal: true, sensitive: false },\n  'launch.wapi.inject.after': { internal: true, sensitive: false },\n  'launch.helper.pre_api.before': { internal: true, sensitive: false },\n  'launch.helper.pre_api.after': { internal: true, sensitive: false },\n  'launch.session.validityCheck.before': { internal: true, sensitive: false },\n  'launch.session.validityCheck.after': { internal: true, sensitive: false },\n  'launch.session.invalid.retry': { internal: true, sensitive: false },\n  'launch.license.check.before': { internal: true, sensitive: false },\n  'launch.license.check.after': { internal: true, sensitive: false },\n  'launch.patch.init.before': { internal: true, sensitive: false },\n  'launch.patch.init.after': { internal: true, sensitive: false },\n  'launch.patch.integrity.before': { internal: true, sensitive: false },\n  'launch.patch.integrity.after': { internal: true, sensitive: false },\n  'launch.client.finalize.before': { internal: true, sensitive: false },\n  'launch.client.finalize.after': { internal: true, sensitive: false },\n\n  'internal_launch_progress': { internal: true, sensitive: false },\n  'critical_internal_message': { internal: true, sensitive: false },\n\n  'session.state.changed': { internal: false, sensitive: false },\n  'session.connection.disconnected': { internal: false, sensitive: false },\n  'session.connection.reconnecting': { internal: false, sensitive: false },\n  'session.connection.reconnected': { internal: false, sensitive: false },\n  'session.frame.navigated': { internal: true, sensitive: false },\n  'session.reinject.detected': { internal: true, sensitive: false },\n  'session.reinject.before': { internal: true, sensitive: false },\n  'session.reinject.after': { internal: true, sensitive: false },\n  'session.reinject.qr.waiting': { internal: true, sensitive: false },\n  'session.stale.detected': { internal: true, sensitive: false },\n  'session.logout': { internal: false, sensitive: false },\n\n  'message.received': { internal: false, sensitive: false },\n  'message.any': { internal: false, sensitive: false },\n  'interactive.response': { internal: false, sensitive: true },\n  'message.deleted': { internal: false, sensitive: false },\n  'ack.changed': { internal: false, sensitive: false },\n  'group.addedToGroup': { internal: false, sensitive: false },\n  'group.removedFromGroup': { internal: false, sensitive: false },\n  'group.participants.changed.global': { internal: false, sensitive: false },\n  'group.approval.request': { internal: false, sensitive: false },\n  'group.changed': { internal: false, sensitive: false },\n  'chat.deleted': { internal: false, sensitive: false },\n  'chat.opened': { internal: false, sensitive: false },\n  'chat.state': { internal: false, sensitive: false },\n  'device.battery': { internal: false, sensitive: false },\n  'device.plugged': { internal: false, sensitive: false },\n  'call.incoming': { internal: false, sensitive: false },\n  'call.state': { internal: false, sensitive: false },\n  'auth.logout': { internal: false, sensitive: false },\n  'ui.button': { internal: false, sensitive: false },\n  'ui.poll.vote': { internal: false, sensitive: false },\n  'broadcast.received': { internal: false, sensitive: false },\n  'label.changed': { internal: false, sensitive: false },\n  'story.received': { internal: false, sensitive: false },\n  'commerce.order': { internal: false, sensitive: false },\n  'commerce.product.new': { internal: false, sensitive: false },\n  'reaction.added': { internal: false, sensitive: false },\n\n  'media.preprocess.before': { internal: true, sensitive: false },\n  'media.preprocess.after': { internal: true, sensitive: false },\n\n  'webhook.registered': { internal: true, sensitive: false },\n  'webhook.unregistered': { internal: true, sensitive: false },\n  'webhook.trigger.before': { internal: true, sensitive: false },\n  'webhook.trigger.after': { internal: true, sensitive: false },\n  'webhook.queue.enqueued': { internal: true, sensitive: false },\n  'webhook.queue.dequeued': { internal: true, sensitive: false },\n  'webhook.deliver.before': { internal: true, sensitive: false },\n  'webhook.deliver.after': { internal: true, sensitive: false },\n\n  'persistence.session.save.before': { internal: true, sensitive: true },\n  'persistence.session.save.after': { internal: true, sensitive: true },\n  'persistence.compress.zstd.before': { internal: true, sensitive: true },\n  'persistence.compress.zstd.after': { internal: true, sensitive: true },\n  'persistence.archive.zip.before': { internal: true, sensitive: true },\n  'persistence.archive.zip.after': { internal: true, sensitive: true },\n  'persistence.upload.s3.before': { internal: true, sensitive: true },\n  'persistence.upload.s3.after': { internal: true, sensitive: true },\n\n  'patch.apply.before': { internal: true, sensitive: false },\n  'patch.apply.after': { internal: true, sensitive: false },\n  'patch.init.before': { internal: true, sensitive: false },\n  'patch.init.after': { internal: true, sensitive: false },\n  'license.check.before': { internal: true, sensitive: false },\n  'license.check.after': { internal: true, sensitive: false },\n  'license.inject.before': { internal: true, sensitive: false },\n  'license.inject.after': { internal: true, sensitive: false },\n\n  'cli.launched': { internal: true, sensitive: false },\n  'server.start.before': { internal: true, sensitive: false },\n  'server.start.after': { internal: true, sensitive: false },\n  'server.port.live': { internal: true, sensitive: false },\n\n  'error': { internal: false, sensitive: false },\n  \n  'core.starting': { internal: false, sensitive: false },\n  'core.started': { internal: false, sensitive: false },\n  'core.stopping': { internal: false, sensitive: false },\n  'core.stopped': { internal: false, sensitive: false },\n  'client.ready': { internal: false, sensitive: false },\n};\n\nexport function isWebhookEligible(event: keyof OpenWAEventMap): boolean {\n  const meta = OpenWAEventMetaMap[event];\n  return !meta.internal && !meta.sensitive;\n}\n\nexport function isLoggingEligible(event: keyof OpenWAEventMap): boolean {\n  const meta = OpenWAEventMetaMap[event];\n  return !meta.sensitive;\n}\n","/**\n * EventGateway — Security-filtered event emitter proxy for plugins\n *\n * Creates a read-only view of HyperEmitter that mechanically enforces\n * the security policy defined in OpenWAEventMetaMap:\n *\n * - Events with `internal: true` → silently blocked\n * - Events with `sensitive: true` → silently blocked\n * - `.emit()` → not exposed (plugins are consumers only)\n *\n * This replaces the old manually-curated CATCHABLE_EVENTS allowlist\n * with a policy derived from the source of truth.\n */\nimport type { HyperEmitter } from '@open-wa/hyperemitter';\nimport type { OpenWAEventMap } from '../events/eventMap';\nimport { OpenWAEventMetaMap } from '../events/eventMap';\nimport type { Logger } from '@open-wa/logger';\nimport type { PluginEventEmitter } from '@open-wa/plugin-sdk';\n\n/**\n * Creates a security-filtered event emitter for a plugin.\n *\n * The returned object only allows subscribing to public, non-sensitive events.\n * Any attempt to listen to a blocked event is silently ignored with a warning log.\n */\nexport function createEventGateway(\n  emitter: HyperEmitter<OpenWAEventMap>,\n  pluginName: string,\n  logger: Logger,\n  signal?: AbortSignal,\n): PluginEventEmitter {\n  const isBlocked = (event: string): boolean => {\n    const meta = OpenWAEventMetaMap[event as keyof OpenWAEventMap];\n    if (!meta) return false; // unknown events pass through (forward compat)\n    return meta.internal || meta.sensitive;\n  };\n\n  return {\n    on(event: string, handler: (payload: unknown) => void) {\n      if (isBlocked(event)) {\n        logger.warn('plugin_event_blocked', {\n          plugin: pluginName,\n          event,\n          reason: 'internal or sensitive',\n        });\n        return;\n      }\n      emitter.on(event as keyof OpenWAEventMap, handler as never, { signal });\n    },\n\n    once(event: string, handler: (payload: unknown) => void) {\n      if (isBlocked(event)) {\n        logger.warn('plugin_event_blocked', {\n          plugin: pluginName,\n          event,\n          reason: 'internal or sensitive',\n        });\n        return;\n      }\n      emitter.once(event as keyof OpenWAEventMap, handler as never, { signal });\n    },\n\n    off(event: string, handler: (payload: unknown) => void) {\n      emitter.off(event as keyof OpenWAEventMap, handler as never);\n    },\n  };\n}\n\n/**\n * Returns the list of events that are NOT blocked by the gateway.\n * Useful for the catch-all event handler to know which events to wire.\n */\nexport function getPublicEvents(): (keyof OpenWAEventMap)[] {\n  return (Object.entries(OpenWAEventMetaMap) as [keyof OpenWAEventMap, { internal: boolean; sensitive: boolean }][])\n    .filter(([, meta]) => !meta.internal && !meta.sensitive)\n    .map(([event]) => event);\n}\n","/**\n * PluginLoader — Config-driven dynamic plugin loading\n *\n * Loads plugins from references specified in the global config.\n *\n * Supported reference formats:\n * - NPM scoped: \"@open-wa/integration-chatwoot\"\n * - NPM community: \"openwa-plugin-calorie-tracker\"\n * - Local relative: \"./plugins/my-plugin\"\n * - Local absolute: \"/path/to/plugin\"\n *\n * Each reference is dynamically imported. The module must export\n * a Plugin as its default export, or as a named `plugin` export.\n */\nimport type { Plugin } from '@open-wa/plugin-sdk';\nimport type { Logger } from '@open-wa/logger';\n\nexport interface LoadedPlugin {\n  /** The original reference string from config */\n  ref: string;\n  /** The loaded & validated plugin */\n  plugin: Plugin;\n}\n\n/**\n * Load plugins from an array of config references.\n *\n * @param refs - Array of npm package names or file paths\n * @param logger - Logger for reporting load success/failure\n * @returns Array of successfully loaded plugins\n *\n * @example\n * ```ts\n * const plugins = await loadPlugins([\n *   '@open-wa/integration-chatwoot',\n *   '@open-wa/integration-webhook',\n *   './my-local-plugin',\n * ], logger);\n * ```\n */\nexport async function loadPlugins(\n  refs: string[],\n  logger: Logger\n): Promise<LoadedPlugin[]> {\n  const loaded: LoadedPlugin[] = [];\n\n  for (const ref of refs) {\n    try {\n      const mod = await import(ref);\n      const plugin: Plugin | undefined = mod.default ?? mod.plugin;\n\n      if (!plugin || typeof plugin !== 'function') {\n        logger.warn('plugin_load_skip', {\n          ref,\n          reason: 'no valid default or named \"plugin\" export found',\n          availableExports: Object.keys(mod),\n        });\n        continue;\n      }\n\n      if (!plugin.meta?.name) {\n        logger.warn('plugin_load_skip', {\n          ref,\n          reason: 'plugin.meta.name is missing — use createPlugin() to define your plugin',\n        });\n        continue;\n      }\n\n      loaded.push({ ref, plugin });\n      logger.info('plugin_loaded', {\n        ref,\n        name: plugin.meta.name,\n        version: plugin.meta.version ?? 'unknown',\n      });\n    } catch (err) {\n      logger.error('plugin_load_error', {\n        ref,\n        error: err instanceof Error ? err.message : String(err),\n      });\n    }\n  }\n\n  return loaded;\n}\n\n/**\n * Validate plugin config against the plugin's schema (if one exists).\n *\n * @param plugin - The plugin with an optional configSchema\n * @param config - The raw config from pluginConfig[pluginName]\n * @param logger - Logger for reporting validation errors\n * @returns Validated config (parsed by Zod), or the raw config if no schema\n */\nexport function validatePluginConfig(\n  plugin: Plugin,\n  config: unknown,\n  logger: Logger\n): unknown {\n  if (!plugin.configSchema) {\n    return config ?? {};\n  }\n\n  const result = plugin.configSchema.safeParse(config ?? {});\n  if (!result.success) {\n    logger.error('plugin_config_invalid', {\n      plugin: plugin.meta.name,\n      errors: result.error.issues,\n    });\n    throw new Error(\n      `Invalid config for plugin \"${plugin.meta.name}\": ${result.error.message}`\n    );\n  }\n\n  return result.data;\n}\n","import type { Hono } from 'hono';\nimport type { HyperEmitter } from '@open-wa/hyperemitter';\nimport type { Logger } from '@open-wa/logger';\nimport type { OpenWAEventMap } from '../events/eventMap';\nimport type {\n  Plugin,\n  Hooks,\n  PluginInput,\n  PluginMeta,\n  ToolDefinition,\n  DashboardPage,\n  PluginManifest,\n  PluginManifestEntry,\n  PluginClient,\n} from '@open-wa/plugin-sdk';\nimport { createEventGateway, getPublicEvents } from './EventGateway';\nimport { validatePluginConfig } from './PluginLoader';\n\n// ============================================================================\n// Hook → Event mapping\n// ============================================================================\n\n/** Maps plugin hook shorthand names to actual OpenWAEventMap keys */\nconst HOOK_EVENT_MAPPING: Record<string, keyof OpenWAEventMap> = {\n  'core.starting': 'core.starting',\n  'core.started': 'core.started',\n  'core.stopping': 'core.stopping',\n  'auth.qr': 'launch.auth.qr.generated',\n  'auth.authenticated': 'launch.auth.check.after',\n  'client.ready': 'client.ready',\n  'message.received': 'message.received',\n  'message.sent': 'message.any',\n  'message.ack': 'ack.changed',\n};\n\n// ============================================================================\n// Internal types\n// ============================================================================\n\ninterface PluginEntry {\n  meta: PluginMeta;\n  hooks: Hooks;\n  abortController: AbortController;\n  activeHandlers: Set<Promise<void>>;\n}\n\n// ============================================================================\n// PluginHost\n// ============================================================================\n\n/**\n * Central registry for plugin lifecycle management.\n *\n * Responsibilities:\n * - Plugin registration with security-filtered input\n * - Wiring hooks to HyperEmitter events\n * - Collecting routes, pages, and tools from plugins\n * - Generating the runtime manifest for the dashboard\n * - Clean disposal of all plugins\n */\nexport class PluginHost {\n  private plugins = new Map<string, PluginEntry>();\n  private readonly logger: Logger;\n  private readonly events: HyperEmitter<OpenWAEventMap>;\n\n  constructor(events: HyperEmitter<OpenWAEventMap>, logger: Logger) {\n    this.events = events;\n    this.logger = logger;\n  }\n\n  /**\n   * Register a plugin with security-filtered input.\n   *\n   * @param plugin - The plugin function (created via createPlugin())\n   * @param options - Registration options\n   */\n  async register(\n    plugin: Plugin,\n    options: {\n      sessionId: string;\n      client: PluginClient;\n      pluginConfig?: Record<string, unknown>;\n    }\n  ): Promise<void> {\n    const name = plugin.meta.name;\n\n    if (this.plugins.has(name)) {\n      throw new Error(`Plugin \"${name}\" is already registered`);\n    }\n\n    // Validate config against plugin's schema\n    const rawConfig = options.pluginConfig?.[name];\n    const validatedConfig = validatePluginConfig(plugin, rawConfig, this.logger);\n\n    const abortController = new AbortController();\n\n    // Create security-filtered event emitter\n    const gateway = createEventGateway(\n      this.events,\n      name,\n      this.logger,\n      abortController.signal,\n    );\n\n    // Build the plugin input\n    const input: PluginInput = {\n      events: gateway,\n      logger: this.createScopedLogger(name),\n      config: validatedConfig,\n      sessionId: options.sessionId,\n      client: options.client,\n      signal: abortController.signal,\n    };\n\n    // Initialize the plugin\n    let hooks: Hooks;\n    try {\n      hooks = await plugin(input);\n    } catch (error) {\n      abortController.abort(error);\n      throw error;\n    }\n    this.plugins.set(name, {\n      meta: plugin.meta,\n      hooks,\n      abortController,\n      activeHandlers: new Set(),\n    });\n\n    // Wire hooks to events\n    this.wireHooks(name, hooks);\n\n    this.logger.info('plugin_registered', {\n      plugin: name,\n      version: plugin.meta.version ?? 'unknown',\n      hasRoutes: !!hooks.routes,\n      pageCount: hooks.pages?.length ?? 0,\n      toolCount: hooks.tool ? Object.keys(hooks.tool).length : 0,\n    });\n  }\n\n  // ── Hook Wiring ──────────────────────────────────────────\n\n  private wireHooks(name: string, hooks: Hooks): void {\n    this.wireSpecificHooks(name, hooks);\n    this.wireCatchAllHandler(name, hooks);\n  }\n\n  private wireSpecificHooks(name: string, hooks: Hooks): void {\n    const entry = this.plugins.get(name);\n    if (!entry) throw new Error(`Plugin \"${name}\" is not registered`);\n\n    for (const [hookName, eventName] of Object.entries(HOOK_EVENT_MAPPING)) {\n      const handler = hooks[hookName as keyof Hooks];\n      if (handler && typeof handler === 'function') {\n        this.events.on(\n          eventName,\n          (payload: unknown) => this.superviseHandler(\n            entry,\n            'plugin_hook_error',\n            hookName,\n            () => (handler as (payload: unknown) => void | Promise<void>)(payload),\n          ),\n          { signal: entry.abortController.signal },\n        );\n      }\n    }\n  }\n\n  private wireCatchAllHandler(name: string, hooks: Hooks): void {\n    if (!hooks.event) return;\n\n    const entry = this.plugins.get(name);\n    if (!entry) throw new Error(`Plugin \"${name}\" is not registered`);\n    const catchAllHandler = hooks.event;\n    const publicEvents = getPublicEvents();\n\n    for (const eventName of publicEvents) {\n      this.events.on(\n        eventName,\n        (payload: unknown) => this.superviseHandler(\n          entry,\n          'plugin_catchall_error',\n          eventName,\n          () => catchAllHandler({ event: eventName, payload }),\n        ),\n        { signal: entry.abortController.signal },\n      );\n    }\n  }\n\n  private superviseHandler(\n    entry: PluginEntry,\n    logEvent: 'plugin_hook_error' | 'plugin_catchall_error',\n    event: string,\n    handler: () => void | Promise<void>,\n  ): Promise<void> {\n    const task = Promise.resolve()\n      .then(handler)\n      .catch((error) => {\n        this.logger.error(logEvent, {\n          plugin: entry.meta.name,\n          event,\n          error,\n        });\n      })\n      .finally(() => {\n        entry.activeHandlers.delete(task);\n      });\n    entry.activeHandlers.add(task);\n    return task;\n  }\n\n  // ── Route Collection ─────────────────────────────────────\n\n  /**\n   * Get all plugin-provided Hono sub-applications.\n   * Each entry is ready to be mounted at `/plugins/<name>/`.\n   */\n  getRoutes(): Array<{ name: string; router: Hono }> {\n    const routes: Array<{ name: string; router: Hono }> = [];\n    for (const [name, { hooks }] of this.plugins) {\n      if (hooks.routes) {\n        try {\n          routes.push({ name, router: hooks.routes() });\n        } catch (err) {\n          this.logger.error('plugin_routes_error', { plugin: name, error: err });\n        }\n      }\n    }\n    return routes;\n  }\n\n  // ── Page Collection ──────────────────────────────────────\n\n  /**\n   * Get all plugin-declared dashboard pages with plugin context.\n   */\n  getPages(): Array<DashboardPage & { pluginName: string }> {\n    const pages: Array<DashboardPage & { pluginName: string }> = [];\n    for (const [name, { hooks }] of this.plugins) {\n      if (hooks.pages) {\n        for (const page of hooks.pages) {\n          pages.push({ ...page, pluginName: name });\n        }\n      }\n    }\n    return pages.sort((a, b) => (a.order ?? 100) - (b.order ?? 100));\n  }\n\n  // ── Tool Collection ──────────────────────────────────────\n\n  /**\n   * Get all plugin-registered tools, namespaced by plugin.\n   */\n  getTools(): Record<string, { plugin: string; tool: ToolDefinition }> {\n    const tools: Record<string, { plugin: string; tool: ToolDefinition }> = {};\n    for (const [name, { hooks }] of this.plugins) {\n      if (hooks.tool) {\n        for (const [toolName, toolDef] of Object.entries(hooks.tool)) {\n          tools[`${name}.${toolName}`] = { plugin: name, tool: toolDef };\n        }\n      }\n    }\n    return tools;\n  }\n\n  // ── Manifest ─────────────────────────────────────────────\n\n  /**\n   * Generate the runtime manifest consumed by the dashboard.\n   * Served at GET /plugins/manifest.\n   */\n  getManifest(): PluginManifest {\n    const plugins: PluginManifestEntry[] = [];\n    for (const [name, { meta, hooks }] of this.plugins) {\n      plugins.push({\n        name,\n        version: meta.version,\n        description: meta.description,\n        pages: hooks.pages ?? [],\n        hasRoutes: !!hooks.routes,\n        tools: hooks.tool ? Object.keys(hooks.tool) : [],\n      });\n    }\n    return { plugins };\n  }\n\n  // ── Lifecycle ────────────────────────────────────────────\n\n  /**\n   * Dispose all plugins in reverse registration order.\n   */\n  async dispose(): Promise<void> {\n    const entries = Array.from(this.plugins.entries()).reverse();\n    for (const [name, entry] of entries) {\n      entry.abortController.abort();\n      await Promise.allSettled([...entry.activeHandlers]);\n      const { hooks } = entry;\n      if (hooks.dispose) {\n        try {\n          await hooks.dispose();\n        } catch (err) {\n          this.logger.error('plugin_dispose_error', { plugin: name, error: err });\n        }\n      }\n    }\n    this.plugins.clear();\n  }\n\n  // ── Queries ──────────────────────────────────────────────\n\n  getPluginNames(): string[] {\n    return Array.from(this.plugins.keys());\n  }\n\n  hasPlugin(name: string): boolean {\n    return this.plugins.has(name);\n  }\n\n  getPluginCount(): number {\n    return this.plugins.size;\n  }\n\n  // ── Private Helpers ──────────────────────────────────────\n\n  private createScopedLogger(pluginName: string): Logger {\n    // Wrap the logger to automatically prefix all messages with the plugin name\n    const scoped = Object.create(this.logger);\n    for (const method of ['info', 'warn', 'error', 'debug'] as const) {\n      const original = this.logger[method].bind(this.logger);\n      scoped[method] = (msg: string, meta?: Record<string, unknown>) => {\n        original(msg, { ...meta, plugin: pluginName });\n      };\n    }\n    return scoped;\n  }\n}\n","import type { HyperEmitter } from '@open-wa/hyperemitter';\nimport type { Logger } from '@open-wa/logger';\nimport type { OpenWAEventMap, STATE } from '../events/eventMap';\n\nexport type SessionValidationStage = 'post_injection' | 'post_patch' | 'post_overlay';\n\nexport interface SessionCapabilitySnapshot {\n    hasRuntime: boolean;\n    hasStoreMsg: boolean;\n    sessionLoaded: boolean;\n}\n\nexport interface SessionValidationSnapshot {\n    stage: SessionValidationStage;\n    attempt: number;\n    usable: boolean;\n    repairable: boolean;\n    repaired: boolean;\n    checkedAt: number;\n    failureReason?: string;\n    capability: SessionCapabilitySnapshot;\n}\n\nexport interface SessionRepairSnapshot {\n    stage: SessionValidationStage;\n    attempt: number;\n    reason: string;\n    success: boolean;\n    at: number;\n}\n\nexport interface SessionFinalizationSnapshot {\n    outcome: 'pending' | 'ready' | 'failed';\n    updatedAt: number;\n    detail?: string;\n}\n\nexport type SessionReadinessRequirementName =\n    | 'runtimeUsable'\n    | 'patchLifecycle'\n    | 'licenseLifecycle'\n    | 'finalization';\n\nexport type SessionReadinessRequirementState = 'pending' | 'satisfied' | 'non_blocking' | 'failed';\n\nexport interface SessionReadinessRequirement {\n    state: SessionReadinessRequirementState;\n    updatedAt: number;\n    detail?: string;\n}\n\nexport type SessionLowerLevelObligationName =\n    | 'driverActiveGeneration'\n    | 'runtimeOperational'\n    | 'runtimeBridgeReady'\n    | 'reinjectionSettled';\n\nexport interface SessionLowerLevelGenerationSnapshot {\n    browserContextId: string | null;\n    documentId: string | null;\n    runtimeId: string | null;\n}\n\nexport interface SessionLowerLevelTruthSnapshot {\n    generation: SessionLowerLevelGenerationSnapshot;\n    phase?: string;\n    driverActiveGeneration: boolean;\n    runtimeOperational: boolean;\n    runtimeBridgeReady: boolean;\n    reinjectionSettled: boolean;\n    missingRuntimeMethods: string[];\n    pending: SessionLowerLevelObligationName[];\n}\n\nexport interface SessionLowerLevelTruthInput {\n    generation?: Partial<SessionLowerLevelGenerationSnapshot> | null;\n    phase?: string;\n    driverActiveGeneration?: boolean;\n    runtimeOperational?: boolean;\n    runtimeBridgeReady?: boolean;\n    reinjectionSettled?: boolean;\n    missingRuntimeMethods?: string[];\n}\n\nexport interface SessionReadinessSnapshot {\n    state: STATE;\n    status: 'ready' | 'not_ready' | 'blocked';\n    ready: boolean;\n    exposureSafe: boolean;\n    pending: Array<SessionReadinessRequirementName | SessionLowerLevelObligationName>;\n    blockers: SessionReadinessRequirementName[];\n    requirements: Record<SessionReadinessRequirementName, SessionReadinessRequirement>;\n    lowerLevel: SessionLowerLevelTruthSnapshot;\n    lastCapability: SessionCapabilitySnapshot | null;\n    validations: SessionValidationSnapshot[];\n    repairs: SessionRepairSnapshot[];\n    finalization: SessionFinalizationSnapshot;\n}\n\nexport interface SessionRuntimeSnapshot {\n    lastCapability: SessionCapabilitySnapshot | null;\n    validations: SessionValidationSnapshot[];\n    repairs: SessionRepairSnapshot[];\n    finalization: SessionFinalizationSnapshot;\n    readiness: Record<SessionReadinessRequirementName, SessionReadinessRequirement>;\n}\n\nexport interface SessionStore {\n    get(sessionId: string): Promise<unknown>;\n    set(sessionId: string, data: unknown): Promise<void>;\n    delete(sessionId: string): Promise<void>;\n}\n\nexport interface SessionManagerOptions {\n    sessionId: string;\n    events: HyperEmitter<OpenWAEventMap>;\n    logger: Logger;\n    store?: SessionStore;\n}\n\nexport class SessionManager {\n    private state: STATE = 'DISCONNECTED';\n    private sessionId: string;\n    private events: HyperEmitter<OpenWAEventMap>;\n    private logger: Logger;\n    private store?: SessionStore;\n    private runtime: SessionRuntimeSnapshot = {\n        lastCapability: null,\n        validations: [],\n        repairs: [],\n        finalization: {\n            outcome: 'pending',\n            updatedAt: Date.now(),\n        },\n        readiness: this.createInitialReadiness(),\n    };\n\n    constructor(options: SessionManagerOptions) {\n        this.sessionId = options.sessionId;\n        this.events = options.events;\n        this.logger = options.logger;\n        this.store = options.store;\n    }\n\n    async setState(newState: STATE, reason?: string): Promise<void> {\n        const prevState = this.state;\n        this.state = newState;\n        this.events.emit('session.state.changed', {\n            correlationId: 'system',\n            ts: Date.now(),\n            step: 'state_change',\n            details: { prev: prevState, next: newState, reason },\n        });\n        this.logger.debug('session_state_changed', {\n            sessionId: this.sessionId,\n            prevState,\n            nextState: newState,\n            reason,\n        });\n    }\n\n    getState(): STATE {\n        return this.state;\n    }\n\n    resetRuntime(): void {\n        this.runtime = {\n            lastCapability: null,\n            validations: [],\n            repairs: [],\n            finalization: {\n                outcome: 'pending',\n                updatedAt: Date.now(),\n            },\n            readiness: this.createInitialReadiness(),\n        };\n    }\n\n    recordValidation(snapshot: SessionValidationSnapshot): void {\n        this.runtime.lastCapability = { ...snapshot.capability };\n        this.runtime.validations = [...this.runtime.validations, snapshot];\n    }\n\n    recordRepair(snapshot: SessionRepairSnapshot): void {\n        this.runtime.repairs = [...this.runtime.repairs, snapshot];\n    }\n\n    setFinalization(outcome: SessionFinalizationSnapshot['outcome'], detail?: string): void {\n        this.runtime.finalization = {\n            outcome,\n            detail,\n            updatedAt: Date.now(),\n        };\n\n        if (outcome === 'ready') {\n            this.updateReadiness('finalization', 'satisfied', detail);\n            return;\n        }\n\n        if (outcome === 'failed') {\n            this.updateReadiness('finalization', 'failed', detail);\n            return;\n        }\n\n        this.updateReadiness('finalization', 'pending', detail);\n    }\n\n    updateReadiness(\n        requirement: SessionReadinessRequirementName,\n        state: SessionReadinessRequirementState,\n        detail?: string\n    ): void {\n        this.runtime.readiness = {\n            ...this.runtime.readiness,\n            [requirement]: {\n                state,\n                detail,\n                updatedAt: Date.now(),\n            },\n        };\n    }\n\n    getRuntimeSnapshot(): SessionRuntimeSnapshot {\n        return {\n            lastCapability: this.runtime.lastCapability ? { ...this.runtime.lastCapability } : null,\n            validations: this.runtime.validations.map((validation) => ({\n                ...validation,\n                capability: { ...validation.capability },\n            })),\n            repairs: this.runtime.repairs.map((repair) => ({ ...repair })),\n            finalization: { ...this.runtime.finalization },\n            readiness: this.cloneReadiness(),\n        };\n    }\n\n    getReadinessSnapshot(lowerLevelTruth?: SessionLowerLevelTruthInput): SessionReadinessSnapshot {\n        const requirements = this.cloneReadiness();\n        const requirementPending = (Object.entries(requirements) as Array<[SessionReadinessRequirementName, SessionReadinessRequirement]>)\n            .filter(([, requirement]) => requirement.state === 'pending')\n            .map(([name]) => name);\n        const blockers = (Object.entries(requirements) as Array<[SessionReadinessRequirementName, SessionReadinessRequirement]>)\n            .filter(([, requirement]) => requirement.state === 'failed')\n            .map(([name]) => name);\n        const lowerLevel = this.createLowerLevelTruthSnapshot(lowerLevelTruth);\n        const pending = [...requirementPending, ...lowerLevel.pending];\n        const exposureSafe = blockers.length === 0\n            && pending.length === 0\n            && this.runtime.finalization.outcome === 'ready';\n        const ready = this.state === 'READY' && exposureSafe;\n\n        return {\n            state: this.state,\n            status: ready ? 'ready' : blockers.length > 0 ? 'blocked' : 'not_ready',\n            ready,\n            exposureSafe,\n            pending,\n            blockers,\n            requirements,\n            lowerLevel,\n            lastCapability: this.runtime.lastCapability ? { ...this.runtime.lastCapability } : null,\n            validations: this.runtime.validations.map((validation) => ({\n                ...validation,\n                capability: { ...validation.capability },\n            })),\n            repairs: this.runtime.repairs.map((repair) => ({ ...repair })),\n            finalization: { ...this.runtime.finalization },\n        };\n    }\n\n    private createInitialReadiness(): Record<SessionReadinessRequirementName, SessionReadinessRequirement> {\n        const updatedAt = Date.now();\n        return {\n            runtimeUsable: {\n                state: 'pending',\n                updatedAt,\n                detail: 'Runtime injection has not yet proven usable capability',\n            },\n            patchLifecycle: {\n                state: 'pending',\n                updatedAt,\n                detail: 'Patch lifecycle has not yet completed',\n            },\n            licenseLifecycle: {\n                state: 'pending',\n                updatedAt,\n                detail: 'License lifecycle has not yet completed',\n            },\n            finalization: {\n                state: 'pending',\n                updatedAt,\n                detail: 'Session finalization has not yet completed',\n            },\n        };\n    }\n\n    private cloneReadiness(): Record<SessionReadinessRequirementName, SessionReadinessRequirement> {\n        return {\n            runtimeUsable: { ...this.runtime.readiness.runtimeUsable },\n            patchLifecycle: { ...this.runtime.readiness.patchLifecycle },\n            licenseLifecycle: { ...this.runtime.readiness.licenseLifecycle },\n            finalization: { ...this.runtime.readiness.finalization },\n        };\n    }\n\n    private createLowerLevelTruthSnapshot(lowerLevelTruth?: SessionLowerLevelTruthInput): SessionLowerLevelTruthSnapshot {\n        const generation = lowerLevelTruth?.generation;\n        const snapshot: SessionLowerLevelTruthSnapshot = {\n            generation: {\n                browserContextId: generation?.browserContextId ?? null,\n                documentId: generation?.documentId ?? null,\n                runtimeId: generation?.runtimeId ?? null,\n            },\n            phase: lowerLevelTruth?.phase,\n            driverActiveGeneration: lowerLevelTruth?.driverActiveGeneration ?? false,\n            runtimeOperational: lowerLevelTruth?.runtimeOperational ?? false,\n            runtimeBridgeReady: lowerLevelTruth?.runtimeBridgeReady ?? false,\n            reinjectionSettled: lowerLevelTruth?.reinjectionSettled ?? false,\n            missingRuntimeMethods: [...(lowerLevelTruth?.missingRuntimeMethods ?? [])],\n            pending: [],\n        };\n\n        if (!snapshot.driverActiveGeneration) {\n            snapshot.pending.push('driverActiveGeneration');\n        }\n\n        if (!snapshot.runtimeOperational) {\n            snapshot.pending.push('runtimeOperational');\n        }\n\n        if (!snapshot.runtimeBridgeReady) {\n            snapshot.pending.push('runtimeBridgeReady');\n        }\n\n        if (!snapshot.reinjectionSettled) {\n            snapshot.pending.push('reinjectionSettled');\n        }\n\n        return snapshot;\n    }\n}\n","/**\n * HTTP Client for remote patch/license operations.\n *\n * Isolates all network concerns from Transport.ts so they can be tested and mocked independently.\n * Uses native `fetch` — no axios dependency.\n *\n * Internals use Effect for retry + typed errors (see EFFECT.md); the exported\n * functions stay Promise-based and return the same `FetchAttemptResult`/throw\n * behavior as before. The per-attempt timeout is enforced by AbortController.\n */\nimport { Cause, Data, Effect, Exit, Schedule } from 'effect';\n\nexport interface PatchFetchParams {\n  waVersion?: string;\n  waAutomateVersion?: string;\n}\n\nexport interface PatchFetchResult {\n  data: string[];\n  tag: string;\n}\n\nexport interface LicenseValidationBody {\n  key: string;\n  number: string;\n  [debugField: string]: unknown;\n}\n\nexport interface HttpClientOptions {\n  timeoutMs?: number;\n  retries?: number;\n}\n\nconst DEFAULT_TIMEOUT_MS = 15_000;\nconst DEFAULT_RETRIES = 1;\n\n/**\n * Fetch patches from a remote endpoint.\n *\n * Mirrors legacy `getPatch()`:\n * - GET `patchesUrl?wv=X&wav=Y`\n * - Response: JSON array of evaluatable JS strings\n * - If no `etag` header, compute MD5 short hash\n * - On failure: try fallback URL if provided\n */\nexport async function fetchPatches(\n  primaryUrl: string,\n  params: PatchFetchParams,\n  options?: HttpClientOptions & { fallbackUrl?: string },\n): Promise<PatchFetchResult> {\n  const timeoutMs = options?.timeoutMs ?? DEFAULT_TIMEOUT_MS;\n  const retries = options?.retries ?? DEFAULT_RETRIES;\n  const fallbackUrl = options?.fallbackUrl;\n\n  const queryParams = new URLSearchParams();\n  if (params.waVersion) queryParams.set('wv', params.waVersion);\n  if (params.waAutomateVersion) queryParams.set('wav', params.waAutomateVersion);\n\n  const primaryFullUrl = queryParams.toString()\n    ? `${primaryUrl}?${queryParams.toString()}`\n    : primaryUrl;\n\n  // Try primary URL (with retry)\n  const primaryResult = await fetchWithRetry(primaryFullUrl, timeoutMs, retries);\n\n  if (primaryResult.ok) {\n    return parsePatchResponse(primaryResult);\n  }\n\n  // Fallback to GitHub raw URL if provided\n  if (fallbackUrl) {\n    const fallbackFullUrl = `${fallbackUrl}?v=${Date.now()}`;\n    const fallbackResult = await fetchWithRetry(fallbackFullUrl, timeoutMs, retries);\n\n    if (fallbackResult.ok) {\n      return parsePatchResponse(fallbackResult);\n    }\n\n    throw new Error(\n      `Patch fetch failed on both primary (${primaryUrl}) and fallback (${fallbackUrl}): ${fallbackResult.error}`,\n    );\n  }\n\n  throw new Error(`Patch fetch failed: ${primaryResult.error}`);\n}\n\n/**\n * Validate a license key with the remote key server.\n *\n * Mirrors legacy `getLicense()`:\n * - POST `licenseCheckUrl` with `{ key, number, ...debugInfo }`\n * - Response: executable JS string payload, or empty/false if invalid\n */\nexport async function validateLicense(\n  url: string,\n  body: LicenseValidationBody,\n  options?: HttpClientOptions,\n): Promise<string | false> {\n  const timeoutMs = options?.timeoutMs ?? DEFAULT_TIMEOUT_MS;\n  const retries = options?.retries ?? DEFAULT_RETRIES;\n\n  const result = await fetchWithRetry(\n    url,\n    timeoutMs,\n    retries,\n    {\n      method: 'POST',\n      headers: { 'Content-Type': 'application/json' },\n      body: JSON.stringify(body),\n    },\n  );\n\n  if (!result.ok) {\n    throw new Error(`License validation request failed: ${result.error}`);\n  }\n\n  const data = result.data;\n\n  // Legacy: empty data or falsy data means invalid key\n  if (!data || data === 'false' || data === 'null') {\n    return false;\n  }\n\n  return typeof data === 'string' ? data : String(data);\n}\n\n// ─── Internal Helpers ───────────────────────────────────────────────────────\n\ninterface FetchAttemptResult {\n  ok: boolean;\n  data?: unknown;\n  headers?: Headers;\n  error?: string;\n  statusCode?: number;\n}\n\n// Typed failure channel for the internal Effect. 4xx is non-retryable; timeout\n// and network errors and 5xx are retryable.\nclass HttpTimeoutError extends Data.TaggedError('HttpTimeoutError')<{\n  readonly timeoutMs: number;\n}> {}\nclass HttpNetworkError extends Data.TaggedError('HttpNetworkError')<{\n  readonly cause: unknown;\n}> {}\nclass HttpStatusError extends Data.TaggedError('HttpStatusError')<{\n  readonly status: number;\n  readonly statusText: string;\n}> {}\n\ntype HttpError = HttpTimeoutError | HttpNetworkError | HttpStatusError;\n\nfunction isRetryable(error: HttpError): boolean {\n  if (error._tag === 'HttpStatusError') return error.status >= 500;\n  return true; // timeout + network errors retry\n}\n\nfunction errorMessage(error: HttpError, timeoutMs: number): string {\n  switch (error._tag) {\n    case 'HttpTimeoutError':\n      return `Request timed out after ${timeoutMs}ms`;\n    case 'HttpStatusError':\n      return `HTTP ${error.status} ${error.statusText}`;\n    case 'HttpNetworkError':\n      return error.cause instanceof Error ? error.cause.message : String(error.cause);\n  }\n}\n\n/** One fetch attempt: fails with a typed error, succeeds with the parsed body. */\nfunction fetchOnce(url: string, timeoutMs: number, init?: RequestInit) {\n  return Effect.tryPromise({\n    try: async () => {\n      const controller = new AbortController();\n      const timeoutId = setTimeout(() => controller.abort(), timeoutMs);\n      try {\n        return await fetch(url, { ...init, signal: controller.signal });\n      } finally {\n        clearTimeout(timeoutId);\n      }\n    },\n    catch: (cause): HttpError =>\n      cause instanceof DOMException && cause.name === 'AbortError'\n        ? new HttpTimeoutError({ timeoutMs })\n        : new HttpNetworkError({ cause }),\n  }).pipe(\n    Effect.flatMap((response) => {\n      if (!response.ok) {\n        return Effect.fail(\n          new HttpStatusError({ status: response.status, statusText: response.statusText }),\n        );\n      }\n      return Effect.tryPromise({\n        try: async (): Promise<{ data: unknown; headers: Headers }> => {\n          const contentType = response.headers.get('content-type') ?? '';\n          const data = contentType.includes('application/json')\n            ? await response.json()\n            : await response.text();\n          return { data, headers: response.headers };\n        },\n        catch: (cause): HttpError => new HttpNetworkError({ cause }),\n      });\n    }),\n  );\n}\n\nasync function fetchWithRetry(\n  url: string,\n  timeoutMs: number,\n  maxRetries: number,\n  init?: RequestInit,\n): Promise<FetchAttemptResult> {\n  const program = fetchOnce(url, timeoutMs, init).pipe(\n    Effect.retry({\n      times: maxRetries,\n      while: isRetryable,\n      schedule: Schedule.exponential('250 millis'),\n    }),\n  );\n\n  const exit = await Effect.runPromiseExit(program);\n  if (Exit.isSuccess(exit)) {\n    return { ok: true, data: exit.value.data, headers: exit.value.headers };\n  }\n\n  const error = Cause.squash(exit.cause) as HttpError;\n  return {\n    ok: false,\n    error: errorMessage(error, timeoutMs),\n    statusCode: error._tag === 'HttpStatusError' ? error.status : undefined,\n  };\n}\n\nasync function parsePatchResponse(result: FetchAttemptResult): Promise<PatchFetchResult> {\n  let data = result.data;\n\n  // The CDN and GitHub raw endpoints return content-type: text/plain,\n  // so fetchWithRetry reads the body as text instead of parsing JSON.\n  // If data is a string, try to JSON.parse it (mirrors legacy axios.get() behavior).\n  if (typeof data === 'string') {\n    try {\n      data = JSON.parse(data);\n    } catch {\n      throw new Error(`Patch response is not valid JSON: ${(data as string).slice(0, 100)}...`);\n    }\n  }\n\n  // Ensure data is an array of strings\n  if (!Array.isArray(data)) {\n    throw new Error(`Unexpected patch response format: expected array, got ${typeof data}`);\n  }\n\n  // Compute tag from etag header, or fall back to MD5-ish hash\n  let tag: string;\n  const etag = result.headers?.get('etag');\n\n  if (etag) {\n    tag = etag.replace(/\"/g, '').slice(-5);\n  } else {\n    // Match legacy: crypto.createHash('md5').update(JSON.stringify(data)).digest('hex').slice(-5)\n    const { createHash } = await import('node:crypto');\n    tag = createHash('md5')\n      .update(JSON.stringify(data))\n      .digest('hex')\n      .slice(-5);\n  }\n\n  return { data: data as string[], tag };\n}\n","import type { DisposableHandle, IFrame, IPage } from '@open-wa/driver-interface';\nimport type { Logger } from '@open-wa/logger';\n\nexport type InjectionPhase =\n  | 'idle'\n  | 'bindings_registered'\n  | 'preload_registered'\n  | 'document_observed'\n  | 'runtime_detected'\n  | 'store_detected'\n  | 'session_ready'\n  | 'patches_applied'\n  | 'bridge_ready'\n  | 'degraded'\n  | 'disposed';\n\nexport interface GenerationRef {\n  browserContextId: string;\n  documentId: string;\n  runtimeId: string | null;\n}\n\nexport interface RuntimeHealth {\n  generation: GenerationRef;\n  phase: InjectionPhase;\n  bridgeBound: boolean;\n  preloadRegistered: boolean;\n  runtimePresent: boolean;\n  storePresent: boolean;\n  hasStoreMsg: boolean;\n  sessionLoaded: boolean;\n  bridgeReady: boolean;\n  requiredRuntimeMethods: string[];\n  missingRuntimeMethods: string[];\n  appliedPatchIds: string[];\n  degradedReasons: string[];\n  lastError?: {\n    message: string;\n    stack?: string;\n    ts: number;\n  };\n}\n\nexport type GenerationSnapshot = GenerationRef;\n\ninterface PersistentBindingRegistration {\n  name: string;\n  handler: (...args: any[]) => any;\n  required: boolean;\n  installed: boolean;\n}\n\ninterface PersistentInitScriptRegistration {\n  id: string;\n  script: string;\n  required: boolean;\n  handle: DisposableHandle | null;\n}\n\ninterface RuntimeBridgeRegistration {\n  id: string;\n  bindingName: string;\n  wapiMethod: string;\n  required: boolean;\n  boundRuntimeId: string | null;\n}\n\ninterface RuntimeBridgeCleanupHandle extends DisposableHandle {\n  readonly runtimeId: string;\n}\n\ninterface NavigationObserverRegistration {\n  id: string;\n  handler: (frame: IFrame, generation: GenerationSnapshot) => Promise<void> | void;\n}\n\ninterface RuntimeBridgeProbeResult {\n  hasRuntime: boolean;\n  hasStoreMsg: boolean;\n  sessionLoaded: boolean;\n}\n\ninterface RuntimeBridgeInstallResult {\n  status: 'registered' | 'already_registered' | 'missing_runtime' | 'missing_method' | 'failed';\n  error?: string;\n  errorStack?: string;\n}\n\ninterface RegistrationFailureContext {\n  bridgeId?: string;\n  bindingName?: string;\n  wapiMethod?: string;\n  runtimeId?: string;\n  installStatus?: RuntimeBridgeInstallResult['status'];\n  installError?: string;\n  installErrorStack?: string;\n  runtimeAsset?: string;\n}\n\nfunction createGenerationToken(prefix: string): string {\n  return `${prefix}_${Date.now().toString(36)}_${Math.random().toString(36).slice(2, 10)}`;\n}\n\nfunction createHealth(generation?: Partial<GenerationRef>): RuntimeHealth {\n  return {\n    generation: {\n      browserContextId: generation?.browserContextId ?? createGenerationToken('ctx'),\n      documentId: generation?.documentId ?? createGenerationToken('doc'),\n      runtimeId: generation?.runtimeId ?? null,\n    },\n    phase: 'idle',\n    bridgeBound: false,\n    preloadRegistered: false,\n    runtimePresent: false,\n    storePresent: false,\n    hasStoreMsg: false,\n    sessionLoaded: false,\n    bridgeReady: false,\n    requiredRuntimeMethods: [],\n    missingRuntimeMethods: [],\n    appliedPatchIds: [],\n    degradedReasons: [],\n  };\n}\n\nexport class DisposableRegistry {\n  private readonly handles = new Set<DisposableHandle>();\n\n  add<T extends DisposableHandle>(handle: T): T {\n    this.handles.add(handle);\n    return handle;\n  }\n\n  async disposeAll(): Promise<void> {\n    const handles = [...this.handles];\n    this.handles.clear();\n    await Promise.allSettled(handles.map((handle) => Promise.resolve(handle.dispose())));\n  }\n}\n\nexport class InjectionController {\n  private page: IPage | null = null;\n  private readonly pageRegistry = new DisposableRegistry();\n  private readonly runtimeRegistry = new DisposableRegistry();\n  private readonly bridgeRegistry = new DisposableRegistry();\n  private readonly persistentBindings = new Map<string, PersistentBindingRegistration>();\n  private readonly persistentInitScripts = new Map<string, PersistentInitScriptRegistration>();\n  private readonly runtimeBridges = new Map<string, RuntimeBridgeRegistration>();\n  private readonly navigationObservers = new Map<string, NavigationObserverRegistration>();\n  private lifecycleQueue: Promise<void> = Promise.resolve();\n  private health: RuntimeHealth = createHealth();\n  private activeBridgeCleanupRuntimeId: string | null = null;\n  private readonly runtimeBridgeResetTimeoutMs = 1_500;\n\n  constructor(private readonly logger: Pick<Logger, 'debug' | 'warn'>) { }\n\n  async registerPersistentBinding(\n    name: string,\n    handler: (...args: any[]) => any,\n    options: { required?: boolean } = {},\n  ): Promise<void> {\n    const existing = this.persistentBindings.get(name);\n    if (existing) {\n      existing.handler = handler;\n      existing.required = options.required ?? existing.required;\n    } else {\n      this.persistentBindings.set(name, {\n        name,\n        handler,\n        required: options.required ?? false,\n        installed: false,\n      });\n    }\n\n    if (this.page) {\n      await this.installPersistentBinding(this.persistentBindings.get(name)!);\n      this.refreshPersistentRegistrationState();\n    }\n  }\n\n  async registerPersistentInitScript(\n    id: string,\n    script: string,\n    options: { required?: boolean } = {},\n  ): Promise<void> {\n    const existing = this.persistentInitScripts.get(id);\n\n    if (existing) {\n      if (existing.handle) {\n        await Promise.resolve(existing.handle.dispose());\n      }\n\n      existing.script = script;\n      existing.required = options.required ?? existing.required;\n      existing.handle = null;\n    } else {\n      this.persistentInitScripts.set(id, {\n        id,\n        script,\n        required: options.required ?? false,\n        handle: null,\n      });\n    }\n\n    if (this.page) {\n      await this.installPersistentInitScript(this.persistentInitScripts.get(id)!);\n      this.refreshPersistentRegistrationState();\n    }\n  }\n\n  async registerRuntimeWapiBridge(\n    id: string,\n    bindingName: string,\n    handler: (...args: any[]) => any,\n    options: { wapiMethod: string; required?: boolean },\n  ): Promise<void> {\n    await this.registerPersistentBinding(bindingName, handler, { required: options.required });\n\n    const existing = this.runtimeBridges.get(id);\n    if (existing) {\n      existing.bindingName = bindingName;\n      existing.wapiMethod = options.wapiMethod;\n      existing.required = options.required ?? existing.required;\n      existing.boundRuntimeId = null;\n      return;\n    }\n\n    this.runtimeBridges.set(id, {\n      id,\n      bindingName,\n      wapiMethod: options.wapiMethod,\n      required: options.required ?? false,\n      boundRuntimeId: null,\n    });\n  }\n\n  registerNavigationObserver(\n    id: string,\n    handler: (frame: IFrame, generation: GenerationSnapshot) => Promise<void> | void,\n  ): void {\n    this.navigationObservers.set(id, { id, handler });\n  }\n\n  getRequiredRuntimeMethods(): string[] {\n    return [...new Set(\n      [...this.runtimeBridges.values()]\n        .filter((bridge) => bridge.required)\n        .map((bridge) => bridge.wapiMethod)\n    )].sort();\n  }\n\n  async ensureRuntimeBridge(): Promise<boolean> {\n    if (!this.page) {\n      return false;\n    }\n\n    this.resetRuntimeBridgeDegradation();\n\n    const probe = await this.probeRuntimeBridgeState();\n    const runtimeId = this.ensureRuntimeId();\n    const registeredRuntimeBridges = [...this.runtimeBridges.values()];\n    const requiredRuntimeMethods = this.getRequiredRuntimeMethods();\n    const missingRuntimeMethods = new Set<string>();\n\n    this.health = {\n      ...this.health,\n      runtimePresent: probe.hasRuntime,\n      storePresent: probe.hasStoreMsg,\n      hasStoreMsg: probe.hasStoreMsg,\n      sessionLoaded: probe.sessionLoaded,\n      bridgeReady: false,\n      requiredRuntimeMethods,\n      missingRuntimeMethods: [],\n      phase: this.deriveRuntimePhase({\n        ...probe,\n        bridgeReady: false,\n      }),\n    };\n\n    if (!probe.hasRuntime) {\n      return false;\n    }\n\n    if (registeredRuntimeBridges.length === 0) {\n      this.health = {\n        ...this.health,\n        bridgeReady: true,\n        requiredRuntimeMethods,\n        missingRuntimeMethods: [],\n        phase: this.deriveRuntimePhase({\n          ...probe,\n          bridgeReady: true,\n        }),\n      };\n\n      return true;\n    }\n\n    let allRequiredBound = true;\n    let anyBridgeBound = false;\n\n    for (const bridge of registeredRuntimeBridges) {\n      const result = await this.installRuntimeBridge(bridge, runtimeId);\n\n      if (result.status === 'registered' || result.status === 'already_registered') {\n        anyBridgeBound = true;\n        bridge.boundRuntimeId = runtimeId;\n        continue;\n      }\n\n      bridge.boundRuntimeId = null;\n\n        if (bridge.required) {\n          allRequiredBound = false;\n          if (result.status === 'missing_method') {\n            missingRuntimeMethods.add(bridge.wapiMethod);\n          }\n          this.noteRegistrationFailure(\n            `runtime_bridge:${bridge.id}`,\n            new Error(result.error ?? result.status),\n            true,\n            {\n              bridgeId: bridge.id,\n              bindingName: bridge.bindingName,\n              wapiMethod: bridge.wapiMethod,\n              runtimeId,\n              installStatus: result.status,\n              installError: result.error,\n              installErrorStack: result.errorStack,\n              runtimeAsset: 'wapi.js',\n            },\n          );\n        }\n      }\n\n    if (anyBridgeBound) {\n      await this.ensureBridgeCleanupHandle(runtimeId);\n    }\n\n    const requiredBridges = registeredRuntimeBridges.filter((bridge) => bridge.required);\n    const bridgeReady = requiredBridges.length > 0\n      ? allRequiredBound\n      : anyBridgeBound;\n\n    this.health = {\n      ...this.health,\n      bridgeReady,\n      requiredRuntimeMethods,\n      missingRuntimeMethods: [...missingRuntimeMethods].sort(),\n      phase: this.deriveRuntimePhase({\n        ...probe,\n        bridgeReady,\n      }),\n    };\n\n    return bridgeReady;\n  }\n\n  async rolloverRuntimeGeneration(): Promise<GenerationSnapshot> {\n    this.clearRuntimeBridgeState();\n    await this.runtimeRegistry.disposeAll();\n    await this.disposeBridgeRegistry();\n\n    const runtimeId = createGenerationToken('rt');\n    this.health = {\n      ...this.health,\n      generation: {\n        ...this.health.generation,\n        runtimeId,\n      },\n      bridgeReady: false,\n      phase: this.deriveRuntimePhase({\n        hasRuntime: this.health.runtimePresent,\n        hasStoreMsg: this.health.hasStoreMsg,\n        sessionLoaded: this.health.sessionLoaded,\n        bridgeReady: false,\n      }),\n    };\n\n    return this.captureGenerationSnapshot();\n  }\n\n  async initialize(page: IPage): Promise<void> {\n    if (this.page && this.page !== page) {\n      await this.disposePageInfrastructure();\n    }\n\n    this.page = page;\n    this.bumpBrowserContextGeneration();\n    await this.installPersistentInfrastructure();\n    this.attachPageLifecycle(page);\n  }\n\n  captureGenerationSnapshot(): GenerationSnapshot {\n    return { ...this.health.generation };\n  }\n\n  isCurrentGeneration(snapshot: GenerationSnapshot): boolean {\n    return (\n      snapshot.browserContextId === this.health.generation.browserContextId\n      && snapshot.documentId === this.health.generation.documentId\n      && snapshot.runtimeId === this.health.generation.runtimeId\n    );\n  }\n\n  getHealthSnapshot(): RuntimeHealth {\n    return {\n      ...this.health,\n      generation: { ...this.health.generation },\n      appliedPatchIds: [...this.health.appliedPatchIds],\n      requiredRuntimeMethods: [...this.health.requiredRuntimeMethods],\n      missingRuntimeMethods: [...this.health.missingRuntimeMethods],\n      degradedReasons: [...this.health.degradedReasons],\n      lastError: this.health.lastError ? { ...this.health.lastError } : undefined,\n    };\n  }\n\n  async enqueue(task: () => Promise<void>): Promise<void> {\n    this.lifecycleQueue = this.lifecycleQueue.then(task, task);\n    return this.lifecycleQueue;\n  }\n\n  async waitForIdle(): Promise<GenerationSnapshot> {\n    await this.enqueue(async () => undefined);\n    return this.captureGenerationSnapshot();\n  }\n\n  async dispose(): Promise<void> {\n    await this.disposePageInfrastructure();\n    this.page = null;\n    this.health = {\n      ...this.health,\n      phase: 'disposed',\n    };\n  }\n\n  private async installPersistentInfrastructure(): Promise<void> {\n    await this.installPersistentBindings();\n    await this.installPersistentInitScripts();\n    this.refreshPersistentRegistrationState();\n  }\n\n  private async installPersistentBindings(): Promise<void> {\n    for (const binding of this.persistentBindings.values()) {\n      await this.installPersistentBinding(binding);\n    }\n  }\n\n  private async installPersistentBinding(binding: PersistentBindingRegistration): Promise<void> {\n    if (!this.page || binding.installed) {\n      return;\n    }\n\n    try {\n      // Keep the page binding stable while allowing registration to update its handler.\n      await this.page.exposeFunction(binding.name, (...args: any[]) => binding.handler(...args));\n      binding.installed = true;\n      this.logger.debug('injection_controller_binding_registered', {\n        binding: binding.name,\n        generation: this.health.generation.browserContextId,\n      });\n    } catch (error) {\n      binding.installed = false;\n      this.noteRegistrationFailure(`binding:${binding.name}`, error, binding.required);\n    }\n  }\n\n  private async installPersistentInitScripts(): Promise<void> {\n    for (const registration of this.persistentInitScripts.values()) {\n      await this.installPersistentInitScript(registration);\n    }\n  }\n\n  private async installPersistentInitScript(registration: PersistentInitScriptRegistration): Promise<void> {\n    if (!this.page || registration.handle) {\n      return;\n    }\n\n    try {\n      registration.handle = await this.page.addInitScript(registration.script);\n\n      this.logger.debug('injection_controller_init_script_registered', {\n        initScript: registration.id,\n        generation: this.health.generation.browserContextId,\n      });\n    } catch (error) {\n      registration.handle = null;\n      this.noteRegistrationFailure(`init:${registration.id}`, error, registration.required);\n    }\n  }\n\n  private attachPageLifecycle(page: IPage): void {\n    this.pageRegistry.add(\n      page.on('framenavigated', (frame) => {\n        if (!this.isMainFrame(frame)) {\n          return;\n        }\n\n        void this.enqueue(async () => {\n          this.bumpDocumentGeneration();\n          this.clearRuntimeBridgeState();\n          await this.runtimeRegistry.disposeAll();\n          await this.disposeBridgeRegistry();\n          const generation = this.captureGenerationSnapshot();\n          await this.notifyNavigationObservers(frame, generation);\n        }).catch((error) => {\n          this.logger.warn('injection_controller_lifecycle_task_failed', {\n            phase: 'framenavigated',\n            error: error instanceof Error ? error.message : String(error),\n          });\n        });\n      }),\n    );\n  }\n\n  private async disposePageInfrastructure(): Promise<void> {\n    await this.pageRegistry.disposeAll();\n    await this.runtimeRegistry.disposeAll();\n    await this.disposeBridgeRegistry();\n\n    const initScripts = [...this.persistentInitScripts.values()];\n    await Promise.allSettled(\n      initScripts\n        .filter((registration) => registration.handle)\n        .map(async (registration) => {\n          await Promise.resolve(registration.handle?.dispose());\n          registration.handle = null;\n        }),\n    );\n\n    for (const binding of this.persistentBindings.values()) {\n      binding.installed = false;\n    }\n\n    this.clearRuntimeBridgeState();\n  }\n\n  private async ensureBridgeCleanupHandle(runtimeId: string): Promise<void> {\n    if (this.activeBridgeCleanupRuntimeId === runtimeId) {\n      return;\n    }\n\n    await this.disposeBridgeRegistry();\n    this.bridgeRegistry.add(this.createBridgeCleanupHandle(runtimeId));\n    this.activeBridgeCleanupRuntimeId = runtimeId;\n  }\n\n  private async disposeBridgeRegistry(): Promise<void> {\n    await this.bridgeRegistry.disposeAll();\n    this.activeBridgeCleanupRuntimeId = null;\n  }\n\n  private createBridgeCleanupHandle(runtimeId: string): RuntimeBridgeCleanupHandle {\n    return {\n      runtimeId,\n      dispose: () => this.resetPageRuntimeBridgeState(`runtime_cleanup:${runtimeId}`),\n    };\n  }\n\n  private async resetPageRuntimeBridgeState(reason: string): Promise<void> {\n    if (!this.page) {\n      return;\n    }\n\n    const cleanupPromise = this.page.evaluate(({ reason: resetReason }) => {\n      const root = globalThis as typeof globalThis & {\n        __OPENWA_RUNTIME_BRIDGE__?: {\n          runtimeId: string | null;\n          runtimeRef: unknown;\n          listeners: Record<string, { dispose?: (() => unknown) | undefined }>;\n          lastResetAt?: number;\n          lastResetReason?: string;\n        };\n      };\n\n      const state = root.__OPENWA_RUNTIME_BRIDGE__;\n      if (!state) {\n        return;\n      }\n\n      for (const listener of Object.values(state.listeners ?? {})) {\n        try {\n          listener.dispose?.();\n        } catch {\n          // Ignore page-side listener cleanup failures during reset.\n        }\n      }\n\n      state.runtimeId = null;\n      state.runtimeRef = null;\n      state.listeners = {};\n      state.lastResetAt = Date.now();\n      state.lastResetReason = resetReason;\n      root.__OPENWA_RUNTIME_BRIDGE__ = state;\n    }, { reason });\n\n    try {\n      let cleanupError: unknown;\n      const guardedCleanupPromise = cleanupPromise.catch((error) => {\n        cleanupError = error;\n      });\n\n      await Promise.race([\n        guardedCleanupPromise,\n        new Promise<void>((_, reject) => {\n          setTimeout(() => {\n            reject(new Error(`runtime_bridge_reset_timeout:${this.runtimeBridgeResetTimeoutMs}`));\n          }, this.runtimeBridgeResetTimeoutMs);\n        }),\n      ]);\n\n      if (cleanupError) {\n        throw cleanupError;\n      }\n    } catch (error) {\n      this.logger.warn('injection_controller_runtime_bridge_reset_failed', {\n        reason,\n        error: error instanceof Error ? error.message : String(error),\n      });\n    }\n  }\n\n  private refreshPersistentRegistrationState(): void {\n    const requiredBindings = [...this.persistentBindings.values()].filter((binding) => binding.required);\n    const requiredInitScripts = [...this.persistentInitScripts.values()].filter((script) => script.required);\n    const optionalBindingsInstalled = [...this.persistentBindings.values()].some((binding) => binding.installed);\n    const optionalInitScriptsInstalled = [...this.persistentInitScripts.values()].some((script) => Boolean(script.handle));\n\n    const bridgeBound = requiredBindings.length > 0\n      ? requiredBindings.every((binding) => binding.installed)\n      : optionalBindingsInstalled;\n\n    const preloadRegistered = requiredInitScripts.length > 0\n      ? requiredInitScripts.every((script) => Boolean(script.handle))\n      : optionalInitScriptsInstalled;\n\n    this.health = {\n      ...this.health,\n      bridgeBound,\n      preloadRegistered,\n      phase: this.derivePhase(bridgeBound, preloadRegistered),\n    };\n  }\n\n  private derivePhase(bridgeBound: boolean, preloadRegistered: boolean): InjectionPhase {\n    if (this.health.phase === 'disposed') {\n      return 'disposed';\n    }\n\n    if (this.health.degradedReasons.length > 0) {\n      return 'degraded';\n    }\n\n    if (preloadRegistered) {\n      return 'preload_registered';\n    }\n\n    if (bridgeBound) {\n      return 'bindings_registered';\n    }\n\n    return 'idle';\n  }\n\n  private bumpBrowserContextGeneration(): void {\n    this.clearRuntimeBridgeState();\n    this.health = createHealth({\n      browserContextId: createGenerationToken('ctx'),\n      documentId: createGenerationToken('doc'),\n      runtimeId: null,\n    });\n  }\n\n  private bumpDocumentGeneration(): void {\n    this.health = {\n      ...createHealth({\n        browserContextId: this.health.generation.browserContextId,\n        documentId: createGenerationToken('doc'),\n        runtimeId: null,\n      }),\n      bridgeBound: this.health.bridgeBound,\n      preloadRegistered: this.health.preloadRegistered,\n      phase: 'document_observed',\n      degradedReasons: [...this.health.degradedReasons],\n      lastError: this.health.lastError ? { ...this.health.lastError } : undefined,\n    };\n  }\n\n  private clearRuntimeBridgeState(): void {\n    for (const bridge of this.runtimeBridges.values()) {\n      bridge.boundRuntimeId = null;\n    }\n\n    this.health = {\n      ...this.health,\n      bridgeReady: false,\n      missingRuntimeMethods: [],\n    };\n  }\n\n  private resetRuntimeBridgeDegradation(): void {\n    const degradedReasons = this.health.degradedReasons.filter(\n      (reason) => !reason.startsWith('runtime_bridge:')\n    );\n\n    this.health = {\n      ...this.health,\n      degradedReasons,\n      missingRuntimeMethods: [],\n      lastError: degradedReasons.length > 0 ? this.health.lastError : undefined,\n    };\n  }\n\n  private ensureRuntimeId(): string {\n    const existingRuntimeId = this.health.generation.runtimeId;\n    if (existingRuntimeId) {\n      return existingRuntimeId;\n    }\n\n    const runtimeId = createGenerationToken('rt');\n    this.health = {\n      ...this.health,\n      generation: {\n        ...this.health.generation,\n        runtimeId,\n      },\n    };\n\n    return runtimeId;\n  }\n\n  private async probeRuntimeBridgeState(): Promise<RuntimeBridgeProbeResult> {\n    if (!this.page) {\n      return {\n        hasRuntime: false,\n        hasStoreMsg: false,\n        sessionLoaded: false,\n      };\n    }\n\n    return this.page.evaluate(() => {\n      const root = globalThis as typeof globalThis & {\n        WAPI?: Record<string, unknown>;\n        Store?: { Msg?: unknown };\n        isSessionLoaded?: () => boolean;\n        WA_AUTHENTICATED?: boolean;\n        document?: { querySelector?: (selector: string) => unknown };\n      };\n\n      const hasRuntime = Boolean(root.WAPI);\n      const hasStoreMsg = Boolean(root.Store && root.Store.Msg);\n      const sessionLoaded = Boolean(\n        (typeof root.isSessionLoaded === 'function' && root.isSessionLoaded())\n        || root.WA_AUTHENTICATED\n        || root.document?.querySelector?.('#pane-side')\n        || root.document?.querySelector?.('[data-testid=\"chat-list-search\"]')\n      );\n\n      return {\n        hasRuntime,\n        hasStoreMsg,\n        sessionLoaded,\n      };\n    }, undefined);\n  }\n\n  private async installRuntimeBridge(\n    bridge: RuntimeBridgeRegistration,\n    runtimeId: string,\n  ): Promise<RuntimeBridgeInstallResult> {\n    if (!this.page) {\n      return { status: 'failed', error: 'page_unavailable' };\n    }\n\n    return this.page.evaluate(({ bridgeId, bindingName, runtimeId: currentRuntimeId, wapiMethod }) => {\n      const root = globalThis as typeof globalThis & {\n        WAPI?: Record<string, (...args: any[]) => unknown>;\n        __OPENWA_RUNTIME_BRIDGE__?: {\n          runtimeId: string | null;\n          runtimeRef: unknown;\n          listeners: Record<string, {\n            bindingName: string;\n            wapiMethod: string;\n            registeredAt: number;\n            dispose?: (() => unknown) | undefined;\n          }>;\n          lastResetAt?: number;\n          lastResetReason?: string;\n        };\n      };\n\n      const normalizeDisposer = (value: unknown): (() => unknown) | undefined => {\n        if (typeof value === 'function') {\n          return value as () => unknown;\n        }\n\n        if (!value || typeof value !== 'object') {\n          return undefined;\n        }\n\n        const candidate = value as Record<string, unknown>;\n        for (const methodName of ['dispose', 'unsubscribe', 'off', 'remove']) {\n          const method = candidate[methodName];\n          if (typeof method === 'function') {\n            return () => (method as () => unknown).call(value);\n          }\n        }\n\n        return undefined;\n      };\n\n      const resetState = (\n        state: NonNullable<typeof root.__OPENWA_RUNTIME_BRIDGE__>,\n        reason: string,\n      ) => {\n        for (const listener of Object.values(state.listeners ?? {})) {\n          try {\n            listener.dispose?.();\n          } catch {\n            // Ignore page-side listener cleanup failures during runtime rollover.\n          }\n        }\n\n        state.runtimeId = null;\n        state.runtimeRef = null;\n        state.listeners = {};\n        state.lastResetAt = Date.now();\n        state.lastResetReason = reason;\n      };\n\n      if (!root.WAPI) {\n        return { status: 'missing_runtime' } satisfies RuntimeBridgeInstallResult;\n      }\n\n      const register = root.WAPI[wapiMethod];\n      if (typeof register !== 'function') {\n        return { status: 'missing_method' } satisfies RuntimeBridgeInstallResult;\n      }\n\n      const state = root.__OPENWA_RUNTIME_BRIDGE__ ?? {\n        runtimeId: null,\n        runtimeRef: null,\n        listeners: {},\n      };\n\n      if (state.runtimeRef && state.runtimeRef !== root.WAPI) {\n        resetState(state, 'runtime_replaced');\n      }\n\n      if (state.runtimeId && state.runtimeId !== currentRuntimeId) {\n        resetState(state, 'runtime_rollover');\n      }\n\n      state.runtimeId = currentRuntimeId;\n      state.runtimeRef = root.WAPI;\n\n      if (state.listeners[bridgeId]) {\n        root.__OPENWA_RUNTIME_BRIDGE__ = state;\n        return { status: 'already_registered' } satisfies RuntimeBridgeInstallResult;\n      }\n\n      const exposed = (root as Record<string, unknown>)[bindingName];\n      if (typeof exposed !== 'function') {\n        return {\n          status: 'failed',\n          error: `missing_exposed_binding:${bindingName}`,\n        } satisfies RuntimeBridgeInstallResult;\n      }\n\n      try {\n        const result = register((payload: unknown) => (exposed as (payload: unknown) => unknown)(payload));\n        if (result === false) {\n          return { status: 'failed', error: `registration_returned_false:${bridgeId}` } satisfies RuntimeBridgeInstallResult;\n        }\n\n        state.listeners[bridgeId] = {\n          bindingName,\n          wapiMethod,\n          registeredAt: Date.now(),\n          dispose: normalizeDisposer(result),\n        };\n        root.__OPENWA_RUNTIME_BRIDGE__ = state;\n\n        return { status: 'registered' } satisfies RuntimeBridgeInstallResult;\n      } catch (error) {\n        return {\n          status: 'failed',\n          error: error instanceof Error ? error.message : String(error),\n          errorStack: error instanceof Error ? error.stack : undefined,\n        } satisfies RuntimeBridgeInstallResult;\n      }\n    }, {\n      bridgeId: bridge.id,\n      bindingName: bridge.bindingName,\n      runtimeId,\n      wapiMethod: bridge.wapiMethod,\n    });\n  }\n\n  private deriveRuntimePhase(\n    probe: RuntimeBridgeProbeResult & { bridgeReady: boolean },\n  ): InjectionPhase {\n    if (this.health.phase === 'disposed') {\n      return 'disposed';\n    }\n\n    if (this.health.degradedReasons.length > 0) {\n      return 'degraded';\n    }\n\n    if (probe.bridgeReady) {\n      return 'bridge_ready';\n    }\n\n    if (probe.sessionLoaded) {\n      return 'session_ready';\n    }\n\n    if (probe.hasStoreMsg) {\n      return 'store_detected';\n    }\n\n    if (probe.hasRuntime) {\n      return 'runtime_detected';\n    }\n\n    return this.health.phase;\n  }\n\n  private async notifyNavigationObservers(frame: IFrame, generation: GenerationSnapshot): Promise<void> {\n    const observers = [...this.navigationObservers.values()];\n    await Promise.allSettled(observers.map((observer) => Promise.resolve(observer.handler(frame, generation))));\n  }\n\n  private isMainFrame(frame: IFrame | undefined): boolean {\n    if (!frame) {\n      return true;\n    }\n\n    try {\n      return frame.isMainFrame();\n    } catch {\n      return true;\n    }\n  }\n\n  private noteRegistrationFailure(scope: string, error: unknown, required: boolean, context?: RegistrationFailureContext): void {\n    const normalized = error instanceof Error ? error : new Error(String(error));\n    const degradedReasons = required\n      ? [...this.health.degradedReasons, scope]\n      : this.health.degradedReasons;\n\n    this.health = {\n      ...this.health,\n      degradedReasons,\n      phase: required ? 'degraded' : this.health.phase,\n      lastError: {\n        message: normalized.message,\n        stack: normalized.stack,\n        ts: Date.now(),\n      },\n    };\n\n    this.logger.warn('injection_controller_registration_failed', {\n      scope,\n      required,\n      error: normalized.message,\n      errorStack: context?.installErrorStack ?? normalized.stack,\n      phase: this.health.phase,\n      generation: this.health.generation,\n      pageUrl: this.page?.url?.(),\n      bridgeId: context?.bridgeId,\n      bindingName: context?.bindingName,\n      wapiMethod: context?.wapiMethod,\n      runtimeId: context?.runtimeId,\n      installStatus: context?.installStatus,\n      installError: context?.installError,\n      runtimeAsset: context?.runtimeAsset,\n    });\n  }\n}\n","import { readFile } from 'node:fs/promises';\nimport { existsSync } from 'node:fs';\nimport { join, dirname } from 'node:path';\nimport { fileURLToPath } from 'node:url';\n\nexport const CORE_TRANSPORT_ASSETS = [\n  'qr.min.js',\n  'hash.js',\n  'init_patch.js',\n  'prog_observer.js',\n  'wapi.js',\n  'launch.js',\n] as const;\n\nexport const LEGACY_WAPI_HELPER_GLOBAL_REQUIREMENTS: readonly string[] = [];\n\nconst WAPI_FORBIDDEN_LEGACY_HELPER_PATTERNS = [\n  { helper: 'axios', pattern: /\\baxios(?:\\.\\w+|\\s*\\()/ },\n  { helper: 'jsSHA', pattern: /\\bjsSHA\\b/ },\n  { helper: 'Base64', pattern: /window\\.Base64\\b/ },\n  { helper: 'CryptoJS', pattern: /\\bCryptoJS\\./ },\n] as const;\n\nexport function auditWapiHelperAssetRequirements(wapiSource: string): {\n  requiredLegacyHelpers: readonly string[];\n  forbiddenMatches: string[];\n} {\n  const forbiddenMatches = WAPI_FORBIDDEN_LEGACY_HELPER_PATTERNS\n    .filter(({ pattern }) => pattern.test(wapiSource))\n    .map(({ helper }) => helper);\n\n  return {\n    requiredLegacyHelpers: LEGACY_WAPI_HELPER_GLOBAL_REQUIREMENTS,\n    forbiddenMatches,\n  };\n}\n\n/**\n * ScriptLoader — loads browser-injectable JS assets from the `assets/` directory.\n *\n * Mirrors the legacy `ScriptLoader` pattern from `wa-automate-nodejs/src/controllers/script_preloader.ts`.\n * Assets are read from disk once and cached in memory for the lifetime of the process.\n *\n * @example\n * ```ts\n * const loader = new ScriptLoader();\n * await loader.loadAll();\n * const initPatchJS = loader.get('init_patch.js');\n * ```\n */\nexport class ScriptLoader {\n  /** Ordered list of asset filenames to preload */\n  private readonly scripts: string[];\n\n  /** Cached file contents keyed by filename */\n  private contentRegistry: Map<string, string> = new Map();\n\n  /** Resolved base directory for asset files */\n  private readonly assetsDir: string;\n\n  constructor(scripts?: string[]) {\n    this.scripts = scripts ?? [...CORE_TRANSPORT_ASSETS];\n\n    // In source, this file lives in src/transport and assets sit beside it in ./assets.\n    // In bundled output, assets are copied to dist/transport/assets by copy-launch-script.mjs.\n    const _dirname = typeof __dirname !== 'undefined' ? __dirname : dirname(fileURLToPath(import.meta.url));\n    const candidates = [\n      join(_dirname, 'assets'),\n      join(_dirname, 'transport', 'assets'),\n    ];\n\n    const resolved = candidates.find((candidate) => existsSync(candidate));\n    if (!resolved) {\n      throw new Error(`ScriptLoader could not resolve asset directory from candidates: ${candidates.join(', ')}`);\n    }\n\n    this.assetsDir = resolved;\n  }\n\n  /**\n   * Load all registered scripts into memory.\n   * Returns the full content registry.\n   */\n  async loadAll(): Promise<Map<string, string>> {\n    await Promise.all(this.scripts.map((name) => this.load(name)));\n    return this.contentRegistry;\n  }\n\n  /**\n   * Load a single script by filename. Returns its content.\n   * Uses the cache if the script has already been loaded.\n   */\n  async load(scriptName: string): Promise<string> {\n    const cached = this.contentRegistry.get(scriptName);\n    if (cached) {\n      return cached;\n    }\n\n    const filePath = join(this.assetsDir, scriptName);\n    const content = await readFile(filePath, 'utf8');\n\n    if (scriptName === 'wapi.js') {\n      const audit = auditWapiHelperAssetRequirements(content);\n      if (audit.forbiddenMatches.length > 0) {\n        // throw new Error(\n        //   `ScriptLoader: wapi.js still depends on legacy helper globals: ${audit.forbiddenMatches.join(', ')}`\n        // );\n      }\n    }\n\n    this.contentRegistry.set(scriptName, content);\n    return content;\n  }\n\n  /**\n   * Get a previously loaded script. Throws if not yet loaded.\n   */\n  get(scriptName: string): string {\n    const content = this.contentRegistry.get(scriptName);\n    if (content === undefined) {\n      throw new Error(\n        `ScriptLoader: \"${scriptName}\" not loaded. Call load() or loadAll() first.`\n      );\n    }\n    return content;\n  }\n\n  /**\n   * Check if a script has been loaded.\n   */\n  has(scriptName: string): boolean {\n    return this.contentRegistry.has(scriptName);\n  }\n\n  /**\n   * Clear all cached scripts (useful for testing / hot-reload scenarios).\n   */\n  flush(): void {\n    this.contentRegistry.clear();\n  }\n\n  /**\n   * Get a snapshot of all loaded scripts and their byte lengths.\n   */\n  getManifest(): Array<{ name: string; bytes: number }> {\n    return Array.from(this.contentRegistry.entries()).map(([name, content]) => ({\n      name,\n      bytes: content.length,\n    }));\n  }\n}\n","import type { IPage } from '@open-wa/driver-interface';\nimport { ScriptLoader } from './ScriptLoader';\n\n/**\n * Shared ScriptLoader instance.\n * Assets are loaded from `transport/assets/*.js` on first use and cached in memory.\n */\nconst scriptLoader = new ScriptLoader();\n\n/**\n * Ensure the ScriptLoader has loaded the required assets.\n * Safe to call multiple times — no-ops on subsequent calls.\n */\nexport async function ensureScriptsLoaded(): Promise<void> {\n  if (!scriptLoader.has('init_patch.js')) {\n    await scriptLoader.loadAll();\n  }\n}\n\n/**\n * Inject the WebPack module interceptor (init-patch) into the browser page.\n *\n * This is the core patch that hooks into WhatsApp Web's module system,\n * enabling WAPI to expose internal APIs.\n *\n * @private\n */\nexport async function injectInitPatch(page: IPage): Promise<void> {\n  await ensureScriptsLoaded();\n  const script = scriptLoader.get('init_patch.js');\n  await page.evaluateScript(script);\n}\n\nexport async function getProgObserverScript(): Promise<string> {\n  await ensureScriptsLoaded();\n  return scriptLoader.get('prog_observer.js');\n}\n\n/**\n * Inject the MutationObserver that tracks the WhatsApp Web progress bar.\n *\n * Fires `ProgressBarEvent` and `CriticalInternalMessage` callbacks that\n * must be exposed on the page context via `page.exposeFunction()` before\n * this injection runs.\n *\n * @private\n */\nexport async function injectProgObserver(page: IPage): Promise<void> {\n  const script = await getProgObserverScript();\n  await page.evaluateScript(script);\n}\n\nexport { scriptLoader };\n","import type { OpenWAEventMap } from '../events/eventMap';\n\ntype RuntimeBridgeEvent = Extract<\n  keyof OpenWAEventMap,\n  'message.received' | 'message.any' | 'interactive.response' | 'ack.changed' | 'session.state.changed' | 'group.addedToGroup'\n>;\n\ntype RuntimeNavigationEvent = Extract<keyof OpenWAEventMap, 'session.logout'>;\n\nexport interface RuntimeWapiListenerSurfaceEntry {\n  kind: 'wapi';\n  event: RuntimeBridgeEvent;\n  bindingName: string;\n  wapiMethod: string;\n  required: boolean;\n}\n\nexport interface RuntimeNavigationListenerSurfaceEntry {\n  kind: 'navigation';\n  event: RuntimeNavigationEvent;\n  observerId: string;\n}\n\nexport type RuntimeListenerSurfaceEntry =\n  | RuntimeWapiListenerSurfaceEntry\n  | RuntimeNavigationListenerSurfaceEntry;\n\nexport const runtimeListenerSurface = {\n  'interactive.response': {\n    kind: 'wapi', event: 'interactive.response', bindingName: 'OpenWA_RuntimeInteractiveResponse',\n    wapiMethod: 'onInteractiveResponse', required: false,\n  },\n  'message.received': {\n    kind: 'wapi',\n    event: 'message.received',\n    bindingName: 'OpenWA_RuntimeMessageReceived',\n    wapiMethod: 'onAnyMessage',\n    required: true,\n  },\n  'message.any': {\n    kind: 'wapi',\n    event: 'message.any',\n    bindingName: 'OpenWA_RuntimeAnyMessage',\n    wapiMethod: 'onAnyMessage',\n    required: false,\n  },\n  'ack.changed': {\n    kind: 'wapi',\n    event: 'ack.changed',\n    bindingName: 'OpenWA_RuntimeAckChanged',\n    wapiMethod: 'onAck',\n    required: true,\n  },\n  'session.state.changed': {\n    kind: 'wapi',\n    event: 'session.state.changed',\n    bindingName: 'OpenWA_RuntimeStateChanged',\n    wapiMethod: 'onStateChanged',\n    required: true,\n  },\n  'group.addedToGroup': {\n    kind: 'wapi',\n    event: 'group.addedToGroup',\n    bindingName: 'OpenWA_RuntimeAddedToGroup',\n    wapiMethod: 'onAddedToGroup',\n    required: false,\n  },\n  'session.logout': {\n    kind: 'navigation',\n    event: 'session.logout',\n    observerId: 'session.logout',\n  },\n} as const satisfies Record<string, RuntimeListenerSurfaceEntry>;\n\nexport function getRuntimeListenerSurfaceEntry<EventName extends keyof typeof runtimeListenerSurface>(\n  eventName: EventName,\n): (typeof runtimeListenerSurface)[EventName] {\n  return runtimeListenerSurface[eventName];\n}\n\nexport const requiredRuntimeWapiMethods = [\n  ...new Set(\n    Object.values(runtimeListenerSurface)\n      .flatMap((entry) => (entry.kind === 'wapi' && entry.required ? [entry.wapiMethod] : [])),\n  ),\n].sort();\n","export const chromiumConfig = {\n    WAUrl: 'https://web.whatsapp.com',\n    width: 1440,\n    height: 900,\n    chromiumArgs: [\n        // `--app=${WAUrl}`,\n        '--log-level=3', // fatal only\n        //'--start-maximized',\n        '--no-default-browser-check',\n        '--disable-site-isolation-trials',\n        '--no-experiments',\n        '--ignore-gpu-blacklist',\n        '--ignore-certificate-errors',\n        '--ignore-certificate-errors-spki-list',\n        '--disable-gpu',\n        '--disable-extensions',\n        '--disable-default-apps',\n        '--enable-features=NetworkService',\n        // Extras\n        '--disable-webgl',\n        '--disable-infobars',\n        '--window-position=0,0',\n        '--ignore-certifcate-errors',\n        '--ignore-certifcate-errors-spki-list',\n        '--disable-threaded-animation',\n        '--disable-threaded-scrolling',\n        '--disable-in-process-stack-traces',\n        '--disable-histogram-customizer',\n        '--disable-gl-extensions',\n        '--disable-composited-antialiasing',\n        '--disable-session-crashed-bubble',\n        '--disable-canvas-aa',\n        '--disable-3d-apis',\n        '--disable-accelerated-2d-canvas',\n        '--disable-accelerated-jpeg-decoding',\n        '--disable-accelerated-mjpeg-decode',\n        '--disable-app-list-dismiss-on-blur',\n        '--disable-accelerated-video-decode',\n        '--disable-dev-shm-usage',\n        '--js-flags=--expose-gc',\n        // '--incognito',\n        //suggested in #563\n        // '--single-process',\n        // '--no-zygote',\n        // '--renderer-process-limit=1',\n        // '--no-first-run'\n        '--disable-features=site-per-process',\n        '--disable-gl-drawing-for-tests',\n        //keep awake in all situations\n        '--disable-background-timer-throttling',\n        '--disable-backgrounding-occluded-windows',\n        '--disable-renderer-backgrounding'\n    ]\n};\n\n/**\n * Chromium args known to crash WhatsApp Web on modern Chrome. Users copy these\n * from old low-RAM Puppeteer guides; they break the multi-process/frame model\n * and surface as \"Navigating frame was detached\" / \"Attempted to use detached\n * Frame\" crash loops (see issue #3350, #3303). Matched by prefix so\n * `--single-process` and any `--single-process=…` form are covered.\n */\nexport const DANGEROUS_BROWSER_ARGS = ['--single-process', '--no-zygote'] as const;\n\nconst argMatchesDangerous = (arg: string): boolean =>\n    DANGEROUS_BROWSER_ARGS.some((bad) => arg === bad || arg.startsWith(`${bad}=`));\n\n/**\n * Split user-supplied browser args into the ones that are safe to pass and the\n * dangerous ones. Pure so it can be unit-tested and reused by any launch path.\n */\nexport const partitionDangerousBrowserArgs = (\n    args: readonly string[]\n): { safe: string[]; dangerous: string[] } => {\n    const safe: string[] = [];\n    const dangerous: string[] = [];\n    for (const arg of args) {\n        (argMatchesDangerous(arg) ? dangerous : safe).push(arg);\n    }\n    return { safe, dangerous };\n};\n\n/**\n * Sanitize user browser args. By default, dangerous args are stripped and\n * reported. When `allowDangerous` is true they are kept (unsupported escape\n * hatch). `onRemoved` is invoked once with the stripped args when any are\n * removed, so callers can warn with their own logger.\n */\nexport const sanitizeBrowserArgs = (\n    args: readonly string[] | undefined,\n    options: { allowDangerous?: boolean; onRemoved?: (removed: string[]) => void } = {}\n): string[] => {\n    const list = args ?? [];\n    if (options.allowDangerous) return [...list];\n\n    const { safe, dangerous } = partitionDangerousBrowserArgs(list);\n    if (dangerous.length > 0) options.onRemoved?.(dangerous);\n    return safe;\n};\n\nexport const createUserAgent = (waVersion: string): string => `WhatsApp/${waVersion} Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/104.0.0.0 Safari/537.36`;\nexport const useragent = createUserAgent('2.2147.16')\n\nexport const width = chromiumConfig.width;\nexport const height = chromiumConfig.height;\n","import { createHash } from 'node:crypto';\nimport { existsSync } from 'node:fs';\nimport { readFile, writeFile, stat } from 'node:fs/promises';\nimport { dirname, join } from 'node:path';\nimport type {\n  DisposableHandle,\n  IConsoleMessage,\n  IDriver,\n  IBrowser,\n  IPage,\n  IRequest,\n  LightpandaOptions,\n  BrowserProvisionOptions,\n  WaitForFunctionOptions,\n} from '@open-wa/driver-interface';\nimport type { HyperEmitter } from '@open-wa/hyperemitter';\nimport type { Logger } from '@open-wa/logger';\nimport type { OpenWAEventMap, STATE } from '../events/eventMap';\nimport { fetchPatches, validateLicense } from './httpClient';\nimport { InjectionController, type GenerationSnapshot } from './InjectionController';\nimport { getProgObserverScript, injectInitPatch } from './initPatchScripts';\nimport { getRuntimeListenerSurfaceEntry, runtimeListenerSurface } from './runtimeListenerSurface';\nimport { auditWapiHelperAssetRequirements } from './ScriptLoader';\nimport { chromiumConfig, sanitizeBrowserArgs } from './browserConfig';\n\nexport interface PatchFetchConfig {\n  /** Use GitHub raw patches as the primary source instead of the default CDN. */\n  ghPatch?: boolean;\n  /** @deprecated Prefer `ghPatch`. When false, disables the CDN -> GitHub fallback path. */\n  ghPatchFallback?: boolean;\n  cachedPatch?: boolean;\n}\n\nexport interface LicenseServerConfig {\n  offlineLicenseMode?: boolean;\n}\n\nexport interface SessionDebugInfo {\n  WA_VERSION: string;\n  WA_AUTOMATE_VERSION: string;\n  hostNumber: string;\n  BROWSER_VERSION?: string;\n  PAGE_UA?: string;\n  OS?: string;\n  NUM_HASH?: string;\n}\n\nexport interface TransportOptions {\n  driver: IDriver;\n  events: HyperEmitter<OpenWAEventMap>;\n  logger: Logger;\n  waWebUrl?: string;\n  headless?: boolean;\n  qrTimeoutMs?: number;\n  authTimeoutMs?: number;\n  oorTimeoutMs?: number;\n  qrPollingMs?: number;\n  navigationTimeoutMs?: number;\n  executablePath?: string;\n  browser?: BrowserProvisionOptions;\n  watermark?: boolean | { text?: string; color?: string; background?: string; };\n  browserArgs?: string[];\n  allowDangerousBrowserArgs?: boolean;\n  userDataDir?: string;\n  linkCode?: string;\n  qrMax?: number;\n  ignoreNuke?: boolean;\n  logConsole?: boolean;\n  logConsoleErrors?: boolean;\n  blockCrashLogs?: boolean;\n  blockAssets?: boolean;\n  safeMode?: boolean;\n  lightpanda?: LightpandaOptions;\n  patchConfig?: PatchFetchConfig;\n  licenseConfig?: LicenseServerConfig;\n}\n\nconst CRASH_LOG_URL_FRAGMENTS = [\n  'https://dit.whatsapp.net/deidentified_telemetry',\n  'https://crashlogs.whatsapp.net/',\n];\n\nconst BLOCKED_ASSET_RESOURCE_TYPES = new Set(['image', 'stylesheet', 'font']);\n\n/** JavaScript snippet to extract QR data from the WA Web page */\nconst QR_CHECK_SCRIPT = `document.querySelector(\"canvas[aria-label]\")?.parentElement?.getAttribute(\"data-ref\") || null`;\nconst INJECTABLE_SESSION_CHECK_SCRIPT = `(() => {\n  try {\n    const debug = window.require && window.require(\"__debug\");\n    return Boolean(debug?.modulesMap?.[\"WAWebCollections\"]);\n  } catch {\n    return false;\n  }\n})()`;\nconst PRE_AUTH_SURFACE_READY_CHECK_SCRIPT = `(() => {\n  try {\n    return Boolean(${INJECTABLE_SESSION_CHECK_SCRIPT})\n      || Boolean(${QR_CHECK_SCRIPT});\n  } catch {\n    return false;\n  }\n})()`;\nconst QR_SELECTOR_PRIMARY = \"canvas[aria-label='Scan this QR code to link a device!']\";\nconst QR_SELECTOR_FALLBACK = 'canvas[aria-label]';\nconst PRE_API_HELPER_READY_CHECK_SCRIPT = `Boolean(!['jsSHA','axios','QRCode','Base64','objectHash'].find(x=>!window[x]))`;\n\nconst WAPI_RUNTIME_CHECK_SCRIPT = '!!window.WAPI';\nconst STORE_MSG_CHECK_SCRIPT = '!!(window.Store && window.Store.Msg)';\nconst ATTEMPTING_REAUTH_CHECK_SCRIPT = `!!(\n  typeof localStorage !== 'undefined'\n  && (localStorage['WAToken2'] || localStorage['last-wid-md'])\n)`;\nconst SESSION_INVALID_CHECK_SCRIPT = `!!(\n  typeof localStorage !== 'undefined'\n  && Object.prototype.hasOwnProperty.call(localStorage, 'old-logout-cred')\n)`;\nconst PHONE_OUT_OF_REACH_CHECK_SCRIPT = `!!(\n  typeof document !== 'undefined'\n  && document.querySelector('body')\n  && document.querySelector('body').innerText.includes('Trying to reach phone')\n)`;\nconst LINK_CODE_AVAILABLE_CHECK_SCRIPT = `!!(typeof window.linkCode === 'function')`;\nconst LEGACY_IS_INSIDE_CHAT_CHECK_SCRIPT = `!!(\n  !!window.WA_AUTHENTICATED\n  || (document.getElementsByClassName('app')[0]\n    && document.getElementsByClassName('app')[0].attributes\n    && !!document.getElementsByClassName('app')[0].attributes.tabindex)\n  || (document.getElementsByClassName('two')[0]\n    && document.getElementsByClassName('two')[0].attributes\n    && !!document.getElementsByClassName('two')[0].attributes.tabindex)\n)`;\nconst AUTHENTICATED_SHELL_CHECK_SCRIPT = `!!(\n  (window.isSessionLoaded && window.isSessionLoaded()) ||\n  window.WA_AUTHENTICATED ||\n  document.querySelector('#pane-side') ||\n  document.querySelector('[aria-label=\"Search or start a new chat\"]') ||\n  document.querySelector('[data-testid=\"chat-list-search\"]') ||\n  (document.getElementsByClassName('app')[0] && document.getElementsByClassName('app')[0].getAttribute('tabindex') != null) ||\n  (document.getElementsByClassName('two')[0] && document.getElementsByClassName('two')[0].getAttribute('tabindex') != null)\n)`;\nconst RIPE_SESSION_CHECK_SCRIPT = `(() => {\n  try {\n    return Boolean(\n      !!window.WA_AUTHENTICATED || (document.getElementsByClassName('app')[0] && document.getElementsByClassName('app')[0].attributes && !!document.getElementsByClassName('app')[0].attributes.tabindex) || (document.getElementsByClassName('two')[0] && document.getElementsByClassName('two')[0].attributes && !!document.getElementsByClassName('two')[0].attributes.tabindex)\n    );\n  } catch {\n    return false;\n  }\n})()`;\nconst DOCUMENT_READY_CHECK_SCRIPT = `!!(\n  typeof document === 'undefined'\n  || document.readyState === 'interactive'\n  || document.readyState === 'complete'\n)`;\n\nconst RUNTIME_REPLACEMENT_OBSERVER_SCRIPT = `(() => {\n  const root = globalThis;\n  const existingState = root.__OPENWA_RUNTIME_REPLACEMENT_OBSERVER__;\n  if (existingState?.installed) {\n    return;\n  }\n\n  const descriptor = Object.getOwnPropertyDescriptor(root, 'WAPI');\n  if (descriptor && descriptor.configurable === false) {\n    root.__OPENWA_RUNTIME_REPLACEMENT_OBSERVER__ = {\n      installed: false,\n      skipped: true,\n      reason: 'non_configurable_property',\n    };\n    return;\n  }\n\n  let currentValue = descriptor?.get ? descriptor.get.call(root) : root.WAPI;\n  const originalGet = descriptor?.get ? descriptor.get.bind(root) : null;\n  const originalSet = descriptor?.set ? descriptor.set.bind(root) : null;\n\n  const notifyRuntimeReplacement = () => {\n    try {\n      const notify = root.OpenWA_RuntimeReplacementDetected;\n      if (typeof notify === 'function') {\n        void notify({ reason: 'runtime_replaced' });\n      }\n    } catch {\n      // Ignore bridge notifications that fail inside the page context.\n    }\n  };\n\n  Object.defineProperty(root, 'WAPI', {\n    configurable: true,\n    enumerable: descriptor ? descriptor.enumerable !== false : true,\n    get() {\n      if (originalGet) {\n        const next = originalGet();\n        if (next !== undefined) {\n          currentValue = next;\n        }\n      }\n      return currentValue;\n    },\n    set(value) {\n      const previous = originalGet ? (originalGet() ?? currentValue) : currentValue;\n      if (originalSet) {\n        originalSet(value);\n      }\n      currentValue = value;\n\n      if (previous && value && previous !== value) {\n        notifyRuntimeReplacement();\n      }\n    },\n  });\n\n  root.__OPENWA_RUNTIME_REPLACEMENT_OBSERVER__ = {\n    installed: true,\n    installedAt: Date.now(),\n  };\n})();`;\n\nexport interface RuntimeCapabilityProbe {\n  hasRuntime: boolean;\n  hasStoreMsg: boolean;\n  sessionLoaded: boolean;\n}\n\nexport type AuthSettlementOutcome = 'authenticated' | 'qr_timeout' | 'auth_timeout' | 'invalid_session' | 'phone_out_of_reach' | 'qr_max';\n\nexport interface AuthSettlementResult {\n  outcome: AuthSettlementOutcome;\n  qrSeen: boolean;\n  qrAttempts: number;\n  authMethod?: 'qr' | 'link_code' | 'resumed_session';\n}\n\nexport interface PostAuthRuntimeReconciliationResult extends RuntimeCapabilityProbe {\n  ripeSessionLoaded: boolean;\n  reinjected: boolean;\n  path: 'fresh_auth' | 'resumed_session';\n}\n\nexport type RuntimeValidationStage = 'post_injection' | 'post_patch' | 'post_overlay';\nexport type RuntimeValidationFailureReason = 'runtime_missing' | 'store_missing' | 'session_not_loaded' | 'required_method_missing';\n\nexport interface RuntimeMethodIntegrityResult {\n  bridgeReady: boolean;\n  requiredMethods: string[];\n  missingMethods: string[];\n}\n\nexport interface RuntimeValidationResult extends RuntimeCapabilityProbe {\n  stage: RuntimeValidationStage;\n  usable: boolean;\n  repairable: boolean;\n  bridgeReady: boolean;\n  requiredMethods: string[];\n  missingMethods: string[];\n  failureReason?: RuntimeValidationFailureReason;\n}\n\nexport interface TransportOperationalReadinessSnapshot {\n  generation: GenerationSnapshot | null;\n  phase: string;\n  driverActiveGeneration: boolean;\n  runtimeOperational: boolean;\n  runtimeBridgeReady: boolean;\n  reinjectionSettled: boolean;\n  missingRuntimeMethods: string[];\n}\n\nexport type LicenseStatus = 'valid' | 'metadata_only' | 'missing' | 'invalid' | 'expired';\nexport type LicenseSource = 'local' | 'remote' | 'cached' | 'none';\nexport type LicenseKeyResolver =\n  | string\n  | Record<string, string | undefined>\n  | ((sessionId: string) => Promise<string | null | undefined> | string | null | undefined);\n\nexport interface LicensePreloadOptions {\n  sessionId: string;\n  licenseKey?: LicenseKeyResolver;\n  source?: Exclude<LicenseSource, 'none'>;\n  sessionInfo?: SessionDebugInfo;\n}\n\nexport interface LicenseArtifact {\n  key: string;\n  maskedKey: string;\n  source: Exclude<LicenseSource, 'none'>;\n  payload: string;\n  keyType: string;\n  payloadSource: 'server' | 'local_metadata';\n}\n\nexport interface LicensePreloadResult {\n  outcome: 'ready' | 'missing' | 'failed';\n  status: LicenseStatus;\n  source: LicenseSource;\n  artifact: LicenseArtifact | null;\n  blockingFailure: boolean;\n  detail?: string;\n  error?: Error;\n}\n\nexport interface LicenseCheckResult {\n  status: LicenseStatus;\n  source: Exclude<LicenseSource, 'none'>;\n  artifact: LicenseArtifact | null;\n  blockingFailure: boolean;\n  detail?: string;\n}\n\nexport interface LicenseApplyResult {\n  status: LicenseStatus;\n  applied: boolean;\n  blockingFailure: boolean;\n  keyType?: string;\n  detail?: string;\n}\n\nexport type PatchArtifactSource = 'builtin' | 'remote' | 'cached';\n\nexport interface PatchArtifact {\n  patchId: string;\n  description: string;\n  required: boolean;\n  script: string;\n  applicabilityCheckScript?: string;\n  source: PatchArtifactSource;\n}\n\nexport interface LivePatchPreloadResult {\n  outcome: 'ready' | 'none' | 'failed';\n  source: 'builtin' | 'remote' | 'cached' | 'none';\n  tag: string | null;\n  artifacts: PatchArtifact[];\n  blockingFailure: boolean;\n  error?: Error;\n}\n\nexport interface PatchApplicationResult {\n  patchId: string;\n  description?: string;\n  required: boolean;\n  outcome: 'applied' | 'not_applicable' | 'failed';\n  detail?: string;\n}\n\nexport interface PatchApplyResult {\n  outcome: 'applied' | 'skipped' | 'failed';\n  applied: string[];\n  blockingFailure: boolean;\n  results: PatchApplicationResult[];\n}\n\ninterface LivePatchFetchResult {\n  data: string[];\n  tag: string;\n  source: 'remote' | 'cached';\n}\n\nconst BUILTIN_LIVE_PATCH_ARTIFACTS: readonly PatchArtifact[] = [\n  {\n    patchId: 'runtime-bootstrap-overlay',\n    description: 'Records bootstrap patch attestation after runtime activation.',\n    required: true,\n    source: 'builtin',\n    applicabilityCheckScript: 'Boolean(window.WAPI)',\n    script: `(() => {\n      if (!window.WAPI) {\n        throw new Error('WAPI runtime not available for bootstrap patch attestation');\n      }\n      window.__OPENWA_PATCH_LIFECYCLE__ = window.__OPENWA_PATCH_LIFECYCLE__ || {};\n      window.__OPENWA_PATCH_LIFECYCLE__['runtime-bootstrap-overlay'] = {\n        appliedAt: Date.now(),\n        mode: 'bootstrap_attestation',\n        hasRuntime: !!window.WAPI,\n        hasStoreMsg: !!(window.Store && window.Store.Msg),\n      };\n      return true;\n    })();`,\n  },\n];\n\n/**\n * Builtin init-patch artifact — wraps `injectInitPatch` as a deferred script\n * applied during the patch-apply phase (post-auth finalization).\n * This mirrors legacy `initializer.ts:429`.\n */\nconst INIT_PATCH_ARTIFACT: PatchArtifact = {\n  patchId: 'init-patch-legacy',\n  description: 'Legacy init-patch: webpack module interceptor + Store.sendMessage guard.',\n  required: true,\n  source: 'builtin',\n  // No applicability check — always inject; the obfuscated blob handles its own guards.\n  script: 'DEFERRED_INIT_PATCH',\n};\n\n/** Default live-patch endpoint (legacy: pkg.patches from package.json) */\nconst DEFAULT_LIVE_PATCHES_URL = 'https://cdn.openwa.dev/patches.json';\n/** Fallback GitHub raw live-patches URL */\nconst GH_LIVE_PATCHES_FALLBACK_URL = 'https://raw.githubusercontent.com/open-wa/wa-automate-nodejs/master/patches.json';\n/** OpenWA license validation endpoint. */\nconst DEFAULT_LICENSE_CHECK_URL = 'https://funcs.openwa.dev/license-check';\n/** Live-patch cache file path relative to cwd */\nconst LIVE_PATCH_CACHE_FILENAME = 'patches.cache.json';\n/** Live-patch cache staleness threshold (24 hours in ms) */\nconst LIVE_PATCH_CACHE_MAX_AGE_MS = 86_400_000;\n/** Maximum consecutive recovery attempts before giving up */\nconst MAX_CONSECUTIVE_RECOVERY_ATTEMPTS = 5;\n\nexport class Transport {\n  private static assetScriptCache = new Map<string, Promise<string>>();\n  private driver: IDriver;\n  private browser: IBrowser | null = null;\n  private page: IPage | null = null;\n  private events: HyperEmitter<OpenWAEventMap>;\n  private logger: Logger;\n  private waWebUrl: string;\n  private headless: boolean;\n  private qrTimeoutMs: number;\n  private authTimeoutMs: number;\n  private oorTimeoutMs: number;\n  private qrPollingMs: number;\n  private navigationTimeoutMs: number;\n  private executablePath?: string;\n  private browserArgs?: string[];\n  private allowDangerousBrowserArgs?: boolean;\n  private userDataDir?: string;\n  private linkCode?: string;\n  private qrMax?: number;\n  private ignoreNuke: boolean;\n  private logConsole: boolean;\n  private logConsoleErrors: boolean;\n  private blockCrashLogs: boolean;\n  private blockAssets: boolean;\n  private safeMode: boolean;\n  private lightpanda?: LightpandaOptions;\n  private qrWatcherAbort: AbortController | null = null;\n  private qrAttempt = 0;\n  private lastQrData: string | null = null;\n  private lastRuntimeState: STATE | null = null;\n  private patchConfig: PatchFetchConfig;\n  private licenseConfig: LicenseServerConfig;\n  private pageListeners: DisposableHandle[] = [];\n  private readonly injectionController: InjectionController;\n  private runtimeRecoveryQueue: Promise<void> = Promise.resolve();\n  private latestRuntimeRecoveryRequestId = 0;\n  private pendingRuntimeRecoveryCount = 0;\n  private consecutiveRecoveryAttempts = 0;\n  /** Cached live patch scripts for re-application during recovery */\n  private cachedLivePatchScripts: string[] = [];\n  private frameNavCounter = 0;\n  private readonly options: TransportOptions;\n\n  constructor(options: TransportOptions) {\n    this.options = options;\n    this.driver = options.driver;\n    this.events = options.events;\n    this.logger = options.logger;\n    this.waWebUrl = options.waWebUrl ?? 'https://web.whatsapp.com';\n    this.headless = options.headless ?? true;\n    this.qrTimeoutMs = options.qrTimeoutMs ?? 60000;\n    this.authTimeoutMs = options.authTimeoutMs ?? 60000;\n    this.oorTimeoutMs = options.oorTimeoutMs ?? 60000;\n    this.qrPollingMs = options.qrPollingMs ?? 500;\n    this.navigationTimeoutMs = options.navigationTimeoutMs ?? 60_000;\n    this.executablePath = options.executablePath;\n    this.browserArgs = options.browserArgs;\n    this.allowDangerousBrowserArgs = options.allowDangerousBrowserArgs;\n    this.userDataDir = options.userDataDir;\n    this.linkCode = options.linkCode;\n    this.qrMax = options.qrMax;\n    this.ignoreNuke = options.ignoreNuke ?? false;\n    this.logConsole = options.logConsole ?? false;\n    this.logConsoleErrors = options.logConsoleErrors ?? false;\n    this.blockCrashLogs = options.blockCrashLogs ?? true;\n    this.blockAssets = options.blockAssets ?? false;\n    this.safeMode = options.safeMode ?? false;\n    this.lightpanda = options.lightpanda;\n    this.patchConfig = options.patchConfig ?? {};\n    this.licenseConfig = options.licenseConfig ?? {};\n    this.injectionController = new InjectionController(this.logger);\n  }\n\n  async initialize(): Promise<void> {\n    this.events.emit('launch.browser.init.before', {\n      correlationId: 'transport-init',\n      ts: Date.now(),\n      step: 'browser_init',\n      details: { headless: this.headless }\n    });\n\n    await this.driver.init({ logger: this.logger });\n    this.browser = await this.driver.launch({\n      headless: this.headless,\n      executablePath: this.executablePath,\n      browser: this.options.browser,\n      args: [\n        ...chromiumConfig.chromiumArgs,\n        ...sanitizeBrowserArgs(this.browserArgs, {\n          allowDangerous: this.allowDangerousBrowserArgs,\n          onRemoved: (removed) =>\n            this.logger.warn(\n              `Removed browser args known to crash WhatsApp Web: ${removed.join(', ')}. ` +\n                'These cause \"Navigating frame was detached\" errors on modern Chrome. ' +\n                'Set allowDangerousBrowserArgs: true to force them (unsupported).',\n              { removed }\n            ),\n        }),\n      ],\n      userDataDir: this.userDataDir,\n      defaultViewport: null,\n      lightpanda: this.lightpanda,\n    });\n    this.page = await this.browser.newPage();\n\n\n    await this.configurePageRuntime(this.page);\n\n    await this.page.setUserAgent(\n      'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/146.0.0.0 Safari/537.36'\n    );\n\n    this.events.emit('launch.browser.init.after', {\n      correlationId: 'transport-init',\n      ts: Date.now(),\n      step: 'browser_init',\n      details: {}\n    });\n\n    this.logger.info('transport_initialized', { driverName: this.driver.name });\n  }\n\n  async navigate(): Promise<void> {\n    if (!this.page) {\n      throw new Error('Transport not initialized');\n    }\n\n    this.events.emit('launch.navigation.gotoWaWeb.before', {\n      correlationId: 'transport-nav',\n      ts: Date.now(),\n      step: 'navigation',\n      details: { url: this.waWebUrl }\n    });\n    await this.page.goto(this.waWebUrl, {\n      waitUntil: 'domcontentloaded',\n      timeoutMs: this.navigationTimeoutMs,\n    });\n\n    this.events.emit('launch.navigation.gotoWaWeb.after', {\n      correlationId: 'transport-nav',\n      ts: Date.now(),\n      step: 'navigation',\n      details: { finalUrl: this.page.url() }\n    });\n\n    this.logger.info('transport_navigated', { url: this.waWebUrl });\n    await this.configureLaunchBootstrap(this.page);\n    await this.waitForInjectableSession();\n  }\n\n  //wait until wawebcollections resolves\n  async waitForInjectableSession(): Promise<boolean> {\n    if (!this.page) return false;\n\n    await this.page.waitForFunction(PRE_AUTH_SURFACE_READY_CHECK_SCRIPT, {\n      timeoutMs: this.navigationTimeoutMs,\n      polling: 'mutation',\n    });\n    return true;\n  }\n\n  async injectWapi(): Promise<boolean> {\n    if (!this.page) {\n      throw new Error('Transport not initialized');\n    }\n\n    // Ensure launch bootstrap is configured\n    // (normally done in navigate() -> configureLaunchBootstrap())\n    if (this.injectionController.getHealthSnapshot().phase === 'idle') {\n      await this.configureLaunchBootstrap(this.page);\n    }\n\n    this.events.emit('launch.wapi.inject.before', {\n      correlationId: 'transport-inject',\n      ts: Date.now(),\n      step: 'wapi_inject',\n      details: { injectPreApiScripts: true }\n    });\n\n    let success = false;\n\n    try {\n      await this.runPreApiHelperPhase();\n      success = await this.performRuntimeInjection();\n\n      if (success) {\n        await this.configureRuntimeEventBridge();\n      }\n\n      return success;\n    } finally {\n      this.events.emit('launch.wapi.inject.after', {\n        correlationId: 'transport-inject',\n        ts: Date.now(),\n        step: 'wapi_inject',\n        details: { success }\n      });\n    }\n  }\n\n  /**\n   * Phase 1: Register Node-side persistent bindings for WAPI event bridge.\n   *\n   * This sets up the `exposeFunction` callbacks that the browser page will\n   * call into. It does NOT wire them to WAPI methods — that happens in\n   * `activateRuntimeEventBridge()`.\n   *\n   * Safe to call pre-patch: only registers Node-side callbacks and records\n   * bridge metadata. No WAPI code is called.\n   */\n  async registerRuntimeEventBridgeBindings(): Promise<void> {\n    const interactiveSurface = getRuntimeListenerSurfaceEntry('interactive.response');\n    await this.injectionController.registerRuntimeWapiBridge(\n      interactiveSurface.event, interactiveSurface.bindingName,\n      (response: unknown) => {\n        this.events.emit('interactive.response', {\n          ctx: { correlationId: 'runtime-interactive-response', ts: Date.now() }, response,\n        });\n      },\n      { wapiMethod: interactiveSurface.wapiMethod, required: interactiveSurface.required },\n    );\n    const messageReceivedSurface = getRuntimeListenerSurfaceEntry('message.received');\n    const messageAnySurface = getRuntimeListenerSurfaceEntry('message.any');\n    const ackChangedSurface = getRuntimeListenerSurfaceEntry('ack.changed');\n    const stateChangedSurface = getRuntimeListenerSurfaceEntry('session.state.changed');\n    const addedToGroupSurface = getRuntimeListenerSurfaceEntry('group.addedToGroup');\n\n    await this.injectionController.registerRuntimeWapiBridge(\n      messageReceivedSurface.event,\n      messageReceivedSurface.bindingName,\n      (message: unknown) => {\n        this.events.emit('message.received', {\n          ctx: { correlationId: 'runtime-message-received', ts: Date.now() },\n          message,\n        });\n      },\n      { wapiMethod: messageReceivedSurface.wapiMethod, required: messageReceivedSurface.required },\n    );\n\n    await this.injectionController.registerRuntimeWapiBridge(\n      messageAnySurface.event,\n      messageAnySurface.bindingName,\n      (message: unknown) => {\n        this.events.emit('message.any', {\n          ctx: { correlationId: 'runtime-message-any', ts: Date.now() },\n          message,\n        });\n      },\n      { wapiMethod: messageAnySurface.wapiMethod, required: messageAnySurface.required },\n    );\n\n    await this.injectionController.registerRuntimeWapiBridge(\n      ackChangedSurface.event,\n      ackChangedSurface.bindingName,\n      (ack: unknown) => {\n        this.events.emit('ack.changed', {\n          ctx: { correlationId: 'runtime-ack-changed', ts: Date.now() },\n          ack,\n        });\n      },\n      { wapiMethod: ackChangedSurface.wapiMethod, required: ackChangedSurface.required },\n    );\n\n    await this.injectionController.registerRuntimeWapiBridge(\n      stateChangedSurface.event,\n      stateChangedSurface.bindingName,\n      (state: unknown) => {\n        const next = (typeof state === 'string' ? state : String(state ?? '')) as STATE;\n        const prev = this.lastRuntimeState ?? next;\n        this.lastRuntimeState = next || this.lastRuntimeState;\n\n        this.events.emit('session.state.changed', {\n          correlationId: 'runtime-session-state',\n          ts: Date.now(),\n          step: 'session_state_changed',\n          details: { prev, next },\n        });\n      },\n      { wapiMethod: stateChangedSurface.wapiMethod, required: stateChangedSurface.required },\n    );\n\n    await this.injectionController.registerRuntimeWapiBridge(\n      addedToGroupSurface.event,\n      addedToGroupSurface.bindingName,\n      (chat: Record<string, unknown> | null | undefined) => {\n        const groupId = String(chat?.id ?? chat?.chatId ?? '');\n        if (!groupId) {\n          return;\n        }\n\n        this.events.emit('group.addedToGroup', {\n          ctx: { correlationId: 'runtime-group-added', ts: Date.now() },\n          groupId,\n          by: typeof chat?.['groupMetadata'] === 'object' ? undefined : undefined,\n        });\n      },\n      { wapiMethod: addedToGroupSurface.wapiMethod, required: addedToGroupSurface.required },\n    );\n\n    this.logger.info('runtime_event_bridge_bindings_registered', {\n      bindings: [\n        interactiveSurface.bindingName,\n        messageReceivedSurface.bindingName,\n        messageAnySurface.bindingName,\n        ackChangedSurface.bindingName,\n        stateChangedSurface.bindingName,\n        addedToGroupSurface.bindingName,\n      ],\n      requiredMethods: this.injectionController.getRequiredRuntimeMethods(),\n    });\n  }\n\n  /**\n   * Phase 2: Wire the registered bridge bindings to WAPI methods in-page.\n   *\n   * This calls `ensureRuntimeBridge()` which executes in-page JavaScript\n   * like `WAPI.onAnyMessage(obj => window.OpenWA_RuntimeMessageReceived(obj))`.\n   *\n   * MUST only be called AFTER patches, license, and init-patch have been\n   * applied — otherwise the WAPI methods being wired may be broken/unpatched.\n   *\n   * Idempotent: if bridges are already wired (e.g. by a post_patch validation\n   * stage), this becomes a no-op via the `already_registered` check.\n   */\n  async activateRuntimeEventBridge(): Promise<void> {\n    const bridgeReady = await this.injectionController.ensureRuntimeBridge();\n    const capability = await this.probeRuntimeCapability();\n    this.logger.info('runtime_event_bridge_ready', {\n      bridgeReady,\n      hasRuntime: capability.hasRuntime,\n      hasStoreMsg: capability.hasStoreMsg,\n      sessionLoaded: capability.sessionLoaded,\n    });\n  }\n\n  /**\n   * Convenience wrapper: registers bindings and then wires them to WAPI.\n   *\n   * Used by recovery flows (e.g. `recoverRuntimeForCurrentDocument`) where\n   * both phases should happen together because patches are already applied.\n   * The bootstrap sequence uses the split methods directly instead.\n   */\n  async configureRuntimeEventBridge(): Promise<void> {\n    await this.registerRuntimeEventBridgeBindings();\n    await this.activateRuntimeEventBridge();\n  }\n\n  async probeRuntimeCapability(): Promise<RuntimeCapabilityProbe> {\n    if (!this.page) {\n      throw new Error('Transport not initialized');\n    }\n\n    const probes = [\n      { key: 'hasRuntime', script: WAPI_RUNTIME_CHECK_SCRIPT },\n      { key: 'hasStoreMsg', script: STORE_MSG_CHECK_SCRIPT },\n      { key: 'sessionLoaded', script: AUTHENTICATED_SHELL_CHECK_SCRIPT },\n    ] as const;\n\n    const capability: RuntimeCapabilityProbe = {\n      hasRuntime: false,\n      hasStoreMsg: false,\n      sessionLoaded: false,\n    };\n\n    for (const probe of probes) {\n      try {\n        const value = await this.evaluateBooleanScript(probe.script);\n        capability[probe.key] = value;\n      } catch (error) {\n        this.logger.error('runtime_capability_probe_failed', {\n          probe: probe.key,\n          scriptPreview: probe.script.replace(/\\s+/g, ' ').trim().slice(0, 180),\n          error: error instanceof Error ? error : new Error(String(error)),\n        });\n        this.logger.error('probe_runtime_capability_failed', {\n          probe: probe.key,\n          error: error instanceof Error ? error : new Error(String(error)),\n        });\n        break;\n      }\n    }\n\n    return capability;\n  }\n\n  async validateRuntimeUsability(stage: RuntimeValidationStage): Promise<RuntimeValidationResult> {\n    try {\n\n      const capability = await this.probeRuntimeCapability();\n      const integrity = capability.hasRuntime\n        ? await this.probeBrokenMethodIntegrity()\n        : {\n          bridgeReady: false,\n          requiredMethods: this.injectionController.getRequiredRuntimeMethods(),\n          missingMethods: [],\n        } satisfies RuntimeMethodIntegrityResult;\n\n      const failureReason = !capability.hasRuntime\n        ? 'runtime_missing'\n        : (stage === 'post_patch' || stage === 'post_overlay') && !capability.hasStoreMsg\n          ? 'store_missing'\n          : (stage === 'post_patch' || stage === 'post_overlay') && !capability.sessionLoaded\n            ? 'session_not_loaded'\n            : integrity.missingMethods.length > 0 || !integrity.bridgeReady\n              ? 'required_method_missing'\n              : undefined;\n\n      const usable = failureReason === undefined;\n\n      return {\n        ...capability,\n        ...integrity,\n        stage,\n        usable,\n        repairable: !usable,\n        failureReason,\n      };\n    } catch (error) {\n      console.log(\"ERRORED OUT IN VALIDATE RUNTIME USABILITY\", error)\n      throw error;\n    }\n  }\n\n  /**\n   * Lightweight runtime validation that checks runtime/store/session presence\n   * WITHOUT checking bridge integrity.\n   *\n   * Used for early validation stages (post_injection) where the WAPI bridge\n   * has not yet been activated and calling `probeBrokenMethodIntegrity()` →\n   * `ensureRuntimeBridge()` would prematurely wire listeners to unpatched WAPI.\n   */\n  async validateRuntimeCapabilityOnly(stage: RuntimeValidationStage): Promise<RuntimeValidationResult> {\n    const capability = await this.probeRuntimeCapability();\n\n    const failureReason = !capability.hasRuntime\n      ? 'runtime_missing'\n      : undefined;\n\n    const usable = failureReason === undefined;\n\n    const result: RuntimeValidationResult = {\n      ...capability,\n      bridgeReady: false,\n      requiredMethods: this.injectionController.getRequiredRuntimeMethods(),\n      missingMethods: [],\n      stage,\n      usable,\n      repairable: !usable,\n      failureReason,\n    };\n\n    this.events.emit('launch.session.validityCheck.after', {\n      correlationId: 'transport-capability-only',\n      ts: Date.now(),\n      step: 'session_validity_check',\n      details: {\n        phase: stage,\n        valid: usable,\n        usable,\n        hasRuntime: result.hasRuntime,\n        hasStore: result.hasStoreMsg,\n        hasMsg: result.hasStoreMsg,\n        sessionLoaded: result.sessionLoaded,\n        bridgeReady: result.bridgeReady,\n        requiredMethods: result.requiredMethods,\n        missingMethods: result.missingMethods,\n        repairable: result.repairable,\n        failureReason,\n      },\n    });\n\n    return result;\n  }\n\n  async repairRuntimeIntegrity(reason: RuntimeValidationFailureReason): Promise<boolean> {\n    this.logger.info('broken_method_integrity_gate_repair', { reason });\n    const recovery = await this.recoverRuntimeForCurrentDocument({\n      trigger: 'validation_failure',\n      forceReinject: true,\n    });\n\n    return recovery.reinjected || recovery.capability.hasRuntime;\n  }\n\n  async preloadLivePatchArtifacts(options?: { sessionInfo?: SessionDebugInfo }): Promise<LivePatchPreloadResult> {\n    const correlationId = 'transport-patch-preload';\n    const startTime = Date.now();\n\n    this.events.emit('launch.patch.init.before', {\n      correlationId,\n      ts: startTime,\n      step: 'patch_preload',\n      details: { phase: 'preload', source: 'builtin' },\n    });\n\n    try {\n      // Start with builtin attestation artifacts\n      const artifacts: PatchArtifact[] = BUILTIN_LIVE_PATCH_ARTIFACTS.map((artifact) => ({ ...artifact }));\n\n      // Attempt remote patch fetch\n      let remoteFetchResult: LivePatchFetchResult | null = null;\n\n      try {\n        remoteFetchResult = await this.fetchLivePatchesWithCache(options?.sessionInfo);\n      } catch (fetchError) {\n        const fetchMsg = fetchError instanceof Error ? fetchError.message : String(fetchError);\n        this.logger.warn('remote_patch_fetch_failed', { error: fetchMsg });\n        // Remote fetch failure is non-blocking — we fall through to builtin-only\n      }\n\n      if (remoteFetchResult) {\n        // Append remote patches after builtin attestation\n        for (let i = 0; i < remoteFetchResult.data.length; i++) {\n          artifacts.push({\n            patchId: `remote-patch-${i}`,\n            description: `Remote live patch #${i} (tag: ${remoteFetchResult.tag})`,\n            script: remoteFetchResult.data[i],\n            required: false,\n            source: remoteFetchResult.source,\n          });\n        }\n      }\n\n      const effectiveSource = remoteFetchResult?.source ?? (artifacts.length > 0 ? 'builtin' : 'none');\n      const tag = remoteFetchResult?.tag\n        ?? (artifacts.length > 0\n          ? createHash('sha1').update(JSON.stringify(artifacts)).digest('hex').slice(0, 8)\n          : null);\n\n      const outcome: LivePatchPreloadResult = {\n        outcome: artifacts.length > 0 ? 'ready' : 'none',\n        source: effectiveSource,\n        tag,\n        artifacts,\n        blockingFailure: false,\n      };\n\n      this.events.emit('launch.patch.init.after', {\n        correlationId,\n        ts: Date.now(),\n        step: 'patch_preload',\n        durationMs: Date.now() - startTime,\n        details: {\n          phase: 'preload',\n          applied: [],\n          available: artifacts.map((artifact) => artifact.patchId),\n          outcome: outcome.outcome,\n          source: outcome.source,\n          tag: outcome.tag,\n          blockingFailure: outcome.blockingFailure,\n        },\n      });\n\n      return outcome;\n    } catch (error) {\n      const normalizedError = error instanceof Error ? error : new Error(String(error));\n      const outcome: LivePatchPreloadResult = {\n        outcome: 'failed',\n        source: 'builtin',\n        tag: null,\n        artifacts: [],\n        blockingFailure: true,\n        error: normalizedError,\n      };\n\n      this.events.emit('launch.patch.init.after', {\n        correlationId,\n        ts: Date.now(),\n        step: 'patch_preload',\n        durationMs: Date.now() - startTime,\n        error: {\n          name: normalizedError.name,\n          message: normalizedError.message,\n          stack: normalizedError.stack,\n        },\n        details: {\n          phase: 'preload',\n          applied: [],\n          available: [],\n          outcome: outcome.outcome,\n          source: outcome.source,\n          tag: outcome.tag,\n          blockingFailure: outcome.blockingFailure,\n        },\n      });\n\n      return outcome;\n    }\n  }\n\n  async applyLivePatchArtifacts(preloaded: LivePatchPreloadResult): Promise<PatchApplyResult> {\n    if (preloaded.outcome === 'failed') {\n      return this.buildFailedLivePatchApplyResult(preloaded);\n    }\n\n    const result = await this.applyPatchArtifactSequence(preloaded.artifacts, {\n      correlationId: 'transport-live-patch-apply',\n      preloadOutcome: preloaded.outcome,\n    });\n\n    // Cache the remote live patch scripts for re-application during recovery.\n    // Only cache scripts that were successfully applied and are real evaluatable\n    // scripts (not builtin attestation or deferred init-patch markers).\n    if (result.outcome !== 'failed') {\n      this.cachedLivePatchScripts = preloaded.artifacts\n        .filter((a) => a.source === 'remote' && a.script !== 'DEFERRED_INIT_PATCH')\n        .map((a) => a.script);\n\n      if (this.cachedLivePatchScripts.length > 0) {\n        this.logger.debug('live_patch_scripts_cached_for_recovery', {\n          count: this.cachedLivePatchScripts.length,\n        });\n      }\n    }\n\n    return result;\n  }\n\n  async applyDeferredInitPatchArtifact(): Promise<PatchApplyResult> {\n    return this.applyPatchArtifactSequence([{ ...INIT_PATCH_ARTIFACT }], {\n      correlationId: 'transport-init-patch-apply',\n      preloadOutcome: 'ready',\n    });\n  }\n\n  private buildFailedLivePatchApplyResult(preloaded: LivePatchPreloadResult): PatchApplyResult {\n    return {\n      outcome: 'failed',\n      applied: [],\n      blockingFailure: preloaded.blockingFailure,\n      results: preloaded.error\n        ? [{\n          patchId: 'patch-preload',\n          description: 'Patch preload failed before application could begin.',\n          required: true,\n          outcome: 'failed',\n          detail: preloaded.error.message,\n        }]\n        : [],\n    };\n  }\n\n  private async applyPatchArtifactSequence(\n    artifacts: PatchArtifact[],\n    options: {\n      correlationId: string;\n      preloadOutcome: 'ready' | 'none' | 'failed';\n    },\n  ): Promise<PatchApplyResult> {\n    if (!this.page) {\n      throw new Error('Transport not initialized');\n    }\n\n    const correlationId = options.correlationId;\n    const startTime = Date.now();\n    const patchIds = artifacts.map((artifact) => artifact.patchId);\n\n    this.events.emit('patch.init.before', {\n      correlationId,\n      ts: startTime,\n      step: 'patch_apply',\n      details: {\n        phase: 'apply',\n        patchIds,\n        preloadOutcome: options.preloadOutcome,\n      },\n    });\n\n    const applied: string[] = [];\n    const results: PatchApplicationResult[] = [];\n    let blockingFailure = false;\n\n    for (const artifact of artifacts) {\n      const patchStartTime = Date.now();\n      this.events.emit('patch.apply.before', {\n        correlationId,\n        ts: patchStartTime,\n        step: 'patch_apply_item',\n        details: {\n          patchId: artifact.patchId,\n          description: artifact.description,\n          required: artifact.required,\n          source: artifact.source,\n        },\n      });\n\n      this.logger.info('live_patch_installing', {\n        patchId: artifact.patchId,\n        description: artifact.description,\n        required: artifact.required,\n        source: artifact.source,\n      });\n\n      let result: PatchApplicationResult;\n\n      try {\n        const applicable = artifact.applicabilityCheckScript\n          ? await this.evaluateBooleanScript(artifact.applicabilityCheckScript)\n          : true;\n\n        if (!applicable) {\n          result = {\n            patchId: artifact.patchId,\n            description: artifact.description,\n            required: artifact.required,\n            outcome: 'not_applicable',\n            detail: 'Patch applicability check returned false.',\n          };\n          if (artifact.required) {\n            blockingFailure = true;\n          }\n        } else {\n          let appliedSuccessfully: boolean;\n          // Handle deferred init-patch: call the actual injection function directly\n          if (artifact.script === 'DEFERRED_INIT_PATCH') {\n            this.logger.info('applying_deferred_init_patch', { patchId: artifact.patchId });\n            await injectInitPatch(this.page);\n            appliedSuccessfully = true; // deferred patches succeed if no exception thrown\n          } else {\n            const applyResult = await this.page.evaluateScript<unknown>(artifact.script);\n            appliedSuccessfully = applyResult !== false;\n          }\n\n          if (!appliedSuccessfully) {\n            result = {\n              patchId: artifact.patchId,\n              description: artifact.description,\n              required: artifact.required,\n              outcome: 'failed',\n              detail: 'Patch script returned a failure signal.',\n            };\n            if (artifact.required) {\n              blockingFailure = true;\n            }\n          } else {\n            applied.push(artifact.patchId);\n            result = {\n              patchId: artifact.patchId,\n              description: artifact.description,\n              required: artifact.required,\n              outcome: 'applied',\n            };\n          }\n        }\n      } catch (error) {\n        const normalizedError = error instanceof Error ? error : new Error(String(error));\n        result = {\n          patchId: artifact.patchId,\n          description: artifact.description,\n          required: artifact.required,\n          outcome: 'failed',\n          detail: normalizedError.message,\n        };\n        if (artifact.required) {\n          blockingFailure = true;\n        }\n      }\n\n      results.push(result);\n\n      this.logger.info('live_patch_install_result', {\n        patchId: artifact.patchId,\n        outcome: result.outcome,\n        required: artifact.required,\n        durationMs: Date.now() - patchStartTime,\n        detail: result.detail,\n      });\n\n      this.events.emit('patch.apply.after', {\n        correlationId,\n        ts: Date.now(),\n        step: 'patch_apply_item',\n        durationMs: Date.now() - patchStartTime,\n        details: {\n          patchId: artifact.patchId,\n          applied: result.outcome === 'applied',\n          outcome: result.outcome,\n          required: artifact.required,\n          detail: result.detail,\n        },\n      });\n    }\n\n    const outcome: PatchApplyResult = {\n      outcome: blockingFailure\n        ? 'failed'\n        : applied.length > 0\n          ? 'applied'\n          : 'skipped',\n      applied,\n      blockingFailure,\n      results,\n    };\n\n    this.logger.info('live_patch_sequence_complete', {\n      outcome: outcome.outcome,\n      appliedCount: applied.length,\n      totalCount: artifacts.length,\n      appliedPatchIds: applied,\n      blockingFailure,\n    });\n\n    this.events.emit('patch.init.after', {\n      correlationId,\n      ts: Date.now(),\n      step: 'patch_apply',\n      durationMs: Date.now() - startTime,\n      details: {\n        phase: 'apply',\n        applied: outcome.applied,\n        outcome: outcome.outcome,\n        blockingFailure: outcome.blockingFailure,\n        results: outcome.results,\n      },\n    });\n\n    return outcome;\n  }\n\n  async preloadLicenseArtifact(options: LicensePreloadOptions): Promise<LicensePreloadResult> {\n    const correlationId = 'transport-license-preload';\n    const startTime = Date.now();\n    const source = options.source ?? 'local';\n\n    this.events.emit('launch.license.preload.before', {\n      correlationId,\n      ts: startTime,\n      step: 'license_preload',\n      details: { source },\n    });\n\n    try {\n      const resolvedKey = await this.resolveLicenseKey(options.licenseKey, options.sessionId);\n\n      if (!resolvedKey) {\n        const outcome: LicensePreloadResult = {\n          outcome: 'missing',\n          status: 'missing',\n          source: 'none',\n          artifact: null,\n          blockingFailure: false,\n          detail: 'No license key resolved for this runtime session.',\n        };\n\n        this.events.emit('launch.license.preload.after', {\n          correlationId,\n          ts: Date.now(),\n          step: 'license_preload',\n          durationMs: Date.now() - startTime,\n          details: {\n            success: false,\n            status: outcome.status,\n            source: outcome.source,\n            detail: outcome.detail,\n            blockingFailure: outcome.blockingFailure,\n          },\n        });\n\n        return outcome;\n      }\n\n      const keyType = this.deriveLicenseKeyType(resolvedKey);\n      // Attempt server validation if not in offline mode\n      let payload: string;\n      let payloadSource: 'server' | 'local_metadata';\n\n      if (!this.licenseConfig.offlineLicenseMode && options.sessionInfo?.hostNumber) {\n\n        try {\n          const serverPayload = await validateLicense(DEFAULT_LICENSE_CHECK_URL, {\n            key: resolvedKey,\n            number: options.sessionInfo.hostNumber,\n            WA_VERSION: options.sessionInfo.WA_VERSION,\n            WA_AUTOMATE_VERSION: options.sessionInfo.WA_AUTOMATE_VERSION,\n            BROWSER_VERSION: options.sessionInfo.BROWSER_VERSION,\n            PAGE_UA: options.sessionInfo.PAGE_UA,\n            OS: options.sessionInfo.OS,\n            NUM_HASH: options.sessionInfo.NUM_HASH,\n          });\n\n\n          if (serverPayload === false) {\n            // Server rejected the key\n            const outcome: LicensePreloadResult = {\n              outcome: 'failed',\n              status: 'invalid',\n              source,\n              artifact: null,\n              blockingFailure: true,\n              detail: 'License key was rejected by the validation server.',\n            };\n\n            this.events.emit('launch.license.preload.after', {\n              correlationId,\n              ts: Date.now(),\n              step: 'license_preload',\n              durationMs: Date.now() - startTime,\n              details: {\n                success: false,\n                status: outcome.status,\n                source: outcome.source,\n                detail: outcome.detail,\n                blockingFailure: outcome.blockingFailure,\n              },\n            });\n\n            return outcome;\n          }\n\n          payload = serverPayload;\n          payloadSource = 'server';\n          this.logger.info('license_server_validation_success', { maskedKey: this.maskLicenseKey(resolvedKey) });\n        } catch (serverError) {\n          const serverMsg = serverError instanceof Error ? serverError.message : String(serverError);\n          this.logger.warn('license_server_validation_failed', { error: serverMsg });\n          // Fall back to local metadata injection\n          payload = this.buildLicensePayload(resolvedKey, keyType);\n          payloadSource = 'local_metadata';\n        }\n      } else {\n        // Offline mode or no host number yet — use local metadata\n        payload = this.buildLicensePayload(resolvedKey, keyType);\n        payloadSource = 'local_metadata';\n      }\n\n      const artifact: LicenseArtifact = {\n        key: resolvedKey,\n        maskedKey: this.maskLicenseKey(resolvedKey),\n        source,\n        payload,\n        keyType,\n        payloadSource,\n      };\n\n      const outcome: LicensePreloadResult = {\n        outcome: 'ready',\n        status: payloadSource === 'server' ? 'valid' : 'metadata_only',\n        source,\n        artifact,\n        blockingFailure: false,\n        detail: payloadSource === 'server'\n          ? 'License capability was confirmed by the validation server.'\n          : 'License metadata fallback was prepared without server confirmation.',\n      };\n\n\n      this.events.emit('launch.license.preload.after', {\n        correlationId,\n        ts: Date.now(),\n        step: 'license_preload',\n        durationMs: Date.now() - startTime,\n        details: {\n          success: true,\n          status: outcome.status,\n          source: outcome.source,\n          payloadSource: artifact.payloadSource,\n          detail: outcome.detail,\n          blockingFailure: outcome.blockingFailure,\n        },\n      });\n\n      return outcome;\n    } catch (error) {\n      const normalizedError = error instanceof Error ? error : new Error(String(error));\n      const outcome: LicensePreloadResult = {\n        outcome: 'failed',\n        status: 'invalid',\n        source,\n        artifact: null,\n        blockingFailure: true,\n        detail: normalizedError.message,\n        error: normalizedError,\n      };\n\n      this.events.emit('launch.license.preload.after', {\n        correlationId,\n        ts: Date.now(),\n        step: 'license_preload',\n        durationMs: Date.now() - startTime,\n        error: {\n          name: normalizedError.name,\n          message: normalizedError.message,\n          stack: normalizedError.stack,\n        },\n        details: {\n          success: false,\n          status: outcome.status,\n          source: outcome.source,\n          detail: outcome.detail,\n          blockingFailure: outcome.blockingFailure,\n        },\n      });\n\n      return outcome;\n    }\n  }\n\n  async checkLicenseArtifact(preloaded: LicensePreloadResult): Promise<LicenseCheckResult> {\n    const correlationId = 'transport-license-check';\n    const startTime = Date.now();\n    const source = preloaded.source === 'none' ? 'local' : preloaded.source;\n\n    this.events.emit('launch.license.check.before', {\n      correlationId,\n      ts: startTime,\n      step: 'license_check',\n      details: { source },\n    });\n\n    this.events.emit('license.check.before', {\n      correlationId,\n      ts: startTime,\n      step: 'license_check',\n      details: { source },\n    });\n\n    let result: LicenseCheckResult;\n\n    if (preloaded.outcome === 'failed') {\n      result = {\n        status: 'invalid',\n        source,\n        artifact: null,\n        blockingFailure: true,\n        detail: preloaded.detail ?? preloaded.error?.message ?? 'License preload failed before validation.',\n      };\n    } else if (!preloaded.artifact) {\n      result = {\n        status: 'missing',\n        source,\n        artifact: null,\n        blockingFailure: false,\n        detail: preloaded.detail ?? 'No license material was available for this session.',\n      };\n    } else if (this.isExpiredLicenseKey(preloaded.artifact.key)) {\n      result = {\n        status: 'expired',\n        source,\n        artifact: null,\n        blockingFailure: true,\n        detail: 'Resolved license key is marked as expired.',\n      };\n    } else if (this.isInvalidLicenseKey(preloaded.artifact.key)) {\n      result = {\n        status: 'invalid',\n        source,\n        artifact: null,\n        blockingFailure: true,\n        detail: 'Resolved license key is marked as invalid.',\n      };\n    } else {\n      result = {\n        status: preloaded.artifact.payloadSource === 'server' ? 'valid' : 'metadata_only',\n        source,\n        artifact: preloaded.artifact,\n        blockingFailure: false,\n        detail: preloaded.artifact.payloadSource === 'server'\n          ? 'License capability remained server-confirmed at check time.'\n          : 'License metadata fallback is available, but capability is not server-confirmed.',\n      };\n    }\n\n    const finishedAt = Date.now();\n    const details = {\n      status: result.status,\n      detail: result.detail,\n      source: result.source,\n      payloadSource: result.artifact?.payloadSource,\n      blockingFailure: result.blockingFailure,\n    };\n\n    this.events.emit('launch.license.check.after', {\n      correlationId,\n      ts: finishedAt,\n      step: 'license_check',\n      durationMs: finishedAt - startTime,\n      details,\n    });\n\n    this.events.emit('license.check.after', {\n      correlationId,\n      ts: finishedAt,\n      step: 'license_check',\n      durationMs: finishedAt - startTime,\n      details,\n    });\n\n    return result;\n  }\n\n  async applyLicenseArtifact(checked: LicenseCheckResult): Promise<LicenseApplyResult> {\n    if (!this.page) {\n      throw new Error('Transport not initialized');\n    }\n\n    if ((checked.status !== 'valid' && checked.status !== 'metadata_only') || !checked.artifact) {\n      return {\n        status: checked.status,\n        applied: false,\n        blockingFailure: checked.blockingFailure,\n        detail: checked.detail,\n      };\n    }\n\n    const correlationId = 'transport-license-apply';\n    const startTime = Date.now();\n\n    this.events.emit('license.inject.before', {\n      correlationId,\n      ts: startTime,\n      step: 'license_apply',\n      details: {\n        source: checked.source,\n        keyType: checked.artifact.keyType,\n      },\n    });\n\n    let result: LicenseApplyResult;\n\n    try {\n      const applied = await this.page.evaluateScript<boolean>(checked.artifact.payload);\n      const launchError = await this.page.evaluateScript<string | null>('window.launchError || null');\n      const detectedKeyType = await this.page.evaluateScript<string | false>('window.KEYTYPE || false');\n\n      if (!applied || launchError) {\n        result = {\n          status: 'invalid',\n          applied: false,\n          blockingFailure: true,\n          detail: launchError ?? 'License payload did not confirm successful application.',\n        };\n      } else {\n        result = {\n          status: checked.status,\n          applied: true,\n          blockingFailure: false,\n          keyType: detectedKeyType || checked.artifact.keyType,\n          detail: checked.status === 'valid'\n            ? 'License capability was unlocked using a server-confirmed payload.'\n            : 'Metadata-only license fallback injected session metadata without server-confirmed unlock.',\n        };\n      }\n\n    } catch (error) {\n      const normalizedError = error instanceof Error ? error : new Error(String(error));\n      result = {\n        status: 'invalid',\n        applied: false,\n        blockingFailure: true,\n        detail: normalizedError.message,\n      };\n    }\n\n    this.events.emit('license.inject.after', {\n      correlationId,\n      ts: Date.now(),\n      step: 'license_apply',\n      durationMs: Date.now() - startTime,\n      details: {\n        success: result.applied,\n        status: result.status,\n        keyType: result.keyType,\n        payloadSource: checked.artifact.payloadSource,\n        detail: result.detail,\n      },\n    });\n\n    return result;\n  }\n\n  async waitForQr(): Promise<string | null> {\n    if (!this.page) {\n      throw new Error('Transport not initialized');\n    }\n\n    this.events.emit('launch.auth.qr.requested', {\n      correlationId: 'qr-wait',\n      ts: Date.now(),\n      step: 'qr_wait',\n      details: { smartQr: false }\n    });\n\n    this.qrWatcherAbort = new AbortController();\n\n    try {\n      await this.waitForFunctionProbe(`Boolean(${QR_CHECK_SCRIPT})`, {\n        timeoutMs: this.qrTimeoutMs,\n        polling: 'mutation',\n      });\n    } catch {\n      this.events.emit('launch.auth.timeout', {\n        correlationId: 'qr-wait',\n        ts: Date.now(),\n        step: 'qr_timeout',\n        details: { timeoutMs: this.qrTimeoutMs }\n      });\n      return null;\n    }\n\n    if (this.qrWatcherAbort?.signal.aborted) {\n      return null;\n    }\n\n    try {\n      const qrData = await this.page.evaluateScript<string | null>(QR_CHECK_SCRIPT);\n      if (qrData && typeof qrData === 'string' && qrData !== this.lastQrData) {\n        this.lastQrData = qrData;\n        this.qrAttempt++;\n        this.events.emit('launch.auth.qr.generated', {\n          correlationId: 'qr-wait',\n          ts: Date.now(),\n          step: 'qr_generated',\n          details: {\n            qr: qrData,\n            attemptInThisCycle: this.qrAttempt\n          }\n        });\n        this.logger.info('qr_code_generated', { attempt: this.qrAttempt });\n      }\n      return qrData;\n    } catch (error) {\n      this.logger.debug('qr_check_error', { error });\n      return null;\n    }\n  }\n\n  async waitForSessionLoaded(timeoutMs: number = this.authTimeoutMs): Promise<boolean> {\n    if (!this.page) {\n      throw new Error('Transport not initialized');\n    }\n\n    try {\n      await this.page.waitForFunction(AUTHENTICATED_SHELL_CHECK_SCRIPT, {\n        timeoutMs,\n        polling: 'mutation',\n      });\n      this.events.emit('launch.auth.qr.scanned', {\n        correlationId: 'auth-wait',\n        ts: Date.now(),\n        step: 'qr_scanned',\n      });\n      return true;\n    } catch {\n      return false;\n    }\n  }\n\n  async waitForRipeSession(timeoutMs: number = this.authTimeoutMs): Promise<boolean> {\n    if (!this.page) {\n      throw new Error('Transport not initialized');\n    }\n\n    try {\n      await this.page.waitForFunction(RIPE_SESSION_CHECK_SCRIPT, {\n        timeoutMs,\n        polling: 1000,\n      });\n      return true;\n    } catch {\n      return false;\n    }\n  }\n\n  async detectAttemptingReauth(): Promise<boolean> {\n    return this.evaluateBooleanScript(ATTEMPTING_REAUTH_CHECK_SCRIPT);\n  }\n\n  async reconcilePostAuthRuntime(options: {\n    freshAuth: boolean;\n    timeoutMs?: number;\n  }): Promise<PostAuthRuntimeReconciliationResult> {\n    if (!this.page) {\n      throw new Error('Transport not initialized');\n    }\n\n    const timeoutMs = options.timeoutMs ?? this.authTimeoutMs;\n    const path = options.freshAuth ? 'fresh_auth' : 'resumed_session';\n    let reinjected = false;\n\n    await this.injectionController.waitForIdle();\n\n    const capabilityBeforeGate = await this.probeRuntimeCapability();\n    if (options.freshAuth || !capabilityBeforeGate.hasRuntime) {\n      const recoveryResult = await this.recoverRuntimeForCurrentDocument({\n        trigger: 'post_authentication',\n        forceReinject: options.freshAuth,\n      });\n      reinjected = recoveryResult.reinjected;\n    }\n\n    const shouldWaitForRipeSession = !options.freshAuth;\n    const ripeSessionLoaded = shouldWaitForRipeSession\n      ? await this.waitForRipeSession(timeoutMs)\n      : true;\n    if (shouldWaitForRipeSession && !ripeSessionLoaded) {\n      this.events.emit('session.reinject.qr.waiting', {\n        correlationId: 'post-auth-ripe-session',\n        ts: Date.now(),\n        step: 'ripe_session_wait',\n        details: {\n          reason: 'ripe_session_timeout',\n        },\n      });\n\n      const timeoutCapability = await this.probeRuntimeCapability();\n      return {\n        ...timeoutCapability,\n        ripeSessionLoaded: false,\n        reinjected,\n        path,\n      };\n    }\n\n    await this.injectionController.waitForIdle();\n    const finalRecovery = await this.recoverRuntimeForCurrentDocument({\n      trigger: 'post_authentication',\n      forceReinject: false,\n    });\n\n    return {\n      ...finalRecovery.capability,\n      ripeSessionLoaded: finalRecovery.capability.sessionLoaded,\n      reinjected: reinjected || finalRecovery.reinjected,\n      path,\n    };\n  }\n\n  private async needsToScan(): Promise<false> {\n    if (!this.page) {\n      throw new Error('Transport not initialized');\n    }\n\n    try {\n      await Promise.race([\n        this.page.waitForSelector(QR_SELECTOR_PRIMARY, { timeoutMs: 0 }),\n        this.page.waitForSelector(QR_SELECTOR_FALLBACK, { timeoutMs: 0 }),\n      ]);\n      return false;\n    } catch {\n      // QR selectors not found = no QR code available right now.\n      // Hang here so that isInsideChat(), sessionDataInvalid(), or the\n      // outer auth-timeout signal in waitForAuthentication() can win.\n      return new Promise(() => { });\n    }\n  }\n\n  private async isInsideChat(): Promise<true> {\n    if (!this.page) {\n      throw new Error('Transport not initialized');\n    }\n\n    try {\n      await this.page.waitForFunction(LEGACY_IS_INSIDE_CHAT_CHECK_SCRIPT, {\n        timeoutMs: 0,\n      });\n      return true;\n    } catch {\n      return new Promise(() => { });\n    }\n  }\n\n  private async sessionDataInvalid(): Promise<'NUKE'> {\n    if (!this.page) {\n      throw new Error('Transport not initialized');\n    }\n\n    try {\n      await this.page.waitForFunction(SESSION_INVALID_CHECK_SCRIPT, {\n        timeoutMs: 0,\n        polling: 'mutation',\n      });\n      return 'NUKE';\n    } catch {\n      return new Promise(() => { });\n    }\n  }\n\n  async isAuthenticated(): Promise<unknown> {\n    const signals: Array<Promise<unknown>> = [\n      this.needsToScan(),\n      this.isInsideChat(),\n    ];\n\n    if (!this.ignoreNuke) {\n      signals.push(this.sessionDataInvalid());\n    }\n\n    return Promise.race(signals);\n  }\n\n  /**\n   * Wait for window.Store.Msg to settle.\n   * This matches legacy v4 robustness and prevents store_missing failures.\n   */\n  async waitForStoreMsg(timeoutMs: number = 15000): Promise<boolean> {\n    return this.waitForFunctionProbe(STORE_MSG_CHECK_SCRIPT, { timeoutMs, polling: 200 });\n  }\n\n  /**\n   * Extract available window.Store keys for diagnostic purposes.\n   */\n  async getStoreKeys(): Promise<string[]> {\n    if (!this.page) return [];\n    try {\n      return await this.page.evaluateScript<string[]>(`Object.keys(window.Store || {})`);\n    } catch {\n      return [];\n    }\n  }\n\n  async waitForAuthentication(_options?: { attemptingReauth?: boolean }): Promise<AuthSettlementResult> {\n    if (!this.page) {\n      throw new Error('Transport not initialized');\n    }\n\n    this.events.emit('launch.auth.check.before', {\n      correlationId: 'auth-settle',\n      ts: Date.now(),\n      step: 'auth_check',\n      details: { timeoutMs: this.authTimeoutMs },\n    });\n\n    this.events.emit('launch.auth.qr.requested', {\n      correlationId: 'auth-settle',\n      ts: Date.now(),\n      step: 'qr_wait',\n      details: { smartQr: false },\n    });\n\n    const authRace: Array<Promise<unknown>> = [this.isAuthenticated().catch(() => undefined)];\n    let authTimer: ReturnType<typeof setTimeout> | undefined;\n    if (this.authTimeoutMs !== 0) {\n      authRace.push(new Promise((resolve) => {\n        authTimer = setTimeout(() => resolve('timeout'), this.authTimeoutMs);\n      }));\n    }\n\n    let authenticated: unknown;\n    try {\n      authenticated = await Promise.race(authRace);\n    } finally {\n      if (authTimer !== undefined) clearTimeout(authTimer);\n    }\n\n    if (authenticated === true) {\n      this.logger.info('successfulScan');\n      this.logger.info('SUCCESS');\n\n      this.events.emit('launch.auth.check.after', {\n        correlationId: 'auth-settle',\n        ts: Date.now(),\n        step: 'auth_check',\n        details: { isAuthenticated: true, method: 'shell_probe' },\n      });\n\n      return {\n        outcome: 'authenticated',\n        qrSeen: false,\n        qrAttempts: this.qrAttempt,\n        authMethod: 'resumed_session',\n      };\n    }\n\n    if (authenticated === 'NUKE') {\n      this.events.emit('launch.auth.nuke.detected', {\n        correlationId: 'auth-settle',\n        ts: Date.now(),\n        step: 'nuke_detected',\n        details: { reason: 'old_logout_cred_detected' },\n      });\n\n      return {\n        outcome: 'invalid_session',\n        qrSeen: false,\n        qrAttempts: this.qrAttempt,\n        authMethod: 'resumed_session',\n      };\n    }\n\n    if (authenticated === 'timeout') {\n      return this.resolveAuthTimeoutOutcome({\n        correlationId: 'auth-settle',\n        qrSeen: false,\n        authMethod: 'resumed_session',\n      });\n    }\n\n    if (this.linkCode) {\n      const linkCodeSupported = await this.evaluateBooleanScript(LINK_CODE_AVAILABLE_CHECK_SCRIPT).catch(() => false);\n      if (linkCodeSupported) {\n        this.events.emit('launch.auth.linkCode.requested', {\n          correlationId: 'auth-settle',\n          ts: Date.now(),\n          step: 'link_code_requested',\n        });\n\n        const generatedLinkCode = await this.page.evaluateScript<string | null>(`(() => {\n          try {\n            return typeof window.linkCode === 'function' ? window.linkCode(${JSON.stringify(this.linkCode)}) : null;\n          } catch {\n            return null;\n          }\n        })()`);\n\n        if (generatedLinkCode && typeof generatedLinkCode === 'string') {\n          this.qrAttempt += 1;\n          this.events.emit('launch.auth.linkCode.generated', {\n            correlationId: 'auth-settle',\n            ts: Date.now(),\n            step: 'link_code_generated',\n            details: { linkCode: generatedLinkCode },\n          });\n          this.logger.info('link_code_generated', { attempt: this.qrAttempt });\n\n          if (this.qrMax && this.qrAttempt >= this.qrMax) {\n            return {\n              outcome: 'qr_max',\n              qrSeen: true,\n              qrAttempts: this.qrAttempt,\n              authMethod: 'link_code',\n            };\n          }\n\n          const linkCodeTimeoutMs = this.qrTimeoutMs === 0 ? 0 : this.qrTimeoutMs * 2;\n          const sessionLoaded = await this.waitForSessionLoaded(linkCodeTimeoutMs);\n          return sessionLoaded\n            ? {\n              outcome: 'authenticated',\n              qrSeen: true,\n              qrAttempts: this.qrAttempt,\n              authMethod: 'link_code',\n            }\n            : {\n              outcome: 'qr_timeout',\n              qrSeen: true,\n              qrAttempts: this.qrAttempt,\n              authMethod: 'link_code',\n            };\n        }\n      } else {\n        this.logger.warn('link_code_not_available', {\n          reason: 'window.linkCode_not_exposed',\n          fallback: 'qr_flow',\n        });\n      }\n    }\n\n    const qrData = await this.waitForQr();\n    if (!qrData) {\n      return this.resolveAuthTimeoutOutcome({\n        correlationId: 'auth-settle',\n        qrSeen: false,\n        authMethod: 'qr',\n      });\n    }\n\n    const qrScanTimeoutMs = this.qrTimeoutMs === 0 ? 0 : this.qrTimeoutMs * 2;\n    const sessionLoaded = await this.waitForSessionLoaded(qrScanTimeoutMs);\n    if (sessionLoaded) {\n      return {\n        outcome: 'authenticated',\n        qrSeen: true,\n        qrAttempts: this.qrAttempt,\n        authMethod: 'qr',\n      };\n    }\n\n    if (this.qrMax && this.qrAttempt >= this.qrMax) {\n      return {\n        outcome: 'qr_max',\n        qrSeen: true,\n        qrAttempts: this.qrAttempt,\n        authMethod: 'qr',\n      };\n    }\n\n    return {\n      outcome: 'qr_timeout',\n      qrSeen: true,\n      qrAttempts: this.qrAttempt,\n      authMethod: 'qr',\n    };\n  }\n\n  private async resolveAuthTimeoutOutcome(options: {\n    correlationId: string;\n    qrSeen: boolean;\n    authMethod: AuthSettlementResult['authMethod'];\n  }): Promise<AuthSettlementResult> {\n    const phoneOutOfReach = await this.waitForPhoneOutOfReach();\n\n    this.events.emit('launch.auth.timeout', {\n      correlationId: options.correlationId,\n      ts: Date.now(),\n      step: 'auth_timeout',\n      details: {\n        timeoutMs: this.authTimeoutMs,\n        phoneOutOfReach,\n      },\n    });\n\n    if (phoneOutOfReach) {\n      this.events.emit('launch.auth.phoneOutOfReach', {\n        correlationId: options.correlationId,\n        ts: Date.now(),\n        step: 'phone_out_of_reach',\n        details: { reason: 'trying_to_reach_phone' },\n      });\n\n      return {\n        outcome: 'phone_out_of_reach',\n        qrSeen: options.qrSeen,\n        qrAttempts: this.qrAttempt,\n        authMethod: options.authMethod,\n      };\n    }\n\n    return {\n      outcome: 'auth_timeout',\n      qrSeen: options.qrSeen,\n      qrAttempts: this.qrAttempt,\n      authMethod: options.authMethod,\n    };\n  }\n\n  private async waitForPhoneOutOfReach(): Promise<boolean> {\n    if (!this.page) {\n      throw new Error('Transport not initialized');\n    }\n\n    try {\n      await this.page.waitForFunction(PHONE_OUT_OF_REACH_CHECK_SCRIPT, {\n        timeoutMs: this.oorTimeoutMs,\n        polling: 'mutation',\n      });\n      return true;\n    } catch {\n      return false;\n    }\n  }\n\n  stopQrWatcher(): void {\n    this.qrWatcherAbort?.abort();\n    this.qrWatcherAbort = null;\n  }\n\n  async evaluate<Arg, Ret>(fn: (arg: Arg) => Ret | Promise<Ret>, arg: Arg): Promise<Ret> {\n    if (!this.page) {\n      throw new Error('Transport not initialized');\n    }\n    return this.page.evaluate(fn, arg);\n  }\n\n  getPage(): IPage | null {\n    return this.page;\n  }\n\n  getOperationalReadinessSnapshot(): TransportOperationalReadinessSnapshot {\n    const health = this.injectionController.getHealthSnapshot();\n    const driverActiveGeneration = Boolean(\n      this.page\n      && !this.page.isClosed()\n      && health.phase !== 'disposed'\n      && health.generation.documentId\n      && health.generation.runtimeId\n    );\n    const missingRuntimeMethods = [...health.missingRuntimeMethods].sort();\n\n    return {\n      generation: driverActiveGeneration ? { ...health.generation } : null,\n      phase: health.phase,\n      driverActiveGeneration,\n      runtimeOperational: health.runtimePresent && health.hasStoreMsg && health.sessionLoaded,\n      runtimeBridgeReady: health.bridgeReady && missingRuntimeMethods.length === 0,\n      reinjectionSettled: this.pendingRuntimeRecoveryCount === 0,\n      missingRuntimeMethods,\n    };\n  }\n\n  async waitForOperationalReadiness(): Promise<TransportOperationalReadinessSnapshot> {\n    await this.injectionController.waitForIdle();\n    await this.runtimeRecoveryQueue;\n    await this.injectionController.waitForIdle();\n    return this.getOperationalReadinessSnapshot();\n  }\n\n  getBrowser(): IBrowser | null {\n    return this.browser;\n  }\n\n  async close(): Promise<void> {\n    this.disposePageListeners();\n    await this.injectionController.dispose();\n    if (this.page) {\n      await this.page.close();\n      this.page = null;\n    }\n    if (this.browser) {\n      await this.browser.close();\n      this.browser = null;\n    }\n    this.logger.info('transport_closed');\n  }\n\n  private async configurePageRuntime(page: IPage): Promise<void> {\n    this.registerPageDiagnostics(page);\n\n    // Inject self-healing watermark if configured\n    if (this.options.watermark) {\n      const wbg = typeof this.options.watermark === 'object' && this.options.watermark.background ? this.options.watermark.background : 'rgba(255, 0, 0, 0.1)';\n      const wcolor = typeof this.options.watermark === 'object' && this.options.watermark.color ? this.options.watermark.color : 'rgba(255, 0, 0, 0.5)';\n      const wtext = typeof this.options.watermark === 'object' && this.options.watermark.text ? this.options.watermark.text : 'RESTRICTED AUTOMATION';\n\n      await page.addInitScript(`\n        (() => {\n          if (window !== window.top) return;\n\n          let element = null;\n          const bg = ${JSON.stringify(wbg)};\n          const color = ${JSON.stringify(wcolor)};\n          const txt = ${JSON.stringify(wtext)};\n\n          const enforceWatermark = () => {\n            if (!element || !element.isConnected) {\n              const host = document.createElement('wa-watermark-host');\n              host.style.position = 'fixed';\n              host.style.top = '0';\n              host.style.left = '0';\n              host.style.width = '100vw';\n              host.style.height = '100vh';\n              host.style.pointerEvents = 'none';\n              host.style.zIndex = '2147483647';\n\n              const shadow = host.attachShadow({ mode: 'closed' });\n\n              const tint = document.createElement('div');\n              tint.style.cssText = \\`position: absolute; top: 0; left: 0; width: 100%; height: 100%; background: \\${bg}; pointer-events: none; mix-blend-mode: multiply;\\`;\n\n              const text = document.createElement('div');\n              text.style.cssText = \\`position: absolute; bottom: 20px; right: 20px; color: \\${color}; font-family: sans-serif; font-size: 24px; font-weight: bold; text-shadow: 1px 1px 2px rgba(255,255,255,0.8); pointer-events: none;\\`;\n              text.textContent = txt;\n\n              shadow.appendChild(tint);\n              shadow.appendChild(text);\n\n              document.documentElement.appendChild(host);\n              element = host;\n            }\n\n            if (element) {\n              element.style.display = 'block';\n              element.style.opacity = '1';\n              element.style.visibility = 'visible';\n              element.style.transform = 'none';\n            }\n\n            requestAnimationFrame(enforceWatermark);\n          };\n\n          requestAnimationFrame(enforceWatermark);\n        })();\n      `);\n    }\n\n    await this.configureRequestInterception(page);\n  }\n\n  private async configureLaunchBootstrap(page: IPage): Promise<void> {\n    const logoutSurface = getRuntimeListenerSurfaceEntry('session.logout');\n\n    await this.injectionController.registerPersistentBinding('ProgressBarEvent', (data: { value?: number; text?: string }) => {\n      const msg = `${(data.value || data.value === 0) ? `${data.value}%:\\t` : ''} ${data.text ?? ''}`;\n      this.logger.info('progress_bar_event', { value: data.value, text: data.text, msg });\n      this.events.emit('internal_launch_progress', {\n        value: data.value,\n        text: data.text,\n      });\n    });\n\n    await this.injectionController.registerPersistentBinding('CriticalInternalMessage', (data: { value?: string; text?: string }) => {\n      this.logger.warn('critical_internal_message', { value: data.value, text: data.text });\n      this.events.emit('critical_internal_message', {\n        value: data.value,\n        text: data.text,\n      });\n    });\n\n    await this.injectionController.registerPersistentBinding('OpenWA_RuntimeReplacementDetected', () => {\n      this.queueRuntimeRecovery('runtime_replaced');\n    });\n\n    this.injectionController.registerNavigationObserver(logoutSurface.observerId, (frame) => {\n      const url = frame.url();\n      if (!url.includes('post_logout=1')) {\n        return;\n      }\n\n      this.events.emit('session.logout', {\n        correlationId: 'page-post-logout',\n        ts: Date.now(),\n        step: 'session_logout',\n        details: { reason: 'post_logout=1' },\n      });\n    });\n\n    this.injectionController.registerNavigationObserver('runtime.navigation_recovery', (_frame, generation) => {\n      this.logger.info(`FRAME NAV DETECTED ${this.frameNavCounter}, ${_frame.url()}, Reinjecting APIs...`);\n      this.queueRuntimeRecovery('main_frame_navigation', generation);\n      this.frameNavCounter++;\n    });\n\n    await this.injectionController.registerPersistentInitScript('prog_observer', await getProgObserverScript());\n    await this.injectionController.registerPersistentInitScript('runtime_replacement_observer', RUNTIME_REPLACEMENT_OBSERVER_SCRIPT);\n    await this.injectionController.initialize(page);\n\n    this.logger.debug('exposed_page_callbacks', {\n      functions: ['ProgressBarEvent', 'CriticalInternalMessage', 'OpenWA_RuntimeReplacementDetected'],\n    });\n    this.logger.info('prog_observer_registered_post_navigation');\n  }\n\n  private async runPreApiHelperPhase(): Promise<void> {\n    const helpersReady = await this.evaluateBooleanScript(PRE_API_HELPER_READY_CHECK_SCRIPT).catch(() => false);\n\n    this.events.emit('launch.helper.pre_api.before', {\n      correlationId: 'transport-pre-api-helper',\n      ts: Date.now(),\n      step: 'pre_api_helper_phase',\n      details: { mode: helpersReady ? 'noop' : 'scripts' },\n    });\n\n    const wapiScript = await Transport.getAssetScript('wapi.js');\n    const audit = auditWapiHelperAssetRequirements(wapiScript);\n\n    if (audit.forbiddenMatches.length > 0) {\n      // throw new Error(`wapi.js still depends on legacy helper globals: ${audit.forbiddenMatches.join(', ')}`);\n    }\n\n    if (audit.requiredLegacyHelpers.length > 0) {\n      throw new Error(`Legacy pre-api helper phase is required but not implemented for: ${audit.requiredLegacyHelpers.join(', ')}`);\n    }\n\n    if (!helpersReady) {\n      const helperAssets: Array<'qr.min.js' | 'hash.js'> = ['qr.min.js', 'hash.js'];\n      for (const asset of helperAssets) {\n        const assetPath = Transport.resolveAssetPath(asset);\n        const helperScript = await Transport.getAssetScript(asset);\n        this.logger.info('transport_injection_asset_evaluating', {\n          asset,\n          assetPath,\n          bytes: helperScript.length,\n        });\n        await this.page!.evaluateScript(helperScript);\n      }\n    }\n\n    this.logger.info('pre_api_helper_phase_complete', {\n      mode: helpersReady ? 'noop' : 'scripts',\n      requiredLegacyHelpers: audit.requiredLegacyHelpers,\n    });\n\n    this.events.emit('launch.helper.pre_api.after', {\n      correlationId: 'transport-pre-api-helper',\n      ts: Date.now(),\n      step: 'pre_api_helper_phase',\n      details: {\n        mode: helpersReady ? 'noop' : 'scripts',\n        success: true,\n        requiredLegacyHelpers: audit.requiredLegacyHelpers,\n      },\n    });\n  }\n\n  private registerPageDiagnostics(page: IPage): void {\n    this.disposePageListeners();\n\n    this.pageListeners.push(\n      page.on('console', (message) => this.handleConsoleMessage(message)),\n      page.on('pageerror', (error) => this.handlePageError(error)),\n    );\n  }\n\n  private async configureRequestInterception(page: IPage): Promise<void> {\n    const shouldBlockAssets = this.headless && this.blockAssets;\n    const shouldEnableInterception = this.blockCrashLogs || shouldBlockAssets;\n\n    this.events.emit('launch.page.interception.before', {\n      correlationId: 'transport-page-interception',\n      ts: Date.now(),\n      step: 'page_interception',\n      details: { enabled: shouldEnableInterception },\n    });\n\n    if (!shouldEnableInterception) {\n      this.events.emit('launch.page.interception.after', {\n        correlationId: 'transport-page-interception',\n        ts: Date.now(),\n        step: 'page_interception',\n        details: {},\n      });\n      return;\n    }\n\n    try {\n      await page.setRequestInterception(true);\n      this.pageListeners.push(page.on('request', (request) => this.handleInterceptedRequest(request)));\n      this.logger.info('page_request_interception_enabled', {\n        blockCrashLogs: this.blockCrashLogs,\n        blockAssets: shouldBlockAssets,\n        safeMode: this.safeMode,\n      });\n    } catch (error) {\n      this.logger.warn('page_request_interception_unavailable', {\n        error: error instanceof Error ? error.message : String(error),\n        blockCrashLogs: this.blockCrashLogs,\n        blockAssets: shouldBlockAssets,\n        safeMode: this.safeMode,\n      });\n    } finally {\n      this.events.emit('launch.page.interception.after', {\n        correlationId: 'transport-page-interception',\n        ts: Date.now(),\n        step: 'page_interception',\n        details: {},\n      });\n    }\n  }\n\n  private handleConsoleMessage(message: IConsoleMessage): void {\n    const meta = {\n      type: message.type(),\n      text: message.text(),\n      location: message.location?.(),\n    };\n\n    if (this.logConsole) {\n      console.log(message.text());\n    }\n\n    this.logger.info('page_console', meta);\n  }\n\n  private handlePageError(error: Error): void {\n    if (this.logConsoleErrors) {\n      console.error(error);\n    }\n\n    this.logger.error('page_console_error', {\n      message: error.message,\n      stack: error.stack,\n    });\n  }\n\n  private async handleInterceptedRequest(request: IRequest): Promise<void> {\n    const shouldBlockAssets = this.headless && this.blockAssets;\n    const url = request.url();\n    const resourceType = request.resourceType();\n\n    if (this.blockCrashLogs && CRASH_LOG_URL_FRAGMENTS.some((fragment) => url.includes(fragment))) {\n      await request.abort();\n      return;\n    }\n\n    if (shouldBlockAssets && resourceType && BLOCKED_ASSET_RESOURCE_TYPES.has(resourceType)) {\n      await request.abort();\n      return;\n    }\n\n    await request.continue();\n  }\n\n  private disposePageListeners(): void {\n    const handles = this.pageListeners.splice(0, this.pageListeners.length);\n    for (const handle of handles) {\n      void Promise.resolve(handle.dispose()).catch(() => undefined);\n    }\n  }\n\n  private static async getAssetScript(assetFileName: 'launch.js' | 'wapi.js' | 'qr.min.js' | 'hash.js'): Promise<string> {\n    const cached = Transport.assetScriptCache.get(assetFileName);\n    if (cached) {\n      return cached;\n    }\n\n    const scriptPromise = readFile(Transport.resolveAssetPath(assetFileName), 'utf8');\n    Transport.assetScriptCache.set(assetFileName, scriptPromise);\n    return scriptPromise;\n  }\n\n  private static resolveAssetPath(assetFileName: 'launch.js' | 'wapi.js' | 'qr.min.js' | 'hash.js'): string {\n    const moduleDir = Transport.resolveCurrentModuleDir();\n    const candidates = [\n      join(moduleDir, 'assets', assetFileName),\n      join(moduleDir, 'transport/assets', assetFileName),\n    ];\n\n    const match = candidates.find((candidate) => existsSync(candidate));\n    if (!match) {\n      throw new Error(`Unable to resolve ${assetFileName} for runtime activation from module-relative candidates: ${candidates.join(', ')}`);\n    }\n\n    return match;\n  }\n\n  static resolveLaunchScriptPath(): string {\n    return Transport.resolveAssetPath('launch.js');\n  }\n\n  static resolveWapiScriptPath(): string {\n    return Transport.resolveAssetPath('wapi.js');\n  }\n\n  private static resolveCurrentModuleDir(): string {\n    const originalPrepareStackTrace = Error.prepareStackTrace;\n\n    try {\n      Error.prepareStackTrace = (_error, stack) => stack;\n      const stack = new Error().stack as unknown as NodeJS.CallSite[] | undefined;\n      const fileName = stack\n        ?.map((callSite) => callSite.getFileName())\n        .find((candidate): candidate is string => (\n          typeof candidate === 'string'\n          && candidate.length > 0\n          && !candidate.startsWith('node:')\n          && !candidate.startsWith('[')\n          && !candidate.includes('/[eval]')\n          && !candidate.includes('\\[eval]')\n        ));\n\n      if (!fileName) {\n        throw new Error('Unable to determine current module path for launch.js resolution');\n      }\n\n      return dirname(fileName);\n    } finally {\n      Error.prepareStackTrace = originalPrepareStackTrace;\n    }\n  }\n\n  private async evaluateBooleanScript(script: string): Promise<boolean> {\n    if (!this.page) {\n      throw new Error('Transport not initialized');\n    }\n\n    return Boolean(await this.page.evaluateScript<boolean>(script));\n  }\n\n  private queueRuntimeRecovery(\n    trigger: 'main_frame_navigation' | 'runtime_replaced',\n    generation?: GenerationSnapshot,\n  ): void {\n    const requestId = ++this.latestRuntimeRecoveryRequestId;\n    this.pendingRuntimeRecoveryCount += 1;\n\n\n    this.logger.warn('runtime_recovery_queued', {\n      trigger,\n      requestId: String(requestId),\n    });\n\n    this.runtimeRecoveryQueue = this.runtimeRecoveryQueue.then(\n      () => this.runRuntimeRecovery({ requestId, trigger, generation }),\n      () => this.runRuntimeRecovery({ requestId, trigger, generation }),\n    ).catch((error) => {\n      this.logger.warn('runtime_recovery_failed', {\n        trigger,\n        requestId: String(requestId),\n        error: error instanceof Error ? error.message : String(error),\n      });\n    });\n  }\n\n  private isLatestRuntimeRecoveryRequest(requestId: number): boolean {\n    return requestId === this.latestRuntimeRecoveryRequestId;\n  }\n\n  private async runRuntimeRecovery(request: {\n    requestId: number;\n    trigger: 'main_frame_navigation' | 'runtime_replaced';\n    generation?: GenerationSnapshot;\n  }): Promise<void> {\n    try {\n      if (!this.page) {\n        return;\n      }\n\n      // Guard: prevent infinite recovery loops\n      this.consecutiveRecoveryAttempts++;\n      if (this.consecutiveRecoveryAttempts > MAX_CONSECUTIVE_RECOVERY_ATTEMPTS) {\n        this.logger.warn('runtime_recovery_max_attempts_exceeded', {\n          trigger: request.trigger,\n          attempts: this.consecutiveRecoveryAttempts,\n          max: MAX_CONSECUTIVE_RECOVERY_ATTEMPTS,\n          requestId: String(request.requestId),\n        });\n        return;\n      }\n\n      const settledGeneration = await this.injectionController.waitForIdle();\n      if (!this.isLatestRuntimeRecoveryRequest(request.requestId)) {\n        this.logger.debug('runtime_recovery_dropped_stale_request', {\n          trigger: request.trigger,\n          requestId: String(request.requestId),\n          latestRequestId: String(this.latestRuntimeRecoveryRequestId),\n        });\n        return;\n      }\n\n      if (\n        request.generation\n        && request.generation.documentId !== settledGeneration.documentId\n      ) {\n        this.logger.debug('runtime_recovery_generation_superseded', {\n          trigger: request.trigger,\n          requestDocumentId: request.generation.documentId,\n          settledDocumentId: settledGeneration.documentId,\n        });\n        return;\n      }\n\n      await this.waitForFunctionProbe(DOCUMENT_READY_CHECK_SCRIPT, {\n        timeoutMs: 3000,\n        polling: 'mutation',\n      });\n\n      if (!this.isLatestRuntimeRecoveryRequest(request.requestId)) {\n        return;\n      }\n\n      // ── Early-exit: check if the session survived the frame nav ──\n      // Frame navigation does NOT always flush the global context. Before doing\n      // heavy recovery (reinject wapi + patches + bridge), probe whether:\n      //   1. The page is still injectable (WAWebCollections module available)\n      //   2. Live patches are still applied (window.moi exists — it's injected by\n      //      CDN live patches, NOT by wapi.js, so its presence proves patches survived)\n      // If both pass, the session is intact — skip recovery entirely.\n      if (request.trigger === 'main_frame_navigation') {\n        try {\n          const injectable = await this.waitForInjectableSession();\n          if (injectable) {\n            const livePatchIntact = await this.evaluateBooleanScript(\n              `!!(typeof window.moi === 'function' && window.moi())`\n            );\n            if (livePatchIntact) {\n              this.logger.info('runtime_recovery_skipped_session_intact', {\n                trigger: request.trigger,\n                requestId: String(request.requestId),\n                reason: 'live_patches_intact_after_frame_nav',\n              });\n              this.consecutiveRecoveryAttempts = 0;\n              return;\n            }\n            this.logger.debug('runtime_recovery_live_patches_missing', {\n              trigger: request.trigger,\n              requestId: String(request.requestId),\n            });\n          }\n        } catch (probeError) {\n          // Probe failed — session is likely flushed, proceed with full recovery\n          this.logger.debug('runtime_recovery_integrity_probe_failed', {\n            trigger: request.trigger,\n            requestId: String(request.requestId),\n            error: probeError instanceof Error ? probeError.message : String(probeError),\n          });\n        }\n      }\n\n      const { reinjected } = await this.recoverRuntimeForCurrentDocument({\n        trigger: request.trigger,\n        shouldContinue: () => this.isLatestRuntimeRecoveryRequest(request.requestId),\n        forceReinject: request.trigger === 'runtime_replaced',\n      });\n\n      this.logger.info('runtime_recovery_completed', {\n        trigger: request.trigger,\n        requestId: String(request.requestId),\n        reinjected,\n        generation: settledGeneration,\n      });\n\n      // Reset consecutive counter on successful recovery\n      this.consecutiveRecoveryAttempts = 0;\n    } finally {\n      this.pendingRuntimeRecoveryCount = Math.max(0, this.pendingRuntimeRecoveryCount - 1);\n    }\n  }\n\n  private async recoverRuntimeForCurrentDocument(options: {\n    trigger: 'main_frame_navigation' | 'runtime_replaced' | 'post_authentication' | 'validation_failure';\n    shouldContinue?: () => boolean;\n    forceReinject?: boolean;\n  }): Promise<{ capability: RuntimeCapabilityProbe; reinjected: boolean }> {\n    const shouldContinue = options.shouldContinue ?? (() => true);\n\n    let capability = await this.probeRuntimeCapability();\n    if (!shouldContinue()) {\n      return { capability, reinjected: false };\n    }\n\n    // ── Short-circuit: runtime is intact AND bridge is NOT tested here ──\n    // We do NOT call ensureRuntimeBridge() as a pre-check because it would try\n    // to wire onStateChanged before live patches and init patch are re-applied,\n    // causing failures that trigger the WAPI setter trap → infinite recovery loop.\n    //\n    // Instead, we only short-circuit if the runtime exists AND we are NOT in a\n    // post_authentication or forceReinject scenario.\n    if (!options.forceReinject && capability.hasRuntime) {\n      const isPostAuth = options.trigger === 'post_authentication';\n      const storeReady = capability.hasStoreMsg;\n\n      // For non-auth triggers: if runtime is present, skip reinjection.\n      // The bridge will be wired after the full recovery sequence.\n      if (!isPostAuth || storeReady) {\n        this.logger.debug('runtime_recovery_runtime_present_skip_reinject', {\n          trigger: options.trigger,\n          hasStoreMsg: storeReady,\n        });\n        return { capability, reinjected: false };\n      }\n\n      if (isPostAuth && !storeReady) {\n        this.logger.info('runtime_recovery_forcing_reinject_store_missing', {\n          trigger: options.trigger,\n          hasRuntime: capability.hasRuntime,\n          hasStoreMsg: false,\n        });\n      }\n    }\n\n    // ── Step 1: Reinject wapi.js + launch.js + cached live patches ──\n    // performRuntimeInjection already re-applies cached live patch scripts.\n    const reinjected = await this.performRuntimeInjection(shouldContinue);\n    if (!shouldContinue()) {\n      capability = await this.probeRuntimeCapability();\n      return { capability, reinjected };\n    }\n\n    // ── Step 2: Re-apply init patch + wire bridge ──\n    // ONLY for actual context-flush recovery (frame nav / runtime_replaced) where\n    // the full patch stack was previously applied and needs restoration.\n    //\n    // For post_authentication and validation_failure, the bootstrap sequence in\n    // createClient.ts manages the correct layering order:\n    //   wapi → live patches (CDN) → license → init patch → bridge wiring\n    // Applying init_patch here would be premature (before live patches exist)\n    // and causes \"Identifier already declared\" when bootstrap tries again later.\n    const isContextFlushRecovery = options.trigger === 'main_frame_navigation'\n      || options.trigger === 'runtime_replaced';\n\n    if (reinjected && isContextFlushRecovery) {\n      try {\n        this.logger.info('recovery_reapplying_init_patch', {\n          trigger: options.trigger,\n        });\n        await injectInitPatch(this.page!);\n        this.logger.debug('recovery_init_patch_reapplied', {\n          trigger: options.trigger,\n        });\n      } catch (initPatchError) {\n        const msg = initPatchError instanceof Error ? initPatchError.message : String(initPatchError);\n        this.logger.warn('recovery_init_patch_reapply_failed', {\n          trigger: options.trigger,\n          error: msg,\n        });\n      }\n\n      // ── Step 3: Wire the bridge (AFTER all patches are applied) ──\n      // This matches the v4 order: patches → init → client.loaded() (bridge)\n      try {\n        const bridgeReady = await this.injectionController.ensureRuntimeBridge();\n        this.logger.info('recovery_bridge_wired', {\n          trigger: options.trigger,\n          bridgeReady,\n        });\n      } catch (bridgeError) {\n        const msg = bridgeError instanceof Error ? bridgeError.message : String(bridgeError);\n        this.logger.warn('recovery_bridge_wiring_failed', {\n          trigger: options.trigger,\n          error: msg,\n        });\n      }\n    }\n\n    capability = await this.probeRuntimeCapability();\n\n    return {\n      capability,\n      reinjected,\n    };\n  }\n\n  private async performRuntimeInjection(shouldContinue: () => boolean = () => true): Promise<boolean> {\n    if (!this.page) {\n      throw new Error('Transport not initialized');\n    }\n\n    const wapiAssetPath = Transport.resolveWapiScriptPath();\n    const wapiScript = await Transport.getAssetScript('wapi.js');\n    this.logger.info('transport_injection_asset_evaluating', {\n      asset: 'wapi.js',\n      assetPath: wapiAssetPath,\n      bytes: wapiScript.length,\n    });\n    await this.page.evaluateScript(wapiScript);\n\n    await this.waitForFunctionProbe(WAPI_RUNTIME_CHECK_SCRIPT, { timeoutMs: 3000, polling: 50 });\n    if (!shouldContinue()) {\n      return false;\n    }\n\n    let capability = await this.probeRuntimeCapability();\n\n    if (!capability.hasRuntime) {\n      this.logger.warn('wapi_bootstrap_missing_runtime_after_wapi_asset');\n    }\n\n    const launchAssetPath = Transport.resolveLaunchScriptPath();\n    const launchScript = await Transport.getAssetScript('launch.js');\n    this.logger.info('transport_injection_asset_evaluating', {\n      asset: 'launch.js',\n      assetPath: launchAssetPath,\n      bytes: launchScript.length,\n    });\n    try {\n      await this.page.evaluateScript(launchScript);\n    } catch (error) {\n      const qrData = await this.page.evaluateScript<string | null>(QR_CHECK_SCRIPT).catch(() => null);\n      if (!qrData) {\n        throw error;\n      }\n\n      this.logger.warn('launch_asset_deferred_for_pre_auth_qr', {\n        reason: 'qr_surface_available',\n        error: error instanceof Error ? error.message : String(error),\n      });\n    }\n\n    await this.waitForFunctionProbe(WAPI_RUNTIME_CHECK_SCRIPT, { timeoutMs: 3000, polling: 50 });\n    if (!shouldContinue()) {\n      return false;\n    }\n\n    capability = await this.probeRuntimeCapability();\n\n    if (!capability.hasRuntime) {\n      this.logger.warn('wapi_bootstrap_missing_runtime_after_launch_asset');\n    }\n\n    const success = capability.hasRuntime;\n\n    this.logger.info('wapi_injection_probe', { ...capability });\n\n    // Re-apply cached live patch scripts after wapi.js/launch.js re-injection.\n    // Without this, the freshly injected WAPI overwrites the live-patched version,\n    // causing onStateChanged (and similar methods) to fail and triggering an\n    // infinite recovery loop.\n    if (success && this.cachedLivePatchScripts.length > 0) {\n      this.logger.info('recovery_reapplying_live_patches', {\n        count: this.cachedLivePatchScripts.length,\n      });\n\n      for (let i = 0; i < this.cachedLivePatchScripts.length; i++) {\n        try {\n          await this.page.evaluateScript(this.cachedLivePatchScripts[i]);\n          this.logger.debug('recovery_live_patch_reapplied', { index: i });\n        } catch (reapplyError) {\n          const msg = reapplyError instanceof Error ? reapplyError.message : String(reapplyError);\n          this.logger.warn('recovery_live_patch_reapply_failed', { index: i, error: msg });\n        }\n      }\n    }\n\n    return success;\n  }\n\n  private async probeBrokenMethodIntegrity(): Promise<RuntimeMethodIntegrityResult> {\n    const requiredMethods = this.injectionController.getRequiredRuntimeMethods();\n    const bridgeReady = await this.injectionController.ensureRuntimeBridge();\n    const health = this.injectionController.getHealthSnapshot();\n\n    return {\n      bridgeReady,\n      requiredMethods,\n      missingMethods: health.missingRuntimeMethods,\n    };\n  }\n\n  private async waitForFunctionProbe(\n    script: string,\n    options?: WaitForFunctionOptions,\n  ): Promise<boolean> {\n    if (!this.page) {\n      throw new Error('Transport not initialized');\n    }\n\n    try {\n      await this.page.waitForFunction(script, options);\n      return true;\n    } catch {\n      return false;\n    }\n  }\n\n  private async resolveLicenseKey(\n    input: LicenseKeyResolver | undefined,\n    sessionId: string,\n  ): Promise<string | null> {\n    if (!input) {\n      return null;\n    }\n\n    let resolved: string | Record<string, string | undefined> | null | undefined;\n    if (typeof input === 'function') {\n      resolved = await input(sessionId);\n    } else {\n      resolved = input;\n    }\n\n    if (typeof resolved === 'object' && resolved !== null) {\n      resolved = resolved[sessionId] ?? null;\n    }\n\n    if (typeof resolved !== 'string') {\n      return null;\n    }\n\n    const trimmed = resolved.trim();\n    return trimmed.length > 0 ? trimmed : null;\n  }\n\n  private deriveLicenseKeyType(key: string): string {\n    const normalizedKey = key.trim();\n    const [head] = normalizedKey.split(/[-:]/);\n    return /^(insiders|restricted)$/i.test(head ?? '')\n      ? head.toLowerCase()\n      : 'license';\n  }\n\n  private maskLicenseKey(key: string): string {\n    if (key.length <= 4) {\n      return key;\n    }\n\n    return `${'*'.repeat(Math.max(0, key.length - 4))}${key.slice(-4)}`;\n  }\n\n  private isInvalidLicenseKey(key: string): boolean {\n    return /^invalid[-:]/i.test(key.trim());\n  }\n\n  private isExpiredLicenseKey(key: string): boolean {\n    return /^expired[-:]/i.test(key.trim());\n  }\n\n  private buildLicensePayload(key: string, keyType: string): string {\n    const safeKeyType = JSON.stringify(keyType);\n    const safeMaskedKey = JSON.stringify(this.maskLicenseKey(key));\n\n    return `(() => {\n      window.__OPENWA_LICENSE__ = {\n        appliedAt: Date.now(),\n        mode: 'metadata_injection',\n        keyType: ${safeKeyType},\n        maskedKey: ${safeMaskedKey}\n      };\n      window.KEYTYPE = ${safeKeyType};\n      window.launchError = null;\n      return true;\n    })();`;\n  }\n\n  // ─── Live Patch Pipeline ────────────────────────────────────────────────\n\n  /**\n   * Fetch live patches from CDN with disk caching.\n   *\n   * Strategy (mirrors legacy `getAndInjectLivePatch`):\n   * 1. Try cached live patches first (if < 24h old)\n   * 2. If stale/missing, fetch from cdn.openwa.dev\n   * 3. If CDN fails, fall back to GitHub raw\n   * 4. Cache result to disk for next session\n   */\n  private async fetchLivePatchesWithCache(\n    sessionInfo?: SessionDebugInfo,\n  ): Promise<LivePatchFetchResult> {\n    const cacheEnabled = this.patchConfig.cachedPatch === true;\n\n    // Try disk cache first only when explicitly enabled.\n    if (cacheEnabled) {\n      try {\n        const cached = await this.loadCachedLivePatches();\n        if (cached) {\n          this.logger.info('live_patch_loaded_from_cache', { tag: cached.tag, patchCount: cached.data.length });\n          void this.refreshLivePatchCacheInBackground(sessionInfo);\n          return { data: cached.data, tag: cached.tag, source: 'cached' };\n        }\n      } catch (cacheError) {\n        const cacheMsg = cacheError instanceof Error ? cacheError.message : String(cacheError);\n        this.logger.debug('live_patch_cache_read_failed', { error: cacheMsg });\n      }\n    }\n\n    const result = await this.fetchFreshLivePatches(sessionInfo);\n    this.logger.info('live_patch_downloaded', {\n      source: 'remote',\n      url: DEFAULT_LIVE_PATCHES_URL,\n      tag: result.tag,\n      patchCount: result.data.length,\n    });\n    return { data: result.data, tag: result.tag, source: 'remote' };\n  }\n\n  private async refreshLivePatchCacheInBackground(sessionInfo?: SessionDebugInfo): Promise<void> {\n    try {\n      const result = await this.fetchFreshLivePatches(sessionInfo);\n      this.logger.debug('live_patch_cache_refreshed_in_background', { tag: result.tag, count: result.data.length });\n    } catch (refreshError) {\n      const refreshMsg = refreshError instanceof Error ? refreshError.message : String(refreshError);\n      this.logger.debug('live_patch_cache_background_refresh_failed', { error: refreshMsg });\n    }\n  }\n\n  private async fetchFreshLivePatches(sessionInfo?: SessionDebugInfo): Promise<{ data: string[]; tag: string }> {\n    const useGithubPrimary = this.patchConfig.ghPatch === true;\n    const primaryUrl = useGithubPrimary ? GH_LIVE_PATCHES_FALLBACK_URL : DEFAULT_LIVE_PATCHES_URL;\n    const fallbackUrl = useGithubPrimary\n      ? undefined\n      : this.patchConfig.ghPatchFallback === false\n        ? undefined\n        : GH_LIVE_PATCHES_FALLBACK_URL;\n\n    const fetchStart = Date.now();\n    const result = await fetchPatches(\n      primaryUrl,\n      {\n        waVersion: sessionInfo?.WA_VERSION,\n        waAutomateVersion: sessionInfo?.WA_AUTOMATE_VERSION,\n      },\n      { fallbackUrl },\n    );\n    const fetchDurationMs = Date.now() - fetchStart;\n\n    this.logger.info('live_patch_fetch_complete', {\n      url: primaryUrl,\n      durationMs: fetchDurationMs,\n      durationFormatted: `${(fetchDurationMs / 1000).toFixed(2)}s`,\n      tag: result.tag,\n      patchCount: result.data.length,\n    });\n\n    if (this.patchConfig.cachedPatch === true) {\n      try {\n        await this.saveCachedLivePatches(result);\n        this.logger.debug('live_patch_saved_to_cache', { tag: result.tag, count: result.data.length });\n      } catch (saveError) {\n        const saveMsg = saveError instanceof Error ? saveError.message : String(saveError);\n        this.logger.debug('live_patch_cache_write_failed', { error: saveMsg });\n      }\n    }\n\n    return result;\n  }\n\n  private async loadCachedLivePatches(): Promise<{ data: string[]; tag: string } | null> {\n    const cachePath = join(process.cwd(), LIVE_PATCH_CACHE_FILENAME);\n\n    if (!existsSync(cachePath)) {\n      return null;\n    }\n\n    // Check staleness\n    const fileStat = await stat(cachePath);\n    if (Date.now() - fileStat.mtime.getTime() > LIVE_PATCH_CACHE_MAX_AGE_MS) {\n      this.logger.debug('live_patch_cache_stale', { ageMs: Date.now() - fileStat.mtime.getTime() });\n      return null;\n    }\n\n    const raw = await readFile(cachePath, 'utf-8');\n    const parsed = JSON.parse(raw);\n\n    if (!parsed || !Array.isArray(parsed.data) || typeof parsed.tag !== 'string') {\n      return null;\n    }\n\n    return { data: parsed.data, tag: parsed.tag };\n  }\n\n  private async saveCachedLivePatches(result: { data: string[]; tag: string }): Promise<void> {\n    const cachePath = join(process.cwd(), LIVE_PATCH_CACHE_FILENAME);\n    await writeFile(cachePath, JSON.stringify({ data: result.data, tag: result.tag }), 'utf-8');\n  }\n\n  // ─── Session Debug Info ───────────────────────────────────────────────────\n\n  /**\n   * Extract session debug info from the authenticated browser page.\n   *\n   * Must be called AFTER authentication completes and the WhatsApp runtime is available.\n   * Returns the data needed for remote overlay requests (patch params + license validation body).\n   *\n   * Mirrors legacy `WAPI.getMe()._serialized` + session debug info collection.\n   */\n  async getSessionDebugInfo(): Promise<SessionDebugInfo> {\n    if (!this.page) {\n      throw new Error('Transport not initialized — cannot extract session debug info');\n    }\n\n    const info = await this.page.evaluate(\n      () => {\n        const runtime = globalThis as any;\n        const connectionHost = runtime.Store?.Conn?.me?._serialized;\n        const patchedHost = !connectionHost && typeof runtime.moi === 'function'\n          ? runtime.moi()\n          : '';\n\n        return {\n          waVersion: runtime.Debug?.VERSION ?? 'unknown',\n          hostNumber: connectionHost || (typeof patchedHost === 'string' ? patchedHost : ''),\n          pageUA: navigator.userAgent,\n          os: navigator.platform ?? 'unknown',\n        };\n      },\n      undefined,\n    );\n\n    const hostNumber = info.hostNumber ?? '';\n    const numHash = hostNumber\n      ? createHash('md5').update(hostNumber).digest('hex').slice(-5)\n      : undefined;\n\n    return {\n      WA_VERSION: info.waVersion,\n      WA_AUTOMATE_VERSION: '5.0.0',\n      hostNumber,\n      BROWSER_VERSION: info.pageUA,\n      PAGE_UA: info.pageUA,\n      OS: info.os,\n      NUM_HASH: numHash,\n    };\n  }\n}\n","import { HyperEmitter } from '@open-wa/hyperemitter';\nimport { createLogger, Logger } from '@open-wa/logger';\nimport type { IDriver, LightpandaOptions, BrowserProvisionOptions } from '@open-wa/driver-interface';\nimport { requireCapability, type CapabilitySubject } from '@open-wa/driver-interface';\nimport { OpenWAEventMap, STATE } from './events/eventMap';\nimport { PluginHost, loadPlugins } from './plugins/index';\nimport type { Plugin, PluginClient } from '@open-wa/plugin-sdk';\nimport {\n  SessionManager,\n  SessionStore,\n  type SessionReadinessSnapshot,\n  type SessionValidationStage,\n} from './sessionmanager/index';\nimport { Transport } from './transport/index';\nimport type {\n  LicenseKeyResolver,\n  PatchFetchConfig,\n  LicenseServerConfig,\n  RuntimeValidationFailureReason,\n} from './transport/index';\nimport { Effect } from 'effect';\nimport {\n  SessionScope,\n  runStartupGraph,\n  type SessionAdmissionShape,\n  type SessionFinalizerReason,\n  type ChatSandboxPolicy,\n  type ExecutionSandboxShape,\n  type SandboxCapabilityHandlers,\n  type RuntimeObservabilityShape,\n  type RuntimeCauseRecord,\n  makeInMemoryObservability,\n} from '@open-wa/runtime-core';\n\nexport interface CreateClientOptions {\n  sessionId?: string;\n  driver: IDriver;\n  deleteSessionDataOnLogout?: boolean;\n  killClientOnLogout?: boolean;\n  sessionDataPath?: string;\n\n  /**\n   * Plugins can be provided directly as Plugin objects,\n   * or loaded from config via plugin refs (npm names / paths).\n   */\n  plugins?: Plugin[];\n\n  /**\n   * Config-driven plugin loading: array of npm package names or file paths.\n   * These are dynamically imported at startup.\n   *\n   * @example ['@open-wa/integration-chatwoot', './my-local-plugin']\n   */\n  pluginRefs?: string[];\n\n  /**\n   * Plugin configuration keyed by plugin name.\n   * Each plugin gets its own config object, validated against its configSchema.\n   *\n   * @example { \"chatwoot\": { apiUrl: \"...\", token: \"...\" } }\n   */\n  pluginConfig?: Record<string, unknown>;\n\n  sessionStore?: SessionStore;\n  debug?: boolean;\n  waWebUrl?: string;\n  headless?: boolean;\n  qrTimeoutMs?: number;\n  authTimeoutMs?: number;\n  oorTimeoutMs?: number;\n  navigationTimeoutMs?: number;\n  executablePath?: string;\n  browser?: BrowserProvisionOptions;\n  watermark?: boolean | { text?: string; color?: string; background?: string; };\n  browserArgs?: string[];\n  allowDangerousBrowserArgs?: boolean;\n  userDataDir?: string;\n  /**\n   * When true, prevents auto-derivation of userDataDir from sessionId.\n   * The browser launches with an ephemeral temp profile discarded on exit.\n   * Useful for testing without leaving `_IGNORE_` directories behind.\n   * @default false\n   */\n  ephemeral?: boolean;\n  linkCode?: string;\n  qrMax?: number;\n  ignoreNuke?: boolean;\n  logConsole?: boolean;\n  logConsoleErrors?: boolean;\n  blockCrashLogs?: boolean;\n  blockAssets?: boolean;\n  licenseKey?: LicenseKeyResolver;\n  safeMode?: boolean;\n  lightpanda?: LightpandaOptions;\n\n  /**\n   * Configuration for remote patch fetching from cdn.openwa.dev.\n   * Controls caching and fallback between OpenWA patch sources.\n   */\n  patchConfig?: PatchFetchConfig;\n\n  /**\n   * Configuration for remote license validation via funcs.openwa.dev.\n   * Controls offline mode.\n   */\n  licenseConfig?: LicenseServerConfig;\n\n  /** Optional process-wide admission policy used to cap browser-session RAM. */\n  sessionAdmission?: SessionAdmissionShape;\n\n  /** Estimated RAM reservation for this browser session. Defaults to 512 MiB. */\n  estimatedMemoryMb?: number;\n\n  /** Execution adapter and policy for explicit per-chat user-code isolation. */\n  executionSandbox?: ExecutionSandboxShape;\n  sandboxPolicy?: ChatSandboxPolicy;\n  /** Extra parent-side capabilities that isolated chat code may request by name. */\n  sandboxCapabilities?: SandboxCapabilityHandlers;\n  observability?: RuntimeObservabilityShape;\n  /** Runtime-specific memory sampler. Its fiber is owned by the session Scope. */\n  memoryObservation?: (\n    observability: RuntimeObservabilityShape,\n    getBrowserProcessId: () => number | undefined,\n  ) => Effect.Effect<never, unknown>;\n}\n\nexport interface OpenWAClient {\n  readonly sessionId: string;\n  readonly events: HyperEmitter<OpenWAEventMap>;\n  readonly logger: Logger;\n  readonly session: SessionManager;\n  readonly plugins: PluginHost;\n  readonly config: Readonly<Pick<CreateClientOptions, 'deleteSessionDataOnLogout' | 'killClientOnLogout' | 'sessionDataPath' | 'userDataDir'>>;\n  readonly observability: RuntimeObservabilityShape;\n\n  registerFinalizationHook(hook: () => void | Promise<void>): () => void;\n  start(): Promise<void>;\n  stop(reason?: string): Promise<void>;\n  getState(): STATE;\n  getReadiness(): SessionReadinessSnapshot;\n  getTransport(): Transport;\n  screenshot(): Promise<Uint8Array | null>;\n  evaluateScript<T = unknown>(script: string): Promise<T | null>;\n  executeInChatSandbox<T = unknown>(chatId: string, source: string, input?: unknown): Promise<T>;\n  closeChatSandbox(chatId: string): Promise<void>;\n  getRuntimeMetrics(): Promise<Readonly<Record<string, number>>>;\n  getRuntimeCauses(): Promise<ReadonlyArray<RuntimeCauseRecord>>;\n}\n\nfunction hasCapabilitySubject(driver: IDriver): driver is IDriver & CapabilitySubject {\n  return 'capabilities' in driver;\n}\n\n/**\n * Create a PluginClient proxy backed by a transport-level ask() pattern.\n * This mirrors SocketClient's Proxy approach — any method call becomes\n * an `ask(methodName, args)` invocation.\n */\nfunction createPluginClientProxy(transport: Transport, logger: Logger): PluginClient {\n  const ask = async <T = unknown>(method: string, args?: unknown[] | Record<string, unknown>): Promise<T> => {\n    const page = transport.getPage();\n    if (!page || page.isClosed()) {\n      throw new Error(`Cannot call \"${method}\" — page is not available`);\n    }\n    // Delegate to the transport's evaluateScript which runs WAPI calls\n    const argsStr = JSON.stringify(args ?? []);\n    const result = await page.evaluateScript<T>(\n      `window.WAPI.${method}(...${argsStr})`\n    );\n    return result as T;\n  };\n\n  const listen = async (listener: string, callback: (data: unknown) => void): Promise<string> => {\n    logger.warn('plugin_listen_not_supported', {\n      listener,\n      reason: 'Direct listen is not supported on SDK-level PluginClient. Use event hooks instead.',\n    });\n    return 'noop';\n  };\n\n  // Base object with explicit convenience methods delegating to ask()\n  const base: Partial<PluginClient> = {\n    ask,\n    listen,\n    sendText: (to: string, content: string) => ask('sendText', [to, content]),\n    sendImage: (to: string, url: string, filename: string, caption?: string) => ask('sendImage', [to, url, filename, caption ?? '']),\n    sendFile: (to: string, base64: string, filename: string, caption?: string) => ask('sendFile', [to, base64, filename, caption ?? '']),\n    sendLocation: (to: string, lat: string, lng: string, text?: string) => ask('sendLocation', [to, lat, lng, text ?? '']),\n    sendLinkWithAutoPreview: (to: string, url: string, text: string) => ask('sendLinkWithAutoPreview', [to, url, text]),\n    reply: (to: string, content: string, quotedMsgId: string) => ask('reply', [to, content, quotedMsgId]),\n    decryptMedia: (message: unknown) => ask('decryptMedia', [message]),\n    getHostNumber: () => ask('getHostNumber'),\n    getContact: (contactId: string) => ask('getContact', [contactId]),\n    getAllContacts: () => ask('getAllContacts'),\n    getAllChats: () => ask('getAllChats'),\n    sendSeen: (chatId: string) => ask('sendSeen', [chatId]),\n  };\n\n  // Proxy: any uncovered method call becomes ask(methodName, args)\n  return new Proxy(base as PluginClient, {\n    get(target, prop: string) {\n      if (prop in target) return target[prop as keyof PluginClient];\n      if (prop === 'then') return undefined; // prevent Promise unwrapping\n      return (...args: unknown[]) => ask(prop, args);\n    },\n  });\n}\n\nexport async function createClient(options: CreateClientOptions): Promise<OpenWAClient> {\n  const sessionId = options.sessionId ?? 'session';\n\n  const logger = createLogger({\n    component: 'core',\n    sessionId,\n  });\n  const observability = options.observability ?? makeInMemoryObservability();\n\n  const events = new HyperEmitter<OpenWAEventMap>({\n    delimiter: '.',\n    captureRejections: true,\n    onError: (err) => logger.error('event_error', { error: err }),\n    logger,\n    debug: options.debug ?? false,\n  });\n\n  // ── userDataDir Resolution ────────────────────────────────────────────────\n  // Matches v4 behavior: auto-derive _IGNORE_{sessionId} unless explicitly\n  // set or ephemeral mode is enabled.\n  let resolvedUserDataDir: string | undefined;\n\n  if (options.ephemeral) {\n    // Ephemeral mode: intentionally use no persistent profile\n    resolvedUserDataDir = undefined;\n    logger.info('user_data_dir_resolved', {\n      mode: 'ephemeral',\n      userDataDir: null,\n      detail: 'Ephemeral mode enabled — browser will use a disposable temp profile with no session persistence',\n    });\n  } else if (options.userDataDir) {\n    // Explicitly provided by caller\n    resolvedUserDataDir = options.userDataDir;\n    logger.info('user_data_dir_resolved', {\n      mode: 'explicit',\n      userDataDir: resolvedUserDataDir,\n      detail: 'Using explicitly configured userDataDir for session persistence',\n    });\n  } else {\n    // Auto-derive from sessionId (v4 parity)\n    const basePath = options.sessionDataPath || '.';\n    resolvedUserDataDir = `${basePath}/_IGNORE_${sessionId}`;\n    logger.info('user_data_dir_resolved', {\n      mode: 'derived',\n      userDataDir: resolvedUserDataDir,\n      sessionId,\n      detail: `Auto-derived userDataDir from sessionId for session persistence (set ephemeral=true to disable)`,\n    });\n  }\n\n  const session = new SessionManager({\n    sessionId,\n    events,\n    logger,\n    store: options.sessionStore,\n  });\n\n  const transport = new Transport({\n    driver: options.driver,\n    events,\n    logger,\n    waWebUrl: options.waWebUrl,\n    headless: options.headless,\n    qrTimeoutMs: options.qrTimeoutMs,\n    authTimeoutMs: options.authTimeoutMs,\n    oorTimeoutMs: options.oorTimeoutMs,\n    navigationTimeoutMs: options.navigationTimeoutMs,\n    executablePath: options.executablePath,\n    browser: options.browser,\n    browserArgs: options.browserArgs,\n    allowDangerousBrowserArgs: options.allowDangerousBrowserArgs,\n    userDataDir: resolvedUserDataDir,\n    linkCode: options.linkCode,\n    qrMax: options.qrMax,\n    ignoreNuke: options.ignoreNuke,\n    logConsole: options.logConsole,\n    logConsoleErrors: options.logConsoleErrors,\n    blockCrashLogs: options.blockCrashLogs,\n    blockAssets: options.blockAssets,\n    safeMode: options.safeMode,\n    watermark: options.watermark,\n    lightpanda: options.lightpanda,\n    patchConfig: options.patchConfig,\n    licenseConfig: options.licenseConfig,\n  });\n\n  const pluginHost = new PluginHost(events, logger);\n  const resourceScope = await SessionScope.make({\n    observability,\n    metricAttributes: { session: sessionId },\n  });\n  await resourceScope.addFinalizer('transport.close', () => transport.close());\n  await resourceScope.addFinalizer('plugins.dispose', () => pluginHost.dispose());\n  if (options.executionSandbox) {\n    await resourceScope.addFinalizer(\n      'chat-sandbox.close',\n      () => Effect.runPromise(options.executionSandbox!.close),\n    );\n  }\n  if (options.memoryObservation) {\n    await resourceScope.fork(options.memoryObservation(\n      observability,\n      () => transport.getBrowser()?.processId?.(),\n    ).pipe(\n      Effect.catchCause(() => Effect.never),\n    ));\n  }\n\n  // Create the PluginClient proxy\n  const pluginClient = createPluginClientProxy(transport, logger);\n  const sandboxCapabilityHandlers: SandboxCapabilityHandlers = {\n    sendText: (...args) => pluginClient.sendText(...args as Parameters<PluginClient['sendText']>),\n    sendImage: (...args) => pluginClient.sendImage(...args as Parameters<PluginClient['sendImage']>),\n    sendFile: (...args) => pluginClient.sendFile(...args as Parameters<PluginClient['sendFile']>),\n    sendLocation: (...args) => pluginClient.sendLocation(...args as Parameters<PluginClient['sendLocation']>),\n    sendLinkWithAutoPreview: (...args) => pluginClient.sendLinkWithAutoPreview(\n      ...args as Parameters<PluginClient['sendLinkWithAutoPreview']>\n    ),\n    reply: (...args) => pluginClient.reply(...args as Parameters<PluginClient['reply']>),\n    sendSeen: (...args) => pluginClient.sendSeen(...args as Parameters<PluginClient['sendSeen']>),\n    getHostNumber: (...args) => pluginClient.getHostNumber(...args as Parameters<PluginClient['getHostNumber']>),\n    getContact: (...args) => pluginClient.getContact(...args as Parameters<PluginClient['getContact']>),\n    getAllContacts: (...args) => pluginClient.getAllContacts(...args as Parameters<PluginClient['getAllContacts']>),\n    getAllChats: (...args) => pluginClient.getAllChats(...args as Parameters<PluginClient['getAllChats']>),\n    ...options.sandboxCapabilities,\n  };\n\n  // Register directly-provided plugins\n  try {\n    if (options.plugins) {\n      for (const plugin of options.plugins) {\n        await pluginHost.register(plugin, {\n          sessionId,\n          client: pluginClient,\n          pluginConfig: options.pluginConfig,\n        });\n      }\n    }\n\n    // Load and register config-referenced plugins\n    if (options.pluginRefs?.length) {\n      const loaded = await loadPlugins(options.pluginRefs, logger);\n      for (const { plugin } of loaded) {\n        await pluginHost.register(plugin, {\n          sessionId,\n          client: pluginClient,\n          pluginConfig: options.pluginConfig,\n        });\n      }\n    }\n  } catch (error) {\n    await resourceScope.close('plugin-failure');\n    throw error;\n  }\n\n  const finalizationHooks = new Set<() => void | Promise<void>>();\n\n  const registerFinalizationHook = (hook: () => void | Promise<void>) => {\n    finalizationHooks.add(hook);\n    return () => {\n      finalizationHooks.delete(hook);\n    };\n  };\n\n  const runFinalizationHooks = async () => {\n    for (const hook of [...finalizationHooks]) {\n      await hook();\n    }\n  };\n\n  const getReadinessSnapshot = () => session.getReadinessSnapshot(transport.getOperationalReadinessSnapshot());\n\n  const client: OpenWAClient = {\n    sessionId,\n    events,\n    logger,\n    session,\n    plugins: pluginHost,\n    observability,\n    config: {\n      deleteSessionDataOnLogout: options.deleteSessionDataOnLogout,\n      killClientOnLogout: options.killClientOnLogout,\n      sessionDataPath: options.sessionDataPath,\n      userDataDir: resolvedUserDataDir,\n    },\n    registerFinalizationHook,\n\n    async start() {\n      try {\n      events.emit('core.starting', { config: options });\n\n      if (options.sessionAdmission) {\n        const memoryMb = Math.max(1, Math.round(options.estimatedMemoryMb ?? 512));\n        const lease = await Effect.runPromise(options.sessionAdmission.acquire(memoryMb));\n        await resourceScope.addFinalizer(\n          'session-admission.release',\n          () => Effect.runPromise(lease.release),\n        );\n      }\n\n      session.resetRuntime();\n      await session.setState('STARTING');\n\n      const markReadinessFailure = (scope: string, detail: string) => {\n        if (scope.includes('license')) {\n          session.updateReadiness('licenseLifecycle', 'failed', detail);\n          return;\n        }\n\n        if (scope.includes('patch')) {\n          session.updateReadiness('patchLifecycle', 'failed', detail);\n          return;\n        }\n\n        if (scope.includes('finalization')) {\n          session.setFinalization('failed', detail);\n          return;\n        }\n\n        if (scope.includes('auth')) {\n          session.setFinalization('failed', detail);\n          return;\n        }\n\n        session.updateReadiness('runtimeUsable', 'failed', detail);\n      };\n\n      const emitFatalBootstrapError = async (scope: string, error: unknown) => {\n        const normalizedError = error instanceof Error ? error : new Error(String(error));\n        markReadinessFailure(scope, normalizedError.message);\n        events.emit('error', {\n          scope,\n          error: normalizedError,\n          fatal: true,\n        });\n        Effect.runSync(observability.recordCause(scope, normalizedError));\n        await session.setState('DISCONNECTED', scope);\n        throw normalizedError;\n      };\n\n      const emitFailedFinalization = (detail: string) => {\n        session.setFinalization('failed', detail);\n        events.emit('launch.client.finalize.after', {\n          correlationId: 'bootstrap-client-finalize',\n          ts: Date.now(),\n          step: 'client_finalize',\n          details: {\n            state: session.getState(),\n            success: false,\n            outcome: 'failed',\n            detail,\n          },\n        });\n      };\n\n      const runValidationStage = async (\n        stage: SessionValidationStage,\n        options: {\n          correlationId: string;\n          allowRepair: boolean;\n          invalidScope: string;\n          deferFailure?: (result: Awaited<ReturnType<Transport['validateRuntimeUsability']>>) => boolean;\n        }\n      ) => {\n        const validateAttempt = async (attempt: number, repaired: boolean) => {\n          events.emit('launch.session.validityCheck.before', {\n            correlationId: options.correlationId,\n            attempt,\n            ts: Date.now(),\n            step: 'session_validity_check',\n            details: { phase: stage },\n          });\n\n          const result = stage === 'post_injection'\n            ? await transport.validateRuntimeCapabilityOnly(stage)\n            : await transport.validateRuntimeUsability(stage);\n\n          session.recordValidation({\n            stage,\n            attempt,\n            usable: result.usable,\n            repairable: result.repairable,\n            repaired,\n            checkedAt: Date.now(),\n            failureReason: result.failureReason,\n            capability: {\n              hasRuntime: result.hasRuntime,\n              hasStoreMsg: result.hasStoreMsg,\n              sessionLoaded: result.sessionLoaded,\n            },\n          });\n\n          events.emit('launch.session.validityCheck.after', {\n            correlationId: options.correlationId,\n            attempt,\n            ts: Date.now(),\n            step: 'session_validity_check',\n            details: {\n              phase: stage,\n              valid: result.usable,\n              usable: result.usable,\n              hasRuntime: result.hasRuntime,\n              hasStore: result.hasStoreMsg,\n              hasMsg: result.hasStoreMsg,\n              sessionLoaded: result.sessionLoaded,\n              bridgeReady: result.bridgeReady,\n              requiredMethods: result.requiredMethods,\n              missingMethods: result.missingMethods,\n              repairable: result.repairable,\n              repaired,\n              failureReason: result.failureReason,\n            },\n          });\n\n          return result;\n        };\n\n        const firstResult = await validateAttempt(1, false);\n        if (firstResult.usable) {\n          return firstResult;\n        }\n\n        if (options.deferFailure?.(firstResult)) {\n          return firstResult;\n        }\n\n        if (!options.allowRepair || !firstResult.repairable) {\n          return emitFatalBootstrapError(\n            options.invalidScope,\n            new Error(`Session validation failed during ${stage}: ${firstResult.failureReason ?? 'unknown_failure'}`)\n          );\n        }\n\n        const repairReason: RuntimeValidationFailureReason = firstResult.failureReason ?? 'runtime_missing';\n\n        events.emit('launch.session.invalid.retry', {\n          correlationId: options.correlationId,\n          attempt: 2,\n          ts: Date.now(),\n          step: 'session_invalid_retry',\n          details: { reason: repairReason },\n        });\n        events.emit('session.stale.detected', {\n          correlationId: options.correlationId,\n          attempt: 1,\n          ts: Date.now(),\n          step: 'session_stale_detected',\n          details: { reason: repairReason },\n        });\n        events.emit('session.reinject.detected', {\n          correlationId: options.correlationId,\n          attempt: 1,\n          ts: Date.now(),\n          step: 'session_reinject_detected',\n          details: { reason: repairReason },\n        });\n        events.emit('session.reinject.before', {\n          correlationId: options.correlationId,\n          attempt: 2,\n          ts: Date.now(),\n          step: 'session_reinject',\n          details: { reason: repairReason },\n        });\n\n        try {\n          await transport.repairRuntimeIntegrity(repairReason);\n        } catch (error) {\n          session.recordRepair({\n            stage,\n            attempt: 2,\n            reason: repairReason,\n            success: false,\n            at: Date.now(),\n          });\n          events.emit('session.reinject.after', {\n            correlationId: options.correlationId,\n            attempt: 2,\n            ts: Date.now(),\n            step: 'session_reinject',\n            details: { success: false },\n          });\n          return emitFatalBootstrapError(options.invalidScope, error);\n        }\n\n        const repairedResult = await validateAttempt(2, true);\n        session.recordRepair({\n          stage,\n          attempt: 2,\n          reason: repairReason,\n          success: repairedResult.usable,\n          at: Date.now(),\n        });\n\n        events.emit('session.reinject.after', {\n          correlationId: options.correlationId,\n          attempt: 2,\n          ts: Date.now(),\n          step: 'session_reinject',\n          details: { success: repairedResult.usable },\n        });\n\n        if (!repairedResult.usable) {\n          return emitFatalBootstrapError(\n            options.invalidScope,\n            new Error(`Session validation failed after repair during ${stage}: ${repairedResult.failureReason ?? repairReason}`)\n          );\n        }\n\n        return repairedResult;\n      };\n\n      const shouldDeferPreAuthRuntimeIntegrity = (\n        result: Awaited<ReturnType<Transport['validateRuntimeUsability']>>\n      ) => result.failureReason === 'required_method_missing' && !result.sessionLoaded;\n\n      const startupGraph = await Effect.runPromise(\n        runStartupGraph([\n          {\n            id: 'transport',\n            run: () => Effect.tryPromise({\n              try: async () => {\n                await transport.initialize();\n                await transport.navigate();\n                return true;\n              },\n              catch: (error) => error instanceof Error ? error : new Error(String(error)),\n            }),\n          },\n          {\n            id: 'patch-preload',\n            run: () => Effect.tryPromise({\n              try: () => transport.preloadLivePatchArtifacts(),\n              catch: (error) => error instanceof Error ? error : new Error(String(error)),\n            }),\n          },\n          {\n            id: 'license-preflight',\n            run: () => Effect.tryPromise({\n              try: () => transport.preloadLicenseArtifact({ sessionId, licenseKey: options.licenseKey }),\n              catch: (error) => error instanceof Error ? error : new Error(String(error)),\n            }),\n          },\n        ], {\n          concurrency: 3,\n          onPhase: ({ id, durationMs }) => {\n            Effect.runSync(observability.gauge('startup_phase_ms', durationMs, { phase: id }));\n          },\n          onComplete: ({ criticalPathMs }) => {\n            Effect.runSync(observability.gauge('startup_critical_path_ms', criticalPathMs));\n          },\n        }),\n      );\n      logger.info('startup_graph_complete', {\n        criticalPathMs: startupGraph.criticalPathMs,\n        phases: startupGraph.phases.map(({ id, durationMs }) => ({ id, durationMs })),\n      });\n\n      const earlyLivePatchPreload = startupGraph.values.get('patch-preload') as\n        Awaited<ReturnType<Transport['preloadLivePatchArtifacts']>>;\n      const earlyLicensePreload = startupGraph.values.get('license-preflight') as\n        Awaited<ReturnType<Transport['preloadLicenseArtifact']>>;\n\n      await session.setState('AUTHENTICATING');\n\n      try {\n        await transport.injectWapi();\n      } catch (error) {\n        return emitFatalBootstrapError('bootstrap.injection', error);\n      }\n\n      const attemptingReauth = await transport.detectAttemptingReauth().catch(() => false);\n      logger.info('launch_auth_mode_detected', {\n        attemptingReauth,\n      });\n\n      const runtimeCapability = await runValidationStage('post_injection', {\n        correlationId: 'bootstrap-runtime-validation',\n        allowRepair: true,\n        invalidScope: 'bootstrap.injection.capability',\n        deferFailure: shouldDeferPreAuthRuntimeIntegrity,\n      });\n\n      const deferredPreAuthRuntimeIntegrity = !runtimeCapability.usable;\n\n      if (deferredPreAuthRuntimeIntegrity) {\n        session.updateReadiness(\n          'runtimeUsable',\n          'pending',\n          'Pre-auth runtime integrity is incomplete before authentication; strict runtime validation is deferred until the authenticated runtime settles'\n        );\n\n        logger.warn('runtime_activation_deferred', {\n          validationPhase: 'pre_auth_post_injection',\n          deferredReason: runtimeCapability.failureReason,\n          sessionLoaded: runtimeCapability.sessionLoaded,\n          missingMethods: runtimeCapability.missingMethods,\n          requiredMethods: runtimeCapability.requiredMethods,\n          nextGate: 'post_auth_post_injection',\n        });\n      } else {\n        session.updateReadiness(\n          'runtimeUsable',\n          'satisfied',\n          'Runtime injection and post-injection validation proved usable capability'\n        );\n\n        logger.info('runtime_activation_ready', {\n          ...runtimeCapability,\n          validationPhase: 'pre_auth_post_injection',\n        });\n      }\n\n      logger.info('bootstrap_sequence_started', {\n        sessionId,\n        usePatch: !!options.patchConfig,\n      });\n\n      const authResult = await transport.waitForAuthentication({ attemptingReauth });\n      if (authResult.outcome === 'qr_timeout') {\n        emitFailedFinalization('QR scan took too long. Increase qrTimeout or set qrTimeout=0 to wait forever.');\n        return emitFatalBootstrapError(\n          'bootstrap.auth.qr_timeout',\n          new Error('QR scan took too long. Increase qrTimeout or set qrTimeout=0 to wait forever.')\n        );\n      }\n\n      if (authResult.outcome === 'auth_timeout') {\n        emitFailedFinalization('Authentication timed out. Increase authTimeout or set authTimeout=0 to wait forever.');\n        return emitFatalBootstrapError(\n          'bootstrap.auth.timeout',\n          new Error('Authentication timed out. Increase authTimeout or set authTimeout=0 to wait forever.')\n        );\n      }\n\n      if (authResult.outcome === 'phone_out_of_reach') {\n        emitFailedFinalization('Authentication timed out because the host phone is out of reach. Open WhatsApp on the phone and try again.');\n        return emitFatalBootstrapError(\n          'bootstrap.auth.phone_out_of_reach',\n          new Error('Authentication timed out because the host phone is out of reach. Open WhatsApp on the phone and try again.')\n        );\n      }\n\n      if (authResult.outcome === 'invalid_session') {\n        emitFailedFinalization('Session data most likely expired due to manual host account logout. Re-authenticate this session or set ignoreNuke to bypass the explicit invalid-session classification.');\n        return emitFatalBootstrapError(\n          'bootstrap.auth.invalid_session',\n          new Error('Session data most likely expired due to manual host account logout. Re-authenticate this session or set ignoreNuke to bypass the explicit invalid-session classification.')\n        );\n      }\n\n      if (authResult.outcome === 'qr_max') {\n        emitFailedFinalization('Authentication aborted because the configured QR/link-code limit was reached before login completed. Increase qrMax or remove it to keep waiting.');\n        return emitFatalBootstrapError(\n          'bootstrap.auth.qr_max',\n          new Error('Authentication aborted because the configured QR/link-code limit was reached before login completed. Increase qrMax or remove it to keep waiting.')\n        );\n      }\n\n      const postAuthRuntime = await transport.reconcilePostAuthRuntime({\n        freshAuth: !attemptingReauth,\n      });\n\n      if (!postAuthRuntime.ripeSessionLoaded) {\n        emitFailedFinalization('Authenticated runtime did not reach a ripe session before post-auth reinjection/gating completed.');\n        return emitFatalBootstrapError(\n          'bootstrap.auth.ripe_session_timeout',\n          new Error('Authenticated runtime did not reach a ripe session before post-auth reinjection/gating completed.')\n        );\n      }\n\n      logger.info('post_auth_runtime_reconciled', {\n        path: postAuthRuntime.path,\n        reinjected: postAuthRuntime.reinjected,\n        hasRuntime: postAuthRuntime.hasRuntime,\n        hasStoreMsg: postAuthRuntime.hasStoreMsg,\n        sessionLoaded: postAuthRuntime.sessionLoaded,\n        ripeSessionLoaded: postAuthRuntime.ripeSessionLoaded,\n      });\n\n      // Bridge bindings registration is deferred to AFTER live patches complete.\n      // The replacement observer (OpenWA_RuntimeReplacementDetected) must not fire\n      // before live patches are applied, and ensureRuntimeBridge() must not wire\n      // onStateChanged to an unpatched WAPI.\n      // See Phase 1 registration below, after live_patch_sequence_complete.\n\n      // Capability-only validation: verify runtime/store/session are alive but\n      // do NOT check bridge integrity — the bridge is not yet wired to WAPI.\n      // Using validateRuntimeCapabilityOnly avoids probeBrokenMethodIntegrity()\n      // which would prematurely call ensureRuntimeBridge() and wire unpatched WAPI.\n      const postAuthRuntimeCapability = await transport.validateRuntimeCapabilityOnly('post_injection');\n\n      session.recordValidation({\n        stage: 'post_injection',\n        attempt: 1,\n        usable: postAuthRuntimeCapability.usable,\n        repairable: postAuthRuntimeCapability.repairable,\n        repaired: false,\n        checkedAt: Date.now(),\n        failureReason: postAuthRuntimeCapability.failureReason,\n        capability: {\n          hasRuntime: postAuthRuntimeCapability.hasRuntime,\n          hasStoreMsg: postAuthRuntimeCapability.hasStoreMsg,\n          sessionLoaded: postAuthRuntimeCapability.sessionLoaded,\n        },\n      });\n\n      if (!postAuthRuntimeCapability.usable) {\n        // Attempt repair: reinject the runtime\n        try {\n          await transport.repairRuntimeIntegrity(postAuthRuntimeCapability.failureReason ?? 'runtime_missing');\n        } catch (repairError) {\n          return emitFatalBootstrapError('bootstrap.auth.runtime_validation', repairError);\n        }\n\n        // Re-validate after repair (capability-only — bridge still not wired)\n        const revalidated = await transport.validateRuntimeCapabilityOnly('post_injection');\n        session.recordValidation({\n          stage: 'post_injection',\n          attempt: 2,\n          usable: revalidated.usable,\n          repairable: revalidated.repairable,\n          repaired: true,\n          checkedAt: Date.now(),\n          failureReason: revalidated.failureReason,\n          capability: {\n            hasRuntime: revalidated.hasRuntime,\n            hasStoreMsg: revalidated.hasStoreMsg,\n            sessionLoaded: revalidated.sessionLoaded,\n          },\n        });\n\n        if (!revalidated.usable) {\n          return emitFatalBootstrapError(\n            'bootstrap.auth.runtime_validation',\n            new Error(`Post-injection capability validation failed after repair: ${revalidated.failureReason ?? 'unknown_failure'}`)\n          );\n        }\n      }\n\n      // ── Store Settle Gate (Option C) ──────────────\n      // Wait for window.Store.Msg to settle before marking readiness satisfied.\n      // This matches legacy v4 robustness and prevents store_missing failures at post_patch.\n      let storeMsgAvailable = postAuthRuntimeCapability.hasStoreMsg;\n      if (!storeMsgAvailable) {\n        logger.info('store_settle_gate_started', {\n          timeoutMs: 15000,\n          reason: 'Store.Msg missing after post-auth validation',\n        });\n        storeMsgAvailable = await transport.waitForStoreMsg(15000);\n      }\n\n      if (!storeMsgAvailable) {\n        const storeKeys = await transport.getStoreKeys().catch(() => []);\n        logger.error('store_settle_gate_timeout', {\n          availableKeys: storeKeys,\n          message: 'Timed out waiting for Store.Msg to settle.',\n        });\n        return emitFatalBootstrapError(\n          'bootstrap.store_settle',\n          new Error(`Store.Msg not available after 15s store-settle window. Available Store keys: ${storeKeys.join(', ')}`)\n        );\n      } else {\n        logger.info('store_settle_gate_satisfied');\n      }\n\n      session.updateReadiness(\n        'runtimeUsable',\n        'satisfied',\n        deferredPreAuthRuntimeIntegrity\n          ? 'Authenticated runtime validation proved usable capability after the deferred pre-auth integrity check and store-settle gate'\n          : 'Authenticated runtime validation proved usable capability after runtime bridge registration and store-settle gate'\n      );\n\n      logger.info('runtime_activation_ready', {\n        ...postAuthRuntimeCapability,\n        validationPhase: 'post_auth_post_injection',\n        deferredFromPreAuth: deferredPreAuthRuntimeIntegrity,\n      });\n\n      // ── Session Info Extraction (post-auth, pre-overlay) ──────────────\n      // Extract debug info from the authenticated page for remote overlay requests.\n      // This mirrors the legacy sequence: auth → session info → patch → integrity → license.\n      let sessionDebugInfo;\n      try {\n        sessionDebugInfo = await transport.getSessionDebugInfo();\n        logger.info('session_debug_info_extracted', {\n          hostNumber: sessionDebugInfo.hostNumber ? '***' + sessionDebugInfo.hostNumber.slice(-4) : 'unknown',\n          waVersion: sessionDebugInfo.WA_VERSION,\n        });\n      } catch (debugInfoError) {\n        const dbgMsg = debugInfoError instanceof Error ? debugInfoError.message : String(debugInfoError);\n        logger.warn('session_debug_info_extraction_failed', { error: dbgMsg });\n        // Continue without debug info — preload methods will fall back gracefully\n      }\n\n      const livePatchPreloadPromise = Promise.resolve(earlyLivePatchPreload);\n      const licensePreloadPromise = sessionDebugInfo?.hostNumber && earlyLicensePreload.artifact\n        ? transport.preloadLicenseArtifact({\n            sessionId,\n            licenseKey: earlyLicensePreload.artifact.key,\n            sessionInfo: sessionDebugInfo,\n          })\n        : Promise.resolve(earlyLicensePreload);\n\n      const livePatchPreload = await livePatchPreloadPromise.catch((error) =>\n        emitFatalBootstrapError('bootstrap.live_patch.preload', error)\n      );\n      logger.info('live_patch_artifacts_preloaded', {\n        outcome: livePatchPreload.outcome,\n        source: livePatchPreload.source,\n        tag: livePatchPreload.tag,\n        artifactCount: livePatchPreload.artifacts.length,\n      });\n\n      const livePatchApply = await transport.applyLivePatchArtifacts(livePatchPreload).catch((error) =>\n        emitFatalBootstrapError('bootstrap.live_patch.apply', error)\n      );\n\n      if (livePatchApply.blockingFailure) {\n        const blockingPatch = livePatchApply.results.find((result) => result.required && result.outcome !== 'applied');\n        await emitFatalBootstrapError(\n          'bootstrap.live_patch.lifecycle',\n          new Error(blockingPatch?.detail ?? 'Required live patch lifecycle did not complete successfully')\n        );\n      }\n\n      /**\n       * Phase 1 (post-live-patch): Register Node-side persistent bindings.\n       * This MUST happen after live patches are applied because the replacement\n       * observer (OpenWA_RuntimeReplacementDetected) would trigger recovery\n       * that overwrites the live-patched WAPI.\n       *\n       * NOTE: This only registers Node-side bindings (exposeFunction etc.).\n       * The actual bridge wiring (ensureRuntimeBridge → onStateChanged, etc.)\n       * is deferred to Phase 2 (activateRuntimeEventBridge) which runs AFTER\n       * init patch, matching the v4 order: patches → license → init → loaded.\n       */\n      try {\n        await transport.registerRuntimeEventBridgeBindings();\n      } catch (error) {\n        return emitFatalBootstrapError('bootstrap.runtime_bridge_registration', error);\n      }\n\n      // ── Post-patch capability validation ──────────────\n      // Check runtime/store/session capability ONLY — do NOT wire the bridge yet.\n      // In v4, event listeners (onStateChanged etc.) are wired in client.loaded()\n      // which runs AFTER init patch. The full bridge wiring happens at Phase 2\n      // (activateRuntimeEventBridge) below, after init patch has been applied.\n      // Using validateRuntimeCapabilityOnly prevents ensureRuntimeBridge() from\n      // prematurely calling onStateChanged before Store.State is ready.\n      const postPatchCapability = await transport.validateRuntimeCapabilityOnly('post_patch');\n\n      session.recordValidation({\n        stage: 'post_patch',\n        attempt: 1,\n        usable: postPatchCapability.usable,\n        repairable: postPatchCapability.repairable,\n        repaired: false,\n        checkedAt: Date.now(),\n        failureReason: postPatchCapability.failureReason,\n        capability: {\n          hasRuntime: postPatchCapability.hasRuntime,\n          hasStoreMsg: postPatchCapability.hasStoreMsg,\n          sessionLoaded: postPatchCapability.sessionLoaded,\n        },\n      });\n\n      if (!postPatchCapability.usable) {\n        return emitFatalBootstrapError(\n          'bootstrap.patch.integrity',\n          new Error(`Post-patch capability validation failed: ${postPatchCapability.failureReason ?? 'unknown_failure'}`)\n        );\n      }\n\n      logger.info('post_patch_runtime_validated', {\n        ...postPatchCapability,\n        validationPhase: 'post_patch_pre_license',\n      });\n\n      events.emit('launch.patch.integrity.after', {\n        correlationId: 'bootstrap-post-patch-integrity',\n        ts: Date.now(),\n        step: 'patch_integrity',\n        details: {\n          phase: 'post_patch',\n          valid: postPatchCapability.usable,\n          usable: postPatchCapability.usable,\n          failureReason: postPatchCapability.failureReason,\n        },\n      });\n\n      let licensePreload = await licensePreloadPromise.catch((error) =>\n        emitFatalBootstrapError('bootstrap.license.preload', error)\n      );\n      if (licensePreload.status === 'metadata_only' && !sessionDebugInfo?.hostNumber && licensePreload.artifact) {\n        try {\n          const patchedSessionInfo = await transport.getSessionDebugInfo();\n          if (patchedSessionInfo.hostNumber) {\n            logger.info('license_host_recovered_after_patch', {\n              hostNumber: '***' + patchedSessionInfo.hostNumber.slice(-4),\n            });\n            licensePreload = await transport.preloadLicenseArtifact({\n              sessionId,\n              licenseKey: licensePreload.artifact.key,\n              sessionInfo: patchedSessionInfo,\n            });\n          }\n        } catch (error) {\n          logger.warn('license_host_recovery_after_patch_failed', {\n            error: error instanceof Error ? error.message : String(error),\n          });\n        }\n      }\n      const licenseCheck = await transport.checkLicenseArtifact(licensePreload).catch((error) =>\n        emitFatalBootstrapError('bootstrap.license.check', error)\n      );\n\n      if (licenseCheck.status === 'missing') {\n        session.updateReadiness(\n          'licenseLifecycle',\n          'non_blocking',\n          licenseCheck.detail ?? 'License metadata lifecycle classified as explicitly non-blocking'\n        );\n        logger.info('license_lifecycle_complete', {\n          status: licenseCheck.status,\n          detail: licenseCheck.detail,\n          readinessImpact: 'allow_ready',\n        });\n      } else if (licenseCheck.status === 'invalid' || licenseCheck.status === 'expired' || licenseCheck.blockingFailure) {\n        await emitFatalBootstrapError(\n          'bootstrap.license.lifecycle',\n          new Error(licenseCheck.detail ?? `License lifecycle blocked readiness with status: ${licenseCheck.status}`)\n        );\n      } else {\n        const licenseApply = await transport.applyLicenseArtifact(licenseCheck).catch((error) =>\n          emitFatalBootstrapError('bootstrap.license.apply', error)\n        );\n\n        if (licenseApply.blockingFailure || !licenseApply.applied) {\n          await emitFatalBootstrapError(\n            'bootstrap.license.apply',\n            new Error(licenseApply.detail ?? 'License lifecycle did not complete successfully')\n          );\n        }\n\n        const readinessState = licenseApply.status === 'valid' ? 'satisfied' : 'non_blocking';\n        const readinessDetail = licenseApply.status === 'valid'\n          ? licenseApply.detail ?? 'License lifecycle completed with a server-confirmed unlock'\n          : licenseApply.detail ?? 'License lifecycle completed with metadata-only fallback; capability was not server-confirmed';\n\n        session.updateReadiness(\n          'licenseLifecycle',\n          readinessState,\n          readinessDetail\n        );\n\n        logger.info('license_lifecycle_complete', {\n          status: licenseApply.status,\n          applied: licenseApply.applied,\n          keyType: licenseApply.keyType,\n          readinessImpact: readinessState === 'satisfied' ? 'satisfy_requirement' : 'allow_ready_without_server_unlock',\n        });\n      }\n\n      const initPatchApply = await transport.applyDeferredInitPatchArtifact().catch((error) =>\n        emitFatalBootstrapError('bootstrap.patch.init', error)\n      );\n\n      if (initPatchApply.blockingFailure) {\n        const blockingInitPatch = initPatchApply.results.find((result) => result.required && result.outcome !== 'applied');\n        await emitFatalBootstrapError(\n          'bootstrap.patch.lifecycle',\n          new Error(blockingInitPatch?.detail ?? 'Deferred init patch did not complete successfully')\n        );\n      }\n\n      // ── Phase 2: Activate runtime event bridge (post-init-patch) ──────────────\n      // Wire listeners to WAPI methods (onStateChanged, onAnyMessage, etc.).\n      // This is the FIRST bridge wiring point — post_patch validation above only\n      // checks capability, not bridge integrity. This matches the v4 order where\n      // event listeners are wired in client.loaded() AFTER init patch.\n      try {\n        await transport.activateRuntimeEventBridge();\n      } catch (error) {\n        return emitFatalBootstrapError('bootstrap.runtime_bridge_activation', error);\n      }\n\n      const combinedPatchResults = [...livePatchApply.results, ...initPatchApply.results];\n      const combinedPatchApplied = [...livePatchApply.applied, ...initPatchApply.applied];\n      const combinedPatchOutcome = livePatchApply.outcome === 'failed' || initPatchApply.outcome === 'failed'\n        ? 'failed'\n        : combinedPatchApplied.length > 0\n          ? 'applied'\n          : 'skipped';\n\n      session.updateReadiness(\n        'patchLifecycle',\n        combinedPatchOutcome === 'applied' ? 'satisfied' : 'non_blocking',\n        combinedPatchOutcome === 'applied'\n          ? 'Patch lifecycle completed successfully, including deferred init patch finalization'\n          : `Patch lifecycle completed with non-blocking outcome: ${combinedPatchOutcome}`\n      );\n\n      logger.info('patch_lifecycle_complete', {\n        outcome: combinedPatchOutcome,\n        applied: combinedPatchApplied,\n        results: combinedPatchResults,\n      });\n\n      events.emit('launch.client.finalize.before', {\n        correlationId: 'bootstrap-client-finalize',\n        ts: Date.now(),\n        step: 'client_finalize',\n        details: {\n          validationStage: 'loaded_equivalent',\n          patchOutcome: combinedPatchOutcome,\n          licenseStatus: licenseCheck.status,\n        },\n      });\n\n      session.setFinalization('pending', 'post-overlay validation in progress');\n\n      try {\n        const finalValidation = await runValidationStage('post_overlay', {\n          correlationId: 'bootstrap-post-overlay-validation',\n          allowRepair: true,\n          invalidScope: 'bootstrap.finalization.validation',\n        });\n\n        logger.info('session_finalization_validated', { ...finalValidation });\n\n        if (finalizationHooks.size > 0) {\n          session.setFinalization('pending', 'Loaded-equivalent client finalization hooks are running');\n          await runFinalizationHooks();\n        }\n\n        session.setFinalization('pending', 'Waiting for finalized operational readiness truth to settle');\n        const operationalReadiness = await transport.waitForOperationalReadiness();\n\n        session.setFinalization('ready', 'Post-overlay validation, client finalization hooks, and operational readiness truth verification completed');\n\n        const finalizedReadiness = session.getReadinessSnapshot(operationalReadiness);\n\n        if (!finalizedReadiness.exposureSafe) {\n          const pendingTruth = finalizedReadiness.pending.join(', ');\n          const detail = pendingTruth.length > 0\n            ? `Finalized readiness truth is still pending: ${pendingTruth}`\n            : 'Finalized readiness truth verification failed unexpectedly';\n          return emitFatalBootstrapError('bootstrap.finalization.readiness_truth', new Error(detail));\n        }\n      } catch (error) {\n        const normalizedError = error instanceof Error ? error : new Error(String(error));\n        emitFailedFinalization(normalizedError.message);\n        throw normalizedError;\n      }\n\n      await session.setState('READY');\n\n      events.emit('launch.client.finalize.after', {\n        correlationId: 'bootstrap-client-finalize',\n        ts: Date.now(),\n        step: 'client_finalize',\n        details: {\n          state: 'READY',\n          success: true,\n          outcome: 'ready',\n        },\n      });\n\n      events.emit('core.started', {});\n      events.emit('client.ready', { sessionId });\n\n      logger.info('client_ready', { sessionId });\n      logger.info('bootstrap_finalized', {\n        sessionId,\n      });\n      } catch (error) {\n        await resourceScope.close('startup-failure');\n        throw error;\n      }\n    },\n\n    async stop(reason?: string) {\n      events.emit('core.stopping', { reason });\n\n      await session.setState('STOPPED', reason);\n      const supportedReasons = new Set<SessionFinalizerReason>([\n        'auth-timeout',\n        'browser-crash',\n        'failure',\n        'interruption',\n        'normal-stop',\n        'plugin-failure',\n        'signal',\n        'startup-failure',\n      ]);\n      const finalizerReason: SessionFinalizerReason = supportedReasons.has(reason as SessionFinalizerReason)\n        ? reason as SessionFinalizerReason\n        : 'normal-stop';\n      await resourceScope.close(finalizerReason);\n\n      events.emit('core.stopped', {});\n\n      logger.info('client_stopped', { sessionId, reason });\n    },\n\n    getState() {\n      return session.getState();\n    },\n\n    getReadiness() {\n      return getReadinessSnapshot();\n    },\n\n    getTransport() {\n      return transport;\n    },\n\n    async screenshot() {\n      if (hasCapabilitySubject(options.driver)) {\n        requireCapability(options.driver, 'screenshot');\n      }\n      const page = transport.getPage();\n      if (!page || page.isClosed()) return null;\n      return page.screenshot({ fullPage: true });\n    },\n\n    async evaluateScript<T = unknown>(script: string): Promise<T | null> {\n      const page = transport.getPage();\n      if (!page || page.isClosed()) return null;\n      return page.evaluateScript<T>(script);\n    },\n\n    async executeInChatSandbox<T = unknown>(chatId: string, source: string, input?: unknown): Promise<T> {\n      if (!options.executionSandbox || !options.sandboxPolicy?.chats) {\n        throw new Error('Chat sandboxing is disabled. Enable sandboxChats and configure an execution adapter.');\n      }\n      return Effect.runPromise(options.executionSandbox.execute({\n        chatId,\n        source,\n        input,\n        policy: options.sandboxPolicy,\n        capabilityHandlers: sandboxCapabilityHandlers,\n      })) as Promise<T>;\n    },\n\n    async closeChatSandbox(chatId: string): Promise<void> {\n      if (!options.executionSandbox) return;\n      await Effect.runPromise(options.executionSandbox.closeChat(chatId));\n    },\n\n    async getRuntimeMetrics(): Promise<Readonly<Record<string, number>>> {\n      return Effect.runPromise(observability.snapshot);\n    },\n\n    async getRuntimeCauses() {\n      return Effect.runPromise(observability.causes);\n    },\n  };\n\n  return client;\n}\n"],"mappings":";;;;;;;;;;;AA2RA,MAAa,qBAAoE;CAC/E,uBAAuB;EAAE,UAAU;EAAM,WAAW;CAAM;CAC1D,uBAAuB;EAAE,UAAU;EAAM,WAAW;CAAM;CAC1D,uBAAuB;EAAE,UAAU;EAAM,WAAW;CAAM;CAC1D,8BAA8B;EAAE,UAAU;EAAM,WAAW;CAAM;CACjE,6BAA6B;EAAE,UAAU;EAAM,WAAW;CAAM;CAChE,+BAA+B;EAAE,UAAU;EAAM,WAAW;CAAM;CAClE,8BAA8B;EAAE,UAAU;EAAM,WAAW;CAAM;CACjE,8BAA8B;EAAE,UAAU;EAAM,WAAW;CAAM;CACjE,6BAA6B;EAAE,UAAU;EAAM,WAAW;CAAM;CAChE,8BAA8B;EAAE,UAAU;EAAM,WAAW;CAAM;CACjE,6BAA6B;EAAE,UAAU;EAAM,WAAW;CAAM;CAChE,2BAA2B;EAAE,UAAU;EAAM,WAAW;CAAM;CAC9D,0BAA0B;EAAE,UAAU;EAAM,WAAW;CAAM;CAC7D,mCAAmC;EAAE,UAAU;EAAM,WAAW;CAAM;C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