@qontinui/ui-bridge-native 0.6.13 → 0.6.15

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/core/vision-fields.ts","../src/core/element-actions.ts","../src/core/registry.ts","../src/core/action-effect.ts","../src/core/param-schema.ts","../src/core/abortable.ts","../src/core/element-identifier.ts","../src/control/action-executor.ts","../src/design/design-inspector-native.ts","../src/server/design-handlers.ts","../src/server/page-health.ts","../src/server/handlers.ts","../src/server/observability.ts","../src/server/ws-types.ts","../src/server/http-server.ts","../src/server/ws-event-bridge.ts","../src/transport/logger.ts","../src/transport/relay-logging.ts","../src/transport/DeviceAnnouncer.ts","../src/transport/CloudRelayClient.ts","../src/modal/modal-detector.ts","../src/toast/toast-capture.ts","../src/undo/undo-tracker.ts","../src/react/UIBridgeNativeProvider.tsx","../src/react/useUIElement.ts","../src/react/useUIComponent.ts","../src/react/useUIBridge.ts","../src/react/useUIBridgeModal.ts","../src/react/useUIBridgeToast.ts","../src/react/StateAnnotation.tsx","../src/server/types.ts","../src/server/ws-protocol.ts","../src/server/bind-retry.ts","../src/server/ws-connection.ts","../src/debug/inspector.tsx"],"names":["error","INTERACTIVE_TYPES","success","Platform","summary","createContext","useMemo","Dimensions","useRef","useState","PixelRatio","useCallback","useEffect","jsx","use","StyleSheet","Fragment","sleep","jsxs","TouchableOpacity","View","Text","ScrollView","Modal"],"mappings":";;;;;;;;;;;;;;AA+EA,IAAM,yBAAA,uBAAqD,GAAA,CAAI;AAAA,EAC7D,SAAA;AAAA,EACA,WAAA;AAAA,EACA,YAAA;AAAA,EACA,aAAA;AAAA,EACA,cAAA;AAAA,EACA,eAAA;AAAA,EACA,UAAA;AAAA,EACA,iBAAA;AAAA,EACA,SAAA;AAAA,EACA,cAAA;AAAA,EACA;AACF,CAAC,CAAA;AAUD,IAAM,iBAAA,uBAAwD,GAAA,CAAuB;AAA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AmB,CAAA;AAAA,IACnB,eAAA,EAAiB,CAAA;AAAA,IACjB,YAAA,EAAc,CAAA;AAAA,IACd,WAAA,EAAa,CAAA;AAAA,IACb,YAAA,EAAc;AAAA,GAChB;AAAA,EACA,iBAAA,EAAmB;AAAA,IACjB,eAAA,EAAiB;AAAA,GACnB;AAAA,EACA,UAAA,EAAY;AAAA,IACV,KAAA,EAAO,MAAA;AAAA,IACP,QAAA,EAAU;AAAA;AAEd,CAAC,CAAA","file":"index.js","sourcesContent":["/**\n * Vision analyzer field projection.\n *\n * The runner's vision pipeline (`POST /ui-bridge/vision/{analyze,assert}`)\n * deserializes a snapshot's `elements[]` straight into the Rust\n * `qontinui_vision_core::Element` struct. Beyond geometry (`bbox` — see\n * {@link projectBbox}), the analyzers read these per-element fields:\n *\n * - `interactable: bool` — elements analyzer (interactive coverage),\n * layout analyzer (WCAG target size).\n * - `text: Option<String>` — elements (no_text), color (contrast gate).\n * - `role: Option<String>` — elements analyzer role vocabulary.\n * - `fg_color`/`bg_color: Rgb` — color analyzer (WCAG contrast).\n * - `font_size_px: f32` — typography analyzer (size drift).\n * - `font_family: String` — typography analyzer (family drift).\n *\n * The web SDK populates the runner-facing equivalents via `getComputedStyle`\n * (`state.computedStyles.{color,backgroundColor,fontSize,fontFamily}`) and\n * the DOM (`textContent`, aria `role`, event handlers / tag → interactable);\n * the runner projects those into the snake_case Rust shape. React Native has\n * NO `getComputedStyle`, so the native SDK derives the same signals from what\n * the registry already carries:\n *\n * - `interactable` ← the element's `actions` (press/click/tap/...) or its\n * interactive `type` (button/input/switch/...). Mirrors web's\n * \"has a click-type handler OR is an interactive tag\".\n * - `text` ← `state.value` / `state.textContent` / `label` (human-visible).\n * - `role` ← `type` mapped to the ARIA-ish vocabulary the analyzer expects.\n * - `fg_color`/`bg_color` ← parsed from `flatStyle.color` /\n * `flatStyle.backgroundColor` when the host wired styles via\n * `captureStyle`/`updateElementStyle`. Same source the design inspector\n * reads. Absent when no style was wired (analyzer soft-skips).\n * - `font_size_px` ← `flatStyle.fontSize` (RN number is already px).\n * - `font_family` ← `flatStyle.fontFamily`.\n *\n * These fields are emitted directly in the runner-native snake_case shape so a\n * visual-audit caller can post the snapshot through with no transform — same\n * rationale as `bbox` emitting `{x,y,w,h}` (see {@link NativeElementBbox}).\n */\n\nimport type { NativeElementState, NativeElementType } from './types';\n\n/** Linear RGB triple, runner-native shape (`qontinui_vision_core::Rgb`). */\nexport interface VisionRgb {\n r: number;\n g: number;\n b: number;\n}\n\n/**\n * Analyzer-facing fields projected onto a snapshot element. Every field is\n * optional/absent-when-unknown so the Rust deserializer's serde defaults\n * (`interactable: false`, the rest `None`) only kick in when we genuinely\n * couldn't derive the value — matching the \"soft skip on missing field\"\n * contract in `element_snapshot.rs`.\n */\nexport interface VisionElementFields {\n interactable: boolean;\n text?: string;\n role?: string;\n fg_color?: VisionRgb;\n bg_color?: VisionRgb;\n font_size_px?: number;\n font_family?: string;\n}\n\n/**\n * Real React Native handler prop names that imply the element accepts\n * pointer/key input. This is the GENUINE interactivity signal — a prop the host\n * actually wired to a function (surfaced by `extractHandlerNames(props)` as the\n * snapshot's `registeredHandlers`). Mirrors the web SDK's \"has a real\n * click-type event handler\" interactable signal.\n *\n * Deliberately NOT derived from the element's `actions` array: `inferActions`\n * synthesizes `click`/`press` for EVERY element (even plain `text`/`view`/\n * `custom`), so an action-based check marks every node interactive. The real\n * handler names below are only present when the app source actually attached\n * `onPress` (etc.) to that element.\n */\nconst INTERACTIVE_HANDLER_NAMES: ReadonlySet<string> = new Set([\n 'onPress',\n 'onPressIn',\n 'onPressOut',\n 'onLongPress',\n 'onChangeText',\n 'onValueChange',\n 'onChange',\n 'onSubmitEditing',\n 'onClick',\n 'onTouchStart',\n 'onTouchEnd',\n]);\n\n/**\n * Element types that are inherently interactive regardless of which actions\n * were inferred/declared. Mirrors web treating `<button>/<a>/<input>/<select>`\n * as interactive by tag. `text`/`view`/`image` are intentionally absent — a\n * plain Text/View is only interactive if it carries a REAL press handler\n * (handled by the handler check), matching web's \"div is interactive only with\n * a handler\".\n */\nconst INTERACTIVE_TYPES: ReadonlySet<NativeElementType> = new Set<NativeElementType>([\n 'button',\n 'input',\n 'switch',\n 'checkbox',\n 'radio',\n 'touchable',\n 'pressable',\n 'listItem',\n]);\n\n/**\n * Map a native element `type` to the ARIA-ish `role` vocabulary the runner's\n * elements analyzer expects (matches the web SDK's aria/role values). Returns\n * `undefined` for generic containers so the analyzer doesn't over-count roles.\n */\nexport function roleForType(type: NativeElementType): string | undefined {\n switch (type) {\n case 'button':\n case 'touchable':\n case 'pressable':\n return 'button';\n case 'input':\n return 'textbox';\n case 'text':\n return 'text';\n case 'switch':\n return 'switch';\n case 'checkbox':\n return 'checkbox';\n case 'radio':\n return 'radio';\n case 'image':\n return 'img';\n case 'list':\n return 'list';\n case 'listItem':\n return 'listitem';\n case 'modal':\n return 'dialog';\n case 'scroll':\n case 'view':\n case 'custom':\n default:\n return undefined;\n }\n}\n\n/**\n * Derive whether an element accepts input. True when it is an\n * inherently-interactive `type` (button/input/switch/...) OR the host wired a\n * REAL interactive handler to it (`onPress`/`onChangeText`/...). Matches web's\n * \"has a real click-type handler OR is an interactive tag\".\n *\n * The `handlerNames` come from `extractHandlerNames(props)` — the names of the\n * element's props whose values are actually functions (the snapshot's\n * `registeredHandlers`). This is the genuine interactivity signal. The\n * element's inferred `actions` array is deliberately NOT consulted:\n * `inferActions` synthesizes `click`/`press` for plain `text`/`view`/`custom`,\n * so an action-based check would mark every node interactive (the very\n * over-count this function exists to avoid). A plain `text`/`view`/`heading`\n * with no real handler is therefore `interactable: false`, mirroring web.\n */\nexport function deriveInteractable(\n type: NativeElementType,\n handlerNames: readonly string[] | undefined\n): boolean {\n if (INTERACTIVE_TYPES.has(type)) return true;\n if (handlerNames) {\n for (const name of handlerNames) {\n if (INTERACTIVE_HANDLER_NAMES.has(name)) return true;\n }\n }\n return false;\n}\n\n/**\n * Derive the human-visible text for an element, preferring the most\n * \"what the user reads\" source. Mirrors web's `textContent`/accessibleName\n * precedence adapted to RN's registry shape:\n * 1. `state.value` — current input value / text element's mirrored label.\n * 2. `state.textContent` — explicit text content if the host set it.\n * 3. `label` — registration label (often the visible string).\n * Returns `undefined` when none carry a non-empty string so the analyzer's\n * `text.is_none()` gate stays accurate.\n */\nexport function deriveText(\n state: Pick<NativeElementState, 'value' | 'textContent'>,\n label: string | undefined\n): string | undefined {\n const candidates = [state.value, state.textContent, label];\n for (const c of candidates) {\n if (typeof c === 'string') {\n const trimmed = c.trim();\n if (trimmed.length > 0) return trimmed;\n }\n }\n return undefined;\n}\n\n// Common CSS/RN named colors. RN accepts the full CSS named-color set; we\n// cover the ones a design system realistically declares inline. Anything\n// outside this map + the hex/rgb parsers returns undefined (analyzer skips).\nconst NAMED_COLORS: Readonly<Record<string, VisionRgb>> = {\n black: { r: 0, g: 0, b: 0 },\n white: { r: 255, g: 255, b: 255 },\n red: { r: 255, g: 0, b: 0 },\n green: { r: 0, g: 128, b: 0 },\n blue: { r: 0, g: 0, b: 255 },\n gray: { r: 128, g: 128, b: 128 },\n grey: { r: 128, g: 128, b: 128 },\n silver: { r: 192, g: 192, b: 192 },\n transparent: { r: 0, g: 0, b: 0 },\n orange: { r: 255, g: 165, b: 0 },\n yellow: { r: 255, g: 255, b: 0 },\n purple: { r: 128, g: 0, b: 128 },\n navy: { r: 0, g: 0, b: 128 },\n};\n\nconst clamp255 = (n: number): number => Math.max(0, Math.min(255, Math.round(n)));\n\n/**\n * Parse an RN/CSS color string into a runner-native `{r,g,b}` triple, dropping\n * alpha (the runner's `Rgb` has no alpha; the analyzers convert to Lab/sRGB on\n * demand). Supports:\n * - `#rgb`, `#rgba`, `#rrggbb`, `#rrggbbaa`\n * - `rgb(r,g,b)` / `rgba(r,g,b,a)` (integer or %),\n * - named colors (subset).\n * Returns `undefined` for `undefined`, non-strings, or unrecognized formats so\n * the snapshot omits the field and the analyzer soft-skips rather than seeing a\n * bogus color. RN integer colors (e.g. `processColor` output) are not handled —\n * inline styles in app source are strings.\n */\nexport function parseColorToRgb(input: unknown): VisionRgb | undefined {\n if (typeof input !== 'string') return undefined;\n const raw = input.trim().toLowerCase();\n if (raw.length === 0) return undefined;\n\n if (Object.prototype.hasOwnProperty.call(NAMED_COLORS, raw)) {\n return NAMED_COLORS[raw];\n }\n\n // Hex: #rgb, #rgba, #rrggbb, #rrggbbaa\n if (raw.startsWith('#')) {\n const hex = raw.slice(1);\n if (hex.length === 3 || hex.length === 4) {\n const r = parseInt(hex[0] + hex[0], 16);\n const g = parseInt(hex[1] + hex[1], 16);\n const b = parseInt(hex[2] + hex[2], 16);\n if ([r, g, b].every((v) => Number.isFinite(v))) return { r, g, b };\n return undefined;\n }\n if (hex.length === 6 || hex.length === 8) {\n const r = parseInt(hex.slice(0, 2), 16);\n const g = parseInt(hex.slice(2, 4), 16);\n const b = parseInt(hex.slice(4, 6), 16);\n if ([r, g, b].every((v) => Number.isFinite(v))) return { r, g, b };\n return undefined;\n }\n return undefined;\n }\n\n // rgb()/rgba()\n const rgbMatch = raw.match(/^rgba?\\(([^)]+)\\)$/);\n if (rgbMatch) {\n const parts = rgbMatch[1].split(',').map((p) => p.trim());\n if (parts.length < 3) return undefined;\n const channel = (p: string): number | undefined => {\n if (p.endsWith('%')) {\n const pct = parseFloat(p.slice(0, -1));\n if (!Number.isFinite(pct)) return undefined;\n return clamp255((pct / 100) * 255);\n }\n const n = parseFloat(p);\n if (!Number.isFinite(n)) return undefined;\n return clamp255(n);\n };\n const r = channel(parts[0]);\n const g = channel(parts[1]);\n const b = channel(parts[2]);\n if (r === undefined || g === undefined || b === undefined) return undefined;\n return { r, g, b };\n }\n\n return undefined;\n}\n\n/**\n * Parse an RN `fontSize` into CSS pixels. RN `fontSize` is a unitless number\n * already in density-independent pixels (the analyzer compares relative sizes,\n * so dp vs px scaling is consistent across all elements in one snapshot).\n * Accepts a bare number or a `\"16px\"`/`\"16\"` string. Returns `undefined` for\n * anything non-numeric so typography soft-skips.\n */\nexport function parseFontSizePx(input: unknown): number | undefined {\n if (typeof input === 'number') {\n return Number.isFinite(input) && input > 0 ? input : undefined;\n }\n if (typeof input === 'string') {\n const m = input.trim().match(/^(-?\\d*\\.?\\d+)/);\n if (m) {\n const n = parseFloat(m[1]);\n return Number.isFinite(n) && n > 0 ? n : undefined;\n }\n }\n return undefined;\n}\n\n/**\n * Project the analyzer-facing fields for one registered element. Pure — takes\n * the already-resolved state + the element's static metadata, returns the\n * snake_case field bag to spread onto the snapshot element. Visual fields\n * (colors/fonts) are present only when `flatStyle` carried them; the runner's\n * serde defaults handle their absence.\n *\n * Unlike `bbox` (gated on `visibility === 'visible'`), interactable/text/role\n * are populated for ALL elements so the elements analyzer's coverage counts\n * are accurate — matching the web SDK, which emits role/text/interactable for\n * every element it discovers regardless of viewport position.\n */\nexport function projectVisionFields(args: {\n type: NativeElementType;\n label: string | undefined;\n /**\n * Names of the element's props that are real functions (from\n * `extractHandlerNames(props)` — the snapshot's `registeredHandlers`). The\n * genuine interactivity signal; the inferred `actions` array is NOT used here\n * because `inferActions` synthesizes press/click for every element.\n */\n handlerNames: readonly string[] | undefined;\n state: Pick<NativeElementState, 'value' | 'textContent'>;\n flatStyle: Record<string, unknown> | undefined;\n}): VisionElementFields {\n const { type, label, handlerNames, state, flatStyle } = args;\n\n const fields: VisionElementFields = {\n interactable: deriveInteractable(type, handlerNames),\n };\n\n const text = deriveText(state, label);\n if (text !== undefined) fields.text = text;\n\n const role = roleForType(type);\n if (role !== undefined) fields.role = role;\n\n if (flatStyle) {\n const fg = parseColorToRgb(flatStyle.color);\n if (fg !== undefined) fields.fg_color = fg;\n const bg = parseColorToRgb(flatStyle.backgroundColor);\n if (bg !== undefined) fields.bg_color = bg;\n const size = parseFontSizePx(flatStyle.fontSize);\n if (size !== undefined) fields.font_size_px = size;\n if (typeof flatStyle.fontFamily === 'string' && flatStyle.fontFamily.trim().length > 0) {\n fields.font_family = flatStyle.fontFamily;\n }\n }\n\n return fields;\n}\n","/**\n * The ONE wire projection for an element's custom actions.\n *\n * Plan `2026-09-04-effect-calculus-joins-the-component-action-registry`,\n * Design decision 4 step 3.\n *\n * DUPLICATE of `@qontinui/ui-bridge` `src/core/element-actions.ts`, for the same\n * reason the types beside it are duplicated: this package must not import from\n * `@qontinui/ui-bridge` (an optional peer). KEEP IN SYNC — a divergence here is\n * a divergence in what the two channels advertise about the same annotation.\n *\n * ---------------------------------------------------------------------------\n * WHAT THIS DOES NOT DO: default the effect\n * ---------------------------------------------------------------------------\n *\n * `effect` is carried through **verbatim and undefaulted**. An action whose\n * author declared nothing is emitted with `effect` absent, never with a\n * manufactured `'read'` — a default rendered as a declaration is a fail-open lie\n * on exactly the surface the annotation exists to protect. **Absent means\n * UNCLASSIFIED, not safe**, which is what served policy `operating-rules`\n * `what-makes-an-action-destructive` requires of an unestablished effect.\n */\n\nimport type { CustomAction, SerializedElementAction } from './types';\n\ntype ProjectableCustomActions = Record<\n string,\n Pick<CustomAction, 'label' | 'description' | 'effect'> | undefined\n>;\n\n/**\n * Project `RegisteredNativeElement.customActions` to its wire shape.\n *\n * - `undefined` in → `undefined` out (an element with no custom actions must not\n * start emitting `[]`; `JSON.stringify` keeps `[]` and drops `undefined`).\n * - An empty record in → `[]` out, matching what `Object.keys({})` gave before.\n *\n * The emitted `id` is the RECORD KEY — the executor dispatches by key, so the\n * key is the name a caller must send. Nullish entries are skipped: they carry no\n * handler, so advertising them would advertise a capability that does not exist.\n */\nexport function serializeElementCustomActions(\n customActions: ProjectableCustomActions | undefined\n): SerializedElementAction[] | undefined {\n if (!customActions) return undefined;\n\n const out: SerializedElementAction[] = [];\n for (const [id, action] of Object.entries(customActions)) {\n if (!action) continue;\n const entry: SerializedElementAction = { id };\n if (action.label !== undefined) entry.label = action.label;\n if (action.description !== undefined) entry.description = action.description;\n // Undefaulted — see the module header. `undefined` stays `undefined`.\n if (action.effect !== undefined) entry.effect = action.effect;\n out.push(entry);\n }\n return out;\n}\n","/**\n * Native Element and Component Registry\n *\n * Central registry for all UI elements and components registered with UI Bridge Native.\n * Adapted from ui-bridge for React Native environments.\n */\n\nimport type {\n RegisteredNativeElement,\n RegisteredNativeComponent,\n NativeElementState,\n NativeElementType,\n NativeStandardAction,\n NativeCustomAction,\n NativeAppInfo,\n NativeBridgeSnapshot,\n NativeElementBbox,\n NativeElementIdentifier,\n NativeElementRef,\n NativeRegistrationCoverage,\n NativeRouteProviderLike,\n NativeSnapshotEnrichers,\n NativeSnapshotEnricher,\n Workflow,\n BridgeEvent,\n BridgeEventType,\n BridgeEventListener,\n IREffect,\n} from './types';\nimport { projectVisionFields } from './vision-fields';\nimport { serializeElementCustomActions } from './element-actions';\n\n/**\n * Options for registering an element\n */\nexport interface RegisterElementOptions {\n type?: NativeElementType;\n label?: string;\n actions?: NativeStandardAction[];\n customActions?: Record<string, NativeCustomAction>;\n props?: Record<string, unknown>;\n treePath?: string;\n testId?: string;\n accessibilityLabel?: string;\n /** Route path where the element was registered (for page-scoped filtering) */\n registrationRoute?: string | null;\n /**\n * Id of the registered scrollable container this element lives inside.\n *\n * When set, {@link computeVisibility} clips the element against that\n * container's measured frame as well as the window, so a row scrolled out of\n * its `ScrollView` / `FlatList` stops reporting `visibility: 'visible'`.\n *\n * DECLARED, not inferred, and that is deliberate. React Native gives the\n * registry no parent chain — `useUIElement` is a hook, so it never wraps its\n * element's children and cannot publish itself as their ancestor. Guessing\n * the ancestor geometrically is worse than not clipping: a full-width scroll\n * container horizontally contains the tab bar and the header too, and\n * clipping those against it would report on-screen chrome as off-screen.\n * A wrong `hidden` is a worse answer than a coarse `visible`.\n *\n * Unset (the default) leaves the window as the only clip region.\n */\n scrollAncestorId?: string;\n /** Flattened RN style (from StyleSheet.flatten) for design review */\n flatStyle?: Record<string, unknown>;\n /** State-specific style overrides for design review */\n stateStyles?: {\n pressed?: Record<string, unknown>;\n focused?: Record<string, unknown>;\n disabled?: Record<string, unknown>;\n };\n}\n\n/**\n * Options for registering a component\n */\nexport interface RegisterComponentOptions {\n name: string;\n description?: string;\n actions?: Array<{\n id: string;\n label?: string;\n description?: string;\n /**\n * Phase 2 (same plan): the action's published parameter schema. It was\n * ABSENT here and dropped by the object literal in `registerComponent`\n * below, so the field `ComponentAction` declares could never reach a\n * registered native component and the native invocation seam had nothing\n * to validate against. That is the silent-drop trap the plan warns about,\n * already realised.\n */\n paramSchema?: Record<string, unknown>;\n /**\n * Phase 4 (same plan): the safety annotation. Absent here, an author's\n * `effect: 'destructive'` would die at this hop exactly the way\n * `paramSchema` did before Phase 2 — the literal in `registerComponent`\n * has a closed field list and nothing type-checks the omission.\n */\n effect?: IREffect;\n /**\n * Phase 3 (plan 2026-08-20-ui-bridge-action-declaration-shape): the second\n * argument is the `ActionHandlerOptions` bag carrying the cancellation\n * signal. A 1-arity handler stays assignable.\n */\n handler: (params?: unknown, options?: { signal?: AbortSignal }) => unknown | Promise<unknown>;\n }>;\n elementIds?: string[];\n}\n\n/**\n * Options for {@link NativeUIBridgeRegistry.updateComponentMeta}.\n *\n * Every field is optional and `undefined` means \"leave the registered value\n * alone\" — the same partial-update semantics {@link RegisterComponentOptions}'s\n * sister {@link NativeUIBridgeRegistry.updateElementMeta} uses. A consequence\n * worth stating: a `description` cannot be CLEARED through this door, only\n * replaced. Pass `actions: []` to publish an empty action list; that is\n * distinguishable from omitting the field.\n */\nexport interface UpdateComponentMetaOptions {\n name?: string;\n description?: string;\n actions?: RegisterComponentOptions['actions'];\n elementIds?: string[];\n}\n\n/**\n * Map declared component actions into the registry's stored shape.\n *\n * ⚠ CLOSED FIELD LIST. Any `ComponentAction` field not named here is dropped at\n * registration time, silently: the literal stays assignable, the serializer\n * still runs, the field is simply never there. `paramSchema` was exactly that\n * until Phase 2, and `effect` is the Phase 4 addition that would have gone the\n * same way.\n *\n * It lives in ONE place on purpose. `registerComponent` and\n * `updateComponentMeta` both publish actions, and a second hand-rolled copy of\n * this list is precisely how the two Phase-2/Phase-4 drops happened — a field\n * added to the declaration type stays assignable at every re-wrap site and\n * simply never arrives.\n */\nfunction toRegisteredComponentActions(\n actions: NonNullable<RegisterComponentOptions['actions']>\n): RegisteredNativeComponent['actions'] {\n return actions.map((a) => ({\n id: a.id,\n label: a.label,\n description: a.description,\n paramSchema: a.paramSchema,\n effect: a.effect,\n handler: a.handler,\n }));\n}\n\n/**\n * Value signature of everything about an action list that reaches a bridge\n * consumer.\n *\n * `handler` is excluded deliberately: it is a function, so it is not\n * serialisable, it is never published, and call sites pass inline closures that\n * are freshly allocated on every render — including it would make\n * `updateComponentMeta` report a change every single time and defeat its\n * idempotence. Order is significant, because published order is the order an\n * agent reads the actions in.\n */\nfunction publishedActionSignature(actions: RegisteredNativeComponent['actions']): string {\n return JSON.stringify(\n actions.map((a) => [a.id, a.label, a.description, a.paramSchema, a.effect])\n );\n}\n\n/** Positional equality for the optional `elementIds` list. */\nfunction sameElementIds(a: string[] | undefined, b: string[] | undefined): boolean {\n if (a === b) return true;\n if (a === undefined || b === undefined) return false;\n return a.length === b.length && a.every((id, i) => id === b[i]);\n}\n\n/**\n * Registry configuration\n */\nexport interface NativeRegistryConfig {\n verbose?: boolean;\n onEvent?: BridgeEventListener;\n}\n\n/**\n * Extract handler function names from an element's props.\n * Returns names of props whose values are functions (e.g. ['onPress', 'onChangeText']).\n */\nexport function extractHandlerNames(props?: Record<string, unknown>): string[] {\n if (!props) return [];\n return Object.keys(props).filter((k) => typeof props[k] === 'function');\n}\n\n/**\n * `currentRouteOnly` filter predicate for `registrationRoute`.\n *\n * Returns `true` when an element should be INCLUDED in a current-route-only\n * view. Two classes of elements pass the filter:\n *\n * 1. Elements registered on the current route\n * (`registrationRoute === currentRoute`).\n * 2. Route-agnostic elements (`registrationRoute == null` or `''`) — these\n * are typically registered at the app root (tab bars, persistent\n * headers, modal hosts) and apply to every route. Excluding them by\n * default makes `currentRouteOnly=true` return empty on mobile where\n * most apps register chrome at the root and screens via routed stacks.\n *\n * The filter only DROPS elements whose `registrationRoute` is set to a\n * non-matching route — i.e. they belong to a different screen. This matches\n * the runner-side semantics: route-tagged DOM nodes that don't match the\n * active URL are scoped out; untagged nodes are always in scope.\n *\n * Surfaced 2026-05-23 (item 4 of the 0.6.6 robustness pass) — the prior\n * strict equality returned 0 elements on mobile screens that register tabs\n * at the root, because tab elements had `registrationRoute: null`.\n */\nexport function matchesCurrentRoute(\n registrationRoute: string | null | undefined,\n currentRoute: string\n): boolean {\n if (registrationRoute == null || registrationRoute === '') return true;\n return registrationRoute === currentRoute;\n}\n\n/**\n * Derive the snapshot's `activeTab` from an Expo Router segment list.\n *\n * Expo Router spells a layout group as a parenthesised segment and a dynamic\n * route as a bracketed one, so `usePathname()`/`useSegments()` on the \"runs\"\n * tab of a `(tabs)` layout yield `\"/(tabs)/runs\"` and `[\"(tabs)\", \"runs\"]`\n * (the shape the `RouteProvider` doc comment already documents). The tab a user\n * is looking at is therefore the segment immediately following the INNERMOST\n * group.\n *\n * Rules, all deliberately conservative — an unknown tab is reported as absent\n * rather than guessed:\n *\n * - `[\"(tabs)\", \"runs\"]` → `\"runs\"`\n * - `[\"(tabs)\", \"runs\", \"[id]\"]`→ `\"runs\"` (a detail screen is still *on* a tab)\n * - `[\"(tabs)\"]` → `\"index\"` (the group's own index route)\n * - `[\"(tabs)\", \"[id]\"]` → `undefined` (dynamic route, not a tab)\n * - `[\"settings\"]` → `undefined` (no group layout ⇒ no tabs)\n * - `[]` / `undefined` → `undefined`\n *\n * Exported so the rules are unit-testable without standing up a registry.\n */\nexport function deriveActiveTabFromSegments(segments?: string[]): string | undefined {\n if (!segments || segments.length === 0) return undefined;\n\n let innermostGroup = -1;\n for (let i = 0; i < segments.length; i++) {\n const segment = segments[i];\n if (typeof segment === 'string' && segment.startsWith('(') && segment.endsWith(')')) {\n innermostGroup = i;\n }\n }\n // No layout group at all — the app has no tab shell, so claiming an active\n // tab would be an invention.\n if (innermostGroup === -1) return undefined;\n\n const next = segments[innermostGroup + 1];\n // The group IS the leaf: the router is showing that group's index route.\n if (next === undefined) return 'index';\n if (typeof next !== 'string' || next.length === 0) return undefined;\n // A dynamic segment is a detail screen reached from a tab, not a tab itself.\n if (next.startsWith('[') && next.endsWith(']')) return undefined;\n return next;\n}\n\n/**\n * Project an element's runtime state into a runner-native pixel-space `bbox`.\n *\n * Returns `{x, y, w, h}` in PHYSICAL pixels (RN `state.layout` is logical dp;\n * we multiply by `pixelRatio` — `PixelRatio.get()`, injected via\n * `registry.setPixelRatio` — so the box aligns with the runner's adb screencap\n * frame). See {@link NativeElementBbox} for why the shape is `{x,y,w,h}` and\n * not the web SDK's `{x,y,width,height}`.\n *\n * `pixelRatio` is INJECTED rather than read from `react-native` here: this is a\n * non-React core module, and a static `import { PixelRatio } from 'react-native'`\n * breaks both the vitest suite (\"Flow is not supported\") and risks the\n * Metro/Hermes `unknownModuleError` that bit `design-handlers`/`page-health`.\n * The provider wires the real ratio via `setPixelRatio`; callers/tests that\n * never wire it get the `1` default (dp ≈ px, still a usable box).\n *\n * Gating (avoid poisoning the snapshot — the flat registry mixes routes and\n * some elements carry stale off-screen coords):\n * - returns `undefined` unless `visibility === 'visible'` (visible + measured)\n * - returns `undefined` when `state.layout` is null/absent\n * Clamps every component to a non-negative integer.\n *\n * Uses `measureInWindow`'s absolute `pageX`/`pageY` for the origin. Falls back\n * to the layout-relative `x`/`y` only when `pageX`/`pageY` weren't measured\n * (rare; keeps a best-effort box rather than dropping the element).\n */\nexport function projectBbox(\n state: NativeElementState,\n visibility: 'visible' | 'likely-visible' | 'hidden',\n pixelRatio = 1\n): NativeElementBbox | undefined {\n if (visibility !== 'visible') return undefined;\n const layout = state.layout;\n if (!layout) return undefined;\n\n const ratio = pixelRatio > 0 && Number.isFinite(pixelRatio) ? pixelRatio : 1;\n const toPx = (v: number): number => Math.max(0, Math.round(v * ratio));\n\n const hasPage =\n typeof layout.pageX === 'number' &&\n typeof layout.pageY === 'number' &&\n Number.isFinite(layout.pageX) &&\n Number.isFinite(layout.pageY);\n const originX = hasPage ? layout.pageX : layout.x;\n const originY = hasPage ? layout.pageY : layout.y;\n\n if (\n typeof originX !== 'number' ||\n typeof originY !== 'number' ||\n typeof layout.width !== 'number' ||\n typeof layout.height !== 'number' ||\n !Number.isFinite(originX) ||\n !Number.isFinite(originY) ||\n !Number.isFinite(layout.width) ||\n !Number.isFinite(layout.height)\n ) {\n return undefined;\n }\n\n return {\n x: toPx(originX),\n y: toPx(originY),\n w: toPx(layout.width),\n h: toPx(layout.height),\n };\n}\n\n// ── Visibility ──────────────────────────────────────────────────────────────\n\n/**\n * A rectangle in window (page) coordinates, logical dp — the same space\n * `measureInWindow` reports `pageX`/`pageY` in.\n */\nexport interface NativePageRect {\n left: number;\n top: number;\n right: number;\n bottom: number;\n}\n\n/**\n * Why an element is not plainly visible.\n *\n * DUPLICATE of `@qontinui/ui-bridge` `VisibilityReason`\n * (`src/core/types.ts` — `'hidden' | 'off-screen' | 'occluded' | 'no-layout'`),\n * for the same reason the action types above are duplicated: `@qontinui/ui-bridge`\n * is an OPTIONAL peer of this package, so this module must not import from it.\n * KEEP IN SYNC — one vocabulary across both SDKs is the point; do not coin\n * native-only spellings.\n *\n * `'occluded'` is declared but never produced here: React Native gives the\n * registry no hit-test equivalent of `document.elementFromPoint`, so this SDK\n * cannot honestly claim occlusion. It stays in the union so a native reason\n * string is always a valid web reason string.\n */\nexport type NativeVisibilityReason = 'hidden' | 'off-screen' | 'occluded' | 'no-layout';\n\n/** The three-value verdict carried on every snapshot element. */\nexport type NativeVisibility = 'visible' | 'likely-visible' | 'hidden';\n\n/**\n * Convert an element's measured layout into a page-space rect, or `null` when\n * it has no TRUSTWORTHY page-space origin.\n *\n * STRICTER THAN {@link projectBbox} ON PURPOSE. `projectBbox` falls back to the\n * parent-relative `x`/`y` when `pageX`/`pageY` weren't measured, because a\n * slightly-wrong box is still a usable box. Clipping cannot take that trade: a\n * parent-relative origin compared against window coordinates silently mixes two\n * coordinate spaces and yields a wrong `hidden` verdict — the outcome\n * `RegisterElementOptions.scrollAncestorId` calls worse than a coarse\n * `visible`. So a layout flagged `pageOriginUnmeasured` returns `null` here,\n * and {@link computeVisibility} declines to clip rather than guess.\n */\nexport function pageRectOf(state: NativeElementState): NativePageRect | null {\n const layout = state.layout;\n if (!layout) return null;\n // The writer told us `pageX`/`pageY` are a parent-relative stand-in, not a\n // `measureInWindow` result. Not a page-space rect, and not guessable into one.\n if (layout.pageOriginUnmeasured === true) return null;\n\n const hasPage =\n typeof layout.pageX === 'number' &&\n typeof layout.pageY === 'number' &&\n Number.isFinite(layout.pageX) &&\n Number.isFinite(layout.pageY);\n if (!hasPage) return null;\n\n const left = layout.pageX;\n const top = layout.pageY;\n\n if (\n typeof layout.width !== 'number' ||\n typeof layout.height !== 'number' ||\n !Number.isFinite(layout.width) ||\n !Number.isFinite(layout.height)\n ) {\n return null;\n }\n\n return { left, top, right: left + layout.width, bottom: top + layout.height };\n}\n\n/** Do two 1-D spans share any extent? A zero-length span counts as touching. */\nfunction spansOverlap(aMin: number, aMax: number, bMin: number, bMax: number): boolean {\n if (aMin === aMax) return aMin >= bMin && aMin <= bMax;\n return aMin < bMax && aMax > bMin;\n}\n\n/**\n * Is this rect empty — nothing can overlap it?\n *\n * {@link intersectRects} returns an INVERTED rect (`right < left`) when the two\n * inputs are disjoint, which is the honest answer for \"the reachable region\",\n * but `spansOverlap`'s `aMin < bMax && aMax > bMin` reads an inverted span as\n * overlapping. Every consumer of an intersection must ask this first.\n */\nexport function isEmptyRect(rect: NativePageRect): boolean {\n return rect.right <= rect.left || rect.bottom <= rect.top;\n}\n\n/**\n * Intersect two page rects, or `null` when either is absent (`null` means\n * UNKNOWN, so it never narrows the other side).\n *\n * The result may be EMPTY — check {@link isEmptyRect}. That happens whenever\n * the two rects are disjoint, e.g. a scroll container that has itself been\n * scrolled out of the window: nothing inside it can be on screen, and an empty\n * clip is exactly how that is expressed.\n */\nexport function intersectRects(\n a: NativePageRect | null,\n b: NativePageRect | null\n): NativePageRect | null {\n if (!a) return b;\n if (!b) return a;\n return {\n left: Math.max(a.left, b.left),\n top: Math.max(a.top, b.top),\n right: Math.min(a.right, b.right),\n bottom: Math.min(a.bottom, b.bottom),\n };\n}\n\n/**\n * Decide what a snapshot should say about an element being on screen.\n *\n * THE DEFECT THIS CLOSES: visibility used to be derived from mount + `measure()`\n * alone — `state.visible ? (state.layout ? 'visible' : 'likely-visible') : 'hidden'`\n * — with no comparison against any bounds at all. Every mounted, measured\n * element reported `visible`, including rows scrolled far past the fold, so a\n * snapshot claimed things were on screen that were not.\n *\n * SCOPE — read this before citing it. This is a PURE PROJECTION: it reads\n * `state.visible` and never writes it. An off-screen element still carries\n * `state.visible === true`; only the snapshot's `visibility` /\n * `visibilityReason` change. That is a deliberate divergence from the web SDK,\n * which folds off-screen INTO the boolean (`@qontinui/ui-bridge`\n * `src/core/registry.ts` — `if (!inViewport) return { visible: false, reason:\n * 'off-screen' }`), and it means any consumer asserting on `state.visible`\n * alone — `/manual-test`'s \"PRESENT IS NOT VISIBLE\" gate among them — sees no\n * change on mobile and stays as vacuous as it was. Closing that needs either a\n * matching demotion of `state.visible` here or a consumer that reads\n * `visibility`; both are contract decisions beyond this projection, and\n * neither is done. The strings are shared with the web SDK; the SHAPE is not.\n *\n * `clip` is the region the element must reach to count as on screen — the\n * window, intersected with the measured frame of a declared\n * `scrollAncestorId`. **A `null`/absent clip means the bounds are UNKNOWN, and\n * an unknown never demotes**: with no viewport injected (every non-RN caller,\n * including this package's own suite) the answer is exactly what it was before.\n * Absence of evidence is not evidence of off-screen.\n *\n * Any overlap at all counts as visible. A half-scrolled row IS on screen, and\n * a ratio threshold would be a second, unshared policy knob for callers to\n * disagree about.\n */\nexport function computeVisibility(\n state: NativeElementState,\n clip?: NativePageRect | null\n): { visibility: NativeVisibility; visibilityReason?: NativeVisibilityReason } {\n if (!state.visible) {\n return { visibility: 'hidden', visibilityReason: 'hidden' };\n }\n if (state.layout === null) {\n // Registered and mounted but not yet measured. `'likely-visible'` already\n // is this SDK's honest-UNKNOWN value; `'no-layout'` names why.\n return { visibility: 'likely-visible', visibilityReason: 'no-layout' };\n }\n if (!clip) {\n return { visibility: 'visible' };\n }\n const rect = pageRectOf(state);\n if (!rect) {\n // Measured, but with no trustworthy page-space origin (see `pageRectOf`).\n // Report it exactly as before — an unknown must not manufacture a verdict.\n return { visibility: 'visible' };\n }\n // A disjoint intersection (a scroll container itself scrolled off the window)\n // inverts rather than zeroing, and `spansOverlap` would read an inverted span\n // as overlapping. Nothing can be inside an empty clip.\n if (isEmptyRect(clip)) {\n return { visibility: 'hidden', visibilityReason: 'off-screen' };\n }\n const onScreen =\n spansOverlap(rect.left, rect.right, clip.left, clip.right) &&\n spansOverlap(rect.top, rect.bottom, clip.top, clip.bottom);\n\n return onScreen\n ? { visibility: 'visible' }\n : { visibility: 'hidden', visibilityReason: 'off-screen' };\n}\n\n/**\n * Infer available actions based on element type.\n *\n * `scrollIntoView` is advertised only when the element DECLARES a\n * `scrollAncestorId`. It is the one input the action cannot work without (the\n * registry keeps no parent chain, so there is nothing else to scroll), and the\n * runner refuses any action an element does not advertise — so advertising it\n * everywhere would put a verb on every element that answers `NOT_SUPPORTED`\n * for all but the declared few. An ancestor that turns out to be unregistered\n * or not a ScrollView is still answered honestly by the executor\n * (`NOT_SUPPORTED`).\n */\nfunction inferActions(type: NativeElementType, scrollAncestorId?: string): NativeStandardAction[] {\n const baseActions: NativeStandardAction[] = scrollAncestorId\n ? ['focus', 'blur', 'scrollIntoView']\n : ['focus', 'blur'];\n\n switch (type) {\n case 'button':\n case 'touchable':\n case 'pressable':\n return [...baseActions, 'click', 'press', 'longPress', 'doubleTap'];\n case 'input':\n return [...baseActions, 'click', 'press', 'type', 'setValue', 'clear'];\n case 'text':\n return [...baseActions, 'click', 'press', 'longPress'];\n case 'view':\n return [...baseActions, 'click', 'press'];\n case 'scroll':\n return [...baseActions, 'scroll', 'swipe'];\n case 'list':\n return [...baseActions, 'scroll', 'swipe'];\n case 'listItem':\n return [...baseActions, 'click', 'press', 'longPress', 'swipe'];\n case 'switch':\n case 'checkbox':\n return [...baseActions, 'click', 'press', 'toggle'];\n case 'radio':\n return [...baseActions, 'click', 'press'];\n case 'image':\n return [...baseActions, 'click', 'press', 'longPress'];\n case 'modal':\n return ['focus', 'blur'];\n case 'custom':\n default:\n return [...baseActions, 'click', 'press'];\n }\n}\n\n/**\n * Native UI Bridge Registry\n *\n * Manages registration and lookup of native UI elements and components.\n */\nexport class NativeUIBridgeRegistry {\n private elements = new Map<string, RegisteredNativeElement>();\n private components = new Map<string, RegisteredNativeComponent>();\n private workflows = new Map<string, Workflow>();\n private eventListeners = new Map<BridgeEventType, Set<BridgeEventListener>>();\n private config: NativeRegistryConfig;\n private enrichers: NativeSnapshotEnrichers = {};\n private snapshotExtras = new Map<string, NativeSnapshotEnricher>();\n /**\n * App identification metadata (appId/appName/appType/framework). Set via\n * `setAppInfo` — typically wired in the server constructor from the\n * `NativeUIBridgeConfig` the host passes to `UIBridgeNativeProvider`.\n *\n * When set, `createSnapshot` includes it on the resulting snapshot so\n * agents can identify the app from snapshot bytes alone (parity with the\n * `uiBridge` block on the `health` response). Snapshots created before\n * this is wired simply omit the field.\n */\n private appInfo: NativeAppInfo | null = null;\n /**\n * Optional route provider. When set, `createSnapshot` reads\n * `currentRoute`/`segments` from it whenever the caller does not pass an\n * explicit `routeInfo` argument. This lets the default `getSnapshot` HTTP\n * handler — which has no direct reference to the `NativeUIBridgeServer`\n * instance — still emit a populated `currentRoute` field.\n *\n * Wired by `NativeUIBridgeServer.setRouteProvider`, which forwards the\n * provider into the registry alongside the per-handler overrides it\n * already installs.\n */\n private routeProvider: NativeRouteProviderLike | null = null;\n /**\n * Device pixel ratio used to project `state.layout` (logical dp) into the\n * physical-pixel `bbox` emitted on each snapshot element. Defaults to `1`\n * (dp ≈ px) so callers/tests that never inject a ratio still get a usable\n * box; the React provider wires the real `PixelRatio.get()` via\n * {@link setPixelRatio}. Read from a non-React core module on purpose — see\n * the `projectBbox` doc comment for why we don't import `react-native` here.\n */\n private pixelRatio = 1;\n /**\n * Injected getter for the device window size in logical dp, used to clip\n * reported visibility. Injected rather than read here for exactly the reason\n * `pixelRatio` is: a static `import { Dimensions } from 'react-native'` in\n * this non-React core module breaks the vitest suite and risks the\n * Metro/Hermes `unknownModuleError`. It is a PROVIDER, not a value, so a\n * rotation is picked up on the next snapshot with nothing to keep in sync.\n *\n * `null` means the window bounds are UNKNOWN, and {@link computeVisibility}\n * treats unknown bounds as \"cannot demote\" — never as an empty viewport.\n */\n private viewportProvider: (() => { width: number; height: number }) | null = null;\n /**\n * Sticky flag: flips `true` the first time any element is registered and\n * stays `true` even after elements are unregistered. Lets agents distinguish\n * \"this route never wired any elements\" from \"this route registered then\n * unmounted\".\n */\n private everHadRegistrations = false;\n\n constructor(config: NativeRegistryConfig = {}) {\n this.config = config;\n }\n\n // ============================================================================\n // App Info & Route Provider\n // ============================================================================\n\n /**\n * Set the app identification metadata returned alongside snapshots.\n * Idempotent — re-calling with the same shape is a no-op.\n * Pass `null` (or omit a previous call) to clear.\n */\n setAppInfo(info: NativeAppInfo | null | undefined): void {\n this.appInfo = info ?? null;\n }\n\n /** Read-only accessor for the registered app info, if any. */\n getAppInfo(): NativeAppInfo | null {\n return this.appInfo;\n }\n\n /**\n * Set a route provider whose `getCurrentRoute`/`getSegments` are read by\n * `createSnapshot` when no explicit `routeInfo` argument is supplied.\n *\n * Call with `null` to detach (e.g. when the host swaps providers on HMR).\n */\n setRouteProvider(provider: NativeRouteProviderLike | null | undefined): void {\n this.routeProvider = provider ?? null;\n }\n\n /** Read-only accessor for the registered route provider, if any. */\n getRouteProvider(): NativeRouteProviderLike | null {\n return this.routeProvider;\n }\n\n /**\n * Resolve the snapshot's `activeTab`: an explicit `getActiveTab()` on the\n * route provider wins, otherwise derive it from the Expo Router segments the\n * provider already exposes.\n *\n * A throwing or empty-string provider degrades to the derivation rather than\n * to `undefined` — the host's opt-in extra should never be able to make the\n * snapshot WORSE than it was without it. A blank derivation stays blank.\n */\n private resolveActiveTab(segments: string[] | undefined): string | undefined {\n const explicit = (() => {\n if (!this.routeProvider?.getActiveTab) return undefined;\n try {\n const value = this.routeProvider.getActiveTab();\n return typeof value === 'string' && value.length > 0 ? value : undefined;\n } catch (error) {\n if (this.config.verbose) {\n console.warn(`[ui-bridge-native] routeProvider getActiveTab threw:`, error);\n }\n return undefined;\n }\n })();\n return explicit ?? deriveActiveTabFromSegments(segments);\n }\n\n /**\n * Set the device pixel ratio used to project per-element `bbox` geometry\n * into physical pixels. The React provider passes `PixelRatio.get()` here\n * once at startup. Ignores non-finite / non-positive values (keeps the\n * previous ratio) so a bad call can't zero out every bbox.\n */\n setPixelRatio(ratio: number): void {\n if (typeof ratio === 'number' && Number.isFinite(ratio) && ratio > 0) {\n this.pixelRatio = ratio;\n }\n }\n\n /** Read-only accessor for the device pixel ratio used for bbox projection. */\n getPixelRatio(): number {\n return this.pixelRatio;\n }\n\n /**\n * Set the getter for the device window size (logical dp) that reported\n * visibility is clipped against. The React provider passes\n * `() => Dimensions.get('window')` here at construction.\n *\n * Pass `null` to detach. While detached the window bounds are UNKNOWN and no\n * element is ever demoted for being outside them.\n */\n setViewportProvider(\n provider: (() => { width: number; height: number }) | null | undefined\n ): void {\n this.viewportProvider = provider ?? null;\n }\n\n /**\n * The window as a page-space rect, or `null` when it is unknown or the\n * provider returned something unusable (it throws in some RN teardown\n * paths, and a zero-size window would silently hide the entire screen).\n */\n getViewportRect(): NativePageRect | null {\n if (!this.viewportProvider) return null;\n let size: { width: number; height: number };\n try {\n size = this.viewportProvider();\n } catch (error) {\n if (this.config.verbose) {\n console.warn(`[ui-bridge-native] viewportProvider threw:`, error);\n }\n return null;\n }\n const { width, height } = size ?? {};\n if (\n typeof width !== 'number' ||\n typeof height !== 'number' ||\n !Number.isFinite(width) ||\n !Number.isFinite(height) ||\n width <= 0 ||\n height <= 0\n ) {\n return null;\n }\n return { left: 0, top: 0, right: width, bottom: height };\n }\n\n /**\n * The region `element` must reach to count as on screen: the window,\n * intersected with the measured frame of its declared `scrollAncestorId`.\n *\n * Returns `null` when neither bound is known — see {@link computeVisibility}\n * for why that means \"do not demote\" rather than \"nothing is visible\".\n * An ancestor that is not registered, or registered but not yet measured,\n * contributes nothing rather than hiding its subtree.\n */\n getClipRectFor(\n element: RegisteredNativeElement,\n viewport?: NativePageRect | null\n ): NativePageRect | null {\n // `undefined` = not supplied, read it now. `null` = the caller already\n // read it and it was UNKNOWN — don't re-read and disagree with them.\n const bounds = viewport === undefined ? this.getViewportRect() : viewport;\n const ancestorId = element.scrollAncestorId;\n if (!ancestorId) return bounds;\n\n // Single level by design: only the DECLARED ancestor is applied, and its\n // own `scrollAncestorId` is not followed. The window clip already covers\n // most of what a second level would add, and a recursive walk needs a\n // visited set to survive a declaration cycle. Revisit together.\n const ancestor = this.elements.get(ancestorId);\n if (!ancestor || ancestorId === element.id) return bounds;\n\n return intersectRects(bounds, pageRectOf(ancestor.getState()));\n }\n\n // ============================================================================\n // Snapshot Enricher Slots\n // ============================================================================\n\n /**\n * Register/replace canonical enrichers (modal/toast/undo). HMR-safe — calling\n * with a partial set merges into existing slots instead of clobbering them.\n */\n setEnrichers(e: Partial<NativeSnapshotEnrichers>): void {\n this.enrichers = { ...this.enrichers, ...e };\n }\n\n /**\n * Read-only accessor for the canonical enrichers slot. Returned object is\n * the live reference, so callers can detect \"no detector wired\" via\n * `getEnrichers().modalDetector === undefined`. Used by the test-hook HTTP\n * handlers (`control/modal/push`, `control/modal/dismiss/:id`) which need\n * to drive the ModalDetector directly without re-instantiating it.\n */\n getEnrichers(): Readonly<NativeSnapshotEnrichers> {\n return this.enrichers;\n }\n\n /**\n * Register a custom snapshot enricher. The returned object will be\n * `Object.assign`ed onto the snapshot, so use unique top-level keys to avoid\n * clobbering canonical fields. Returns a disposer.\n */\n registerSnapshotEnricher(name: string, fn: NativeSnapshotEnricher): () => void {\n this.snapshotExtras.set(name, fn);\n return () => this.unregisterSnapshotEnricher(name);\n }\n\n /** Remove a custom snapshot enricher by name */\n unregisterSnapshotEnricher(name: string): void {\n this.snapshotExtras.delete(name);\n }\n\n // ============================================================================\n // Element Management\n // ============================================================================\n\n /**\n * Register a native element\n */\n registerElement(\n id: string,\n ref: React.RefObject<NativeElementRef>,\n options: RegisterElementOptions = {}\n ): RegisteredNativeElement {\n const {\n type = 'custom',\n label,\n customActions,\n props,\n treePath = id,\n testId,\n accessibilityLabel,\n registrationRoute,\n scrollAncestorId,\n flatStyle,\n stateStyles,\n } = options;\n const actions = options.actions ?? inferActions(type, scrollAncestorId);\n\n // Create state getter\n const getState = (): NativeElementState => {\n const element = ref.current;\n if (!element) {\n return {\n mounted: false,\n visible: false,\n enabled: false,\n focused: false,\n layout: null,\n };\n }\n\n // State is populated by the element during onLayout\n // Here we return the stored state from the element's metadata\n const stored = this.elements.get(id);\n if (stored && stored.getState !== getState) {\n return stored.getState();\n }\n\n return {\n mounted: true,\n visible: true,\n enabled: true,\n focused: false,\n layout: null,\n };\n };\n\n // Create identifier getter\n const getIdentifier = (): NativeElementIdentifier => ({\n uiId: id,\n testId: testId || id,\n accessibilityLabel,\n treePath,\n });\n\n const registered: RegisteredNativeElement = {\n id,\n ref,\n type,\n label,\n actions,\n customActions,\n props,\n getState,\n getIdentifier,\n registeredAt: Date.now(),\n mounted: true,\n registrationRoute: registrationRoute ?? null,\n scrollAncestorId,\n flatStyle,\n stateStyles,\n };\n\n this.elements.set(id, registered);\n this.everHadRegistrations = true;\n\n this.emit('element:registered', { id, type, label });\n\n if (this.config.verbose) {\n console.log(`[ui-bridge-native] Registered element: ${id} (${type})`);\n }\n\n // Seed a sensible initial state so elements are immediately visible in snapshots\n // even before onLayout fires. Layout-measuring code can overwrite this later.\n //\n // For controlled-input elements (`type:'input'` with a string `props.value`),\n // also seed `state.value` from the prop so bridge consumers can read the\n // default value before the user has typed. See `updateElementProps` for\n // the corresponding re-sync path on prop changes.\n const seededState: Partial<NativeElementState> = {\n mounted: true,\n visible: true,\n enabled: true,\n focused: false,\n layout: null,\n };\n if (type === 'input' && typeof props?.value === 'string') {\n seededState.value = props.value;\n }\n // For `type:'text'` elements, surface the (dynamic) label as `state.value`\n // so bridge consumers can read text content with a uniform `state.value`\n // accessor instead of parsing the `label` field (\"Status: ...\"). The hook\n // already re-publishes the label via `updateElementMeta` when consumers\n // call `updateLabel(newLabel)` — that path also re-syncs `state.value`\n // (see `updateElementMeta`).\n if (type === 'text' && typeof label === 'string') {\n seededState.value = label;\n }\n this.updateElementState(id, seededState);\n\n return registered;\n }\n\n /**\n * Unregister an element\n */\n unregisterElement(id: string): void {\n const element = this.elements.get(id);\n if (element) {\n this.elements.delete(id);\n this.emit('element:unregistered', { id });\n\n if (this.config.verbose) {\n console.log(`[ui-bridge-native] Unregistered element: ${id}`);\n }\n }\n }\n\n /**\n * Get a registered element\n */\n getElement(id: string): RegisteredNativeElement | undefined {\n return this.elements.get(id);\n }\n\n /**\n * Get all registered elements\n */\n getAllElements(): RegisteredNativeElement[] {\n return Array.from(this.elements.values());\n }\n\n /**\n * Get all registered elements that are visible AND have a measured layout.\n *\n * This is the *strict* visibility filter: requires `state.visible === true`\n * AND `state.layout !== null`. Use this when you need both signals\n * (e.g. coord-based tap, where you need an actual rect to hit-test against).\n *\n * Callers driving an LLM agent typically want\n * {@link getMountedVisibleElements} instead — that variant accepts\n * elements that *should* be on screen (visible:true) but whose first\n * `onLayout` has not yet fired. Without it, a snapshot taken in the gap\n * between mount and the first layout pass returns 0 elements on a fully\n * populated screen.\n */\n getVisibleElements(): RegisteredNativeElement[] {\n return this.getAllElements().filter((e) => {\n const state = e.getState();\n return state.visible && state.layout !== null;\n });\n }\n\n /**\n * Get all registered elements marked as visible (regardless of layout).\n *\n * Looser than {@link getVisibleElements}: includes elements whose\n * `onLayout` callback has not yet fired (so `layout === null`). React\n * Native's `onLayout` is async — there's a one-tick window after mount\n * where elements are in the tree, the user *sees* them, but the\n * registry hasn't received their measurements yet. Excluding those\n * elements makes `getSnapshot?visibleOnly=true` return 0 on a populated\n * screen, which is a worse failure mode than including a few elements\n * we can't yet locate spatially.\n *\n * Used by `createSnapshot`'s `visibleOnly` filter and by the\n * `getSnapshot` / `getElements` handlers. Each emitted element carries a\n * `visibility` discriminator (`\"visible\"` / `\"likely-visible\"`) so\n * agents that *do* require a known rect can branch downstream.\n */\n getMountedVisibleElements(): RegisteredNativeElement[] {\n return this.getAllElements().filter((e) => e.getState().visible);\n }\n\n /**\n * Get elements registered on a specific route (for page-scoped filtering)\n */\n getElementsForRoute(route: string): RegisteredNativeElement[] {\n return this.getAllElements().filter((e) => e.registrationRoute === route);\n }\n\n /**\n * Mark elements registered on a route as off-screen (visible: false, layout: null).\n *\n * Use this when a screen loses focus but stays mounted — common in React Navigation\n * tab navigators where inactive tabs remain in the tree. Without this call, stale\n * `layout` data lingers in snapshots and makes off-screen elements look rendered.\n *\n * Does NOT unregister the elements — they stay registered so the user's next visit\n * re-measures them via `onLayout` without re-mount cost. Elements without a\n * `registrationRoute` (app-wide registrations) are untouched.\n */\n markRouteOffscreen(route: string): void {\n // Guard against accidental global wipes. Elements registered without a\n // route have `registrationRoute: null` — passing null/empty here would\n // match every globally-registered element and erase their layouts.\n if (route == null || route === '') {\n if (this.config.verbose) {\n console.warn(\n `[ui-bridge-native] markRouteOffscreen called with null/empty route — ignoring`\n );\n }\n return;\n }\n let cleared = 0;\n for (const element of this.elements.values()) {\n if (element.registrationRoute === route) {\n this.updateElementState(element.id, {\n visible: false,\n layout: null,\n });\n cleared++;\n }\n }\n if (this.config.verbose && cleared > 0) {\n console.log(`[ui-bridge-native] Marked ${cleared} elements offscreen for route: ${route}`);\n }\n }\n\n /**\n * Re-measure every mounted-visible element's geometry via its stored React\n * ref and write the fresh coordinates into the registry (\"measure-on-\n * snapshot\").\n *\n * Why: element geometry is otherwise captured ONCE at mount time\n * (`onLayout` + `measureInWindow` in `useUIElement`) and RN never re-fires\n * `onLayout` on pure translation — scrolling a virtualized list\n * (FlashList), recycling a cell, a keyboard shift or an orientation change\n * all move elements WITHOUT updating the stored `state.layout`. Snapshot\n * consumers (vision analyzers hit-testing `bbox`, coord-based tap) then\n * operate on stale positions. Re-measuring at READ time is correct\n * regardless of what moved the element and needs zero per-consumer wiring:\n * every registry entry already stores its ref (see `registerElement`).\n *\n * Per-element outcomes:\n * - non-zero dims → write a fresh full layout (same state shape as the\n * mount-time measure loop in `useUIElement`); counted as `measured`.\n * - zero dims AND the element previously had a non-null `state.layout` →\n * the view collapsed / left the screen; clear to\n * `{ visible: false, layout: null }` (same shape `markRouteOffscreen`\n * writes); counted as `cleared`.\n * - zero dims and it never had a layout → leave state untouched (element\n * in the mount→first-onLayout gap; don't demote `likely-visible`);\n * counted as `skipped`.\n * - no ref / no callable `measureInWindow` (test fixtures, web) → leave\n * untouched; counted as `skipped`.\n *\n * The whole sweep races an overall timeout (default 250 ms) so a dead ref\n * whose `measureInWindow` never calls back can never hang a snapshot: the\n * returned promise resolves at the deadline with whatever counts have\n * accumulated. Late callbacks may still write state afterwards — harmless,\n * freshest data wins. Never throws.\n *\n * Non-React core module on purpose — `measureInWindow` is duck-typed off\n * the stored ref rather than imported from `react-native` (see the\n * `projectBbox` doc comment for why this file must not import RN).\n */\n async refreshMeasurements(options?: {\n timeoutMs?: number;\n }): Promise<{ measured: number; cleared: number; skipped: number }> {\n const timeoutMs =\n typeof options?.timeoutMs === 'number' &&\n Number.isFinite(options.timeoutMs) &&\n options.timeoutMs > 0\n ? options.timeoutMs\n : 250;\n\n const counts = { measured: 0, cleared: 0, skipped: 0 };\n const pending: Array<Promise<void>> = [];\n\n for (const element of this.getMountedVisibleElements()) {\n const node = element.ref?.current as\n | (NativeElementRef & {\n measureInWindow?: (\n callback: (pageX: number, pageY: number, w: number, h: number) => void\n ) => void;\n })\n | null\n | undefined;\n\n if (!node || typeof node.measureInWindow !== 'function') {\n counts.skipped++;\n continue;\n }\n\n const id = element.id;\n pending.push(\n new Promise<void>((resolve) => {\n let settled = false;\n try {\n node.measureInWindow!((pageX: number, pageY: number, w: number, h: number) => {\n if (settled) return;\n settled = true;\n try {\n if (w > 0 && h > 0) {\n this.updateElementState(id, {\n mounted: true,\n visible: true,\n enabled: true,\n focused: false,\n layout: { x: pageX, y: pageY, width: w, height: h, pageX, pageY },\n });\n counts.measured++;\n } else if (this.elements.get(id)?.getState().layout != null) {\n // Collapsed / off-screen: it HAD a measured rect and now\n // reports zeros. Clear it so stale coords can't poison the\n // snapshot (same shape as markRouteOffscreen).\n this.updateElementState(id, { visible: false, layout: null });\n counts.cleared++;\n } else {\n counts.skipped++;\n }\n } finally {\n resolve();\n }\n });\n } catch {\n // A throwing measureInWindow must never break the sweep.\n if (!settled) {\n settled = true;\n counts.skipped++;\n resolve();\n }\n }\n })\n );\n }\n\n if (pending.length > 0) {\n await new Promise<void>((resolve) => {\n const timer = setTimeout(resolve, timeoutMs);\n void Promise.all(pending).then(() => {\n clearTimeout(timer);\n resolve();\n });\n });\n }\n\n return counts;\n }\n\n /**\n * Update element state\n */\n updateElementState(id: string, state: Partial<NativeElementState>): void {\n const element = this.elements.get(id);\n if (element) {\n // Create a new getState that includes the updated state\n const currentState = element.getState();\n const newState = { ...currentState, ...state };\n\n const updated: RegisteredNativeElement = {\n ...element,\n getState: () => newState,\n };\n\n this.elements.set(id, updated);\n this.emit('element:stateChanged', { id, state: newState });\n }\n }\n\n /**\n * Update an element's descriptive metadata (label / accessibilityLabel /\n * testId). Sister to {@link updateElementState} (which carries layout +\n * visibility) and {@link updateElementProps} (which carries event handlers).\n *\n * Idempotent — if every passed field equals the existing value, the call\n * returns without mutating the entry or emitting an event. This keeps\n * `useUIElement().updateLabel(...)` cheap when consumers re-publish from a\n * render path that produces the same string on every tick.\n *\n * Returns `true` when the entry was mutated, `false` otherwise. Callers\n * that want to gate a `console.warn` on no-op invocations can use the\n * return value instead of recomputing equality.\n */\n updateElementMeta(\n id: string,\n meta: { label?: string; accessibilityLabel?: string; testId?: string }\n ): boolean {\n const element = this.elements.get(id);\n if (!element) return false;\n\n // The `testId` on a registered element lives inside the identifier\n // closure (see registerElement's `getIdentifier`). To rebuild it we\n // need the current value — read it via the existing identifier and\n // overlay the new one if provided.\n const currentIdentifier = element.getIdentifier();\n const nextLabel = meta.label !== undefined ? meta.label : element.label;\n const nextAccessibilityLabel =\n meta.accessibilityLabel !== undefined\n ? meta.accessibilityLabel\n : currentIdentifier.accessibilityLabel;\n const nextTestId = meta.testId !== undefined ? meta.testId : currentIdentifier.testId;\n\n const labelChanged = nextLabel !== element.label;\n const accessibilityLabelChanged =\n nextAccessibilityLabel !== currentIdentifier.accessibilityLabel;\n const testIdChanged = nextTestId !== currentIdentifier.testId;\n\n if (!labelChanged && !accessibilityLabelChanged && !testIdChanged) {\n return false;\n }\n\n const updated: RegisteredNativeElement = {\n ...element,\n label: nextLabel,\n getIdentifier: (): NativeElementIdentifier => ({\n uiId: id,\n testId: nextTestId,\n accessibilityLabel: nextAccessibilityLabel,\n treePath: currentIdentifier.treePath,\n }),\n };\n this.elements.set(id, updated);\n\n // For text-type elements, mirror the new label into `state.value` so\n // bridge consumers can read text content with a uniform `state.value`\n // accessor. Initial seed lives in `registerElement`; this keeps the\n // mirror in sync when consumers call `updateLabel(newLabel)` from a\n // state-driven render path (e.g. `Status: ${connected ? 'online' : 'offline'}`).\n if (element.type === 'text' && labelChanged && typeof nextLabel === 'string') {\n this.updateElementState(id, { value: nextLabel });\n }\n\n // Reuse `element:registered` rather than minting a new event — downstream\n // consumers already subscribe to it for label/identifier diffs, and\n // adding a new BridgeEventType ('element:metaChanged') would force a\n // SemVer-major bump on every snapshot consumer.\n this.emit('element:registered', {\n id,\n type: element.type,\n label: nextLabel,\n });\n\n return true;\n }\n\n /**\n * Update element props (for action execution).\n *\n * Side effect for `type: 'input'` elements: when `props.value` is a string,\n * mirror it into `state.value` so AI drivers reading the registry don't see\n * `state.value === undefined` until the user types. Before this mirror,\n * controlled-input consumers (`<TextInput value={x} onChangeText={setX} />`\n * with `captureProps({ value: x, onChangeText: setX })`) registered an\n * input whose `state.value` only became defined after the FIRST\n * `onChangeText` call — bridge consumers couldn't read the default value\n * (e.g. a pre-populated API-URL input) until someone typed into it.\n *\n * Re-runs on every `updateElementProps` so a parent passing a fresh\n * `value` prop (controlled re-render) keeps the registry in sync. The\n * mirror is gated on `type === 'input'` to avoid touching non-input\n * elements that may carry an unrelated `value` prop (e.g. a Switch's\n * boolean value, which lives on `state.checked`).\n */\n updateElementProps(id: string, props: Record<string, unknown>): void {\n const element = this.elements.get(id);\n if (element) {\n const updated: RegisteredNativeElement = {\n ...element,\n props: { ...element.props, ...props },\n };\n this.elements.set(id, updated);\n\n // Controlled-input value mirror — see doc comment above.\n if (\n element.type === 'input' &&\n Object.prototype.hasOwnProperty.call(props, 'value') &&\n typeof props.value === 'string'\n ) {\n const currentState = updated.getState();\n if (currentState.value !== props.value) {\n this.updateElementState(id, { value: props.value });\n }\n }\n }\n }\n\n /**\n * Update element style for design review\n */\n updateElementStyle(\n id: string,\n flatStyle: Record<string, unknown>,\n stateStyles?: {\n pressed?: Record<string, unknown>;\n focused?: Record<string, unknown>;\n disabled?: Record<string, unknown>;\n }\n ): void {\n const element = this.elements.get(id);\n if (element) {\n const updated: RegisteredNativeElement = {\n ...element,\n flatStyle,\n ...(stateStyles !== undefined ? { stateStyles } : {}),\n };\n this.elements.set(id, updated);\n }\n }\n\n /**\n * Get element style for design review\n */\n getElementStyle(id: string): Record<string, unknown> | null {\n const element = this.elements.get(id);\n return element?.flatStyle ?? null;\n }\n\n /**\n * Find element by testID\n */\n findByTestId(testId: string): RegisteredNativeElement | undefined {\n for (const element of this.elements.values()) {\n const identifier = element.getIdentifier();\n if (identifier.testId === testId) {\n return element;\n }\n }\n return undefined;\n }\n\n /**\n * Find elements by type\n */\n findByType(type: NativeElementType): RegisteredNativeElement[] {\n return Array.from(this.elements.values()).filter((e) => e.type === type);\n }\n\n // ============================================================================\n // Component Management\n // ============================================================================\n\n /**\n * Register a component\n */\n registerComponent(id: string, options: RegisterComponentOptions): RegisteredNativeComponent {\n const { name, description, actions = [], elementIds } = options;\n\n const registered: RegisteredNativeComponent = {\n id,\n name,\n description,\n // Closed field list, applied once — see `toRegisteredComponentActions`.\n actions: toRegisteredComponentActions(actions),\n elementIds,\n registeredAt: Date.now(),\n mounted: true,\n };\n\n this.components.set(id, registered);\n\n this.emit('component:registered', { id, name });\n\n if (this.config.verbose) {\n console.log(`[ui-bridge-native] Registered component: ${id} (${name})`);\n }\n\n return registered;\n }\n\n /**\n * Update a registered component's declaration in place — name, description,\n * actions, elementIds.\n *\n * Sister to {@link updateElementMeta}, and it exists for the same reason one\n * level up. `registerComponent` publishes the declaration exactly once, and\n * `useUIComponent` registers on mount and never again, so an action whose\n * `label` carries a count, an action that only exists while a row is\n * selected, a `paramSchema` that widens once options load, or an `elementIds`\n * list that grows after mount, all published their mount-time shape to\n * `/control/components` forever. PR #176 closed that hole for an ELEMENT's\n * label; this closes it for a COMPONENT's declaration.\n *\n * **Idempotent by VALUE over the PUBLISHED shape.** `handler` identity is\n * excluded from the comparison — call sites pass inline closures that are\n * freshly allocated every render, so including it would report a change on\n * every call and make the door useless for a render-path publisher. The\n * newest handlers are still STORED whenever `actions` is supplied, which is\n * the other half of the same defect: without it the registry keeps the\n * closure from the render that registered the component, so a handler reading\n * component state read the state as it was at mount.\n *\n * Returns `true` when the published shape changed and an event was emitted,\n * `false` otherwise — the same contract as `updateElementMeta`, so a caller\n * can gate a warning or a state write on a real change.\n */\n updateComponentMeta(id: string, meta: UpdateComponentMetaOptions): boolean {\n const component = this.components.get(id);\n if (!component) return false;\n\n const nextName = meta.name !== undefined ? meta.name : component.name;\n const nextDescription =\n meta.description !== undefined ? meta.description : component.description;\n const nextActions =\n meta.actions !== undefined ? toRegisteredComponentActions(meta.actions) : component.actions;\n const nextElementIds = meta.elementIds !== undefined ? meta.elementIds : component.elementIds;\n\n const changed =\n nextName !== component.name ||\n nextDescription !== component.description ||\n !sameElementIds(nextElementIds, component.elementIds) ||\n publishedActionSignature(nextActions) !== publishedActionSignature(component.actions);\n\n // Nothing published changed AND no fresh handlers were offered: leave the\n // stored entry untouched so its identity stays stable for consumers holding\n // a reference.\n if (!changed && meta.actions === undefined) return false;\n\n // Store even when `changed` is false, provided actions were supplied: the\n // handlers in `nextActions` are the CURRENT render's closures. Keeping the\n // old ones is exactly how a component action ends up reading state from the\n // render it was first declared in.\n this.components.set(id, {\n ...component,\n name: nextName,\n description: nextDescription,\n actions: nextActions,\n elementIds: nextElementIds,\n });\n\n if (!changed) return false;\n\n // Reuse `component:registered` rather than minting a\n // 'component:metaChanged' BridgeEventType — same reasoning as\n // `updateElementMeta`'s reuse of `element:registered`: a new event type is a\n // breaking change for every consumer switching exhaustively over the union.\n this.emit('component:registered', { id, name: nextName });\n\n if (this.config.verbose) {\n console.log(`[ui-bridge-native] Updated component: ${id} (${nextName})`);\n }\n\n return true;\n }\n\n /**\n * Unregister a component\n */\n unregisterComponent(id: string): void {\n const component = this.components.get(id);\n if (component) {\n this.components.delete(id);\n this.emit('component:unregistered', { id });\n\n if (this.config.verbose) {\n console.log(`[ui-bridge-native] Unregistered component: ${id}`);\n }\n }\n }\n\n /**\n * Get a registered component\n */\n getComponent(id: string): RegisteredNativeComponent | undefined {\n return this.components.get(id);\n }\n\n /**\n * Get all registered components\n */\n getAllComponents(): RegisteredNativeComponent[] {\n return Array.from(this.components.values());\n }\n\n // ============================================================================\n // Workflow Management\n // ============================================================================\n\n /**\n * Register a workflow\n */\n registerWorkflow(workflow: Workflow): void {\n this.workflows.set(workflow.id, workflow);\n\n if (this.config.verbose) {\n console.log(`[ui-bridge-native] Registered workflow: ${workflow.id}`);\n }\n }\n\n /**\n * Unregister a workflow\n */\n unregisterWorkflow(id: string): void {\n this.workflows.delete(id);\n }\n\n /**\n * Get a workflow\n */\n getWorkflow(id: string): Workflow | undefined {\n return this.workflows.get(id);\n }\n\n /**\n * Get all workflows\n */\n getAllWorkflows(): Workflow[] {\n return Array.from(this.workflows.values());\n }\n\n // ============================================================================\n // Event System\n // ============================================================================\n\n /**\n * Subscribe to events\n */\n on<T = unknown>(type: BridgeEventType, listener: BridgeEventListener<T>): () => void {\n if (!this.eventListeners.has(type)) {\n this.eventListeners.set(type, new Set());\n }\n this.eventListeners.get(type)!.add(listener as BridgeEventListener);\n\n // Return unsubscribe function\n return () => this.off(type, listener);\n }\n\n /**\n * Unsubscribe from events\n */\n off<T = unknown>(type: BridgeEventType, listener: BridgeEventListener<T>): void {\n this.eventListeners.get(type)?.delete(listener as BridgeEventListener);\n }\n\n /**\n * Emit an event\n */\n emit(type: BridgeEventType, data: unknown): void {\n const event: BridgeEvent = {\n type,\n timestamp: Date.now(),\n data,\n };\n\n // Notify listeners\n const listeners = this.eventListeners.get(type);\n if (listeners) {\n for (const listener of listeners) {\n try {\n listener(event);\n } catch (error) {\n console.error(`[ui-bridge-native] Event listener error:`, error);\n }\n }\n }\n\n // Notify global handler\n if (this.config.onEvent) {\n try {\n this.config.onEvent(event);\n } catch (error) {\n console.error(`[ui-bridge-native] Global event handler error:`, error);\n }\n }\n }\n\n // ============================================================================\n // Snapshots\n // ============================================================================\n\n /**\n * Create a snapshot of the current state.\n *\n * Route resolution: `routeInfo` wins when provided. Otherwise — and this\n * is the path the default `getSnapshot` HTTP handler takes — we fall back\n * to the registered `routeProvider`. This means callers that never wire a\n * server-level override (the bare-server / cloud-relay path) still get a\n * populated `currentRoute` field as long as `setRouteProvider` was called\n * on the registry.\n *\n * `activeTab` resolves through {@link resolveActiveTab} on BOTH branches. An\n * explicit `routeInfo.activeTab` wins outright; otherwise a registered\n * provider's `getActiveTab()` answers and the Expo Router derivation is the\n * fallback. Deriving straight from `routeInfo.segments` here instead — which\n * is what this branch did when `activeTab` was introduced — silently ignored\n * `RouteProvider.getActiveTab` on the ONLY path that serves\n * `control/snapshot` once `setRouteProvider` is wired (the server installs a\n * `getSnapshot` override that passes `routeInfo`), so the opt-in hook for an\n * app whose visible pane is decoupled from the router reached no consumer.\n */\n createSnapshot(\n routeInfo?: {\n currentRoute?: string | null;\n segments?: string[];\n /**\n * Explicit active tab for callers that own the answer outright. Omit to\n * let the registered `routeProvider` / the segment derivation resolve it.\n */\n activeTab?: string | null;\n },\n options?: { visibleOnly?: boolean; currentRouteOnly?: boolean }\n ): NativeBridgeSnapshot {\n // Resolve route info: prefer the explicit argument, fall back to a\n // registered route provider. We treat an explicitly-passed `routeInfo`\n // (even if both fields are null/undefined) as \"the caller is in charge\"\n // so server-layer overrides that pass `{currentRoute: null}` keep working.\n const resolvedRoute: {\n currentRoute: string | null;\n segments: string[] | undefined;\n activeTab: string | undefined;\n } = (() => {\n if (routeInfo !== undefined) {\n const explicit =\n typeof routeInfo.activeTab === 'string' && routeInfo.activeTab.length > 0\n ? routeInfo.activeTab\n : undefined;\n return {\n currentRoute: routeInfo.currentRoute ?? null,\n segments: routeInfo.segments,\n activeTab: explicit ?? this.resolveActiveTab(routeInfo.segments),\n };\n }\n if (this.routeProvider) {\n try {\n const segments = this.routeProvider.getSegments?.();\n return {\n currentRoute: this.routeProvider.getCurrentRoute() ?? null,\n segments,\n activeTab: this.resolveActiveTab(segments),\n };\n } catch (error) {\n if (this.config.verbose) {\n console.warn(`[ui-bridge-native] routeProvider getCurrentRoute threw:`, error);\n }\n return { currentRoute: null, segments: undefined, activeTab: undefined };\n }\n }\n return { currentRoute: null, segments: undefined, activeTab: undefined };\n })();\n\n // visibleOnly uses the *looser* mounted-visible filter so a snapshot\n // taken in the gap between mount and the first `onLayout` doesn't\n // return 0 elements on a populated screen. Each element in the\n // payload carries a `visibility` field so agents can branch on\n // measured vs unmeasured.\n let elements = options?.visibleOnly ? this.getMountedVisibleElements() : this.getAllElements();\n\n // Filter to elements that belong on the current route. Route-agnostic\n // elements (no `registrationRoute`) pass through too — see the\n // `matchesCurrentRoute` doc comment for the rationale (tab bars, modal\n // hosts and other app-root registrations have a null route and apply to\n // every screen).\n if (options?.currentRouteOnly && resolvedRoute.currentRoute) {\n const currentRoute = resolvedRoute.currentRoute;\n elements = elements.filter((e) => matchesCurrentRoute(e.registrationRoute, currentRoute));\n }\n\n // Read ONCE per snapshot, not once per element: it is a `Dimensions.get`\n // call behind a try/catch, and a rotation landing mid-map would otherwise\n // give elements in the SAME snapshot different clip regions.\n const viewport = this.getViewportRect();\n\n const snapshot: NativeBridgeSnapshot = {\n timestamp: Date.now(),\n elements: elements.map((e) => {\n const handlers = extractHandlerNames(e.props);\n const state = e.getState();\n const { visibility, visibilityReason } = computeVisibility(\n state,\n this.getClipRectFor(e, viewport)\n );\n const bbox = projectBbox(state, visibility, this.pixelRatio);\n const vision = projectVisionFields({\n type: e.type,\n label: e.label,\n // Real interactivity signal: the names of props that are actually\n // functions (onPress/onChangeText/...). NOT `e.actions`, which\n // `inferActions` synthesizes press/click onto for every element —\n // using it would mark plain text/view nodes interactable.\n handlerNames: handlers,\n state,\n flatStyle: e.flatStyle,\n });\n return {\n id: e.id,\n type: e.type,\n label: e.label,\n identifier: e.getIdentifier(),\n state,\n actions: e.actions,\n customActions: serializeElementCustomActions(e.customActions),\n registeredHandlers: handlers.length > 0 ? handlers : undefined,\n registrationRoute: e.registrationRoute,\n visibility,\n ...(visibilityReason ? { visibilityReason } : {}),\n ...(bbox ? { bbox } : {}),\n ...vision,\n };\n }),\n components: this.getAllComponents().map((c) => ({\n id: c.id,\n name: c.name,\n description: c.description,\n actions: c.actions.map((a) => a.id),\n elementIds: c.elementIds,\n })),\n workflows: this.getAllWorkflows().map((w) => ({\n id: w.id,\n name: w.name,\n description: w.description,\n stepCount: w.steps.length,\n })),\n currentRoute: resolvedRoute.currentRoute,\n segments: resolvedRoute.segments,\n // Canonical aliases, spelled the way the web SDK's `BridgeSnapshot`\n // spells them so a cross-platform consumer reads one field name on both\n // platforms. Omitted rather than nulled when unknown — same convention\n // as the web fields, and it keeps the emitted shape byte-identical for\n // hosts that wire no route provider.\n ...(resolvedRoute.currentRoute ? { route: resolvedRoute.currentRoute } : {}),\n ...(resolvedRoute.activeTab ? { activeTab: resolvedRoute.activeTab } : {}),\n registration: this.getRegistrationCoverage(),\n };\n\n // Include app identification metadata so consumers can identify which\n // app produced this snapshot without a separate health probe.\n if (this.appInfo) {\n snapshot.appInfo = this.appInfo;\n }\n\n // Canonical enrichers — each in its own try/catch so a misbehaving tracker\n // can never break the rest of the snapshot.\n if (this.enrichers.modalDetector) {\n try {\n snapshot.modalStack = this.enrichers.modalDetector.getSnapshotModalContext();\n } catch (error) {\n if (this.config.verbose) {\n console.warn(`[ui-bridge-native] modalDetector enricher threw:`, error);\n }\n }\n }\n if (this.enrichers.toastCapture) {\n try {\n snapshot.toasts = this.enrichers.toastCapture.getSnapshotToastContext();\n } catch (error) {\n if (this.config.verbose) {\n console.warn(`[ui-bridge-native] toastCapture enricher threw:`, error);\n }\n }\n }\n if (this.enrichers.undoTracker) {\n try {\n snapshot.undoRedo = this.enrichers.undoTracker.getSnapshotUndoContext();\n } catch (error) {\n if (this.config.verbose) {\n console.warn(`[ui-bridge-native] undoTracker enricher threw:`, error);\n }\n }\n }\n\n // Custom enrichers — keys assign-merged onto the snapshot\n if (this.snapshotExtras.size > 0) {\n const ctx = { elements, currentRoute: resolvedRoute.currentRoute };\n for (const [name, fn] of this.snapshotExtras) {\n try {\n const extra = fn(ctx);\n if (extra && typeof extra === 'object') {\n Object.assign(snapshot, extra);\n }\n } catch (error) {\n if (this.config.verbose) {\n console.warn(`[ui-bridge-native] snapshot enricher \"${name}\" threw:`, error);\n }\n }\n }\n }\n\n return snapshot;\n }\n\n /**\n * Get registry statistics\n */\n getStats(): { elements: number; components: number; workflows: number } {\n return {\n elements: this.elements.size,\n components: this.components.size,\n workflows: this.workflows.size,\n };\n }\n\n /**\n * Compute registration coverage metadata for the current registry state.\n *\n * Groups currently-registered elements by `registrationRoute`, bucketing\n * elements without a route under `'?'`. `everHadRegistrations` is sticky —\n * once true, it stays true for the lifetime of the registry instance.\n */\n getRegistrationCoverage(): NativeRegistrationCoverage {\n const byRoute: Record<string, number> = {};\n for (const element of this.elements.values()) {\n const key =\n element.registrationRoute == null || element.registrationRoute === ''\n ? '?'\n : element.registrationRoute;\n byRoute[key] = (byRoute[key] ?? 0) + 1;\n }\n return {\n totalRegistered: this.elements.size,\n everHadRegistrations: this.everHadRegistrations,\n byRoute,\n };\n }\n\n /**\n * Clear all registrations\n */\n clear(): void {\n this.elements.clear();\n this.components.clear();\n this.workflows.clear();\n\n if (this.config.verbose) {\n console.log(`[ui-bridge-native] Registry cleared`);\n }\n }\n}\n\n// ============================================================================\n// Global Registry\n// ============================================================================\n\nlet globalRegistry: NativeUIBridgeRegistry | null = null;\n\n/**\n * Set the global registry\n */\nexport function setGlobalRegistry(registry: NativeUIBridgeRegistry): void {\n globalRegistry = registry;\n}\n\n/**\n * Get the global registry\n */\nexport function getGlobalRegistry(): NativeUIBridgeRegistry | null {\n return globalRegistry;\n}\n\n/**\n * Reset the global registry\n */\nexport function resetGlobalRegistry(): void {\n globalRegistry?.clear();\n globalRegistry = null;\n}\n","/**\n * Action effect defaults for `@qontinui/ui-bridge-native`.\n *\n * Plan `2026-08-20-ui-bridge-action-declaration-shape`, Phase 4.\n *\n * `IREffect` (\"read\" | \"write\" | \"destructive\") has exactly one job: **exclude\n * destructive actions from automatic walks.** Two sources feed it, in order:\n *\n * 1. `action.effect` — the author's explicit per-registration declaration.\n * 2. `NATIVE_STANDARD_ACTION_EFFECTS[action.id]` — the static default below.\n *\n * **1 wins.** A static `press → write` map is wrong precisely on a delete\n * control — guaranteed wrong in the one case the annotation exists for — and it\n * fails *open*, so an unmarked destructive action gets walked.\n *\n * DUPLICATE of `@qontinui/ui-bridge` `src/core/action-effect.ts` +\n * `src/native/core/action-effect.ts`, and deliberately not a re-export:\n * `@qontinui/ui-bridge` is an OPTIONAL peer of this package, so a consumer may\n * install `@qontinui/ui-bridge-native` alone. Same constraint that keeps\n * `ActionHandler` / `ComponentAction` / `IREffect` duplicated in\n * `./types` — see the long note there. KEEP IN SYNC.\n */\n\nimport type { IREffect, NativeStandardAction } from './types';\n\n/**\n * Static default effect for each {@link NativeStandardAction} verb.\n *\n * Typed `Record<NativeStandardAction, IREffect>` so adding a verb without\n * classifying it is a compile error — a *map* silently falling behind the\n * *union* it describes is exactly the drift class this plan exists to fix.\n *\n * **No verb maps to `'destructive'`, and none ever should.** Destructiveness\n * is a property of what a control does, not of the verb used to reach it;\n * `'destructive'` is reachable only through an explicit `effect`.\n *\n * The non-obvious calls, justified:\n *\n * - **`longPress` → `read`.** The touch analogue of a right-click: it reveals\n * a context menu / selection affordance. Long-press is *associated* with\n * delete on mobile, but it only surfaces the option — the delete is a\n * separate press with its own effect.\n * - **`swipe` → `write`.** Genuinely ambiguous, and it resolves the other way\n * from `longPress`: a swipe is sometimes just a scroll gesture (read), but\n * swipe-to-delete / swipe-to-archive **commits on the gesture itself**, with\n * nothing in the verb to tell the two apart. It takes the more cautious\n * classification, and a swipe-to-delete row must still declare\n * `effect: 'destructive'`.\n * - **`focus` / `blur` → `read`.** They move focus, which is UI state, not\n * persistent state.\n * - **`scrollIntoView` → `read`.** It moves the declared scroll container's\n * content offset (UI state) and fires no element handler.\n *\n * Note this union carries `click`, `setValue` and `scrollIntoView` that the\n * `@qontinui/ui-bridge` `native/core` copy does not — a real divergence\n * between the two native unions, not a sync error.\n */\nexport const NATIVE_STANDARD_ACTION_EFFECTS: Record<NativeStandardAction, IREffect> = {\n // --- Reads ---------------------------------------------------------------\n focus: 'read',\n blur: 'read',\n scroll: 'read',\n scrollIntoView: 'read',\n longPress: 'read',\n\n // --- Writes --------------------------------------------------------------\n press: 'write',\n click: 'write',\n doubleTap: 'write',\n type: 'write',\n setValue: 'write',\n clear: 'write',\n swipe: 'write',\n toggle: 'write',\n};\n\n/**\n * The static default for a native action id, or `undefined` when the id is not\n * one of the native standard verbs (the normal case for a `ComponentAction`,\n * whose ids are free-form).\n *\n * `undefined` means **unknown**, not \"safe\" — a caller that walks unknown\n * actions is choosing to fail open and should say so.\n */\nexport function nativeStandardActionEffect(actionId: string): IREffect | undefined {\n return Object.prototype.hasOwnProperty.call(NATIVE_STANDARD_ACTION_EFFECTS, actionId)\n ? NATIVE_STANDARD_ACTION_EFFECTS[actionId as NativeStandardAction]\n : undefined;\n}\n\n/**\n * Resolve the effective annotation for a declared action: **explicit\n * declaration first, static verb map second.**\n */\nexport function resolveActionEffect(action: {\n id: string;\n effect?: IREffect;\n}): IREffect | undefined {\n return action.effect ?? nativeStandardActionEffect(action.id);\n}\n","/**\n * Parameter-schema validation for component actions.\n *\n * Plan `2026-08-20-ui-bridge-action-declaration-shape`, Phase 2.\n *\n * `ComponentAction.paramSchema` is **published to agents** — it is spread onto\n * `/control/components` and `/control/component/:id` by\n * `server/handlers.ts` `annotateComponentWithInvocationPaths`, and four live\n * runner consumers read it off the wire. Until Phase 2 nothing enforced it, so\n * an agent that read the schema and sent conforming params had no guarantee\n * the handler agreed. That is worse than publishing nothing: it invites trust\n * it cannot honour. This module is what makes the declaration enforceable.\n *\n * ---------------------------------------------------------------------------\n * THE SUPPORTED SUBSET — this is a CROSS-REPO CONTRACT\n * ---------------------------------------------------------------------------\n *\n * `qontinui-runner` reads these same schemas\n * (`workflow_generation/wrapper_manifest.rs`, `commands/command_interpreter.rs`,\n * `bin/wrappers_mcp.rs`), and `command_interpreter.rs` feeds one to an LLM and\n * asks it to produce conforming args. So the grammar below is not a private\n * implementation detail — changing it changes what those consumers may emit.\n *\n * **No dependency.** `@qontinui/ui-bridge` ships to browsers and has exactly\n * one runtime dependency (`dom-accessibility-api`). A full JSON Schema\n * validator (`ajv` and friends) would be the SDK's first heavyweight runtime\n * dep, which the plan rejected on bundle size. Hence a hand-implemented subset,\n * documented here rather than inferred from the code.\n *\n * **Two accepted top-level shapes**, because `useUIComponent`'s own author-\n * facing doc has always sanctioned both:\n *\n * 1. **Object-schema form** — the shape `paramSchemaOf()`\n * (`@qontinui/ui-bridge-wrapper`) emits:\n *\n * ```jsonc\n * { \"type\": \"object\",\n * \"properties\": { \"username\": { \"type\": \"string\" },\n * \"remember\": { \"type\": \"boolean\" } },\n * \"required\": [\"username\"],\n * \"additionalProperties\": false }\n * ```\n *\n * 2. **Map form** — the lightweight shorthand the doc describes as\n * \"a map of `{ paramName: \"string\" | \"number\" | ... }`\":\n *\n * ```jsonc\n * { \"username\": \"string\", \"count\": { \"type\": \"integer\", \"minimum\": 1 } }\n * ```\n *\n * **Disambiguation rule** (deterministic, no heuristics). The schema is read as\n * form 1 **iff** either:\n *\n * - it carries a `properties` object; or\n * - `type === \"object\"` **and every other top-level key is a JSON Schema\n * object-applicable keyword** ({@link OBJECT_SCHEMA_KEYWORDS}).\n *\n * Everything else is form 2. So `{ \"type\": \"string\" }` is a map declaring one\n * param named `type` of type `string`, not a top-level string schema — a\n * params bag is always an object, so a non-object top-level `type` cannot be\n * describing the bag.\n *\n * ⚠️ **The second clause is load-bearing, and a naive `type === \"object\"` test\n * is a silent-validation-loss bug.** Consider the map form\n * `{ \"type\": \"object\", \"id\": \"string\" }` — an action taking a param literally\n * named `type` whose hint is `\"object\"`, plus an `id`. Reading that as form 1\n * would find no `properties`, express no constraint, and **silently drop every\n * sibling declaration in the map**: `validateActionParams(schema, { id: 12345 })`\n * would answer `{ valid: true }` for a schema that plainly says `id` is a\n * string. `id` is not an object keyword, so the keyword test sends it to form 2\n * and both params validate. A param named `type` is not exotic — it is one of\n * the most common names there is.\n *\n * The one genuinely ambiguous input is a bare `{ \"type\": \"object\" }`: it is\n * both an empty object schema and a one-entry map declaring a param named\n * `type` of type `object`. It is read as form 1 (the empty object schema),\n * which constrains nothing either way, so the choice is unobservable except in\n * combination with `additionalProperties: false` — where form 1 is clearly the\n * intended reading.\n *\n * ### Map form is a TYPE hint, never a REQUIREDNESS hint\n *\n * A bare string value in map form is read as a type name **only when it is one\n * of the seven JSON Schema primitive names** — `string`, `number`, `integer`,\n * `boolean`, `object`, `array`, `null` — which is exactly `paramSchemaOf`'s\n * own `PRIMITIVE_TYPES` set. **Any other string is prose and constrains\n * nothing.**\n *\n * That is not defensive coding, it is the corpus: a census of every literal\n * `paramSchema` in the fleet (2026-08-22) found ~50 map-form declarations in\n * `qontinui-runner` alone whose values are human-readable hints, not types —\n * `{ count: \"number (>= 1, defaults to 1)\", account: \"string — either a Claude\n * account label … or the literal \\\"best\\\"\" }`. Reading `\"number (>= 1,\n * defaults to 1)\"` as a type name would make every one of them unvalidatable\n * noise. The file that declares them says so itself: *\"loose `Record<string,\n * unknown>` with hint strings, no runtime validation\"*.\n *\n * For the same reason, **map form never marks anything required.** It has no\n * `required` array and no other way to express optionality, and most of those\n * ~50 real declarations describe params that are explicitly optional in their\n * own prose (\"defaults to 1\", \"optional initial prompt\"). Requiring by default\n * would report a violation on nearly every real call. An author who needs\n * required params writes form 1, which has a keyword for it.\n *\n * **Optionality in form 1** is exactly `required`: a property is required iff\n * listed there. Note `paramSchemaOf` **omits `required` entirely** when every\n * field is optional, so its absence means \"nothing required\", never \"malformed\".\n *\n * `optional: true` is not a JSON Schema keyword — it is this monorepo's\n * convention on `paramSchemaOf`'s *input* descriptors, and `paramSchemaOf`\n * strips it before the schema reaches the wire. It is honoured here (form 2\n * only) purely so an unstripped input-shaped object is read the same way.\n *\n * **Recognised property keywords** — everything else is IGNORED:\n *\n * | Keyword | Applies to | Meaning |\n * |---|---|---|\n * | `type` | any | `\"string\" \\| \"number\" \\| \"integer\" \\| \"boolean\" \\| \"object\" \\| \"array\" \\| \"null\"`, or an array of those (union — a value matching any member passes). Any OTHER type name constrains nothing (`paramSchemaOf` passes unknown names through verbatim, so they do occur) |\n * | `enum` | any | value must equal one of the listed JSON values |\n * | `const` | any | value must equal this JSON value |\n * | `properties` | objects | per-key sub-schemas, applied recursively |\n * | `required` | objects | array of key names that must be present |\n * | `additionalProperties` | objects | when exactly `false`, keys absent from `properties` are rejected — **including when the schema declares no `properties` at all**, which is the natural spelling of \"takes no params\". Any other value is ignored |\n * | `items` | arrays | one sub-schema applied to every element, recursively |\n * | `minimum` / `maximum` | numbers | inclusive bounds |\n * | `minLength` / `maxLength` | strings | inclusive bounds on `.length` |\n * | `pattern` | strings | ECMAScript regex, unanchored. An uncompilable **or catastrophically-backtracking** pattern is ignored, never a failure — see {@link MAX_PATTERN_LENGTH} |\n *\n * **⚠ Anything outside this table is IGNORED, never rejected.** `description`,\n * `default`, `title`, `format`, `examples`, `$schema`, `$ref`, `oneOf`,\n * `anyOf`, `allOf`, `not`, `patternProperties`, `minItems`, `exclusiveMinimum`\n * … all pass silently. This is deliberate and load-bearing: a schema outside\n * this subset is still *valid JSON Schema*, and rejecting an unrecognised\n * keyword would convert a documentation nicety into a hard invocation failure\n * for every author who wrote a richer schema than this validator reads. An\n * unreadable schema means \"no constraint expressed here\", not \"invalid\".\n * The same rule applies one level up: a `paramSchema` that is not a plain\n * object at all (`null`, an array, a string) expresses no constraint and\n * validates everything.\n *\n * **No coercion.** `\"5\"` does not satisfy `{\"type\":\"number\"}`. The runner's\n * LLM router is already instructed to \"coerce numeric tokens to numbers\"\n * (`command_interpreter.rs`), so coercing here would hide that contract rather\n * than enforce it.\n *\n * ### A validator must return a verdict, never throw\n *\n * {@link validateActionParams} is called at an invocation seam whose only\n * generic failure label is `UB-ACTION-FAILED` — \"the handler failed\". A\n * validator that throws would therefore be reported as a *handler* fault, and\n * the author would go debug code that never ran. Two inputs could do it, and\n * both are **author-supplied schema data**, not caller params:\n *\n * - **A self-referential schema.** `const s = { type: 'object', properties: {} };\n * s.properties.self = s;` recurses until `RangeError: Maximum call stack size\n * exceeded`. Bounded by {@link MAX_SCHEMA_DEPTH}: past that depth the walk\n * stops and expresses no further constraint (the ignore-don't-reject rule,\n * applied to depth).\n * - **A catastrophically-backtracking `pattern`.** This one does not throw at\n * all — it *hangs*, which no `try`/`catch` can rescue. Guarded before\n * compilation by {@link MAX_PATTERN_LENGTH} and a nested-quantifier test,\n * the same pair `control/action-executor.ts` already applies to a\n * caller-supplied `srcPattern`.\n *\n * The seams wrap the call anyway (belt and braces) and report a validator\n * fault distinguishably from a handler fault — see the executors.\n *\n * ---------------------------------------------------------------------------\n * DUPLICATE — deliberately not an import\n * ---------------------------------------------------------------------------\n *\n * DUPLICATE OF `@qontinui/ui-bridge` `src/core/param-schema.ts` — DELIBERATELY\n * NOT AN IMPORT, for the same reason as `core/abortable.ts` beside it:\n * `@qontinui/ui-bridge` is an OPTIONAL peerDependency of this package and is\n * absent from `dependencies`, so a consumer may install\n * `@qontinui/ui-bridge-native` alone; importing from it would resolve inside\n * this monorepo and then fail for that consumer.\n *\n * KEEP IN SYNC with `@qontinui/ui-bridge` `src/core/param-schema.ts`. The\n * module has no imports and touches no DOM or Node API — only `RegExp`,\n * `JSON`, `Set` and `Number`, all present in React Native. The documented\n * subset above is a cross-repo contract, so the two copies drifting is a\n * contract break, not a style nit.\n */\n\n/** Which rule rejected a value. Machine-readable; pairs with `message`. */\nexport type ParamSchemaKeyword =\n | 'required'\n | 'type'\n | 'enum'\n | 'const'\n | 'additionalProperties'\n | 'minimum'\n | 'maximum'\n | 'minLength'\n | 'maxLength'\n | 'pattern';\n\n/**\n * One rejected parameter. `path` is the whole point — an agent told only\n * \"invalid params\" cannot fix anything, so every issue names the param it is\n * about.\n */\nexport interface ParamSchemaIssue {\n /**\n * Location of the offending value, in dotted/bracketed form relative to the\n * params object: `\"username\"`, `\"filter.status\"`, `\"ids[2]\"`. Empty string\n * means the params object itself.\n */\n path: string;\n /** Which rule rejected it. */\n keyword: ParamSchemaKeyword;\n /** What the schema demanded, rendered for a human/agent reader. */\n expected: string;\n /** What was actually supplied, rendered compactly. Absent for `required`. */\n received?: string;\n /** One-line explanation naming both the param and the reason. */\n message: string;\n}\n\n/** Outcome of {@link validateActionParams}. */\nexport interface ParamValidationResult {\n valid: boolean;\n /** Empty iff `valid`. */\n issues: ParamSchemaIssue[];\n}\n\n/**\n * What the executor does with a schema violation.\n *\n * - `'enforce'` — reject the invocation before the handler runs, with\n * `errorCode: 'UB-ACTION-REJECTED'` and the issue list attached.\n * - `'warn'` — log the violation and invoke the handler anyway.\n * - `'off'` — skip validation entirely (no schema walk, no allocation).\n */\nexport type ParamValidationMode = 'enforce' | 'warn' | 'off';\n\n/**\n * **`'warn'`.** Decided on the plan's priority order — *powerful features →\n * scalability → robustness → clean code* — not on backward compatibility,\n * which is explicitly not a factor on this project.\n *\n * The feature Phase 2 delivers is *an enforceable declaration*, and warn mode\n * delivers all of it except the refusal: the schema is walked, the violating\n * param is named, and the violation is reported. Enforcement is one call to\n * {@link setDefaultParamValidationMode} away, per deployment.\n *\n * What arming `'enforce'` by default would buy is the refusal — and the\n * population it would refuse first is not attackers, it is the fleet's own\n * schemas. Nothing has ever validated these declarations, so on the balance of\n * evidence some existing `paramSchema` values are wrong about their own\n * handlers rather than the callers being wrong about the schema; a validator\n * armed on day one reports that as the caller's failure. Worse, the largest\n * live producer of action params is a *model*:\n * `qontinui-runner/src-tauri/src/commands/command_interpreter.rs` asks an LLM\n * for \"args whose keys match the chosen action's `paramSchema`\", and that\n * failure surfaces to a user running a slash command. Defaulting to enforce\n * would convert a documentation defect into a user-visible outage on a\n * population that was never measured.\n *\n * Robustness — third in the order, and the tiebreaker here — argues the same\n * way: the robust move is to collect violations from a validator that has\n * never seen production traffic before letting it refuse anything. A default\n * that fails open and is *observable* beats a default that fails closed and is\n * *unmeasured*.\n */\nexport const DEFAULT_PARAM_VALIDATION_MODE: ParamValidationMode = 'warn';\n\nlet currentDefaultMode: ParamValidationMode = DEFAULT_PARAM_VALIDATION_MODE;\n\n/**\n * Arm or disarm validation process-wide. Call once at app boot; each\n * invocation may still override it via `executeComponentAction`'s\n * `{ paramValidation }` option.\n */\nexport function setDefaultParamValidationMode(mode: ParamValidationMode): void {\n currentDefaultMode = mode;\n}\n\n/** The mode an invocation gets when it does not pass one. */\nexport function getDefaultParamValidationMode(): ParamValidationMode {\n return currentDefaultMode;\n}\n\n/** Test/teardown helper: restore {@link DEFAULT_PARAM_VALIDATION_MODE}. */\nexport function resetDefaultParamValidationMode(): void {\n currentDefaultMode = DEFAULT_PARAM_VALIDATION_MODE;\n}\n\n// ---------------------------------------------------------------------------\n// Implementation\n// ---------------------------------------------------------------------------\n\ntype PlainObject = Record<string, unknown>;\n\n/**\n * The only strings read as type names. Byte-identical to `paramSchemaOf`'s\n * `PRIMITIVE_TYPES` (`@qontinui/ui-bridge-wrapper` `helpers/schema.ts`) —\n * KEEP IN SYNC. Anything else is prose.\n */\nconst PRIMITIVE_TYPE_NAMES = new Set([\n 'string',\n 'number',\n 'integer',\n 'boolean',\n 'object',\n 'array',\n 'null',\n]);\n\n/**\n * Top-level keys that a JSON Schema *object* schema may legitimately carry\n * alongside `type: \"object\"`. Used only by the form-1/form-2 disambiguation\n * (see the module header): a top level whose non-`type` keys are all in here\n * is an object schema; anything else is a map of param declarations.\n *\n * Deliberately generous — it lists keywords this validator does not implement\n * (`oneOf`, `patternProperties`, `$defs`, …) because the question it answers\n * is \"was this written as a schema?\", not \"can we enforce it?\". A schema\n * richer than the subset must still be *recognised* as a schema, or its\n * `properties` would be re-read as param names.\n */\nconst OBJECT_SCHEMA_KEYWORDS = new Set([\n 'type',\n 'properties',\n 'required',\n 'additionalProperties',\n 'patternProperties',\n 'propertyNames',\n 'minProperties',\n 'maxProperties',\n 'dependentRequired',\n 'dependentSchemas',\n 'unevaluatedProperties',\n 'allOf',\n 'anyOf',\n 'oneOf',\n 'not',\n 'if',\n 'then',\n 'else',\n 'enum',\n 'const',\n 'default',\n 'examples',\n 'title',\n 'description',\n 'deprecated',\n 'readOnly',\n 'writeOnly',\n '$schema',\n '$id',\n '$ref',\n '$comment',\n '$defs',\n 'definitions',\n]);\n\n/**\n * Depth ceiling for the recursive schema walk. A schema nested deeper than\n * this expresses no further constraint here (ignore-don't-reject), which is\n * what keeps a self-referential `paramSchema` from becoming a `RangeError` at\n * the invocation seam.\n *\n * 32 is far past any hand-written declaration — the deepest real `paramSchema`\n * in the fleet is 2 levels — and far short of a default stack.\n */\nconst MAX_SCHEMA_DEPTH = 32;\n\n/**\n * Longest `pattern` this validator will compile, and the companion\n * nested-quantifier test below.\n *\n * A `pattern` is author-supplied but it is evaluated against caller-supplied\n * strings, so `(a+)+$` against a long non-matching input is a hang, not an\n * exception — unrescuable by `try`/`catch` because the engine never returns.\n * The pair (length cap + nested-quantifier reject) is the same guard\n * `control/action-executor.ts` applies to a caller-supplied `srcPattern`; over\n * the cap or on a risky construct the keyword is IGNORED, exactly like an\n * uncompilable pattern.\n */\nconst MAX_PATTERN_LENGTH = 200;\n\n/**\n * Nested-quantifier detector — a group that itself contains a quantifier and\n * is then quantified (`(a+)+`, `(a*)*`, `(?:a{2,})+`), the classic\n * catastrophic-backtracking shape.\n *\n * A deliberate duplicate of `@qontinui/ui-bridge` `control/action-executor.ts`\n * `hasNestedQuantifiers`: this module imports nothing so that `src/native/*`\n * and the standalone React Native package can share it (see the header), while\n * `action-executor.ts` pulls in the DOM. KEEP THE COPIES IN SYNC.\n */\nfunction hasNestedQuantifiers(pattern: string): boolean {\n return /(\\((?:[^()]*[+*}])[^()]*\\))[+*?]|\\(\\?:[^()]*[+*}][^()]*\\)[+*?]/.test(pattern);\n}\n\nfunction isPlainObject(value: unknown): value is PlainObject {\n return typeof value === 'object' && value !== null && !Array.isArray(value);\n}\n\n/** `Object.prototype.hasOwnProperty`, safely — see {@link hasOwn}. */\nconst hasOwnProperty = Object.prototype.hasOwnProperty;\n\n/**\n * Own-property test.\n *\n * **Not `key in value`.** `in` walks the prototype chain, so a param named\n * `toString`, `valueOf`, `constructor` or `hasOwnProperty` is never reported\n * missing (it \"exists\" on `Object.prototype`) and is then validated against\n * `Object.prototype`'s member instead of the caller's value — a required\n * param that was never supplied silently passes, and a type constraint on it\n * is checked against a function. `standardActionEffect` already spells this\n * correctly; this is the same rule.\n */\nfunction hasOwn(value: object, key: string): boolean {\n return hasOwnProperty.call(value, key);\n}\n\n/** Compact rendering of a supplied value, for the `received` field. */\nfunction render(value: unknown): string {\n if (value === null) return 'null';\n if (value === undefined) return 'undefined';\n if (Array.isArray(value)) return `array(${value.length})`;\n const t = typeof value;\n if (t === 'string') return JSON.stringify(value);\n if (t === 'number' || t === 'boolean') return String(value);\n if (t === 'object') return 'object';\n return t;\n}\n\n/** Longest JSON rendering {@link renderJson} will emit before truncating. */\nconst MAX_RENDERED_JSON_LENGTH = 120;\n\n/**\n * Rendering for `enum` / `const`, where the *identity* of the value is the\n * whole message.\n *\n * {@link render} collapses every object to the literal string `\"object\"`,\n * which turns a `const` violation into **\"must equal object, received\n * object.\"** — a message that tells an agent nothing, in a module whose stated\n * purpose is that \"invalid params\" tells an agent nothing. So these two\n * keywords render structurally instead, capped so a large schema value cannot\n * blow up a log line.\n */\nfunction renderJson(value: unknown): string {\n if (value === undefined) return 'undefined';\n let text: string;\n try {\n text = JSON.stringify(value) ?? String(value);\n } catch {\n // Cyclic or a BigInt — fall back to the compact rendering.\n return render(value);\n }\n return text.length > MAX_RENDERED_JSON_LENGTH\n ? `${text.slice(0, MAX_RENDERED_JSON_LENGTH)}…`\n : text;\n}\n\n/** The JSON Schema type name a runtime value would be reported as. */\nfunction jsonTypeOf(value: unknown): string {\n if (value === null) return 'null';\n if (Array.isArray(value)) return 'array';\n const t = typeof value;\n if (t === 'number') return Number.isInteger(value) ? 'integer' : 'number';\n if (t === 'string' || t === 'boolean' || t === 'object') return t;\n return t;\n}\n\nfunction matchesType(value: unknown, typeName: string): boolean {\n switch (typeName) {\n case 'string':\n return typeof value === 'string';\n case 'number':\n return typeof value === 'number' && Number.isFinite(value);\n case 'integer':\n return typeof value === 'number' && Number.isInteger(value);\n case 'boolean':\n return typeof value === 'boolean';\n case 'null':\n return value === null;\n case 'array':\n return Array.isArray(value);\n case 'object':\n return isPlainObject(value);\n default:\n // Unrecognised type name — outside the subset, so it constrains nothing.\n return true;\n }\n}\n\n/**\n * Structural equality for JSON `enum` / `const` members.\n *\n * **Not `JSON.stringify(a) === JSON.stringify(b)`.** That comparison is\n * key-order sensitive, so `const: { a: 1, b: 2 }` would reject `{ b: 2, a: 1 }`\n * — two renderings of the same JSON value. Object key order is not semantic in\n * JSON, and the caller does not control it (it is whatever the producing\n * serializer emitted), so an order-sensitive test produces a false failure on\n * a value that IS the declared constant.\n *\n * Depth-bounded for the same reason the schema walk is: a cyclic `const` in a\n * hand-built (non-JSON) schema would otherwise recurse forever. Past the\n * bound the two are treated as unequal rather than throwing.\n */\nfunction jsonEquals(a: unknown, b: unknown, depth = 0): boolean {\n if (a === b) return true;\n if (depth > MAX_SCHEMA_DEPTH) return false;\n if (a === null || b === null || a === undefined || b === undefined) return false;\n if (typeof a !== typeof b) return false;\n if (typeof a !== 'object') return false;\n\n const aIsArray = Array.isArray(a);\n if (aIsArray !== Array.isArray(b)) return false;\n if (aIsArray) {\n const bArr = b as unknown[];\n const aArr = a as unknown[];\n if (aArr.length !== bArr.length) return false;\n return aArr.every((item, i) => jsonEquals(item, bArr[i], depth + 1));\n }\n\n const aObj = a as PlainObject;\n const bObj = b as PlainObject;\n const aKeys = Object.keys(aObj);\n const bKeys = Object.keys(bObj);\n if (aKeys.length !== bKeys.length) return false;\n return aKeys.every((key) => hasOwn(bObj, key) && jsonEquals(aObj[key], bObj[key], depth + 1));\n}\n\nfunction joinPath(base: string, key: string): string {\n return base === '' ? key : `${base}.${key}`;\n}\n\n/**\n * Read a `type` keyword into the list of accepted type names, or `null` when\n * the keyword is absent or shaped outside the subset (in which case it\n * constrains nothing).\n */\nfunction readTypes(schema: PlainObject): string[] | null {\n const raw = schema['type'];\n if (typeof raw === 'string') return [raw];\n if (Array.isArray(raw)) {\n const names = raw.filter((t): t is string => typeof t === 'string');\n return names.length > 0 ? names : null;\n }\n return null;\n}\n\n/** Validate one value against one property schema, appending to `issues`. */\nfunction validateValue(\n value: unknown,\n schema: unknown,\n path: string,\n issues: ParamSchemaIssue[],\n depth: number\n): void {\n // Depth bound — a self-referential `paramSchema` would otherwise recurse to\n // `RangeError`, which the seam can only report as a HANDLER failure. Past\n // the bound the schema expresses no further constraint. See MAX_SCHEMA_DEPTH.\n if (depth > MAX_SCHEMA_DEPTH) return;\n\n // A property schema that is not an object expresses no constraint. A bare\n // PRIMITIVE type-name string IS a constraint though, and is how map form\n // spells one; any other string is prose (see the module header).\n if (typeof schema === 'string') {\n if (PRIMITIVE_TYPE_NAMES.has(schema) && !matchesType(value, schema)) {\n issues.push({\n path,\n keyword: 'type',\n expected: schema,\n received: render(value),\n message: `Parameter \"${path}\" must be of type ${schema}, received ${jsonTypeOf(value)} (${render(value)}).`,\n });\n }\n return;\n }\n if (!isPlainObject(schema)) return;\n\n const types = readTypes(schema);\n if (types !== null && !types.some((t) => matchesType(value, t))) {\n const expected = types.join(' | ');\n issues.push({\n path,\n keyword: 'type',\n expected,\n received: render(value),\n message: `Parameter \"${path}\" must be of type ${expected}, received ${jsonTypeOf(value)} (${render(value)}).`,\n });\n // A wrong-typed value cannot meaningfully fail the type-specific keywords\n // below; reporting those too would bury the one issue that matters.\n return;\n }\n\n if (hasOwn(schema, 'const') && !jsonEquals(value, schema['const'])) {\n // `renderJson`, not `render`: the identity of the value IS the message\n // here, and `render` would collapse both sides to the word \"object\".\n const expected = renderJson(schema['const']);\n const received = renderJson(value);\n issues.push({\n path,\n keyword: 'const',\n expected,\n received,\n message: `Parameter \"${path}\" must equal ${expected}, received ${received}.`,\n });\n return;\n }\n\n const enumValues = schema['enum'];\n if (Array.isArray(enumValues) && !enumValues.some((allowed) => jsonEquals(value, allowed))) {\n const expected = enumValues.map((v) => renderJson(v)).join(', ');\n const received = renderJson(value);\n issues.push({\n path,\n keyword: 'enum',\n expected,\n received,\n message: `Parameter \"${path}\" must be one of [${expected}], received ${received}.`,\n });\n return;\n }\n\n if (typeof value === 'number') {\n const min = schema['minimum'];\n if (typeof min === 'number' && value < min) {\n issues.push({\n path,\n keyword: 'minimum',\n expected: `>= ${min}`,\n received: render(value),\n message: `Parameter \"${path}\" must be >= ${min}, received ${value}.`,\n });\n }\n const max = schema['maximum'];\n if (typeof max === 'number' && value > max) {\n issues.push({\n path,\n keyword: 'maximum',\n expected: `<= ${max}`,\n received: render(value),\n message: `Parameter \"${path}\" must be <= ${max}, received ${value}.`,\n });\n }\n }\n\n if (typeof value === 'string') {\n const minLength = schema['minLength'];\n if (typeof minLength === 'number' && value.length < minLength) {\n issues.push({\n path,\n keyword: 'minLength',\n expected: `length >= ${minLength}`,\n received: `length ${value.length}`,\n message: `Parameter \"${path}\" must be at least ${minLength} characters, received ${value.length}.`,\n });\n }\n const maxLength = schema['maxLength'];\n if (typeof maxLength === 'number' && value.length > maxLength) {\n issues.push({\n path,\n keyword: 'maxLength',\n expected: `length <= ${maxLength}`,\n received: `length ${value.length}`,\n message: `Parameter \"${path}\" must be at most ${maxLength} characters, received ${value.length}.`,\n });\n }\n const pattern = schema['pattern'];\n // ReDoS guard, BEFORE compilation: a catastrophically-backtracking pattern\n // does not throw, it hangs — no `try`/`catch` can rescue it, so the only\n // defence is not to run it. Same pair of tests `action-executor.ts` applies\n // to a caller-supplied `srcPattern`. Over the cap, or a nested-quantifier\n // construct, and the keyword is ignored like an uncompilable one.\n if (\n typeof pattern === 'string' &&\n pattern.length <= MAX_PATTERN_LENGTH &&\n !hasNestedQuantifiers(pattern)\n ) {\n // Declared WITHOUT an initializer on purpose: both arms below assign\n // before any read, so an initializer here would be dead (eslint\n // `no-useless-assignment`). The regex carries no `g` flag and is rebuilt\n // per call, so there is no `lastIndex` state to carry between values.\n let re: RegExp | null;\n try {\n re = new RegExp(pattern);\n } catch {\n // An uncompilable pattern expresses no constraint we can read. Ignored,\n // never a failure — same rule as an unrecognised keyword.\n re = null;\n }\n if (re !== null && !re.test(value)) {\n issues.push({\n path,\n keyword: 'pattern',\n expected: `match /${pattern}/`,\n received: render(value),\n message: `Parameter \"${path}\" must match /${pattern}/, received ${render(value)}.`,\n });\n }\n }\n }\n\n if (Array.isArray(value) && hasOwn(schema, 'items')) {\n const items = schema['items'];\n value.forEach((element, index) => {\n validateValue(element, items, `${path}[${index}]`, issues, depth + 1);\n });\n }\n\n if (\n isPlainObject(value) &&\n (isPlainObject(schema['properties']) ||\n hasOwn(schema, 'required') ||\n schema['additionalProperties'] === false)\n ) {\n validateObject(value, schema, path, issues, depth);\n }\n}\n\n/**\n * Validate a plain object against the `properties` / `required` /\n * `additionalProperties` triple. Shared by the top level and by nested\n * `type: \"object\"` properties.\n */\nfunction validateObject(\n value: PlainObject,\n schema: PlainObject,\n basePath: string,\n issues: ParamSchemaIssue[],\n depth: number\n): void {\n if (depth > MAX_SCHEMA_DEPTH) return;\n\n const properties = isPlainObject(schema['properties']) ? schema['properties'] : {};\n const requiredRaw = schema['required'];\n const required = Array.isArray(requiredRaw)\n ? requiredRaw.filter((k): k is string => typeof k === 'string')\n : [];\n\n for (const key of required) {\n // `hasOwn`, not `key in value` — see `hasOwn`. With `in`, a required param\n // named `toString` is never reported missing.\n if (!hasOwn(value, key) || value[key] === undefined) {\n const at = joinPath(basePath, key);\n issues.push({\n path: at,\n keyword: 'required',\n expected: 'present',\n message: `Required parameter \"${at}\" is missing.`,\n });\n }\n }\n\n if (schema['additionalProperties'] === false) {\n const declared = new Set(Object.keys(properties));\n // With no `properties` at all the schema says \"no params are accepted\" —\n // say that, rather than the empty \"one of []\" the generic phrasing gives.\n const expected = declared.size === 0 ? 'no parameters' : `one of [${[...declared].join(', ')}]`;\n for (const key of Object.keys(value)) {\n if (!declared.has(key)) {\n const at = joinPath(basePath, key);\n issues.push({\n path: at,\n keyword: 'additionalProperties',\n expected,\n received: render(value[key]),\n message: `Parameter \"${at}\" is not declared by the schema, which sets additionalProperties: false.`,\n });\n }\n }\n }\n\n for (const [key, propSchema] of Object.entries(properties)) {\n // `hasOwn`, not `key in value` — with `in`, a declared param named\n // `valueOf` would be \"present\" and validated against `Object.prototype`'s\n // function instead of the caller's (absent) value.\n if (!hasOwn(value, key) || value[key] === undefined) continue;\n validateValue(value[key], propSchema, joinPath(basePath, key), issues, depth + 1);\n }\n}\n\n/**\n * The form-1/form-2 disambiguation, in one place. See the module header for\n * the rule and for why the `type === 'object'` half is not enough on its own.\n *\n * @returns `true` for object-schema form (form 1), `false` for map form.\n */\nfunction isObjectSchemaForm(schema: PlainObject): boolean {\n if (isPlainObject(schema['properties'])) return true;\n if (schema['type'] !== 'object') return false;\n // `type: \"object\"` with NO `properties`. Object schema only if everything\n // else present is a schema keyword; a single non-keyword key (`id`,\n // `username`, …) means this is a map that happens to declare a param called\n // `type`, and reading it as a schema would silently drop every sibling\n // declaration in it.\n return Object.keys(schema).every((key) => OBJECT_SCHEMA_KEYWORDS.has(key));\n}\n\n/**\n * Normalise map form into the object-schema form so one walker serves both.\n * Returns `null` when `schema` is already object form.\n */\nfunction normalizeMapForm(schema: PlainObject): PlainObject | null {\n if (isObjectSchemaForm(schema)) return null;\n\n const properties: PlainObject = {};\n for (const [key, raw] of Object.entries(schema)) {\n if (raw === null || raw === undefined) continue;\n if (typeof raw === 'string') {\n // Type name, or prose? Only the seven primitive names are types. Every\n // other string is a human hint — ~50 live declarations in\n // `qontinui-runner` are exactly that — and expresses no constraint.\n properties[key] = PRIMITIVE_TYPE_NAMES.has(raw) ? { type: raw } : {};\n continue;\n }\n if (isPlainObject(raw)) {\n // `optional` is this monorepo's non-standard marker, not JSON Schema.\n // Nothing in map form is required, so it only needs stripping.\n const { optional: _optional, ...rest } = raw as PlainObject & { optional?: unknown };\n properties[key] = rest;\n continue;\n }\n // A value that is neither a type name nor a schema object expresses no\n // constraint — ignored, per the unrecognised-keyword rule.\n }\n // NO `required`: map form cannot express requiredness. See the module header.\n return { type: 'object', properties };\n}\n\n/**\n * Validate `params` against an action's `paramSchema`.\n *\n * Returns `{ valid: true, issues: [] }` for anything the documented subset\n * cannot read — that is the ignore-don't-reject rule, and it is why a schema\n * this validator does not understand can never fail an invocation.\n *\n * @param schema the action's declared `paramSchema` (any shape; unreadable\n * shapes constrain nothing)\n * @param params the params the caller supplied. `undefined` is treated as an\n * empty object, so a schema with required properties still reports them.\n */\nexport function validateActionParams(\n schema: unknown,\n params: unknown\n): ParamValidationResult {\n if (!isPlainObject(schema)) return { valid: true, issues: [] };\n\n const normalized = normalizeMapForm(schema) ?? schema;\n\n const hasProperties = isPlainObject(normalized['properties']);\n const hasRequired = Array.isArray(normalized['required']);\n // `additionalProperties: false` is a constraint ON ITS OWN, even with no\n // `properties` key: `{ type: 'object', additionalProperties: false }` is the\n // natural way to spell \"this action takes no params at all\", and the keyword\n // table above documents it. Omitting it from this test made that schema\n // accept every payload — the same silent-drop defect as the map-form one.\n const forbidsExtras = normalized['additionalProperties'] === false;\n if (!hasProperties && !hasRequired && !forbidsExtras) {\n // e.g. a bare `{ type: \"object\" }`. No constraint expressed.\n //\n // (The map-form branch cannot reach here: `normalizeMapForm` always\n // returns a `properties` object, empty or not — so `hasProperties` is\n // true for every map form, including one whose every entry was prose.)\n return { valid: true, issues: [] };\n }\n\n const issues: ParamSchemaIssue[] = [];\n\n if (params === undefined || params === null) {\n validateObject({}, normalized, '', issues, 0);\n return { valid: issues.length === 0, issues };\n }\n\n if (!isPlainObject(params)) {\n issues.push({\n path: '',\n keyword: 'type',\n expected: 'object',\n received: render(params),\n message: `Action params must be an object, received ${jsonTypeOf(params)} (${render(params)}).`,\n });\n return { valid: false, issues };\n }\n\n validateObject(params, normalized, '', issues, 0);\n return { valid: issues.length === 0, issues };\n}\n\n/**\n * One-line summary of a violation set, naming the action and every offending\n * param. Used as the `error` / `message` string at every invocation seam so\n * the three trees phrase the rejection identically.\n */\nexport function formatParamValidationFailure(\n componentId: string,\n actionId: string,\n issues: ParamSchemaIssue[]\n): string {\n const detail = issues.map((i) => i.message).join(' ');\n return `Action \"${actionId}\" on component \"${componentId}\" was rejected: params do not match the action's declared paramSchema. ${detail}`;\n}\n","/**\n * Abandonment primitive for action invocation.\n *\n * Plan `2026-08-20-ui-bridge-action-declaration-shape`, Phase 3.\n *\n * `ActionHandler`'s `options.signal` is **cooperative**: a well-behaved handler\n * observes it and returns early. Cooperation cannot be enforced, and a handler\n * that hangs is exactly the case cancellation exists for — so the executor\n * never trusts the handler to observe the signal. It races the handler promise\n * against the abort and reports the outcome either way.\n *\n * DUPLICATE OF `@qontinui/ui-bridge` `src/core/abortable.ts` — DELIBERATELY NOT\n * AN IMPORT. `@qontinui/ui-bridge` is an OPTIONAL peerDependency of this\n * package and is absent from `dependencies`, so a consumer may install\n * `@qontinui/ui-bridge-native` alone; importing from it would resolve inside\n * this monorepo and then fail for that consumer. See the same note on\n * `core/types.ts` `ActionHandler`.\n *\n * KEEP IN SYNC with `@qontinui/ui-bridge` `src/core/abortable.ts` — including\n * `MAX_ACTION_TIMEOUT_MS` and `normalizeActionTimeoutMs` below. The module has\n * no imports and touches no DOM API — only `AbortController` and `setTimeout`,\n * both present in React Native.\n */\n\n/** Which of the two cancellation sources fired. */\nexport type AbortReason = 'signal' | 'timeout';\n\n/**\n * Ceiling applied to a caller-supplied `timeoutMs` — **24 hours**.\n *\n * `ComponentActionRequest.timeoutMs` crosses the wire, so it is attacker- (or\n * typo-) controlled: an HTTP or WebSocket caller can put any JSON number in\n * it and it would otherwise land in `setTimeout` unchecked. Two concrete\n * hazards that ceiling closes:\n *\n * - **`setTimeout`'s 32-bit delay overflow.** Any delay above 2147483647ms\n * wraps to a *negative* 32-bit int in every major runtime and the timer\n * fires **immediately** — so `timeoutMs: 2147483648` (\"about 25 days,\n * effectively no timeout\") would abandon the action on the next tick, the\n * exact opposite of what the caller asked for. Clamping below that boundary\n * makes the semantics monotonic: a bigger number never means a shorter wait.\n * - **A pinned timer per in-flight request.** Nothing here is unbounded work,\n * but a 100-year timeout is indistinguishable from \"no timeout\" while still\n * holding the handler's abandonment machinery alive, so there is nothing to\n * buy above a day.\n *\n * Clamping (rather than rejecting) is right at the top end because the intent\n * is unambiguous — \"effectively forever\" — and the clamped value honours it as\n * closely as the platform can. The malformed cases below are rejected instead,\n * because there the intent is NOT recoverable.\n */\nexport const MAX_ACTION_TIMEOUT_MS = 86_400_000;\n\n/**\n * Outcome of {@link normalizeActionTimeoutMs}. Discriminated on `ok` so a\n * rejected value cannot be read as a timeout by accident.\n */\nexport type TimeoutNormalization =\n | {\n ok: true;\n /** `undefined` ≡ no timeout. Always a finite integer in `[0, MAX]`. */\n timeoutMs: number | undefined;\n /** True iff the caller's value was above {@link MAX_ACTION_TIMEOUT_MS}. */\n clamped: boolean;\n }\n | { ok: false; reason: string };\n\n/**\n * Validate and clamp a wire-supplied `timeoutMs` before it can reach a timer.\n *\n * The policy, stated once so all three executors share it:\n *\n * | Supplied | Result | Why |\n * |---|---|---|\n * | absent / `null` | no timeout | the documented \"omitted ⇒ no timeout\" default |\n * | `0` | abandon on the next tick | a coherent request (\"don't let it run\"), and what `setTimeout(…, 0)` already means |\n * | `1 … MAX` | honoured, floored to an integer | fractional ms is not a thing a timer can express |\n * | `> MAX` | clamped to {@link MAX_ACTION_TIMEOUT_MS} | see that constant — above 2^31-1 the platform timer silently inverts |\n * | negative | **rejected** | `setTimeout` would treat it as `0`, i.e. a sign typo would abandon every call instantly and silently |\n * | `NaN` / `±Infinity` | **rejected** | `setTimeout(NaN)` is `setTimeout(0)` — same silent-instant-abandon trap |\n * | not a number (`\"5000\"`, `{}`, `true`) | **rejected** | JSON has numbers; a string here means the caller built the body wrong, and coercing would hide it |\n *\n * Rejection is loud on purpose: every rejected case is one where *ignoring*\n * the field fails open (the action runs uncancellable) and *coercing* it fails\n * closed at zero. Neither is what the caller asked for, and both are silent —\n * which is the defect class this whole plan exists to remove.\n */\nexport function normalizeActionTimeoutMs(raw: unknown): TimeoutNormalization {\n if (raw === undefined || raw === null) {\n return { ok: true, timeoutMs: undefined, clamped: false };\n }\n if (typeof raw !== 'number') {\n return {\n ok: false,\n reason: `timeoutMs must be a number of milliseconds, received ${typeof raw === 'string' ? JSON.stringify(raw) : typeof raw}`,\n };\n }\n if (!Number.isFinite(raw)) {\n return {\n ok: false,\n reason: `timeoutMs must be a finite number of milliseconds, received ${String(raw)}`,\n };\n }\n if (raw < 0) {\n return {\n ok: false,\n reason: `timeoutMs must not be negative, received ${String(raw)}`,\n };\n }\n if (raw > MAX_ACTION_TIMEOUT_MS) {\n return { ok: true, timeoutMs: MAX_ACTION_TIMEOUT_MS, clamped: true };\n }\n return { ok: true, timeoutMs: Math.floor(raw), clamped: false };\n}\n\n/**\n * Result of {@link runAbortable}. Discriminated on `aborted` so the caller\n * cannot read `result` off an abandoned invocation.\n */\nexport type AbortableOutcome<T> =\n | { aborted: false; result: T }\n | { aborted: true; reason: AbortReason };\n\n/** Cancellation sources composed by {@link runAbortable}. */\nexport interface RunAbortableOptions {\n /**\n * An in-process caller's signal. Cannot cross the wire — that is what\n * `timeoutMs` is for.\n */\n signal?: AbortSignal;\n /**\n * Milliseconds after which the invocation is abandoned. Serializable, so\n * this is the arm an HTTP/WebSocket caller can actually use.\n *\n * Expected to have been through {@link normalizeActionTimeoutMs} already —\n * every executor seam runs it, because this value arrives from the wire.\n * The `Number.isFinite` / `>= 0` guard below is defence in depth for a\n * direct in-process caller, and ignores anything malformed rather than\n * letting it reach `setTimeout`.\n */\n timeoutMs?: number;\n}\n\n/**\n * A fresh `AbortSignal` that is never aborted.\n *\n * `ActionHandlerOptions` promises the bag is *always* supplied, so a handler\n * written the way the docs describe — `(params, { signal }) => …` — must never\n * be called with `undefined` as its second argument. Not every invocation seam\n * has a cancellation source to give it though: an ELEMENT custom action\n * (`ControlActionRequest`) carries no `timeoutMs` and the executor holds no\n * controller for it, so there is nothing that could ever abort. Those seams\n * pass this instead of `undefined`, which keeps the destructure safe and keeps\n * `signal.aborted` honestly `false`.\n *\n * **Fresh per call, deliberately.** A shared singleton would accumulate one\n * listener per handler that calls `signal.addEventListener('abort', …)` and\n * never releases them — a leak on a hot path. A `AbortController` allocation\n * is a few bytes and custom element actions are not a hot path.\n *\n * When element actions grow a cancellation source, replace the call sites with\n * a real `runAbortable` race — the handler contract does not change.\n */\nexport function inertAbortSignal(): AbortSignal {\n return new AbortController().signal;\n}\n\n/**\n * Invoke `invoke` with a derived `AbortSignal`, abandoning it if either the\n * caller's signal aborts or `timeoutMs` elapses.\n *\n * - Returns `{ aborted: true, reason }` **without invoking at all** when the\n * caller's signal is already aborted.\n * - Returns `{ aborted: false, result }` on normal completion.\n * - **Rejects** if `invoke` throws/rejects while the race is still live, so a\n * genuine handler error stays distinguishable from a cancellation.\n * - A rejection that arrives *after* an abort already won is swallowed:\n * `Promise.race` has a rejection handler attached, so the abandoned handler\n * cannot surface as an unhandled rejection.\n */\nexport async function runAbortable<T>(\n invoke: (signal: AbortSignal) => T | Promise<T>,\n options: RunAbortableOptions = {}\n): Promise<AbortableOutcome<T>> {\n const callerSignal = options.signal;\n const timeoutMs = options.timeoutMs;\n\n if (callerSignal?.aborted) {\n return { aborted: true, reason: 'signal' };\n }\n\n const controller = new AbortController();\n // Set before `controller.abort()` in both arms, so the abort listener reads\n // the reason that actually fired.\n let reason: AbortReason = 'signal';\n let timer: ReturnType<typeof setTimeout> | undefined;\n\n const onCallerAbort = (): void => {\n reason = 'signal';\n controller.abort();\n };\n\n callerSignal?.addEventListener('abort', onCallerAbort, { once: true });\n\n if (typeof timeoutMs === 'number' && Number.isFinite(timeoutMs) && timeoutMs >= 0) {\n // The clamp is applied AGAIN here, at the only place a delay actually\n // reaches a timer. `normalizeActionTimeoutMs` already did it for every\n // wire path, but a direct in-process caller reaches `runAbortable`\n // without passing through an executor — and above 2^31-1 `setTimeout`\n // wraps negative and fires immediately, turning \"wait a century\" into\n // \"abandon now\". See MAX_ACTION_TIMEOUT_MS.\n timer = setTimeout(\n () => {\n reason = 'timeout';\n controller.abort();\n },\n Math.min(timeoutMs, MAX_ACTION_TIMEOUT_MS)\n );\n }\n\n try {\n const abandoned = new Promise<AbortableOutcome<T>>((resolve) => {\n controller.signal.addEventListener('abort', () => resolve({ aborted: true, reason }), {\n once: true,\n });\n });\n\n const completed = (async (): Promise<AbortableOutcome<T>> => ({\n aborted: false,\n result: await invoke(controller.signal),\n }))();\n\n return await Promise.race([completed, abandoned]);\n } finally {\n if (timer !== undefined) clearTimeout(timer);\n callerSignal?.removeEventListener('abort', onCallerAbort);\n }\n}\n","/**\n * Native Element Identifier\n *\n * Utilities for identifying and finding native elements.\n * In React Native, we use testID, accessibilityLabel, and tree paths\n * instead of XPath/CSS selectors.\n */\n\nimport type { NativeElementIdentifier, RegisteredNativeElement } from './types';\nimport { getGlobalRegistry } from './registry';\n\n/**\n * Create an element identifier for a native element\n */\nexport function createNativeElementIdentifier(\n id: string,\n options: {\n testId?: string;\n accessibilityLabel?: string;\n accessibilityHint?: string;\n treePath?: string;\n } = {}\n): NativeElementIdentifier {\n return {\n uiId: id,\n testId: options.testId || id,\n accessibilityLabel: options.accessibilityLabel,\n accessibilityHint: options.accessibilityHint,\n treePath: options.treePath || id,\n };\n}\n\n/**\n * Find an element by its identifier in the global registry\n */\nexport function findElementByIdentifier(\n identifier: string | NativeElementIdentifier\n): RegisteredNativeElement | null {\n const registry = getGlobalRegistry();\n if (!registry) return null;\n\n // If string, try different lookup strategies\n if (typeof identifier === 'string') {\n // Try direct ID lookup\n const byId = registry.getElement(identifier);\n if (byId) return byId;\n\n // Try testID lookup\n const byTestId = registry.findByTestId(identifier);\n if (byTestId) return byTestId;\n\n // Try pattern matching\n return findByPattern(registry, identifier);\n }\n\n // If identifier object, try each strategy\n if (identifier.uiId) {\n const byId = registry.getElement(identifier.uiId);\n if (byId) return byId;\n }\n\n if (identifier.testId) {\n const byTestId = registry.findByTestId(identifier.testId);\n if (byTestId) return byTestId;\n }\n\n return null;\n}\n\n/**\n * Find element by pattern (supports wildcards)\n */\nfunction findByPattern(\n registry: ReturnType<typeof getGlobalRegistry>,\n pattern: string\n): RegisteredNativeElement | null {\n if (!registry) return null;\n\n // Convert pattern to regex\n const regexPattern = pattern\n .replace(/[.+^${}()|[\\]\\\\]/g, '\\\\$&') // Escape special chars\n .replace(/\\*/g, '.*') // Convert * to .*\n .replace(/\\?/g, '.'); // Convert ? to .\n\n const regex = new RegExp(`^${regexPattern}$`, 'i');\n\n for (const element of registry.getAllElements()) {\n const identifier = element.getIdentifier();\n\n // Match against testId\n if (identifier.testId && regex.test(identifier.testId)) {\n return element;\n }\n\n // Match against uiId\n if (identifier.uiId && regex.test(identifier.uiId)) {\n return element;\n }\n\n // Match against treePath\n if (identifier.treePath && regex.test(identifier.treePath)) {\n return element;\n }\n\n // Match against accessibilityLabel\n if (identifier.accessibilityLabel && regex.test(identifier.accessibilityLabel)) {\n return element;\n }\n }\n\n return null;\n}\n\n/**\n * Find all elements matching a pattern\n */\nexport function findAllByPattern(pattern: string): RegisteredNativeElement[] {\n const registry = getGlobalRegistry();\n if (!registry) return [];\n\n // Convert pattern to regex\n const regexPattern = pattern\n .replace(/[.+^${}()|[\\]\\\\]/g, '\\\\$&')\n .replace(/\\*/g, '.*')\n .replace(/\\?/g, '.');\n\n const regex = new RegExp(`^${regexPattern}$`, 'i');\n const results: RegisteredNativeElement[] = [];\n\n for (const element of registry.getAllElements()) {\n const identifier = element.getIdentifier();\n\n if (\n (identifier.testId && regex.test(identifier.testId)) ||\n (identifier.uiId && regex.test(identifier.uiId)) ||\n (identifier.treePath && regex.test(identifier.treePath)) ||\n (identifier.accessibilityLabel && regex.test(identifier.accessibilityLabel))\n ) {\n results.push(element);\n }\n }\n\n return results;\n}\n\n/**\n * Build a tree path for an element based on its position in the component tree\n */\nexport function buildTreePath(componentPath: string[], elementIndex?: number): string {\n let path = componentPath.join('/');\n if (elementIndex !== undefined) {\n path += `[${elementIndex}]`;\n }\n return path;\n}\n\n/**\n * Parse a tree path into its components\n */\nexport function parseTreePath(treePath: string): { components: string[]; index?: number } {\n const indexMatch = treePath.match(/\\[(\\d+)\\]$/);\n const index = indexMatch ? parseInt(indexMatch[1], 10) : undefined;\n const pathWithoutIndex = treePath.replace(/\\[\\d+\\]$/, '');\n const components = pathWithoutIndex.split('/').filter(Boolean);\n\n return { components, index };\n}\n\n/**\n * Check if an identifier matches criteria\n */\nexport function matchesIdentifier(\n identifier: NativeElementIdentifier,\n criteria: Partial<NativeElementIdentifier>\n): boolean {\n if (criteria.uiId && identifier.uiId !== criteria.uiId) {\n return false;\n }\n if (criteria.testId && identifier.testId !== criteria.testId) {\n return false;\n }\n if (\n criteria.accessibilityLabel &&\n identifier.accessibilityLabel !== criteria.accessibilityLabel\n ) {\n return false;\n }\n if (criteria.treePath && identifier.treePath !== criteria.treePath) {\n return false;\n }\n return true;\n}\n","/**\n * Native Action Executor\n *\n * Executes actions on registered native elements and components.\n * In React Native, we execute actions by calling prop handlers directly\n * (onPress, onChangeText, etc.) rather than simulating DOM events.\n */\n\nimport type { NativeUIBridgeRegistry } from '../core/registry';\nimport type {\n NativeStandardAction,\n NativeFindRequest,\n NativeFindResponse,\n DiscoveredNativeElement,\n WaitOptions,\n} from '../core/types';\nimport { findElementByIdentifier } from '../core/element-identifier';\nimport { pageRectOf, isEmptyRect, intersectRects } from '../core/registry';\nimport type { NativePageRect } from '../core/registry';\n// Phase 3 (plan 2026-08-20-ui-bridge-action-declaration-shape). A justified\n// duplicate of the web SDK's primitive — see the header of `core/abortable.ts`\n// for why this package cannot import it.\nimport { runAbortable, normalizeActionTimeoutMs, inertAbortSignal } from '../core/abortable';\n// Phase 2 (same plan). A justified duplicate of the web SDK's validator — see\n// the header of `core/param-schema.ts` for why this package cannot import it.\nimport {\n validateActionParams,\n formatParamValidationFailure,\n getDefaultParamValidationMode,\n} from '../core/param-schema';\nimport type {\n ControlActionRequest,\n ControlActionResponse,\n ComponentActionRequest,\n ComponentActionResponse,\n ComponentActionInvokeOptions,\n WaitResult,\n NativeActionExecutor,\n NativeActionEvent,\n NativeActionListener,\n TypeActionParams,\n ScrollActionParams,\n ScrollIntoViewActionParams,\n SwipeActionParams,\n PressActionParams,\n} from './types';\n\n/**\n * Default wait options\n */\nconst DEFAULT_WAIT_OPTIONS: Required<WaitOptions> = {\n visible: true,\n enabled: true,\n focused: false,\n state: {},\n timeout: 10000,\n interval: 100,\n};\n\n/**\n * An action failure that carries a machine-readable code of its own, so the\n * HTTP handler can report it as that code instead of the generic\n * `ACTION_FAILED`. Used for `NOT_SUPPORTED` — \"this element cannot do that\",\n * which a caller must not retry with a different request shape.\n */\nexport class NativeActionError extends Error {\n constructor(\n message: string,\n readonly code: string\n ) {\n super(message);\n this.name = 'NativeActionError';\n }\n}\n\n/** Default gap (logical dp) left above an element scrolled into view. */\nconst DEFAULT_SCROLL_INTO_VIEW_PADDING = 16;\n\n/** Upper bound on waiting for `measureLayout` to call back. */\nconst SCROLL_INTO_VIEW_MEASURE_TIMEOUT_MS = 1000;\n\n/** The slice of a React Native `ScrollView` instance `scrollIntoView` drives. */\ninterface ScrollContainerRef {\n scrollTo: (options: { x?: number; y?: number; animated?: boolean }) => void;\n getInnerViewRef?: () => unknown;\n getInnerViewNode?: () => unknown;\n /** VirtualizedList family (FlatList / SectionList): the underlying ScrollView. */\n getNativeScrollRef?: () => unknown;\n getScrollResponder?: () => unknown;\n}\n\n/** Upper bound on the targeted `measureInWindow` used for the visibility check. */\nconst SCROLL_INTO_VIEW_WINDOW_MEASURE_TIMEOUT_MS = 250;\n\ntype WindowMeasurable = {\n measureInWindow?: (cb: (x: number, y: number, w: number, h: number) => void) => void;\n};\n\n/**\n * The page rect of one registered element, measured NOW where its ref allows.\n *\n * A ref with `measureInWindow` is measured directly (bounded); a timeout,\n * throw, or zero-size answer is UNKNOWN (`null`). A ref without it (a test\n * fixture, a non-host wrapper) falls back to the registry's stored layout —\n * the same evidence the snapshot route would report for it.\n */\nfunction measurePageRectNow(\n element: NonNullable<ReturnType<NativeUIBridgeRegistry['getElement']>>,\n preferred?: unknown\n): Promise<NativePageRect | null> {\n // `preferred` lets a caller measure a better node than the registered ref —\n // the ScrollView a FlatList wraps, whose class instance has no measureInWindow.\n const preferredNode = preferred as WindowMeasurable | null | undefined;\n const node =\n preferredNode && typeof preferredNode.measureInWindow === 'function'\n ? preferredNode\n : (element.ref.current as unknown as WindowMeasurable | null);\n if (!node || typeof node.measureInWindow !== 'function') {\n const state = element.getState();\n return Promise.resolve(state.visible ? pageRectOf(state) : null);\n }\n return new Promise((resolve) => {\n let settled = false;\n const done = (rect: NativePageRect | null) => {\n if (settled) return;\n settled = true;\n clearTimeout(timer);\n resolve(rect);\n };\n const timer = setTimeout(() => done(null), SCROLL_INTO_VIEW_WINDOW_MEASURE_TIMEOUT_MS);\n try {\n node.measureInWindow!((x, y, w, h) =>\n done(\n [x, y, w, h].every(Number.isFinite) && w > 0 && h > 0\n ? { left: x, top: y, right: x + w, bottom: y + h }\n : null\n )\n );\n } catch {\n done(null);\n }\n });\n}\n\n/** The slice of a React Native host view `scrollIntoView` measures with. */\ninterface MeasurableRef {\n measureLayout: (\n relativeTo: unknown,\n onSuccess: (x: number, y: number, width: number, height: number) => void,\n onFail?: () => void\n ) => void;\n}\n\n/**\n * The ScrollView-shaped object behind a container ref: the ref itself when it\n * has `scrollTo`, else the ScrollView a VirtualizedList (FlatList /\n * SectionList) wraps. `null` when neither yields one.\n */\nfunction resolveScrollView(\n current: unknown\n): (Partial<ScrollContainerRef> & Pick<ScrollContainerRef, 'scrollTo'>) | null {\n const c = current as Partial<ScrollContainerRef> | null | undefined;\n if (!c) return null;\n if (typeof c.scrollTo === 'function')\n return c as Partial<ScrollContainerRef> & Pick<ScrollContainerRef, 'scrollTo'>;\n for (const unwrap of [c.getNativeScrollRef, c.getScrollResponder]) {\n if (typeof unwrap !== 'function') continue;\n let inner: Partial<ScrollContainerRef> | null | undefined;\n try {\n inner = unwrap.call(c) as Partial<ScrollContainerRef> | null | undefined;\n } catch {\n inner = null;\n }\n if (inner && typeof inner.scrollTo === 'function')\n return inner as Partial<ScrollContainerRef> & Pick<ScrollContainerRef, 'scrollTo'>;\n }\n return null;\n}\n\n/**\n * Is the container visibly declared `horizontal`? Checks captured registry\n * props, then a class-component ref's own `props` (FlatList / SectionList\n * instances), then the resolved ScrollView's. See the LIMIT note at the call\n * site — an invisible declaration cannot be detected.\n */\nfunction isDeclaredHorizontal(\n registeredProps: Record<string, unknown> | undefined,\n ...refs: unknown[]\n): boolean {\n if (registeredProps?.horizontal === true) return true;\n return refs.some((r) => {\n const props = (r as { props?: { horizontal?: unknown } } | null | undefined)?.props;\n return props !== null && typeof props === 'object' && props.horizontal === true;\n });\n}\n\n/**\n * Sleep for a duration\n */\nfunction sleep(ms: number): Promise<void> {\n return new Promise((resolve) => setTimeout(resolve, ms));\n}\n\n/**\n * Default native action executor implementation\n */\nexport class DefaultNativeActionExecutor implements NativeActionExecutor {\n private actionListeners = new Set<NativeActionListener>();\n\n constructor(private registry: NativeUIBridgeRegistry) {}\n\n onActionExecuted(listener: NativeActionListener): () => void {\n this.actionListeners.add(listener);\n return () => {\n this.actionListeners.delete(listener);\n };\n }\n\n /** Notify listeners out-of-band; isolate each invocation so one bad listener can't poison the rest. */\n private emitActionEvent(event: NativeActionEvent): void {\n for (const listener of this.actionListeners) {\n try {\n listener(event);\n } catch (error) {\n console.warn(`[ui-bridge-native] Action listener error:`, error);\n }\n }\n }\n\n /**\n * Execute an action on an element\n */\n async executeAction(\n elementId: string,\n request: ControlActionRequest\n ): Promise<ControlActionResponse> {\n const startTime = Date.now();\n let waitDurationMs = 0;\n\n try {\n // Find the element\n let registered = this.registry.getElement(elementId);\n\n // If not in registry, try by identifier\n if (!registered) {\n registered = findElementByIdentifier(elementId) ?? undefined;\n }\n\n if (!registered) {\n const failTime = Date.now();\n const errorMsg = `Element not found: ${elementId}`;\n this.emitActionEvent({\n elementId,\n action: request.action,\n params: request.params,\n success: false,\n error: errorMsg,\n timestamp: failTime,\n requestId: request.requestId,\n durationMs: failTime - startTime,\n });\n return {\n success: false,\n error: errorMsg,\n durationMs: failTime - startTime,\n timestamp: failTime,\n requestId: request.requestId,\n };\n }\n\n // Wait for conditions if specified\n if (request.waitOptions) {\n const waitResult = await this.waitForElementInternal(registered.id, request.waitOptions);\n waitDurationMs = waitResult.waitedMs;\n if (!waitResult.met) {\n const failTime = Date.now();\n const errorMsg = waitResult.error || 'Wait condition not met';\n this.emitActionEvent({\n elementId,\n action: request.action,\n params: request.params,\n success: false,\n error: errorMsg,\n timestamp: failTime,\n requestId: request.requestId,\n durationMs: failTime - startTime,\n });\n return {\n success: false,\n error: errorMsg,\n durationMs: failTime - startTime,\n timestamp: failTime,\n requestId: request.requestId,\n waitDurationMs,\n };\n }\n }\n\n // Execute the action\n const result = await this.performAction(registered, request.action, request.params);\n\n const successTime = Date.now();\n this.emitActionEvent({\n elementId,\n action: request.action,\n params: request.params,\n success: true,\n timestamp: successTime,\n requestId: request.requestId,\n durationMs: successTime - startTime,\n });\n // Re-fetch the element from the registry rather than reusing the\n // `registered` reference captured before `performAction`. Mutating\n // actions (`type`/`setValue`/`clear`/`focus`/...) call\n // `registry.updateElementState`, which REPLACES the map entry with a\n // fresh object carrying a new `getState` closure — the captured\n // `registered.getState` is stale and omits the just-set `value`. Without\n // this re-fetch the action response's `elementState` disagrees with a\n // subsequent `GET /control/element/:id` and `/control/snapshot`, which is\n // the inconsistent read-path the manual-test session flagged.\n const fresh = this.registry.getElement(registered.id) ?? registered;\n return {\n success: true,\n elementState: fresh.getState(),\n result,\n durationMs: successTime - startTime,\n timestamp: successTime,\n requestId: request.requestId,\n waitDurationMs,\n };\n } catch (error) {\n const failTime = Date.now();\n const errorMsg = error instanceof Error ? error.message : String(error);\n this.emitActionEvent({\n elementId,\n action: request.action,\n params: request.params,\n success: false,\n error: errorMsg,\n timestamp: failTime,\n requestId: request.requestId,\n durationMs: failTime - startTime,\n });\n return {\n success: false,\n error: errorMsg,\n ...(error instanceof NativeActionError ? { code: error.code } : {}),\n stack: error instanceof Error ? error.stack : undefined,\n durationMs: failTime - startTime,\n timestamp: failTime,\n requestId: request.requestId,\n waitDurationMs,\n };\n }\n }\n\n /**\n * Perform an action on an element\n */\n private async performAction(\n element: ReturnType<NativeUIBridgeRegistry['getElement']>,\n action: NativeStandardAction | string,\n params?: Record<string, unknown>\n ): Promise<unknown> {\n if (!element) {\n throw new Error('Element not found');\n }\n\n const props = element.props || {};\n\n // Check for custom action first\n if (element.customActions && action in element.customActions) {\n // The options bag is ALWAYS supplied — `ActionHandlerOptions` promises\n // it, and a handler written the documented way (`(params, { signal }) =>\n // …`) throws on `undefined`. An element action carries no cancellation\n // source, so the signal is inert; see `inertAbortSignal`.\n return element.customActions[action].handler(params, { signal: inertAbortSignal() });\n }\n\n // Execute standard actions\n switch (action) {\n case 'click': // Web UI Bridge compatibility alias\n case 'press':\n return this.performPress(props, params as PressActionParams | undefined);\n\n case 'longPress':\n return this.performLongPress(props, params as PressActionParams | undefined);\n\n case 'doubleTap':\n return this.performDoubleTap(props);\n\n case 'type':\n return this.performType(element, props, params as unknown as TypeActionParams);\n\n case 'setValue':\n return this.performSetValue(element, props, params as unknown as TypeActionParams);\n\n case 'clear':\n return this.performClear(element, props);\n\n case 'focus':\n return this.performFocus(element);\n\n case 'blur':\n return this.performBlur(element);\n\n case 'scroll':\n return this.performScroll(props, params as ScrollActionParams | undefined);\n\n case 'scrollIntoView':\n return this.performScrollIntoView(\n element,\n params as ScrollIntoViewActionParams | undefined\n );\n\n case 'swipe':\n return this.performSwipe(props, params as unknown as SwipeActionParams);\n\n case 'toggle':\n return this.performToggle(props);\n\n default:\n throw new Error(`Unknown action: ${action}`);\n }\n }\n\n /**\n * Perform press action\n */\n private async performPress(\n props: Record<string, unknown>,\n params?: PressActionParams\n ): Promise<void> {\n // Try different press handlers in order of preference\n const handlers = ['onPress', 'onPressIn', 'onResponderRelease'];\n\n for (const handler of handlers) {\n if (typeof props[handler] === 'function') {\n // Create a synthetic event object\n const event = this.createPressEvent(params);\n (props[handler] as (event: unknown) => void)(event);\n return;\n }\n }\n\n throw new Error('No press handler found on element');\n }\n\n /**\n * Perform long press action\n */\n private async performLongPress(\n props: Record<string, unknown>,\n params?: PressActionParams\n ): Promise<void> {\n if (typeof props.onLongPress === 'function') {\n const event = this.createPressEvent(params);\n (props.onLongPress as (event: unknown) => void)(event);\n return;\n }\n\n throw new Error('No long press handler found on element');\n }\n\n /**\n * Perform double tap action\n */\n private async performDoubleTap(props: Record<string, unknown>): Promise<void> {\n // First try dedicated double tap handler\n if (typeof props.onDoubleTap === 'function') {\n (props.onDoubleTap as () => void)();\n return;\n }\n\n // Fall back to calling press twice\n if (typeof props.onPress === 'function') {\n const event = this.createPressEvent();\n (props.onPress as (event: unknown) => void)(event);\n await sleep(50);\n (props.onPress as (event: unknown) => void)(event);\n return;\n }\n\n throw new Error('No press handler found for double tap');\n }\n\n /**\n * Perform type action\n */\n private async performType(\n element: ReturnType<NativeUIBridgeRegistry['getElement']>,\n props: Record<string, unknown>,\n params: TypeActionParams\n ): Promise<void> {\n if (!params?.text) {\n throw new Error('Type action requires text parameter');\n }\n\n // Clear first if requested. Accept either `clearFirst` (native SDK\n // convention) or `clear` (runner UI Bridge convention) — so agents\n // using the same action across platforms don't hit a naming mismatch.\n if (params.clearFirst || params.clear) {\n await this.performClear(element, props);\n }\n\n // Type character by character if delay specified\n if (params.delay && params.delay > 0) {\n const currentValue = (element?.getState().value || '') as string;\n for (const char of params.text) {\n const newValue = currentValue + char;\n if (typeof props.onChangeText === 'function') {\n (props.onChangeText as (text: string) => void)(newValue);\n }\n await sleep(params.delay);\n }\n } else {\n // Type all at once\n if (typeof props.onChangeText === 'function') {\n (props.onChangeText as (text: string) => void)(params.text);\n } else if (typeof props.onChange === 'function') {\n (props.onChange as (event: { nativeEvent: { text: string } }) => void)({\n nativeEvent: { text: params.text },\n });\n } else {\n throw new Error('No text change handler found on element');\n }\n }\n\n // Update element state\n if (element) {\n this.registry.updateElementState(element.id, { value: params.text });\n }\n }\n\n /**\n * Perform setValue action.\n *\n * Web/runner UI Bridge parity: `setValue` replaces the input's value\n * atomically in a single call (no per-character keystroke simulation),\n * mirroring the web bridge's `setValue` semantics. On native there is no\n * DOM value to assign, so we drive the controlled-input handler\n * (`onChangeText`, falling back to `onChange`) with the full string. The\n * registry's `state.value` is then synced so a subsequent GET on the\n * element reflects the new value.\n *\n * Unlike `type`, this does not append to existing content and ignores\n * `delay` — it is the deterministic \"set the field to exactly this\" action.\n */\n private async performSetValue(\n element: ReturnType<NativeUIBridgeRegistry['getElement']>,\n props: Record<string, unknown>,\n params: TypeActionParams\n ): Promise<void> {\n // `text` is the canonical key; accept `value` as an alias so callers using\n // the web bridge's `{ value }` body shape work without translation.\n const next =\n typeof params?.text === 'string'\n ? params.text\n : typeof (params as { value?: unknown })?.value === 'string'\n ? ((params as { value?: string }).value as string)\n : undefined;\n\n if (typeof next !== 'string') {\n throw new Error('setValue action requires a string \"text\" (or \"value\") parameter');\n }\n\n if (typeof props.onChangeText === 'function') {\n (props.onChangeText as (text: string) => void)(next);\n } else if (typeof props.onChange === 'function') {\n (props.onChange as (event: { nativeEvent: { text: string } }) => void)({\n nativeEvent: { text: next },\n });\n } else {\n throw new Error('No text change handler found on element');\n }\n\n if (element) {\n this.registry.updateElementState(element.id, { value: next });\n }\n }\n\n /**\n * Perform clear action\n */\n private async performClear(\n element: ReturnType<NativeUIBridgeRegistry['getElement']>,\n props: Record<string, unknown>\n ): Promise<void> {\n if (typeof props.onChangeText === 'function') {\n (props.onChangeText as (text: string) => void)('');\n } else if (typeof props.onChange === 'function') {\n (props.onChange as (event: { nativeEvent: { text: string } }) => void)({\n nativeEvent: { text: '' },\n });\n }\n\n // Update element state\n if (element) {\n this.registry.updateElementState(element.id, { value: '' });\n }\n }\n\n /**\n * Perform focus action\n */\n private async performFocus(\n element: ReturnType<NativeUIBridgeRegistry['getElement']>\n ): Promise<void> {\n if (element?.ref.current && 'focus' in element.ref.current) {\n (element.ref.current as { focus: () => void }).focus();\n }\n\n // Update element state\n if (element) {\n this.registry.updateElementState(element.id, { focused: true });\n }\n }\n\n /**\n * Perform blur action\n */\n private async performBlur(\n element: ReturnType<NativeUIBridgeRegistry['getElement']>\n ): Promise<void> {\n if (element?.ref.current && 'blur' in element.ref.current) {\n (element.ref.current as { blur: () => void }).blur();\n }\n\n // Update element state\n if (element) {\n this.registry.updateElementState(element.id, { focused: false });\n }\n }\n\n /**\n * Perform scroll action\n */\n private async performScroll(\n props: Record<string, unknown>,\n params?: ScrollActionParams\n ): Promise<void> {\n if (typeof props.onScroll === 'function') {\n const event = {\n nativeEvent: {\n contentOffset: params?.offset || { x: 0, y: 0 },\n },\n };\n (props.onScroll as (event: unknown) => void)(event);\n }\n }\n\n /**\n * Perform scrollIntoView: scroll the element's DECLARED scroll container so\n * the element sits `padding` dp below the top of its viewport.\n *\n * The container comes from `scrollAncestorId` and nowhere else — the\n * registry keeps no parent chain (`RegisterElementOptions.scrollAncestorId`),\n * so there is no \"nearest ScrollView\" to find. Nothing here tracks a\n * ScrollView's content offset either (`performScroll` only fakes an\n * `onScroll` event), so the target is measured CONTENT-relative with\n * `measureLayout` against the container's inner content view: stateless,\n * and immune to a stale-offset race.\n *\n * Result shape mirrors the web executor's `scrollIntoView`\n * (`@qontinui/ui-bridge` `control/action-executor.ts`):\n * `{ alreadyVisible, scrolled }`, short-circuiting when the element is\n * already fully inside its clip region. \"Fully visible\" is only claimed when\n * it is MEASURED — a page-space rect for the element and a known,\n * non-empty clip (window ∩ declared container), both measured at call\n * time. Anything unknown scrolls.\n *\n * Containers: a ScrollView, or a VirtualizedList (FlatList / SectionList)\n * unwrapped through `getNativeScrollRef()` / `getScrollResponder()`.\n * Vertical only — a `horizontal` container is NOT_SUPPORTED. The action\n * returns once `scrollTo` is dispatched; positions settle on the next frame.\n *\n * Prerequisites are checked BEFORE the visibility short-circuit, so whether\n * the element supports the action does not depend on where it happens to be\n * on screen. Each missing prerequisite is a `NOT_SUPPORTED` failure.\n */\n private async performScrollIntoView(\n element: NonNullable<ReturnType<NativeUIBridgeRegistry['getElement']>>,\n params?: ScrollIntoViewActionParams\n ): Promise<{ alreadyVisible: boolean; scrolled: boolean }> {\n const padding = params?.padding ?? DEFAULT_SCROLL_INTO_VIEW_PADDING;\n if (typeof padding !== 'number' || !Number.isFinite(padding) || padding < 0) {\n throw new Error('scrollIntoView \"padding\" must be a finite, non-negative number');\n }\n\n const ancestorId = element.scrollAncestorId;\n if (!ancestorId) {\n throw new NativeActionError(\n `scrollIntoView is not supported on element \"${element.id}\": it declares no scrollAncestorId, ` +\n 'and the registry keeps no parent chain to find its scroll container from',\n 'NOT_SUPPORTED'\n );\n }\n const ancestor = ancestorId === element.id ? undefined : this.registry.getElement(ancestorId);\n if (!ancestor) {\n throw new NativeActionError(\n `scrollIntoView is not supported on element \"${element.id}\": its declared scrollAncestorId ` +\n `\"${ancestorId}\" is not a registered element`,\n 'NOT_SUPPORTED'\n );\n }\n const container = resolveScrollView(ancestor.ref.current);\n if (!container) {\n throw new NativeActionError(\n `scrollIntoView is not supported on element \"${element.id}\": its scroll ancestor ` +\n `\"${ancestorId}\" has no scrollTo (not a mounted ScrollView, and no ` +\n 'getNativeScrollRef/getScrollResponder yielding one)',\n 'NOT_SUPPORTED'\n );\n }\n if (isDeclaredHorizontal(ancestor.props, ancestor.ref.current, container)) {\n // `scrollTo` here moves only y; RN sends `x || 0`, so on a horizontal\n // ScrollView this would jump the content to its start and still report\n // success. Refuse rather than lie.\n //\n // LIMIT: detected only where `horizontal` is visible to the bridge —\n // captured props (`captureProps({ horizontal: true })` / a direct\n // `registerElement` with `props`) or a class-component ref carrying\n // `props.horizontal` (FlatList / SectionList instances). A horizontal\n // ScrollView registered through `useUIElement` without captured props\n // is NOT detected; the action is documented as vertical-only.\n throw new NativeActionError(\n `scrollIntoView is not supported on element \"${element.id}\": its scroll ancestor ` +\n `\"${ancestorId}\" is horizontal (only vertical containers are supported)`,\n 'NOT_SUPPORTED'\n );\n }\n // `getInnerViewRef()` returns a host instance on both architectures and is\n // the primary path. `getInnerViewNode()` returns a numeric tag, which only\n // the legacy architecture's `measureLayout` accepts (Fabric ignores it and\n // never calls back — the timeout below then names that cause).\n const innerViewRef = container.getInnerViewRef?.();\n const innerView = innerViewRef ?? container.getInnerViewNode?.();\n const innerViewIsTag = innerViewRef == null && typeof innerView === 'number';\n if (innerView === undefined || innerView === null) {\n throw new NativeActionError(\n `scrollIntoView is not supported on element \"${element.id}\": its scroll ancestor ` +\n `\"${ancestorId}\" exposes no inner content view to measure against`,\n 'NOT_SUPPORTED'\n );\n }\n const target = element.ref.current as unknown as Partial<MeasurableRef> | null;\n if (!target || typeof target.measureLayout !== 'function') {\n throw new NativeActionError(\n `scrollIntoView is not supported on element \"${element.id}\": its ref has no measureLayout ` +\n '(not a mounted host view)',\n 'NOT_SUPPORTED'\n );\n }\n\n // Already-visible short-circuit — only on MEASURED evidence: the target\n // AND its declared container are both measured now (targeted, bounded —\n // not a registry-wide sweep), and the target lies fully inside\n // window ∩ container. An unknown container rect must NOT fall back to the\n // window alone: a row below a short ScrollView's bottom edge is still\n // inside the window. Anything unknown scrolls.\n const [rect, ancestorRect] = await Promise.all([\n measurePageRectNow(element),\n measurePageRectNow(ancestor, container),\n ]);\n // With no viewport provider the window is UNKNOWN and only the container\n // bounds the check — the same answer `getClipRectFor` gives.\n const viewport = this.registry.getViewportRect();\n const clip = ancestorRect ? intersectRects(viewport, ancestorRect) : null;\n if (\n rect &&\n clip &&\n !isEmptyRect(clip) &&\n rect.right > rect.left &&\n rect.bottom > rect.top &&\n rect.top >= clip.top &&\n rect.left >= clip.left &&\n rect.bottom <= clip.bottom &&\n rect.right <= clip.right\n ) {\n return { alreadyVisible: true, scrolled: false };\n }\n\n const measured = await new Promise<{ x: number; y: number; width: number }>(\n (resolve, reject) => {\n let settled = false;\n const timer = setTimeout(() => {\n if (settled) return;\n settled = true;\n reject(\n new Error(\n `scrollIntoView: measureLayout did not call back within ${SCROLL_INTO_VIEW_MEASURE_TIMEOUT_MS}ms` +\n (innerViewIsTag\n ? ' (measured against a numeric inner-view tag from getInnerViewNode, which the new architecture does not support)'\n : '')\n )\n );\n }, SCROLL_INTO_VIEW_MEASURE_TIMEOUT_MS);\n const finish = (fn: () => void) => {\n if (settled) return;\n settled = true;\n clearTimeout(timer);\n fn();\n };\n try {\n target.measureLayout!(\n innerView,\n (x, y, width) =>\n finish(() =>\n Number.isFinite(y)\n ? resolve({ x, y, width })\n : reject(new Error('scrollIntoView: measureLayout returned a non-finite y'))\n ),\n () =>\n finish(() =>\n reject(\n new Error(\n `scrollIntoView: measureLayout failed for \"${element.id}\" relative to \"${ancestorId}\"`\n )\n )\n )\n );\n } catch (error) {\n finish(() => reject(error));\n }\n }\n );\n\n // Undeclared-horizontal backstop: content laid out sideways past the\n // container's measured width means scrolling only y cannot reach it (and\n // RN's `x || 0` would reset the x offset). Refuse rather than report a\n // scroll that did not bring the element into view. Skipped when the\n // container width is unknown.\n if (\n ancestorRect &&\n Number.isFinite(measured.x) &&\n Number.isFinite(measured.width) &&\n measured.x + measured.width > ancestorRect.right - ancestorRect.left + 1\n ) {\n throw new NativeActionError(\n `scrollIntoView is not supported on element \"${element.id}\": it is laid out beyond the ` +\n `horizontal extent of its scroll ancestor \"${ancestorId}\" (sideways overflow, a horizontal ` +\n 'container, or a nested horizontal container — declare that inner container as its ' +\n 'scrollAncestorId); only vertical scrolling is supported',\n 'NOT_SUPPORTED'\n );\n }\n\n container.scrollTo({ y: Math.max(0, measured.y - padding), animated: false });\n return { alreadyVisible: false, scrolled: true };\n }\n\n /**\n * Perform swipe action\n */\n private async performSwipe(\n props: Record<string, unknown>,\n params: SwipeActionParams\n ): Promise<void> {\n if (!params?.direction) {\n throw new Error('Swipe action requires direction parameter');\n }\n\n // Try dedicated swipe handlers\n const handlerMap: Record<string, string> = {\n left: 'onSwipeLeft',\n right: 'onSwipeRight',\n up: 'onSwipeUp',\n down: 'onSwipeDown',\n };\n\n const handler = handlerMap[params.direction];\n if (handler && typeof props[handler] === 'function') {\n (props[handler] as () => void)();\n return;\n }\n\n // Fall back to generic swipe handler\n if (typeof props.onSwipe === 'function') {\n (props.onSwipe as (direction: string) => void)(params.direction);\n }\n }\n\n /**\n * Perform toggle action\n */\n private async performToggle(props: Record<string, unknown>): Promise<void> {\n // For Switch components\n if (typeof props.onValueChange === 'function') {\n const currentValue = props.value as boolean;\n (props.onValueChange as (value: boolean) => void)(!currentValue);\n return;\n }\n\n // Fall back to press\n if (typeof props.onPress === 'function') {\n (props.onPress as () => void)();\n return;\n }\n\n throw new Error('No toggle handler found on element');\n }\n\n /**\n * Create a synthetic press event\n */\n private createPressEvent(params?: PressActionParams): object {\n return {\n nativeEvent: {\n locationX: params?.position?.x ?? 0,\n locationY: params?.position?.y ?? 0,\n timestamp: Date.now(),\n },\n persist: () => {},\n };\n }\n\n /**\n * Execute a component action\n */\n async executeComponentAction(\n componentId: string,\n request: ComponentActionRequest,\n options: ComponentActionInvokeOptions = {}\n ): Promise<ComponentActionResponse> {\n const startTime = Date.now();\n\n try {\n const component = this.registry.getComponent(componentId);\n\n if (!component) {\n return {\n success: false,\n error: `Component not found: ${componentId}`,\n durationMs: Date.now() - startTime,\n timestamp: Date.now(),\n requestId: request.requestId,\n };\n }\n\n // Find the action\n const action = component.actions.find((a) => a.id === request.action);\n\n if (!action) {\n return {\n success: false,\n error: `Action not found: ${request.action}`,\n durationMs: Date.now() - startTime,\n timestamp: Date.now(),\n requestId: request.requestId,\n };\n }\n\n // `timeoutMs` is WIRE data — the HTTP entry point forwards it verbatim\n // from a JSON body — so it is validated and clamped here, before it can\n // reach a timer. See `normalizeActionTimeoutMs` for the policy (0\n // abandons on the next tick; negative / NaN / non-numeric are refused;\n // anything above 24h is clamped, because past 2^31-1 `setTimeout` wraps\n // negative and fires immediately).\n const timeout = normalizeActionTimeoutMs(request.timeoutMs);\n if (!timeout.ok) {\n return {\n success: false,\n error: `Action \"${request.action}\" on component \"${componentId}\" was rejected: ${timeout.reason}.`,\n durationMs: Date.now() - startTime,\n timestamp: Date.now(),\n requestId: request.requestId,\n };\n }\n const timeoutMs = timeout.timeoutMs;\n\n // Phase 2: `paramSchema` is published to agents, so it has to mean\n // something. Validate BEFORE the handler runs — a rejection after a\n // side-effect is not a rejection.\n const validationMode = options.paramValidation ?? getDefaultParamValidationMode();\n if (validationMode !== 'off' && action.paramSchema !== undefined) {\n // The validator walks AUTHOR-supplied schema data. It is bounded\n // against both known fault routes (`param-schema.ts` MAX_SCHEMA_DEPTH /\n // MAX_PATTERN_LENGTH), but it is wrapped anyway: without this, a\n // validator fault would fall into the generic catch below and be\n // reported as a HANDLER failure, for a handler that never ran.\n let validation: ReturnType<typeof validateActionParams>;\n try {\n validation = validateActionParams(action.paramSchema, request.params);\n } catch (validatorFault) {\n const detail =\n validatorFault instanceof Error ? validatorFault.message : String(validatorFault);\n const faultMessage = `Action \"${request.action}\" on component \"${componentId}\": its declared paramSchema could not be evaluated (${detail}).`;\n if (validationMode === 'enforce') {\n // A gate that cannot be evaluated has not been cleared. The prose\n // names the SCHEMA, so it is not mistaken for a handler fault.\n return {\n success: false,\n error: faultMessage,\n durationMs: Date.now() - startTime,\n timestamp: Date.now(),\n requestId: request.requestId,\n };\n }\n console.warn(`[ui-bridge-native] ${faultMessage}`);\n validation = { valid: true, issues: [] };\n }\n if (!validation.valid) {\n const message = formatParamValidationFailure(\n componentId,\n request.action,\n validation.issues\n );\n if (validationMode === 'enforce') {\n // Prose `error` rather than structured `failureDetails` — this\n // tree's response type has no such field. See the note on\n // `ComponentActionInvokeOptions.paramValidation`.\n return {\n success: false,\n error: message,\n durationMs: Date.now() - startTime,\n timestamp: Date.now(),\n requestId: request.requestId,\n };\n }\n console.warn(`[ui-bridge-native] ${message}`);\n }\n }\n\n // The handler is *given* a signal (cooperative cancellation) and is\n // *raced* against it (enforced abandonment) — a handler that ignores its\n // signal must still be abandonable at the caller. Phase 3 of plan\n // 2026-08-20-ui-bridge-action-declaration-shape.\n const outcome = await runAbortable((signal) => action.handler(request.params, { signal }), {\n signal: options.signal,\n timeoutMs,\n });\n\n if (outcome.aborted) {\n // NOTE: this tree's `ComponentActionResponse` has no `failureDetails`\n // field and this package ships no diagnostics module, so the\n // cancellation surfaces as a prose `error` rather than through\n // `buildActionFailureDetails('UB-ACTION-FAILED', ...)` the way the web\n // seam does. Giving the native channel structured failure details is a\n // separate change, not Phase 3.\n return {\n success: false,\n error:\n outcome.reason === 'timeout'\n ? `Action \"${request.action}\" on component \"${componentId}\" was abandoned after its ${timeoutMs}ms timeout elapsed.`\n : `Action \"${request.action}\" on component \"${componentId}\" was cancelled by the caller's abort signal.`,\n durationMs: Date.now() - startTime,\n timestamp: Date.now(),\n requestId: request.requestId,\n };\n }\n\n return {\n success: true,\n result: outcome.result,\n durationMs: Date.now() - startTime,\n timestamp: Date.now(),\n requestId: request.requestId,\n };\n } catch (error) {\n return {\n success: false,\n error: error instanceof Error ? error.message : String(error),\n stack: error instanceof Error ? error.stack : undefined,\n durationMs: Date.now() - startTime,\n timestamp: Date.now(),\n requestId: request.requestId,\n };\n }\n }\n\n /**\n * Find elements\n */\n async find(request: NativeFindRequest): Promise<NativeFindResponse> {\n const startTime = Date.now();\n\n const allElements = this.registry.getAllElements();\n let filtered = allElements;\n\n // Filter by type\n if (request.types && request.types.length > 0) {\n filtered = filtered.filter((e) => request.types!.includes(e.type));\n }\n\n // Filter by testID pattern\n if (request.testIdPattern) {\n const regex = new RegExp(request.testIdPattern.replace(/\\*/g, '.*').replace(/\\?/g, '.'));\n filtered = filtered.filter((e) => {\n const identifier = e.getIdentifier();\n return identifier.testId && regex.test(identifier.testId);\n });\n }\n\n // Filter by accessibility label pattern\n if (request.accessibilityLabelPattern) {\n const regex = new RegExp(\n request.accessibilityLabelPattern.replace(/\\*/g, '.*').replace(/\\?/g, '.')\n );\n filtered = filtered.filter((e) => {\n const identifier = e.getIdentifier();\n return identifier.accessibilityLabel && regex.test(identifier.accessibilityLabel);\n });\n }\n\n // Filter by visibility\n if (request.visibleOnly) {\n filtered = filtered.filter((e) => e.getState().visible);\n }\n\n // Apply limit\n if (request.limit && request.limit > 0) {\n filtered = filtered.slice(0, request.limit);\n }\n\n // Map to discovered elements\n const elements: DiscoveredNativeElement[] = filtered.map((e) => ({\n id: e.id,\n type: e.type,\n identifier: e.getIdentifier(),\n state: e.getState(),\n actions: e.actions,\n label: e.label,\n }));\n\n return {\n elements,\n total: elements.length,\n durationMs: Date.now() - startTime,\n timestamp: Date.now(),\n };\n }\n\n /**\n * Wait for element conditions\n */\n async waitForElement(elementId: string, options: WaitOptions): Promise<WaitResult> {\n return this.waitForElementInternal(elementId, options);\n }\n\n /**\n * Internal wait implementation\n */\n private async waitForElementInternal(\n elementId: string,\n options: WaitOptions\n ): Promise<WaitResult> {\n const opts = { ...DEFAULT_WAIT_OPTIONS, ...options };\n const startTime = Date.now();\n\n while (Date.now() - startTime < opts.timeout) {\n const element = this.registry.getElement(elementId);\n\n if (!element) {\n await sleep(opts.interval);\n continue;\n }\n\n const state = element.getState();\n\n // Check conditions\n let conditionsMet = true;\n\n if (opts.visible && !state.visible) {\n conditionsMet = false;\n }\n\n if (opts.enabled && !state.enabled) {\n conditionsMet = false;\n }\n\n if (opts.focused && !state.focused) {\n conditionsMet = false;\n }\n\n // Check custom state conditions\n if (opts.state && Object.keys(opts.state).length > 0) {\n const stateRecord = state as unknown as Record<string, unknown>;\n for (const [key, value] of Object.entries(opts.state)) {\n if (stateRecord[key] !== value) {\n conditionsMet = false;\n break;\n }\n }\n }\n\n if (conditionsMet) {\n return {\n met: true,\n waitedMs: Date.now() - startTime,\n state,\n };\n }\n\n await sleep(opts.interval);\n }\n\n return {\n met: false,\n waitedMs: Date.now() - startTime,\n error: `Timeout waiting for conditions on element: ${elementId}`,\n };\n }\n}\n\n/**\n * Create a native action executor\n */\nexport function createNativeActionExecutor(registry: NativeUIBridgeRegistry): NativeActionExecutor {\n return new DefaultNativeActionExecutor(registry);\n}\n","/**\n * Native Design Inspector\n *\n * Pure TypeScript functions that map flattened React Native styles to the\n * web SDK's ExtendedComputedStyles format. No react-native imports — works\n * with already-flattened style objects from the registry.\n *\n * Key differences from web:\n * - No `window.getComputedStyle()` — styles are declarative objects\n * - No hover/active states — uses pressed/focused/disabled\n * - No pseudo-elements (::before/::after)\n * - No CSS grid, cursor, visibility, transitions, background-image\n * - RN default flexDirection is 'column' (not 'row')\n * - Shadows differ: iOS uses shadow* props, Android uses elevation\n * - Numeric values → \"Npx\" strings\n */\n\nimport type {\n ExtendedComputedStyles,\n ElementDesignData,\n StateStyles,\n StyleDiff,\n ResponsiveSnapshot,\n NativeInteractionStateName,\n} from './design-types';\nimport type { NativeLayout } from '../core/types';\n\n// ============================================================================\n// Helpers\n// ============================================================================\n\n/**\n * Convert a numeric RN value to a CSS px string.\n * String values (like \"50%\") pass through unchanged.\n */\nfunction toCssValue(value: unknown): string {\n if (value == null) return '';\n if (typeof value === 'number') return `${value}px`;\n return String(value);\n}\n\n/**\n * Convert RN transform array to CSS transform string.\n * e.g. [{translateX: 10}, {rotate: '45deg'}] → \"translateX(10px) rotate(45deg)\"\n */\nfunction transformToCss(transform: unknown): string {\n if (!Array.isArray(transform) || transform.length === 0) return '';\n\n return transform\n .map((t: Record<string, unknown>) => {\n const key = Object.keys(t)[0];\n if (!key) return '';\n const val = t[key];\n // Rotation values are already strings like '45deg'\n if (typeof val === 'string') return `${key}(${val})`;\n // Numeric values need px for translate, unitless for scale\n if (typeof val === 'number') {\n const needsPx = key.startsWith('translate') || key === 'perspective';\n return `${key}(${val}${needsPx ? 'px' : ''})`;\n }\n return '';\n })\n .filter(Boolean)\n .join(' ');\n}\n\n/**\n * Convert RN shadow props (iOS) + elevation (Android) to CSS box-shadow string.\n */\nfunction shadowToCss(style: Record<string, unknown>): string {\n const parts: string[] = [];\n\n // iOS shadow\n const shadowColor = style.shadowColor as string | undefined;\n const shadowOffset = style.shadowOffset as { width: number; height: number } | undefined;\n const shadowOpacity = style.shadowOpacity as number | undefined;\n const shadowRadius = style.shadowRadius as number | undefined;\n\n if (shadowColor && shadowOffset && shadowOpacity != null && shadowOpacity > 0) {\n const { width, height } = shadowOffset;\n parts.push(\n `${width}px ${height}px ${shadowRadius ?? 0}px ${shadowColor}` +\n (shadowOpacity < 1 ? ` /* opacity: ${shadowOpacity} */` : '')\n );\n }\n\n // Android elevation\n const elevation = style.elevation as number | undefined;\n if (elevation != null && elevation > 0) {\n parts.push(`elevation(${elevation})`);\n }\n\n return parts.join(', ');\n}\n\n/**\n * Convert RN border props to CSS border shorthand.\n */\nfunction borderToCss(style: Record<string, unknown>): string {\n const width = style.borderWidth as number | undefined;\n const color = style.borderColor as string | undefined;\n\n if (width == null && color == null) return '';\n return `${width ?? 0}px solid ${color ?? 'transparent'}`;\n}\n\n/**\n * Convert RN borderRadius to CSS border-radius string.\n * Handles both uniform radius and per-corner values.\n */\nfunction borderRadiusToCss(style: Record<string, unknown>): string {\n const uniform = style.borderRadius as number | undefined;\n if (uniform != null) return `${uniform}px`;\n\n const tl = style.borderTopLeftRadius as number | undefined;\n const tr = style.borderTopRightRadius as number | undefined;\n const bl = style.borderBottomLeftRadius as number | undefined;\n const br = style.borderBottomRightRadius as number | undefined;\n\n if (tl == null && tr == null && bl == null && br == null) return '';\n return `${tl ?? 0}px ${tr ?? 0}px ${br ?? 0}px ${bl ?? 0}px`;\n}\n\n/**\n * Resolve margin/padding shorthand + Horizontal/Vertical expansions.\n * Returns top, right, bottom, left values.\n */\nfunction resolveSpacing(\n style: Record<string, unknown>,\n prefix: 'margin' | 'padding'\n): { top: string; right: string; bottom: string; left: string; shorthand: string } {\n const all = style[prefix];\n const top = style[`${prefix}Top`] ?? style[`${prefix}Vertical`] ?? all;\n const bottom = style[`${prefix}Bottom`] ?? style[`${prefix}Vertical`] ?? all;\n const right = style[`${prefix}Right`] ?? style[`${prefix}Horizontal`] ?? all;\n const left = style[`${prefix}Left`] ?? style[`${prefix}Horizontal`] ?? all;\n\n const t = toCssValue(top);\n const r = toCssValue(right);\n const b = toCssValue(bottom);\n const l = toCssValue(left);\n\n // Build shorthand\n let shorthand = '';\n if (t || r || b || l) {\n if (t === r && r === b && b === l) {\n shorthand = t || '0px';\n } else if (t === b && r === l) {\n shorthand = `${t || '0px'} ${r || '0px'}`;\n } else {\n shorthand = `${t || '0px'} ${r || '0px'} ${b || '0px'} ${l || '0px'}`;\n }\n }\n\n return {\n top: t,\n right: r,\n bottom: b,\n left: l,\n shorthand,\n };\n}\n\n/**\n * Resolve gap values (gap, rowGap, columnGap).\n */\nfunction resolveGap(style: Record<string, unknown>): string {\n const gap = style.gap as number | undefined;\n const rowGap = style.rowGap as number | undefined;\n const columnGap = style.columnGap as number | undefined;\n\n if (gap != null) return `${gap}px`;\n if (rowGap != null && columnGap != null) return `${rowGap}px ${columnGap}px`;\n if (rowGap != null) return `${rowGap}px`;\n if (columnGap != null) return `${columnGap}px`;\n return '';\n}\n\n// ============================================================================\n// Core mapping function\n// ============================================================================\n\n/**\n * Map a flattened React Native style object to ExtendedComputedStyles.\n *\n * Rules:\n * - Numeric values → \"Npx\"\n * - String values → pass through\n * - textDecorationLine → textDecoration\n * - RN shadow props → boxShadow string\n * - CSS-only properties (cursor, visibility, grid*, etc.) → empty string\n */\nexport function mapNativeStyleToExtended(\n rnStyle: Record<string, unknown> | undefined | null\n): ExtendedComputedStyles {\n const s = rnStyle ?? {};\n\n const margin = resolveSpacing(s, 'margin');\n const padding = resolveSpacing(s, 'padding');\n\n return {\n // Layout\n display: (s.display as string) ?? 'flex',\n position: (s.position as string) ?? 'relative',\n boxSizing: '', // CSS-only\n width: toCssValue(s.width),\n height: toCssValue(s.height),\n minWidth: toCssValue(s.minWidth),\n maxWidth: toCssValue(s.maxWidth),\n minHeight: toCssValue(s.minHeight),\n maxHeight: toCssValue(s.maxHeight),\n margin: margin.shorthand,\n marginTop: margin.top,\n marginRight: margin.right,\n marginBottom: margin.bottom,\n marginLeft: margin.left,\n padding: padding.shorthand,\n paddingTop: padding.top,\n paddingRight: padding.right,\n paddingBottom: padding.bottom,\n paddingLeft: padding.left,\n overflow: (s.overflow as string) ?? '',\n overflowX: '', // CSS-only\n overflowY: '', // CSS-only\n\n // Flex/Grid — RN defaults to column, not row\n flexDirection: (s.flexDirection as string) ?? '',\n flexWrap: (s.flexWrap as string) ?? '',\n justifyContent: (s.justifyContent as string) ?? '',\n alignItems: (s.alignItems as string) ?? '',\n alignSelf: (s.alignSelf as string) ?? '',\n gap: resolveGap(s),\n gridTemplateColumns: '', // CSS-only\n gridTemplateRows: '', // CSS-only\n\n // Typography\n fontFamily: (s.fontFamily as string) ?? '',\n fontSize: toCssValue(s.fontSize),\n fontWeight: (s.fontWeight as string) ?? '',\n lineHeight: toCssValue(s.lineHeight),\n letterSpacing: toCssValue(s.letterSpacing),\n textAlign: (s.textAlign as string) ?? '',\n textTransform: (s.textTransform as string) ?? '',\n textDecoration: (s.textDecorationLine as string) ?? '', // RN name → CSS name\n color: (s.color as string) ?? '',\n\n // Visual\n backgroundColor: (s.backgroundColor as string) ?? '',\n backgroundImage: '', // CSS-only\n border: borderToCss(s),\n borderRadius: borderRadiusToCss(s),\n boxShadow: shadowToCss(s),\n opacity: s.opacity != null ? String(s.opacity) : '',\n outline: '', // CSS-only\n\n // Effects\n transform: transformToCss(s.transform),\n transition: '', // CSS-only\n cursor: '', // CSS-only\n zIndex: s.zIndex != null ? String(s.zIndex) : '',\n visibility: '', // CSS-only\n pointerEvents: (s.pointerEvents as string) ?? '',\n };\n}\n\n// ============================================================================\n// Design data functions\n// ============================================================================\n\n/**\n * Produce ElementDesignData for a single native element.\n */\nexport function getNativeElementDesignData(\n id: string,\n label: string | undefined,\n type: string,\n rnStyle: Record<string, unknown> | undefined | null,\n layout: NativeLayout | null\n): ElementDesignData {\n return {\n elementId: id,\n label,\n type,\n styles: mapNativeStyleToExtended(rnStyle),\n pseudoElements: [], // RN has no pseudo-elements\n rect: layout\n ? {\n x: layout.pageX,\n y: layout.pageY,\n width: layout.width,\n height: layout.height,\n }\n : { x: 0, y: 0, width: 0, height: 0 },\n };\n}\n\n/**\n * Compute style diffs between default and a state variation.\n */\nfunction computeStyleDiff(\n defaultStyles: ExtendedComputedStyles,\n stateStyles: ExtendedComputedStyles\n): StyleDiff[] {\n const diffs: StyleDiff[] = [];\n for (const key of Object.keys(defaultStyles) as Array<keyof ExtendedComputedStyles>) {\n if (defaultStyles[key] !== stateStyles[key]) {\n diffs.push({\n property: key,\n defaultValue: defaultStyles[key],\n stateValue: stateStyles[key],\n });\n }\n }\n return diffs;\n}\n\n/**\n * Merge a base RN style with a state override.\n */\nfunction mergeStyles(\n base: Record<string, unknown>,\n override: Record<string, unknown> | undefined\n): Record<string, unknown> {\n if (!override) return base;\n return { ...base, ...override };\n}\n\n/**\n * Produce StateStyles[] for default/pressed/focused/disabled.\n * Only includes states that have actual overrides or the default state.\n */\nexport function captureNativeStateVariations(\n baseStyle: Record<string, unknown> | undefined | null,\n stateStyles?: {\n pressed?: Record<string, unknown>;\n focused?: Record<string, unknown>;\n disabled?: Record<string, unknown>;\n }\n): StateStyles[] {\n const base = baseStyle ?? {};\n const defaultExtended = mapNativeStyleToExtended(base);\n\n const results: StateStyles[] = [\n {\n state: 'default',\n styles: defaultExtended,\n diffFromDefault: [],\n },\n ];\n\n if (!stateStyles) return results;\n\n const states: Array<{ name: NativeInteractionStateName; override?: Record<string, unknown> }> = [\n { name: 'pressed', override: stateStyles.pressed },\n { name: 'focused', override: stateStyles.focused },\n { name: 'disabled', override: stateStyles.disabled },\n ];\n\n for (const { name, override } of states) {\n if (!override) continue;\n const merged = mergeStyles(base, override);\n const extended = mapNativeStyleToExtended(merged);\n const diff = computeStyleDiff(defaultExtended, extended);\n if (diff.length > 0) {\n results.push({ state: name, styles: extended, diffFromDefault: diff });\n }\n }\n\n return results;\n}\n\n/**\n * Capture a responsive snapshot.\n *\n * Platform limitation: RN cannot constrain screen width at runtime.\n * This returns a single snapshot at the current device dimensions.\n */\nexport function captureNativeResponsiveSnapshot(\n elements: Array<{\n id: string;\n label?: string;\n type: string;\n flatStyle?: Record<string, unknown>;\n layout: NativeLayout | null;\n }>,\n screenDimensions: { width: number; height: number }\n): ResponsiveSnapshot[] {\n const elementData = elements.map((el) =>\n getNativeElementDesignData(el.id, el.label, el.type, el.flatStyle, el.layout)\n );\n\n return [\n {\n viewportWidth: screenDimensions.width,\n viewportLabel: 'current',\n elements: elementData,\n timestamp: Date.now(),\n },\n ];\n}\n","/**\n * UI Bridge Native Design Review Handlers\n *\n * HTTP handlers for the 8 design review endpoints.\n * Maps registered element styles to the web SDK's design data format.\n */\n\nimport type { NativeUIBridgeRegistry } from '../core/registry';\nimport type { APIResponse, HandlerContext } from './types';\nimport type { ElementDesignData, StateStyles, ResponsiveSnapshot } from '../design/design-types';\nimport {\n mapNativeStyleToExtended,\n getNativeElementDesignData,\n captureNativeStateVariations,\n captureNativeResponsiveSnapshot,\n} from '../design/design-inspector-native';\n\n// Style guide and baseline stored in closure (same pattern as web SDK)\nlet loadedStyleGuide: unknown = null;\nlet savedBaseline: unknown = null;\n\n// Try to load the style validator from the web SDK (optional peer dep)\nlet styleValidator: {\n runStyleAudit: (\n elements: Array<{ elementId: string; styles: Record<string, string> }>,\n guide: unknown\n ) => unknown;\n} | null = null;\n\n// Try to load quality evaluator from the web SDK (optional peer dep)\nlet qualityEvaluator: {\n evaluateQuality: (\n elements: ElementDesignData[],\n viewport: { width: number; height: number },\n context?: unknown\n ) => unknown;\n listContexts: () => Array<{ name: string; description: string }>;\n createBaseline: (\n elements: ElementDesignData[],\n viewport: { width: number; height: number },\n label?: string\n ) => unknown;\n diffSnapshots: (baseline: unknown, current: ElementDesignData[]) => unknown;\n} | null = null;\n\ntry {\n // eslint-disable-next-line @typescript-eslint/no-require-imports\n const specs = require('@qontinui/ui-bridge/specs');\n styleValidator = specs;\n qualityEvaluator = specs;\n} catch {\n // Optional dependency not installed — audit/evaluate endpoints will return an error\n}\n\nfunction success<T>(data: T): APIResponse<T> {\n return { success: true, data, timestamp: Date.now() };\n}\n\nfunction error<T = unknown>(message: string, code?: string): APIResponse<T> {\n return { success: false, error: message, code, timestamp: Date.now() };\n}\n\n/**\n * Design handler interface (subset of NativeServerHandlers)\n */\nexport interface NativeDesignHandlers {\n getElementStyles: (ctx: HandlerContext) => Promise<APIResponse<ElementDesignData>>;\n getElementStateStyles: (\n ctx: HandlerContext\n ) => Promise<APIResponse<{ elementId: string; stateStyles: StateStyles[] }>>;\n getDesignSnapshot: (\n ctx: HandlerContext\n ) => Promise<APIResponse<{ elements: ElementDesignData[]; timestamp: number }>>;\n getResponsiveSnapshots: (ctx: HandlerContext) => Promise<APIResponse<ResponsiveSnapshot[]>>;\n runDesignAudit: (ctx: HandlerContext) => Promise<APIResponse<unknown>>;\n loadStyleGuide: (ctx: HandlerContext) => Promise<APIResponse<{ loaded: boolean }>>;\n getStyleGuide: (ctx: HandlerContext) => Promise<APIResponse<unknown>>;\n clearStyleGuide: (ctx: HandlerContext) => Promise<APIResponse<{ cleared: boolean }>>;\n evaluateQuality: (ctx: HandlerContext) => Promise<APIResponse<unknown>>;\n getQualityContexts: (\n ctx: HandlerContext\n ) => Promise<APIResponse<Array<{ name: string; description: string }>>>;\n saveBaseline: (\n ctx: HandlerContext\n ) => Promise<APIResponse<{ saved: boolean; elementCount: number }>>;\n diffBaseline: (ctx: HandlerContext) => Promise<APIResponse<unknown>>;\n}\n\n/**\n * Create design review handlers.\n *\n * @param registry - the registered native element registry\n * @param viewportProvider - optional injected viewport getter. Same shape as\n * the `viewportProvider` consumed by `handlers.ts`/`getPageHealth`. This is\n * injected by `createServerHandlers` from the `NativeServerConfig` the host\n * passes to `UIBridgeNativeProvider`/`NativeUIBridgeServer`, which in turn\n * reads `Dimensions.get('screen')` (or `'window'`). The indirection exists\n * because `require('react-native')` from this file crashes the host RN\n * app the moment any design endpoint is invoked: Metro/Hermes raise\n * `unknownModuleError` past every try/catch and tear down the JS thread.\n * This was the same latent crash that took out 0.6.3/0.6.4 page-health\n * handler — the design handlers had it too, just hiding on unused\n * endpoints until `POST /design/responsive` was first called.\n *\n * When the injected provider is absent (tests, custom hosts) the design\n * handlers fall back to `{width:0, height:0}` — the responsive snapshot\n * degenerates to \"zero-dimension viewport\" rather than crashing.\n */\nexport function createDesignHandlers(\n registry: NativeUIBridgeRegistry,\n viewportProvider?: () => { width: number; height: number }\n): NativeDesignHandlers {\n // Helper to get screen dimensions via the injected provider.\n //\n // The 0.6.3/0.6.4 implementation called `require('react-native')` here\n // inside a try/catch; Metro/Hermes still surfaced `unknownModuleError`\n // up the stack and tore down the JS thread the moment any design endpoint\n // was touched. The fix is to take the viewport as an injected dependency\n // (parity with `getPageHealth`) so this file has no `react-native` dep\n // at all — see the doc comment on `createDesignHandlers` above and the\n // project memory entry `feedback_metro_require_gotcha.md`.\n function getScreenDimensions(): { width: number; height: number } {\n return viewportProvider?.() ?? { width: 0, height: 0 };\n }\n\n return {\n // 1. GET /design/element/:id/styles\n getElementStyles: async (ctx) => {\n const { id } = ctx.params;\n const element = registry.getElement(id);\n\n if (!element) {\n return error('Element not found: ' + id, 'ELEMENT_NOT_FOUND');\n }\n\n const state = element.getState();\n const data = getNativeElementDesignData(\n id,\n element.label,\n element.type,\n element.flatStyle,\n state.layout\n );\n\n return success(data);\n },\n\n // 2. POST /design/element/:id/state-styles\n getElementStateStyles: async (ctx) => {\n const { id } = ctx.params;\n const element = registry.getElement(id);\n\n if (!element) {\n return error('Element not found: ' + id, 'ELEMENT_NOT_FOUND');\n }\n\n const stateStyles = captureNativeStateVariations(element.flatStyle, element.stateStyles);\n\n return success({ elementId: id, stateStyles });\n },\n\n // 3. POST /design/snapshot\n getDesignSnapshot: async (ctx) => {\n const body = ctx.body as\n | {\n elementIds?: string[];\n includePseudoElements?: boolean;\n }\n | undefined;\n\n let elements = registry.getAllElements();\n\n // Filter to requested IDs if specified\n if (body?.elementIds && body.elementIds.length > 0) {\n const idSet = new Set(body.elementIds);\n elements = elements.filter((e) => idSet.has(e.id));\n }\n\n const designData: ElementDesignData[] = elements.map((el) => {\n const state = el.getState();\n return getNativeElementDesignData(el.id, el.label, el.type, el.flatStyle, state.layout);\n });\n\n return success({ elements: designData, timestamp: Date.now() });\n },\n\n // 4. POST /design/responsive\n getResponsiveSnapshots: async () => {\n // Platform limitation: RN cannot constrain screen width at runtime.\n // Returns a single snapshot at current device dimensions.\n const elements = registry.getAllElements();\n const elementData = elements.map((el) => {\n const state = el.getState();\n return {\n id: el.id,\n label: el.label,\n type: el.type,\n flatStyle: el.flatStyle,\n layout: state.layout,\n };\n });\n\n const snapshots = captureNativeResponsiveSnapshot(elementData, getScreenDimensions());\n return success(snapshots);\n },\n\n // 5. POST /design/audit\n runDesignAudit: async (ctx) => {\n const body = ctx.body as\n | {\n guide?: unknown;\n elementIds?: string[];\n }\n | undefined;\n\n const guide = body?.guide ?? loadedStyleGuide;\n\n if (!guide) {\n return error('No style guide loaded or provided', 'NO_STYLE_GUIDE');\n }\n\n if (!styleValidator) {\n return error(\n 'Install @qontinui/ui-bridge for style audit support. ' +\n 'Add it as a dependency: npm install @qontinui/ui-bridge',\n 'VALIDATOR_NOT_AVAILABLE'\n );\n }\n\n let elements = registry.getAllElements();\n if (body?.elementIds && body.elementIds.length > 0) {\n const idSet = new Set(body.elementIds);\n elements = elements.filter((e) => idSet.has(e.id));\n }\n\n // Map elements to the format expected by the validator\n const auditElements = elements.map((el) => ({\n elementId: el.id,\n styles: mapNativeStyleToExtended(el.flatStyle) as unknown as Record<string, string>,\n }));\n\n try {\n const report = styleValidator.runStyleAudit(auditElements, guide);\n return success(report);\n } catch (err) {\n return error(\n 'Audit failed: ' + (err instanceof Error ? err.message : String(err)),\n 'DESIGN_AUDIT_ERROR'\n );\n }\n },\n\n // 6. POST /design/style-guide/load\n loadStyleGuide: async (ctx) => {\n const body = ctx.body as { guide?: unknown } | undefined;\n\n if (!body?.guide) {\n return error('Style guide is required in request body', 'INVALID_REQUEST');\n }\n\n loadedStyleGuide = body.guide;\n return success({ loaded: true });\n },\n\n // 7. GET /design/style-guide\n getStyleGuide: async () => {\n return success(loadedStyleGuide);\n },\n\n // 8. DELETE /design/style-guide\n clearStyleGuide: async () => {\n loadedStyleGuide = null;\n return success({ cleared: true });\n },\n\n // 9. POST /design/evaluate\n evaluateQuality: async (ctx) => {\n if (!qualityEvaluator) {\n return error(\n 'Install @qontinui/ui-bridge for quality evaluation support. ' +\n 'Add it as a dependency: npm install @qontinui/ui-bridge',\n 'EVALUATOR_NOT_AVAILABLE'\n );\n }\n\n const body = ctx.body as\n | {\n context?: string;\n customContext?: unknown;\n elementIds?: string[];\n viewport?: { width: number; height: number };\n }\n | undefined;\n\n let elements = registry.getAllElements();\n if (body?.elementIds && body.elementIds.length > 0) {\n const idSet = new Set(body.elementIds);\n elements = elements.filter((e) => idSet.has(e.id));\n }\n\n const designData: ElementDesignData[] = elements.map((el) => {\n const state = el.getState();\n return getNativeElementDesignData(el.id, el.label, el.type, el.flatStyle, state.layout);\n });\n\n const viewport = body?.viewport ?? getScreenDimensions();\n\n // Resolve context: custom object > style guide context > built-in name\n let context: unknown = body?.customContext ?? body?.context ?? 'general';\n if (typeof context === 'string' && loadedStyleGuide) {\n const guide = loadedStyleGuide as { qualityContexts?: Record<string, unknown> };\n if (guide.qualityContexts?.[context]) {\n context = guide.qualityContexts[context];\n }\n }\n\n try {\n const report = qualityEvaluator.evaluateQuality(designData, viewport, context);\n return success(report);\n } catch (err) {\n return error(\n 'Evaluation failed: ' + (err instanceof Error ? err.message : String(err)),\n 'QUALITY_EVALUATION_ERROR'\n );\n }\n },\n\n // 10. GET /design/evaluate/contexts\n getQualityContexts: async () => {\n if (!qualityEvaluator) {\n return error(\n 'Install @qontinui/ui-bridge for quality evaluation support.',\n 'EVALUATOR_NOT_AVAILABLE'\n );\n }\n return success(qualityEvaluator.listContexts());\n },\n\n // 11. POST /design/evaluate/baseline\n saveBaseline: async (ctx) => {\n if (!qualityEvaluator) {\n return error(\n 'Install @qontinui/ui-bridge for quality evaluation support.',\n 'EVALUATOR_NOT_AVAILABLE'\n );\n }\n\n const body = ctx.body as\n | {\n label?: string;\n elementIds?: string[];\n }\n | undefined;\n\n let elements = registry.getAllElements();\n if (body?.elementIds && body.elementIds.length > 0) {\n const idSet = new Set(body.elementIds);\n elements = elements.filter((e) => idSet.has(e.id));\n }\n\n const designData: ElementDesignData[] = elements.map((el) => {\n const state = el.getState();\n return getNativeElementDesignData(el.id, el.label, el.type, el.flatStyle, state.layout);\n });\n\n const viewport = getScreenDimensions();\n savedBaseline = qualityEvaluator.createBaseline(designData, viewport, body?.label);\n return success({ saved: true, elementCount: designData.length });\n },\n\n // 12. POST /design/evaluate/diff\n diffBaseline: async (ctx) => {\n if (!qualityEvaluator) {\n return error(\n 'Install @qontinui/ui-bridge for quality evaluation support.',\n 'EVALUATOR_NOT_AVAILABLE'\n );\n }\n\n if (!savedBaseline) {\n return error('No baseline saved. Call saveBaseline first.', 'NO_BASELINE');\n }\n\n const body = ctx.body as { elementIds?: string[] } | undefined;\n\n let elements = registry.getAllElements();\n if (body?.elementIds && body.elementIds.length > 0) {\n const idSet = new Set(body.elementIds);\n elements = elements.filter((e) => idSet.has(e.id));\n }\n\n const designData: ElementDesignData[] = elements.map((el) => {\n const state = el.getState();\n return getNativeElementDesignData(el.id, el.label, el.type, el.flatStyle, state.layout);\n });\n\n try {\n const report = qualityEvaluator.diffSnapshots(savedBaseline, designData);\n return success(report);\n } catch (err) {\n return error(\n 'Diff failed: ' + (err instanceof Error ? err.message : String(err)),\n 'DIFF_BASELINE_ERROR'\n );\n }\n },\n };\n}\n","/**\n * Page Health Diagnostics — Mobile (React Native) variant.\n *\n * Mirrors the runner / web analyzer in\n * `ui-bridge/packages/ui-bridge/src/server/page-health.ts`\n * and the canonical Rust implementation in\n * `qontinui-runner/src-tauri/src/mcp/ui_bridge/screenshots.rs::ui_bridge_page_health_handler`\n *\n * Output shape (`summary`/`findings`/`heatmap`/`element_count`/`visible_count`)\n * matches those byte-for-byte so the same `page-health` skill works on web,\n * runner, and mobile without branching per platform.\n *\n * Mobile-specific differences from the web/runner analyzer:\n *\n * • Layout source: React Native elements expose `state.layout` in *pixels*\n * (`{x, y, width, height, pageX, pageY}` relative to the device viewport).\n * We normalize via `Dimensions.get('window')` into the 0-1 space the\n * analyzer expects. The web/runner analyzer reads pre-normalized\n * `state.normalizedRect` directly.\n *\n * • Interactivity detection: mobile elements don't carry a `category` field.\n * We treat `type ∈ {button, input, switch, checkbox, radio, touchable,\n * listItem}` as interactive instead.\n *\n * • CSS class signals: React Native has no class names, so the\n * `class contains spin|pulse|skeleton|...` heuristic is always empty.\n * We still emit the `css_signals` field (as `[]`) so the response shape\n * stays platform-neutral.\n *\n * Fold semantics (see Step 7: Visual anomalies):\n *\n * The `outside_viewport` count tracks only *horizontal* overflow — elements\n * whose normalized x is left of the viewport (`x + width < 0`) or right of\n * it (`x > 1`). Vertical offsets (`y > 1`, `y + height < 0`) are NOT an\n * anomaly on mobile: ScrollView / FlatList content legitimately extends\n * above or below the visible fold, and the user reaches it by scrolling.\n * Flagging those would WARNING every scrollable screen (settings, feed,\n * list pages). Only horizontal overflow is unreachable by the user on\n * typical mobile layouts (the viewport is ~full-width, no horizontal\n * scroll), so that's the meaningful anomaly we surface.\n */\n\nimport type { NativeElementState } from '../core/types';\n\n// ============================================================================\n// Types (mirrors ui-bridge/src/server/page-health.ts)\n// ============================================================================\n\nexport type PageHealthSeverity = 'OK' | 'WARNING' | 'CRITICAL';\n\nexport interface PageHealthFinding {\n check: string;\n severity: PageHealthSeverity;\n detail: string;\n data: Record<string, unknown>;\n}\n\nexport interface PageHealthReport {\n summary: PageHealthSeverity;\n findings: PageHealthFinding[];\n heatmap: string[];\n element_count: number;\n visible_count: number;\n}\n\n/**\n * Mobile element shape consumed by the analyzer. A loosened subset of the\n * registry's full element record — only fields the analyzer actually reads.\n */\nexport interface PageHealthElement {\n type: string;\n state: NativeElementState;\n}\n\n// ============================================================================\n// Constants (lifted verbatim from the canonical analyzer)\n// ============================================================================\n\nconst GRID_SIZE = 20;\n\nconst NAV_TYPES = new Set(['button', 'heading', 'badge', 'status-message']);\n\nconst SKIP_TEXT_TYPES = new Set(['button', 'link', 'tab', 'menuitem']);\n\nconst INTERACTIVE_TYPES = new Set([\n 'button',\n 'input',\n 'switch',\n 'checkbox',\n 'radio',\n 'touchable',\n 'listItem',\n]);\n\nconst ERROR_PHRASES = [\n 'error occurred',\n 'failed to',\n 'exception',\n 'crash',\n 'unavailable',\n 'something went wrong',\n 'could not',\n];\n\nconst LOADING_PHRASES = [\n 'loading',\n 'starting',\n 'connecting',\n 'please wait',\n 'initializing',\n 'fetching',\n];\n\nconst EMPTY_PHRASES = [\n 'no data',\n 'no results',\n 'nothing here',\n 'empty',\n 'no items',\n 'get started',\n];\n\n// ============================================================================\n// Helpers\n// ============================================================================\n\nfunction severityRank(s: PageHealthSeverity): number {\n if (s === 'CRITICAL') return 3;\n if (s === 'WARNING') return 2;\n return 1;\n}\n\nfunction worstSeverity(findings: PageHealthFinding[]): PageHealthSeverity {\n let worst: PageHealthSeverity = 'OK';\n for (const f of findings) {\n if (severityRank(f.severity) > severityRank(worst)) {\n worst = f.severity;\n }\n }\n return worst;\n}\n\nfunction truncate(s: string, n: number): string {\n if (s.length <= n) return s;\n return [...s].slice(0, n).join('');\n}\n\ninterface NormRect {\n x: number;\n y: number;\n width: number;\n height: number;\n}\n\n/**\n * Project a mobile `state.layout` (pixels) into 0-1 viewport coords.\n *\n * Returns null when the element hasn't been measured yet (layout=null), the\n * viewport is degenerate (width/height ≤ 0), or pageX/pageY are absent —\n * the analyzer skips those rather than guessing.\n */\nfunction normalizeRect(\n state: NativeElementState,\n viewport: { width: number; height: number }\n): NormRect | null {\n const layout = state.layout;\n if (!layout) return null;\n if (viewport.width <= 0 || viewport.height <= 0) return null;\n // pageX/pageY are the absolute device-relative coords — what the analyzer\n // wants. Fall back to x/y (parent-relative) if the platform didn't fill\n // pageX/pageY; this loses absolute positioning but is better than dropping\n // the element entirely.\n const px = layout.pageX ?? layout.x;\n const py = layout.pageY ?? layout.y;\n return {\n x: px / viewport.width,\n y: py / viewport.height,\n width: layout.width / viewport.width,\n height: layout.height / viewport.height,\n };\n}\n\n// ============================================================================\n// Analyzer\n// ============================================================================\n\n/**\n * Run the page-health analyzer over a list of mobile registry elements.\n *\n * The pipeline mirrors the canonical analyzer step-for-step:\n *\n * 1. Visible filter (state.visible + measurable layout)\n * 2. Spatial coverage on a 20x20 grid + left/right halves\n * 3. Layout regions (sidebar/header/content) by center-point\n * 4. Element diversity (nav-only flag)\n * 5. Text signal scanning (errors / loading / empty)\n * 6. Interactive readiness (disabled ratio across interactive types)\n * 7. Visual anomalies (zero-size, outside-viewport)\n * 8. ASCII heatmap\n * 9. Worst severity rollup\n */\nexport function diagnosePageHealth(\n elements: PageHealthElement[],\n viewport: { width: number; height: number }\n): PageHealthReport {\n const findings: PageHealthFinding[] = [];\n\n // Project each element's layout once; the analyzer iterates the result\n // multiple times.\n const projected = elements.map((el) => ({\n el,\n rect: el.state.visible ? normalizeRect(el.state, viewport) : null,\n }));\n const visible = projected.filter((p) => p.rect !== null) as Array<{\n el: PageHealthElement;\n rect: NormRect;\n }>;\n\n // --- Step 2: Spatial coverage ---------------------------------------------\n const grid: boolean[][] = Array.from({ length: GRID_SIZE }, () =>\n Array.from({ length: GRID_SIZE }, () => false)\n );\n\n for (const { rect } of visible) {\n const colStart = Math.max(0, Math.floor(rect.x * GRID_SIZE));\n const colEnd = Math.min(GRID_SIZE, Math.ceil((rect.x + rect.width) * GRID_SIZE));\n const rowStart = Math.max(0, Math.floor(rect.y * GRID_SIZE));\n const rowEnd = Math.min(GRID_SIZE, Math.ceil((rect.y + rect.height) * GRID_SIZE));\n for (let r = rowStart; r < rowEnd; r++) {\n for (let c = colStart; c < colEnd; c++) {\n grid[r][c] = true;\n }\n }\n }\n\n const totalCells = GRID_SIZE * GRID_SIZE;\n const halfCells = totalCells / 2;\n let filled = 0;\n let leftFilled = 0;\n let rightFilled = 0;\n const half = GRID_SIZE / 2;\n for (let r = 0; r < GRID_SIZE; r++) {\n for (let c = 0; c < GRID_SIZE; c++) {\n if (grid[r][c]) {\n filled++;\n if (c < half) leftFilled++;\n else rightFilled++;\n }\n }\n }\n const coveragePct = Math.round((filled / totalCells) * 100);\n const leftHalfPct = Math.round((leftFilled / halfCells) * 100);\n const rightHalfPct = Math.round((rightFilled / halfCells) * 100);\n\n let spatialSeverity: PageHealthSeverity = 'OK';\n if (coveragePct < 15) spatialSeverity = 'CRITICAL';\n else if (coveragePct < 30) spatialSeverity = 'WARNING';\n if (rightHalfPct < 5 && leftHalfPct > 20) spatialSeverity = 'CRITICAL';\n\n findings.push({\n check: 'spatial_coverage',\n severity: spatialSeverity,\n detail: `Elements cover ${coveragePct}% of viewport. Left=${leftHalfPct}%, Right=${rightHalfPct}%`,\n data: {\n coverage_pct: coveragePct,\n left_half_pct: leftHalfPct,\n right_half_pct: rightHalfPct,\n },\n });\n\n // --- Step 3: Layout regions -----------------------------------------------\n let sidebar = 0;\n let header = 0;\n let content = 0;\n for (const { rect } of visible) {\n const cx = rect.x + rect.width / 2;\n const cy = rect.y + rect.height / 2;\n if (cx < 0.2) sidebar++;\n else if (cy < 0.08) header++;\n else content++;\n }\n\n let layoutSeverity: PageHealthSeverity = 'OK';\n if (content === 0) layoutSeverity = 'CRITICAL';\n else if (content < 3) layoutSeverity = 'WARNING';\n\n findings.push({\n check: 'layout_regions',\n severity: layoutSeverity,\n detail: `sidebar=${sidebar}, header=${header}, content=${content}`,\n data: { sidebar, header, content },\n });\n\n // --- Step 4: Element diversity --------------------------------------------\n const typeCounts: Record<string, number> = {};\n for (const el of elements) {\n const t = el.type || 'unknown';\n typeCounts[t] = (typeCounts[t] ?? 0) + 1;\n }\n const allNav =\n elements.length > 5 && Object.keys(typeCounts).every((k) => NAV_TYPES.has(k));\n const diversitySeverity: PageHealthSeverity = allNav ? 'WARNING' : 'OK';\n\n findings.push({\n check: 'element_diversity',\n severity: diversitySeverity,\n detail: `${Object.keys(typeCounts).length} type(s) across ${elements.length} elements${\n allNav ? ' (navigation-only)' : ''\n }`,\n data: { types: typeCounts },\n });\n\n // --- Step 5: Text signal scanning -----------------------------------------\n // No CSS-class scan on RN (no class names) — we still emit `css_signals:[]`\n // so callers branching on the field shape don't need a mobile special case.\n const detectedErrors: string[] = [];\n const detectedLoading: string[] = [];\n const detectedEmpty: string[] = [];\n const detectedCss: string[] = [];\n\n for (const el of elements) {\n const elType = el.type ?? '';\n if (SKIP_TEXT_TYPES.has(elType)) continue;\n\n const text = (el.state.textContent ?? '').toString();\n if (!text) continue;\n const textLower = text.toLowerCase();\n for (const p of ERROR_PHRASES) {\n if (textLower.includes(p)) {\n detectedErrors.push(truncate(text, 120));\n break;\n }\n }\n for (const p of LOADING_PHRASES) {\n if (textLower.includes(p)) {\n detectedLoading.push(truncate(text, 120));\n break;\n }\n }\n for (const p of EMPTY_PHRASES) {\n if (textLower.includes(p)) {\n detectedEmpty.push(truncate(text, 120));\n break;\n }\n }\n }\n\n let textSeverity: PageHealthSeverity = 'OK';\n if (detectedErrors.length > 0) textSeverity = 'CRITICAL';\n else if (detectedLoading.length > 0 || detectedEmpty.length > 0) textSeverity = 'WARNING';\n\n findings.push({\n check: 'text_signals',\n severity: textSeverity,\n detail: `errors=${detectedErrors.length}, loading=${detectedLoading.length}, empty=${detectedEmpty.length}, css_signals=${detectedCss.length}`,\n data: {\n errors: detectedErrors,\n loading: detectedLoading,\n empty: detectedEmpty,\n css_signals: detectedCss,\n },\n });\n\n // --- Step 6: Interactive readiness ----------------------------------------\n let interactiveTotal = 0;\n let interactiveDisabled = 0;\n for (const el of elements) {\n if (!INTERACTIVE_TYPES.has(el.type)) continue;\n interactiveTotal++;\n if (el.state.enabled === false) interactiveDisabled++;\n }\n const interactiveSeverity: PageHealthSeverity =\n interactiveTotal > 0 && interactiveDisabled / interactiveTotal > 0.5 ? 'WARNING' : 'OK';\n\n findings.push({\n check: 'interactive_readiness',\n severity: interactiveSeverity,\n detail: `${interactiveTotal} interactive elements, ${interactiveDisabled} disabled`,\n data: { total: interactiveTotal, disabled: interactiveDisabled },\n });\n\n // --- Step 7: Visual anomalies ---------------------------------------------\n // `outside_viewport` counts only *horizontal* overflow. Below-fold and\n // above-fold content is normal on scrollable mobile screens and must not\n // flag — see the fold-semantics note at the top of this file.\n let zeroSize = 0;\n let outsideViewport = 0;\n for (const { rect } of visible) {\n if (rect.width === 0 || rect.height === 0) zeroSize++;\n if (rect.x + rect.width < 0 || rect.x > 1) {\n outsideViewport++;\n }\n }\n const anomalySeverity: PageHealthSeverity =\n zeroSize > 0 || outsideViewport > 0 ? 'WARNING' : 'OK';\n\n findings.push({\n check: 'visual_anomalies',\n severity: anomalySeverity,\n detail: `zero_size=${zeroSize}, outside_viewport=${outsideViewport} (horizontal-overflow only; below/above-fold scrollable content is not an anomaly)`,\n data: { zero_size: zeroSize, outside_viewport: outsideViewport },\n });\n\n // --- Step 8: ASCII heatmap ------------------------------------------------\n const heatmap: string[] = grid.map((row) =>\n row.map((cell) => (cell ? '#' : '.')).join('')\n );\n\n return {\n summary: worstSeverity(findings),\n findings,\n heatmap,\n element_count: elements.length,\n visible_count: visible.length,\n };\n}\n","/**\n * UI Bridge Native Server Handlers\n *\n * Request handlers for the HTTP API endpoints.\n */\n\n/**\n * SDK version string, injected at build time by tsup's `define` and at\n * test time by vitest's `define` (both source from this package's\n * `package.json` `version` field). Surfaced on the `/health` endpoint's\n * `data.uiBridge.version` so external automation agents can fingerprint\n * which on-device SDK build a runner is consuming without parsing the\n * bundle. Mirrors the web SDK's `__SDK_VERSION__` convention in\n * `@qontinui/ui-bridge` (see UIBridgeProviderInit.ts / tsup.config.ts).\n */\ndeclare const __SDK_VERSION__: string;\n\nimport {\n type NativeUIBridgeRegistry,\n computeVisibility,\n extractHandlerNames,\n matchesCurrentRoute,\n projectBbox,\n} from '../core/registry';\nimport { projectVisionFields } from '../core/vision-fields';\nimport type { NativeElementType, NativeLayout, NativeModalInfo, WorkflowStep } from '../core/types';\nimport type { ControlActionRequest, NativeActionExecutor } from '../control/types';\nimport type {\n APIResponse,\n ConsoleErrorsResponse,\n DismissModalResponse,\n FillFormFieldInput,\n FillFormFieldResult,\n FillFormResponse,\n HandlerContext,\n NativeServerHandlers,\n NetworkRequestsResponse,\n PushModalRequest,\n PushModalResponse,\n TapAtResponse,\n} from './types';\nimport { createDesignHandlers } from './design-handlers';\nimport type { ConsoleErrorBuffer, NetworkRequestBuffer } from './observability';\nimport { diagnosePageHealth, type PageHealthElement } from './page-health';\nimport { serializeElementCustomActions } from '../core/element-actions';\n\n/**\n * Registry-based text/label match used by the app-agnostic interaction\n * handlers (clickByText / typeInto / findByText). Mirrors the priority order\n * the `find` handler applies to a `query`: label first, then identifier\n * fields (testId / accessibilityLabel / treePath / uiId), then registered\n * handler names. Returns matches sorted by best-priority, then registry\n * insertion order (stable). `visibleOnly` filters to currently-visible\n * elements before scoring.\n *\n * Native has no DOM, so there is no `query` field on `NativeFindRequest`\n * (the executor only filters by type/testId/accessibilityLabel pattern);\n * this helper provides the same free-text matching the `find` handler does\n * for its `query` param, shared so the interaction handlers stay aligned.\n */\nfunction matchElementsByText(\n registry: NativeUIBridgeRegistry,\n text: string,\n opts?: { visibleOnly?: boolean }\n): Array<{ id: string; type: NativeElementType; label?: string }> {\n const needle = text.toLowerCase();\n const contains = (v: unknown): boolean =>\n typeof v === 'string' && v.toLowerCase().includes(needle);\n\n let all = registry.getAllElements();\n if (opts?.visibleOnly) {\n all = all.filter((e) => e.getState().visible);\n }\n\n const scored: Array<{\n rank: number;\n element: { id: string; type: NativeElementType; label?: string };\n }> = [];\n\n for (const e of all) {\n let rank = Number.POSITIVE_INFINITY;\n if (contains(e.label)) rank = Math.min(rank, 0);\n const ident = e.getIdentifier();\n if (ident) {\n if (contains(ident.testId)) rank = Math.min(rank, 1);\n if (contains(ident.accessibilityLabel)) rank = Math.min(rank, 1);\n if (contains(ident.treePath)) rank = Math.min(rank, 1);\n if (contains(ident.uiId)) rank = Math.min(rank, 1);\n }\n if (rank === Number.POSITIVE_INFINITY) {\n const handlers = extractHandlerNames(e.props);\n if (handlers.some((h) => h.toLowerCase().includes(needle))) rank = 2;\n }\n if (rank !== Number.POSITIVE_INFINITY) {\n scored.push({ rank, element: { id: e.id, type: e.type, label: e.label } });\n }\n }\n\n scored.sort((a, b) => a.rank - b.rank);\n return scored.map((s) => s.element);\n}\n\n/**\n * Resolve the element's runtime state for the single-element read endpoints,\n * guaranteeing `state.value` is populated for controlled inputs.\n *\n * Why this exists: `setValue`/`type`/`clear` write the new value into\n * `state.value` via `registry.updateElementState`, and `/control/snapshot`\n * reads it straight back. But a controlled `<TextInput value={x} />` carries\n * its value on `props.value` too, and there are windows where `state.value`\n * has not yet been mirrored from the prop (registration before the first\n * `updateElementProps`, or a host that wires `onChangeText` without threading\n * `value` into `useUIElement`). In those windows `GET /control/element/:id`\n * returned `value: undefined` while the snapshot — which benefits from the\n * registry's prop→state mirror on the same element — showed the real value.\n *\n * The fallback keeps the single-element read path consistent with the\n * snapshot: when `state.value` is absent for an input that has a string\n * `props.value`, surface the prop value. Never overwrites an explicit\n * `state.value` (which an action or `onChangeText` set), and only applies to\n * `type: 'input'` so non-inputs that happen to carry a `value` prop are\n * untouched (mirrors the gating in `registry.updateElementProps`).\n */\nfunction resolveElementState(\n element: NonNullable<ReturnType<NativeUIBridgeRegistry['getElement']>>\n): ReturnType<NonNullable<ReturnType<NativeUIBridgeRegistry['getElement']>>['getState']> {\n const state = element.getState();\n if (\n element.type === 'input' &&\n state.value === undefined &&\n typeof element.props?.value === 'string'\n ) {\n return { ...state, value: element.props.value as string };\n }\n return state;\n}\n\n/**\n * Result of executing a single workflow step\n */\ninterface WorkflowStepResult {\n stepId: string;\n type: string;\n status: 'completed' | 'failed' | 'skipped';\n result?: unknown;\n error?: string;\n durationMs: number;\n}\n\n/**\n * Execute a single workflow step using the registry and executor\n */\nasync function executeWorkflowStep(\n step: WorkflowStep,\n registry: NativeUIBridgeRegistry,\n executor: NativeActionExecutor\n): Promise<WorkflowStepResult> {\n const startTime = Date.now();\n\n try {\n switch (step.type) {\n case 'element-action': {\n if (!step.target || !step.action) {\n return {\n stepId: step.id,\n type: step.type,\n status: 'failed',\n error: 'element-action step requires target and action',\n durationMs: Date.now() - startTime,\n };\n }\n\n const response = await executor.executeAction(step.target, {\n action: step.action,\n params: step.params,\n waitOptions: step.waitOptions,\n });\n\n return {\n stepId: step.id,\n type: step.type,\n status: response.success ? 'completed' : 'failed',\n result: response.result,\n error: response.error,\n durationMs: Date.now() - startTime,\n };\n }\n\n case 'component-action': {\n if (!step.target || !step.action) {\n return {\n stepId: step.id,\n type: step.type,\n status: 'failed',\n error: 'component-action step requires target and action',\n durationMs: Date.now() - startTime,\n };\n }\n\n const response = await executor.executeComponentAction(step.target, {\n action: step.action,\n params: step.params,\n });\n\n return {\n stepId: step.id,\n type: step.type,\n status: response.success ? 'completed' : 'failed',\n result: response.result,\n error: response.error,\n durationMs: Date.now() - startTime,\n };\n }\n\n case 'wait': {\n if (!step.target) {\n return {\n stepId: step.id,\n type: step.type,\n status: 'failed',\n error: 'wait step requires target element id',\n durationMs: Date.now() - startTime,\n };\n }\n\n const waitResult = await executor.waitForElement(\n step.target,\n step.waitOptions || { visible: true, timeout: 10000, interval: 100 }\n );\n\n return {\n stepId: step.id,\n type: step.type,\n status: waitResult.met ? 'completed' : 'failed',\n result: waitResult.state,\n error: waitResult.error,\n durationMs: Date.now() - startTime,\n };\n }\n\n case 'assert': {\n if (!step.target) {\n return {\n stepId: step.id,\n type: step.type,\n status: 'failed',\n error: 'assert step requires target element id',\n durationMs: Date.now() - startTime,\n };\n }\n\n const element = registry.getElement(step.target);\n if (!element) {\n return {\n stepId: step.id,\n type: step.type,\n status: 'failed',\n error: `Element not found: ${step.target}`,\n durationMs: Date.now() - startTime,\n };\n }\n\n const state = element.getState();\n const expected = step.params || {};\n const stateRecord = state as unknown as Record<string, unknown>;\n const mismatches: string[] = [];\n\n for (const [key, value] of Object.entries(expected)) {\n const actual = stateRecord[key];\n const isEqual =\n typeof value === 'object' && value !== null\n ? JSON.stringify(actual) === JSON.stringify(value)\n : actual === value;\n if (!isEqual) {\n mismatches.push(\n `${key}: expected ${JSON.stringify(value)}, got ${JSON.stringify(actual)}`\n );\n }\n }\n\n return {\n stepId: step.id,\n type: step.type,\n status: mismatches.length === 0 ? 'completed' : 'failed',\n result: { state, mismatches },\n error: mismatches.length > 0 ? `Assertion failed: ${mismatches.join('; ')}` : undefined,\n durationMs: Date.now() - startTime,\n };\n }\n\n case 'custom': {\n if (!step.handler) {\n return {\n stepId: step.id,\n type: step.type,\n status: 'failed',\n error: 'custom step requires a handler function',\n durationMs: Date.now() - startTime,\n };\n }\n\n const result = await step.handler();\n // Allow handlers to signal failure by returning { success: false, error: '...' }\n const failed =\n result &&\n typeof result === 'object' &&\n 'success' in result &&\n (result as Record<string, unknown>).success === false;\n\n return {\n stepId: step.id,\n type: step.type,\n status: failed ? 'failed' : 'completed',\n result,\n error: failed\n ? ((result as Record<string, unknown>).error as string) ||\n 'Custom handler returned failure'\n : undefined,\n durationMs: Date.now() - startTime,\n };\n }\n\n case 'log': {\n const message = step.params?.message ?? step.params?.text ?? `[workflow] step ${step.id}`;\n console.log(`[ui-bridge-native] workflow log: ${message}`);\n\n return {\n stepId: step.id,\n type: step.type,\n status: 'completed',\n result: { message },\n durationMs: Date.now() - startTime,\n };\n }\n\n case 'navigate':\n case 'branch':\n case 'loop':\n case 'extract':\n return {\n stepId: step.id,\n type: step.type,\n status: 'skipped',\n error: `Step type \"${step.type}\" is not yet supported in native workflow execution`,\n durationMs: Date.now() - startTime,\n };\n\n default:\n return {\n stepId: step.id,\n type: step.type,\n status: 'failed',\n error: `Unknown step type: ${step.type}`,\n durationMs: Date.now() - startTime,\n };\n }\n } catch (err) {\n return {\n stepId: step.id,\n type: step.type,\n status: 'failed',\n error: err instanceof Error ? err.message : String(err),\n durationMs: Date.now() - startTime,\n };\n }\n}\n\n/**\n * Create a success response\n */\nfunction success<T>(data: T): APIResponse<T> {\n return {\n success: true,\n data,\n timestamp: Date.now(),\n };\n}\n\n/**\n * Create an error response\n */\nfunction error<T = unknown>(message: string, code?: string): APIResponse<T> {\n return {\n success: false,\n error: message,\n code,\n timestamp: Date.now(),\n };\n}\n\n/**\n * Create server handlers\n */\nexport function createServerHandlers(\n registry: NativeUIBridgeRegistry,\n executor: NativeActionExecutor,\n config?: {\n appInfo?: { appId: string; appName: string; appType: string; framework?: string };\n /** Optional console-error ring buffer powering `GET /control/console-errors`. */\n consoleErrorBuffer?: ConsoleErrorBuffer;\n /** Optional network-request ring buffer powering `GET /sdk/network-requests`. */\n networkRequestBuffer?: NetworkRequestBuffer;\n /**\n * Optional viewport getter for `POST /control/page-health`. Injected by\n * `UIBridgeNativeProvider` from `Dimensions.get('window')`. Kept out of\n * `handlers.ts` so this file has no `react-native` dep at all — the\n * `require('react-native')` pattern crashed the host in 0.6.3/0.6.4\n * (Metro/Hermes can't statically resolve the require even with a\n * `try/catch`; the `unknownModuleError` escapes and tears down the JS\n * thread). When absent (e.g. tests, or a custom host that doesn't pass\n * one), `getPageHealth` falls back to `body.viewport` then `{0,0}`.\n */\n viewportProvider?: () => { width: number; height: number };\n }\n): NativeServerHandlers {\n // Pipe the injected viewportProvider through to the design handlers so\n // they share the same react-native-free dependency-injection pattern as\n // `getPageHealth`. Without this, `design-handlers.ts` falls back to\n // `require('react-native')` inside `getScreenDimensions()` — which is the\n // identical Metro/Hermes `unknownModuleError` latent crash that 0.6.3/0.6.4\n // shipped on the page-health endpoint. See the `viewportProvider` doc\n // comment on this config and `feedback_metro_require_gotcha.md`.\n const designHandlers = createDesignHandlers(registry, config?.viewportProvider);\n\n return {\n // Elements\n getElements: async (ctx: HandlerContext) => {\n // Measure-on-read: refresh every mounted-visible element's geometry\n // from its live ref before serving stored layouts. Without this, the\n // registry serves mount-time coordinates that go stale on scroll /\n // recycle / re-render (RN never re-fires onLayout on pure translation).\n // Bounded by refreshMeasurements' internal timeout; never throws.\n await registry.refreshMeasurements();\n\n const visibleOnly =\n ctx.query?.visibleOnly === 'true' ||\n (ctx.body as Record<string, unknown>)?.visibleOnly === true;\n const forRoute = (ctx.query?.route || (ctx.body as Record<string, unknown>)?.route) as\n | string\n | undefined;\n\n // visibleOnly uses the looser mounted-visible filter so callers don't\n // miss elements whose first `onLayout` hasn't fired yet. Each element\n // carries a `visibility` field (`\"visible\"` / `\"likely-visible\"`) so\n // agents can branch on measured vs unmeasured downstream.\n let allElements = visibleOnly\n ? registry.getMountedVisibleElements()\n : registry.getAllElements();\n\n // Filter by specific route. Uses the same loose `matchesCurrentRoute`\n // semantics as `createSnapshot` so app-root chrome (tabs, persistent\n // headers) registered with `registrationRoute: null` survives the\n // filter alongside elements explicitly tagged for `forRoute`. See\n // `matchesCurrentRoute` in core/registry.ts for the contract.\n if (forRoute) {\n allElements = allElements.filter((e) => matchesCurrentRoute(e.registrationRoute, forRoute));\n }\n\n // Read once for the whole response, for the same reason `createSnapshot`\n // does: per-element reads cost a `Dimensions.get` each and let a rotation\n // split one response across two clip regions.\n const viewport = registry.getViewportRect();\n\n const elements = allElements.map((e) => {\n const handlers = extractHandlerNames(e.props);\n const state = e.getState();\n // Same helper `createSnapshot` uses — this used to be a hand-copied\n // duplicate of the predicate, which is how the two surfaces could\n // disagree about what \"visible\" means.\n const { visibility, visibilityReason } = computeVisibility(\n state,\n registry.getClipRectFor(e, viewport)\n );\n const bbox = projectBbox(state, visibility, registry.getPixelRatio());\n const vision = projectVisionFields({\n type: e.type,\n label: e.label,\n // Real handler names (onPress/...), NOT inferred actions which\n // synthesize press/click onto every element. See projectVisionFields.\n handlerNames: handlers,\n state,\n flatStyle: e.flatStyle,\n });\n return {\n id: e.id,\n type: e.type,\n label: e.label,\n identifier: e.getIdentifier(),\n state,\n actions: e.actions,\n customActions: serializeElementCustomActions(e.customActions),\n registeredHandlers: handlers.length > 0 ? handlers : undefined,\n registrationRoute: e.registrationRoute,\n visibility,\n ...(visibilityReason ? { visibilityReason } : {}),\n ...(bbox ? { bbox } : {}),\n ...vision,\n };\n });\n\n return success({ elements });\n },\n\n getElement: async (ctx: HandlerContext) => {\n const { id } = ctx.params;\n const element = registry.getElement(id);\n\n if (!element) {\n return error(`Element not found: ${id}`, 'ELEMENT_NOT_FOUND');\n }\n\n const handlers = extractHandlerNames(element.props);\n\n return success({\n element: {\n id: element.id,\n type: element.type,\n label: element.label,\n identifier: element.getIdentifier(),\n state: resolveElementState(element),\n actions: element.actions,\n customActions: serializeElementCustomActions(element.customActions),\n registeredHandlers: handlers.length > 0 ? handlers : undefined,\n registrationRoute: element.registrationRoute,\n },\n });\n },\n\n getElementState: async (ctx: HandlerContext) => {\n const { id } = ctx.params;\n const element = registry.getElement(id);\n\n if (!element) {\n return error(`Element not found: ${id}`, 'ELEMENT_NOT_FOUND');\n }\n\n return success({ state: resolveElementState(element) });\n },\n\n executeAction: async (ctx: HandlerContext) => {\n // Accept BOTH action-envelope shapes so the mobile server matches the\n // runner/web SDK contract:\n // 1. Flat HTTP body — `POST /control/element/:id/action` with\n // `{ action, params, waitOptions }` (the documented HTTP shape).\n // 2. Relay/WS nested envelope — the runner SDK dispatches element\n // actions as `relayCommand('executeElementAction', { id, request })`\n // where `request = { action, params, waitOptions }` (see\n // `ui-bridge/src/react/commandHandlers.ts` `executeElementAction`).\n // Over the WS/JSON-RPC and cloud-relay transports the whole `params`\n // object becomes `ctx.body`, so the action lives at `body.request`,\n // NOT `body.action`. Without this unwrap a runner-driven\n // `{ action: 'press' }` was rejected with \"Action is required\".\n const rawBody = (ctx.body ?? {}) as Partial<ControlActionRequest> & {\n id?: string;\n request?: Partial<ControlActionRequest>;\n };\n\n // The nested `request` envelope wins when present (relay/WS path);\n // otherwise read the flat fields (direct HTTP path).\n const envelope =\n rawBody.request && typeof rawBody.request === 'object' ? rawBody.request : rawBody;\n\n // Element id comes from the path param (`/control/element/:id/action`),\n // falling back to `body.id` for the relay `{ id, request }` envelope.\n const id = ctx.params.id ?? rawBody.id ?? '';\n\n if (!envelope?.action) {\n return error('Action is required', 'INVALID_REQUEST');\n }\n\n // Forwarded WHOLE, not field-by-field. Re-listing the fields is how the\n // web seam silently dropped every request option added after the list\n // was written — the caller opted in, the executor never heard about it,\n // and the response still came back `success: true`.\n const response = await executor.executeAction(id, envelope as ControlActionRequest);\n\n if (!response.success) {\n // An action that failed with a code of its own (`NOT_SUPPORTED` from\n // `scrollIntoView`) keeps it — mapped to 501 by `http-server.ts` — so\n // \"this element cannot do that\" is not reported as a retryable 400.\n return error(response.error || 'Action failed', response.code ?? 'ACTION_FAILED');\n }\n\n return success(response);\n },\n\n // Components\n getComponents: async () => {\n const components = registry.getAllComponents().map((c) => ({\n id: c.id,\n name: c.name,\n description: c.description,\n // Phase 4 (plan 2026-08-20-ui-bridge-action-declaration-shape):\n // carry the safety annotation onto the native wire too — a walker\n // driving a React Native app needs the same `destructive` exclusion\n // the web channel gets.\n actions: c.actions.map((a) => ({ id: a.id, label: a.label, effect: a.effect })),\n elementIds: c.elementIds,\n }));\n\n return success({ components });\n },\n\n getComponent: async (ctx: HandlerContext) => {\n const { id } = ctx.params;\n const component = registry.getComponent(id);\n\n if (!component) {\n return error(`Component not found: ${id}`, 'COMPONENT_NOT_FOUND');\n }\n\n return success({\n component: {\n id: component.id,\n name: component.name,\n description: component.description,\n actions: component.actions.map((a) => ({\n id: a.id,\n label: a.label,\n description: a.description,\n // Phase 4 — see the listing twin above.\n effect: a.effect,\n })),\n elementIds: component.elementIds,\n },\n });\n },\n\n executeComponentAction: async (ctx: HandlerContext) => {\n const { id, actionId } = ctx.params;\n // `timeoutMs` is read from the body, not dropped: an HTTP caller cannot\n // hand over an `AbortSignal`, so this is its ONLY way to call off a hung\n // handler. The executor validates and clamps it\n // (`normalizeActionTimeoutMs`) before it can reach a timer.\n const body = ctx.body as { params?: Record<string, unknown>; timeoutMs?: number };\n\n const response = await executor.executeComponentAction(id, {\n action: actionId,\n params: body?.params,\n timeoutMs: body?.timeoutMs,\n });\n\n if (!response.success) {\n return error(response.error || 'Action failed', 'ACTION_FAILED');\n }\n\n return success(response);\n },\n\n // Discovery\n //\n // Native parity with the runner's `POST /ui-bridge/ai/find`. The runner\n // matches a free-text `query` against label > text > value > aria-label >\n // placeholder > name. We replicate that here against the native registry's\n // analogues:\n // 1. `label` (the registered display label)\n // 2. identifier fields: `testId`, `accessibilityLabel`, `treePath`, `uiId`\n // 3. registered handler names (e.g. `onPress`, `onChangeText`)\n //\n // Match is case-insensitive substring. Empty/missing query falls back to\n // the structured filters (types/visibleOnly/etc.) so callers that don't\n // pass `query` still get the legacy behaviour. Once we've narrowed by\n // query the response is shaped through the executor's NativeFindResponse\n // envelope so the wire format stays stable.\n find: async (ctx: HandlerContext) => {\n const body = ctx.body as {\n query?: string;\n types?: NativeElementType[];\n testIdPattern?: string;\n accessibilityLabelPattern?: string;\n visibleOnly?: boolean;\n limit?: number;\n };\n\n const response = await executor.find({\n types: body?.types,\n testIdPattern: body?.testIdPattern,\n accessibilityLabelPattern: body?.accessibilityLabelPattern,\n visibleOnly: body?.visibleOnly,\n // When `query` is supplied we apply our own limit *after* ranking so\n // the highest-priority matches survive the cap; defer slicing to us\n // by widening here.\n limit: body?.query && body.query.length > 0 ? undefined : body?.limit,\n });\n\n const rawQuery = typeof body?.query === 'string' ? body.query.trim() : '';\n if (rawQuery.length === 0) {\n return success(response);\n }\n\n const needle = rawQuery.toLowerCase();\n const containsNeedle = (value: unknown): boolean =>\n typeof value === 'string' && value.toLowerCase().includes(needle);\n\n // Score each discovered element by best-priority field match. Lower\n // priorityRank wins; ties keep registry insertion order (stable sort).\n const scored: Array<{ priorityRank: number; element: (typeof response.elements)[number] }> =\n [];\n\n for (const el of response.elements) {\n let priorityRank = Number.POSITIVE_INFINITY;\n\n // 1. label\n if (containsNeedle(el.label)) {\n priorityRank = Math.min(priorityRank, 0);\n }\n\n // 2. identifier fields\n const ident = el.identifier;\n if (ident) {\n if (containsNeedle(ident.testId)) priorityRank = Math.min(priorityRank, 1);\n if (containsNeedle(ident.accessibilityLabel)) priorityRank = Math.min(priorityRank, 1);\n if (containsNeedle(ident.treePath)) priorityRank = Math.min(priorityRank, 1);\n if (containsNeedle(ident.uiId)) priorityRank = Math.min(priorityRank, 1);\n }\n\n // 3. registered handler names — pull from the registry since the\n // discovered envelope doesn't include props.\n if (priorityRank === Number.POSITIVE_INFINITY) {\n const registered = registry.getElement(el.id);\n const handlers = extractHandlerNames(registered?.props);\n if (handlers.some((h) => h.toLowerCase().includes(needle))) {\n priorityRank = 2;\n }\n }\n\n if (priorityRank !== Number.POSITIVE_INFINITY) {\n scored.push({ priorityRank, element: el });\n }\n }\n\n scored.sort((a, b) => a.priorityRank - b.priorityRank);\n\n const limit = body?.limit && body.limit > 0 ? body.limit : undefined;\n const filtered = limit ? scored.slice(0, limit) : scored;\n\n return success({\n ...response,\n elements: filtered.map((s) => s.element),\n total: filtered.length,\n });\n },\n\n getSnapshot: async (ctx: HandlerContext) => {\n // Measure-on-snapshot: re-measure geometry at read time so snapshot\n // `bbox` values reflect where elements ARE, not where they mounted.\n // Critical for virtualized lists (FlashList) whose cells move without\n // re-firing onLayout. `createSnapshot` itself stays sync; the refresh\n // is bounded by an internal timeout and never throws.\n await registry.refreshMeasurements();\n\n const visibleOnly =\n ctx.query?.visibleOnly === 'true' ||\n (ctx.body as Record<string, unknown>)?.visibleOnly === true;\n const currentRouteOnly =\n ctx.query?.currentRouteOnly === 'true' ||\n (ctx.body as Record<string, unknown>)?.currentRouteOnly === true;\n // Pass `undefined` (not `null`) for routeInfo so `createSnapshot`\n // falls back to a registry-registered route provider if one exists —\n // without that fallback, the cloud-relay / bare-server path would\n // emit `currentRoute: null` even when a `RouteTracker` was wired.\n const snapshot = registry.createSnapshot(undefined, { visibleOnly, currentRouteOnly });\n return success(snapshot);\n },\n\n getPageHealth: async (ctx: HandlerContext) => {\n // Viewport resolution priority:\n // 1. Explicit body.viewport — for offline analysis, replaying a\n // snapshot from a different device, or any caller that wants to\n // override the device's reported viewport.\n // 2. `config.viewportProvider()` — injected by\n // `UIBridgeNativeProvider` from `Dimensions.get('window')`.\n // 3. `{0,0}` fallback (degenerates to a coverage_pct=0 report\n // rather than crashing).\n //\n // The injection indirection exists because importing react-native\n // from this file (or `require('react-native')` with try/catch) both\n // crash the host RN app — see the [[viewportProvider]] doc comment\n // in `NativeServerConfig` and the project memory entry\n // `feedback_metro_require_gotcha.md`.\n const bodyViewport = (ctx.body as { viewport?: { width: number; height: number } })?.viewport;\n const viewport = bodyViewport ?? config?.viewportProvider?.() ?? { width: 0, height: 0 };\n\n const elements: PageHealthElement[] = registry.getAllElements().map((e) => ({\n type: e.type,\n state: e.getState(),\n }));\n\n const report = diagnosePageHealth(elements, viewport);\n return success(report);\n },\n\n // Workflows\n getWorkflows: async () => {\n const workflows = registry.getAllWorkflows().map((w) => ({\n id: w.id,\n name: w.name,\n description: w.description,\n stepCount: w.steps.length,\n }));\n\n return success({ workflows });\n },\n\n runWorkflow: async (ctx: HandlerContext) => {\n const { id } = ctx.params;\n const workflow = registry.getWorkflow(id);\n\n if (!workflow) {\n return error(`Workflow not found: ${id}`, 'WORKFLOW_NOT_FOUND');\n }\n\n const runId = `run-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`;\n const startTime = Date.now();\n const stepResults: WorkflowStepResult[] = [];\n let status: 'completed' | 'failed' = 'completed';\n\n registry.emit('workflow:started', {\n runId,\n workflowId: id,\n workflowName: workflow.name,\n totalSteps: workflow.steps.length,\n });\n\n for (const step of workflow.steps) {\n const stepResult = await executeWorkflowStep(step, registry, executor);\n stepResults.push(stepResult);\n\n if (stepResult.status === 'completed' || stepResult.status === 'skipped') {\n registry.emit('workflow:stepCompleted', {\n runId,\n workflowId: id,\n step: stepResult,\n });\n }\n\n if (stepResult.status === 'failed') {\n status = 'failed';\n registry.emit('workflow:failed', {\n runId,\n workflowId: id,\n failedStep: stepResult,\n completedSteps: stepResults.length - 1,\n totalSteps: workflow.steps.length,\n });\n break;\n }\n }\n\n if (status === 'completed') {\n registry.emit('workflow:completed', {\n runId,\n workflowId: id,\n steps: stepResults,\n totalDurationMs: Date.now() - startTime,\n });\n }\n\n return success({\n runId,\n status,\n steps: stepResults,\n totalSteps: workflow.steps.length,\n completedSteps: stepResults.filter((s) => s.status === 'completed').length,\n failedSteps: stepResults.filter((s) => s.status === 'failed').length,\n skippedSteps: stepResults.filter((s) => s.status === 'skipped').length,\n durationMs: Date.now() - startTime,\n });\n },\n\n // Page Navigation (stubs — React Native apps should override with their navigation provider)\n pageRefresh: async () => {\n return error('Page refresh not supported on native platform', 'NOT_SUPPORTED');\n },\n\n pageNavigate: async () => {\n return error('Page navigation not supported on native platform', 'NOT_SUPPORTED');\n },\n\n pageReplace: async () => {\n return error('Page replace not supported on native platform', 'NOT_SUPPORTED');\n },\n\n pageGoBack: async () => {\n return error('Page go back not supported on native platform', 'NOT_SUPPORTED');\n },\n\n pageGoForward: async () => {\n return error('Page go forward not supported on native platform', 'NOT_SUPPORTED');\n },\n\n // Screenshot (stub — apps should override with their screen capture library)\n getScreenshot: async () => {\n return error(\n 'Screenshot not supported. Provide a screenshotProvider to UIBridgeNativeProvider.',\n 'NOT_SUPPORTED'\n );\n },\n\n // Keep-awake (stub — apps should override via setKeepAwakeProvider, which\n // the provider wires when a keepAwakeProvider prop is supplied)\n keepAwake: async () => {\n return error(\n 'keep-awake not configured. Provide a keepAwakeProvider to UIBridgeNativeProvider.',\n 'NOT_SUPPORTED'\n );\n },\n\n // AI helpers — runner-only endpoints that have no React Native analog.\n //\n // The mobile bridge mounts explicit NOT_SUPPORTED stubs at the runner's\n // cheatsheet paths so callers (and the /manual-test skill in particular)\n // get a structured envelope explaining the gap rather than a bare\n // \"no such route\". These answer **HTTP 501** — `httpStatusForResponse` in\n // server/http-server.ts maps NOT_SUPPORTED → 501, so the status line and\n // the envelope agree; an unmounted path answers 404 instead. Each error\n // message names an in-tree mobile replacement so operators aren't left\n // guessing what to use instead.\n aiForms: async () => {\n return error<never>(\n 'ai/forms (form discovery) is runner-only; mobile React Native has no DOM to walk. ' +\n 'Use GET /ui-bridge/control/snapshot and filter for type === \"input\" instead.',\n 'NOT_SUPPORTED'\n );\n },\n\n aiIdleStatus: async () => {\n return error<never>(\n 'ai/idle-status (page-idle signal) is runner-only; mobile React Native has no DOM-mutation / network-idle signals. ' +\n 'Use the registry event stream (WS subscribe to \"element:registered\"/\"element:stateChanged\") or poll /control/snapshot for stability.',\n 'NOT_SUPPORTED'\n );\n },\n\n aiChangeBufferEnable: async () => {\n return error<never>(\n 'ai/change-buffer (DOM mutation diff buffer) is runner-only; mobile React Native has no DOM. ' +\n 'Use the WS event bridge (subscribe to \"element:registered\"/\"element:unregistered\"/\"element:stateChanged\") for change notifications.',\n 'NOT_SUPPORTED'\n );\n },\n\n aiWaitForElement: async () => {\n return error<never>(\n 'POST /ai/wait-for-element is runner-only on mobile. ' +\n 'Use the WS \"waitForElement\" JSON-RPC method or \"waitForCondition\" instead — same semantics, no HTTP polling overhead.',\n 'NOT_SUPPORTED'\n );\n },\n\n // Meta / Introspection (stub — server constructor overrides with real route table)\n getMethods: async () => {\n return error('Methods introspection not configured', 'NOT_SUPPORTED');\n },\n\n // AI helpers\n //\n // Mobile-side parity with the runner's `POST /ui-bridge/ai/fill-form`.\n // Each entry in `fields` is dispatched through the existing executor as a\n // `type` action with `clear: true` so the input value is replaced\n // atomically (the closest native equivalent to the web bridge's\n // \"setValue\" semantics — there is no `setValue` action on native).\n //\n // Failures do not short-circuit: every field is attempted, and the\n // response carries per-field success/error plus aggregate counts.\n fillForm: async (ctx: HandlerContext): Promise<APIResponse<FillFormResponse>> => {\n const body = ctx.body as { fields?: unknown } | undefined;\n const rawFields = body?.fields;\n\n if (!Array.isArray(rawFields)) {\n return error('Request body must include \"fields\" array', 'INVALID_REQUEST');\n }\n\n const results: FillFormFieldResult[] = [];\n\n for (let i = 0; i < rawFields.length; i++) {\n const field = rawFields[i] as Partial<FillFormFieldInput> | null | undefined;\n\n // Validate per-field shape; record the failure but keep going so the\n // caller gets a complete picture of what worked and what didn't.\n if (!field || typeof field !== 'object') {\n results.push({\n elementId: '',\n success: false,\n error: `fields[${i}] must be an object with \"elementId\" and \"value\"`,\n });\n continue;\n }\n\n const { elementId, value } = field;\n\n if (typeof elementId !== 'string' || elementId.length === 0) {\n results.push({\n elementId: typeof elementId === 'string' ? elementId : '',\n success: false,\n error: `fields[${i}] is missing a non-empty \"elementId\"`,\n });\n continue;\n }\n\n if (typeof value !== 'string') {\n results.push({\n elementId,\n success: false,\n error: `fields[${i}] is missing a string \"value\"`,\n });\n continue;\n }\n\n try {\n const response = await executor.executeAction(elementId, {\n action: 'type',\n params: { text: value, clear: true },\n });\n\n if (response.success) {\n results.push({ elementId, success: true });\n } else {\n results.push({\n elementId,\n success: false,\n error: response.error ?? 'Action failed',\n });\n }\n } catch (err) {\n // executor.executeAction normally captures errors itself, but a\n // bespoke executor implementation may still throw — surface that.\n results.push({\n elementId,\n success: false,\n error: err instanceof Error ? err.message : String(err),\n });\n }\n }\n\n const succeededCount = results.filter((r) => r.success).length;\n const failedCount = results.length - succeededCount;\n\n return success({ results, succeededCount, failedCount });\n },\n\n // ========================================================================\n // App-agnostic interaction parity (cross-platform `/control/page/*`)\n //\n // Mirrors the web/runner convenience endpoints so the SAME contract drives\n // mobile. Text/label interactions compose `executor.find` (registry-based\n // discovery) + `executor.executeAction` (press/type). Selector-only\n // variants have no React-Native analog and return NOT_SUPPORTED — the\n // mobile bridge's snapshot + `/control/find` (testID / accessibilityLabel)\n // cover what a selector would on web.\n // ========================================================================\n\n clickByText: async (\n ctx: HandlerContext\n ): Promise<APIResponse<{ clicked: boolean; element?: unknown }>> => {\n const body = ctx.body as { text?: string; visibleOnly?: boolean } | undefined;\n const text = typeof body?.text === 'string' ? body.text.trim() : '';\n if (!text) {\n return error('text is required and must not be empty', 'INVALID_REQUEST');\n }\n const match = matchElementsByText(registry, text, { visibleOnly: body?.visibleOnly })[0];\n if (!match) {\n return error(`No element found with text \"${text}\"`, 'ELEMENT_NOT_FOUND');\n }\n const response = await executor.executeAction(match.id, { action: 'press' });\n if (!response.success) {\n return error(response.error || 'Press failed', 'ACTION_FAILED');\n }\n return success({\n clicked: true,\n element: { id: match.id, type: match.type, label: match.label },\n });\n },\n\n clickBySelector: async (): Promise<APIResponse<never>> => {\n return error(\n 'clickBySelector is not supported on native platform — React Native has no CSS-selector DOM. Use clickByText, or /control/find with testIdPattern/accessibilityLabelPattern then /control/element/:id/action.',\n 'NOT_SUPPORTED'\n );\n },\n\n typeInto: async (\n ctx: HandlerContext\n ): Promise<APIResponse<{ typed: boolean; element?: unknown }>> => {\n const body = ctx.body as\n | { label?: string; text?: string; clear?: boolean; visibleOnly?: boolean }\n | undefined;\n const label = typeof body?.label === 'string' ? body.label.trim() : '';\n if (!label) {\n return error(\n 'label is required on native (selector-based typeInto is web-only)',\n 'INVALID_REQUEST'\n );\n }\n const text = typeof body?.text === 'string' ? body.text : '';\n const match = matchElementsByText(registry, label, { visibleOnly: body?.visibleOnly })[0];\n if (!match) {\n return error(`No input found for label \"${label}\"`, 'ELEMENT_NOT_FOUND');\n }\n const response = await executor.executeAction(match.id, {\n action: 'type',\n params: { text, clear: body?.clear === true },\n });\n if (!response.success) {\n return error(response.error || 'Type failed', 'ACTION_FAILED');\n }\n return success({\n typed: true,\n element: { id: match.id, type: match.type, label: match.label },\n });\n },\n\n readValue: async (): Promise<APIResponse<never>> => {\n return error(\n 'readValue is not supported on native platform — React Native has no CSS-selector DOM. Use /control/element/:id/state to read an element value.',\n 'NOT_SUPPORTED'\n );\n },\n\n findByText: async (\n ctx: HandlerContext\n ): Promise<APIResponse<Array<{ index: number; id: string; type: string; label?: string }>>> => {\n const body = ctx.body as { text?: string; visibleOnly?: boolean } | undefined;\n const text = typeof body?.text === 'string' ? body.text.trim() : '';\n if (!text) {\n return error('text is required and must not be empty', 'INVALID_REQUEST');\n }\n const matches = matchElementsByText(registry, text, { visibleOnly: body?.visibleOnly });\n return success(\n matches.map((el, index) => ({\n index,\n id: el.id,\n type: el.type,\n label: el.label,\n }))\n );\n },\n\n // Coord-based tap\n //\n // Synthesizes a press at the given screen coordinates by scanning the\n // registered elements' layout rects for a containing match. We prefer the\n // *topmost* match (smallest area = innermost child) since native UIs\n // generally render parents before children, and the user's tap should\n // logically hit the leaf-most interactive element.\n //\n // Coords are interpreted in the absolute (screen) space published by\n // `measureInWindow`; we compare against `pageX/pageY` when available and\n // fall back to the layout's relative `x/y` so this works in test fixtures\n // that don't measure (the fallback only matches single-rooted screens but\n // is good enough for the unit suite).\n tapAt: async (ctx: HandlerContext): Promise<APIResponse<TapAtResponse>> => {\n // Measure-on-read: refresh stored geometry before hit-testing, so taps\n // land on elements' CURRENT rects (post-scroll/recycle), not their\n // mount-time positions. Bounded by an internal timeout; never throws.\n await registry.refreshMeasurements();\n\n const body = ctx.body as\n | Partial<{\n x: number;\n y: number;\n action: 'press' | 'longPress' | 'doubleTap';\n }>\n | undefined;\n\n const x = body?.x;\n const y = body?.y;\n\n if (typeof x !== 'number' || !Number.isFinite(x)) {\n return error<TapAtResponse>('\"x\" must be a finite number', 'INVALID_REQUEST');\n }\n if (typeof y !== 'number' || !Number.isFinite(y)) {\n return error<TapAtResponse>('\"y\" must be a finite number', 'INVALID_REQUEST');\n }\n\n const action = body?.action ?? 'press';\n const allowedActions: ReadonlyArray<TapAtResponse['action']> = [\n 'press',\n 'longPress',\n 'doubleTap',\n ];\n if (!allowedActions.includes(action)) {\n return error<TapAtResponse>(\n `\"action\" must be one of: ${allowedActions.join(', ')}`,\n 'INVALID_REQUEST'\n );\n }\n\n // Collect all candidates whose layout rect contains (x, y). Prefer\n // pageX/pageY (absolute coords) when both are populated; fall back to\n // the relative x/y otherwise.\n type Candidate = {\n elementId: string;\n layout: NativeLayout;\n area: number;\n };\n const candidates: Candidate[] = [];\n\n for (const el of registry.getAllElements()) {\n const state = el.getState();\n const layout = state?.layout;\n if (!layout) continue;\n if (\n typeof layout.width !== 'number' ||\n typeof layout.height !== 'number' ||\n layout.width <= 0 ||\n layout.height <= 0\n ) {\n continue;\n }\n\n const hasPage =\n typeof layout.pageX === 'number' &&\n typeof layout.pageY === 'number' &&\n Number.isFinite(layout.pageX) &&\n Number.isFinite(layout.pageY);\n\n const left = hasPage ? layout.pageX : layout.x;\n const top = hasPage ? layout.pageY : layout.y;\n\n if (x >= left && x <= left + layout.width && y >= top && y <= top + layout.height) {\n candidates.push({\n elementId: el.id,\n layout,\n area: layout.width * layout.height,\n });\n }\n }\n\n if (candidates.length === 0) {\n return error<TapAtResponse>(\n `No element registered at (${x}, ${y})`,\n 'no_element_at_coords'\n );\n }\n\n // Topmost = smallest area. Stable sort preserves registration order for\n // ties, so a parent and a same-size child won't flip non-deterministically.\n candidates.sort((a, b) => a.area - b.area);\n const target = candidates[0];\n\n const response = await executor.executeAction(target.elementId, { action });\n if (!response.success) {\n return error<TapAtResponse>(response.error || 'Action failed', 'ACTION_FAILED');\n }\n\n return success<TapAtResponse>({\n elementId: target.elementId,\n action,\n layout: {\n x: target.layout.x,\n y: target.layout.y,\n width: target.layout.width,\n height: target.layout.height,\n pageX: target.layout.pageX,\n pageY: target.layout.pageY,\n },\n });\n },\n\n // Observability — console error / network request ring buffers.\n //\n // The buffers are owned by NativeUIBridgeServer and patched onto the\n // globals on `start()` (gated behind `features.testHooks`). When no\n // buffer is provided (no testHooks, or a stripped-down server fixture),\n // these handlers gracefully return empty arrays so callers can probe\n // without 500ing.\n getConsoleErrors: async (ctx: HandlerContext): Promise<APIResponse<ConsoleErrorsResponse>> => {\n const buf = config?.consoleErrorBuffer;\n const since = ctx.query?.since !== undefined ? Number(ctx.query.since) : undefined;\n const limit = ctx.query?.limit !== undefined ? Number(ctx.query.limit) : undefined;\n\n if (!buf) {\n return success<ConsoleErrorsResponse>({\n entries: [],\n count: 0,\n bufferSize: 0,\n installed: false,\n });\n }\n\n const entries = buf.entries({\n since: typeof since === 'number' && Number.isFinite(since) ? since : undefined,\n limit: typeof limit === 'number' && Number.isFinite(limit) ? limit : undefined,\n });\n\n return success<ConsoleErrorsResponse>({\n entries,\n count: entries.length,\n bufferSize: buf.size(),\n installed: buf.isInstalled(),\n });\n },\n\n getNetworkRequests: async (\n ctx: HandlerContext\n ): Promise<APIResponse<NetworkRequestsResponse>> => {\n const buf = config?.networkRequestBuffer;\n const since = ctx.query?.since !== undefined ? Number(ctx.query.since) : undefined;\n const limit = ctx.query?.limit !== undefined ? Number(ctx.query.limit) : undefined;\n\n if (!buf) {\n return success<NetworkRequestsResponse>({\n entries: [],\n count: 0,\n bufferSize: 0,\n installed: false,\n });\n }\n\n const entries = buf.entries({\n since: typeof since === 'number' && Number.isFinite(since) ? since : undefined,\n limit: typeof limit === 'number' && Number.isFinite(limit) ? limit : undefined,\n });\n\n return success<NetworkRequestsResponse>({\n entries,\n count: entries.length,\n bufferSize: buf.size(),\n installed: buf.isInstalled(),\n });\n },\n\n // Test hooks — modal stack manipulation\n //\n // These two endpoints exist so external automation runners can drive\n // ModalDetector state via HTTP, mirroring the in-tree `pushModal` /\n // `dismissModal` calls that components normally make. They're gated by\n // `features.testHooks` at the route layer (see http-server.ts); the\n // handlers themselves still defend against a missing modalDetector\n // because the bare server path used by CloudRelayClient may run before\n // enrichers are wired.\n pushModal: async (ctx: HandlerContext): Promise<APIResponse<PushModalResponse>> => {\n const detector = registry.getEnrichers().modalDetector;\n if (!detector) {\n return error<PushModalResponse>('modal detector not registered', 'ENRICHER_UNAVAILABLE');\n }\n\n const body = ctx.body as Partial<PushModalRequest> | undefined;\n const id = body?.id;\n if (typeof id !== 'string' || id.length === 0) {\n return error<PushModalResponse>('pushModal requires a non-empty \"id\"', 'INVALID_REQUEST');\n }\n\n const allowedTypes = ['modal', 'sheet', 'drawer', 'popover', 'alertdialog', 'dialog'];\n const requestedType = body?.type;\n if (\n requestedType !== undefined &&\n (typeof requestedType !== 'string' || !allowedTypes.includes(requestedType))\n ) {\n return error<PushModalResponse>(\n `pushModal \"type\" must be one of: ${allowedTypes.join(', ')}`,\n 'INVALID_REQUEST'\n );\n }\n\n detector.pushModal({\n id,\n title: body?.title,\n // requestedType is narrowed by the allowedTypes guard above; the cast\n // converts the validated string to the NativeModalInfo['type'] union.\n type: requestedType as NativeModalInfo['type'] | undefined,\n blocking: body?.blocking,\n dismissible: body?.dismissible,\n });\n\n // Pull the canonicalised entry back out so the response reflects what's\n // actually in the stack (defaults applied, detectedAt populated).\n const stored = detector.getActive().find((m) => m.id === id);\n return success<PushModalResponse>({\n pushed: true,\n id,\n title: stored?.title,\n type: stored?.type,\n blocking: stored?.blocking,\n dismissible: stored?.dismissible,\n pushedAt: stored?.detectedAt ?? Date.now(),\n });\n },\n\n dismissModal: async (ctx: HandlerContext): Promise<APIResponse<DismissModalResponse>> => {\n const detector = registry.getEnrichers().modalDetector;\n if (!detector) {\n return error<DismissModalResponse>('modal detector not registered', 'ENRICHER_UNAVAILABLE');\n }\n\n const { id } = ctx.params;\n if (typeof id !== 'string' || id.length === 0) {\n return error<DismissModalResponse>(\n 'dismissModal requires a modal id in the path',\n 'INVALID_REQUEST'\n );\n }\n\n // The slot type allows `dismissModal` to return either `boolean` (the\n // canonical ModalDetector class) or `void` (legacy/duck-typed impls).\n // Probe via `getActive()` first so the result is consistent regardless\n // of the implementation's return signal.\n const wasPresent = detector.getActive().some((m) => m.id === id);\n if (!wasPresent) {\n return error<DismissModalResponse>(`modal not found: ${id}`, 'MODAL_NOT_FOUND');\n }\n\n detector.dismissModal(id);\n return success<DismissModalResponse>({ dismissed: id });\n },\n\n // Design Review\n ...designHandlers,\n\n // Health\n health: async () => {\n const stats = registry.getStats();\n const registration = registry.getRegistrationCoverage();\n const response: Record<string, unknown> = {\n status: 'healthy',\n timestamp: Date.now(),\n ...stats,\n registration,\n };\n\n if (config?.appInfo) {\n response.uiBridge = {\n version: __SDK_VERSION__,\n ...config.appInfo,\n capabilities: ['elements', 'components', 'actions', 'design'],\n elementCount: stats.elements,\n componentCount: stats.components,\n };\n }\n\n return success(response);\n },\n };\n}\n","/**\n * UI Bridge Native — observability ring buffers.\n *\n * Two small last-N buffers backing the `/control/console-errors` and\n * `/sdk/network-requests` endpoints. Each buffer monkey-patches the relevant\n * global on `install()` and restores the original on `uninstall()`, so they\n * can be installed/torn-down with the server's lifecycle.\n *\n * Both buffers are gated behind `features.observability` by the caller (see\n * NativeUIBridgeServer), which defaults to the `features.testHooks` value.\n * Builds with both flags off never run these patches; release builds can\n * opt in with `observability: true` without enabling testHooks.\n *\n * Implementation notes:\n * - Buffers default to capacity 100 entries and drop oldest on overflow.\n * - Patches are idempotent: `install()` is a no-op when already installed;\n * `uninstall()` is a no-op when not installed.\n * - Patches only restore the *original* function captured at install time;\n * if other code wraps `console.error` / `fetch` between install and\n * uninstall, those wrappers will be lost. Acceptable for test hooks.\n */\nimport type { ConsoleErrorEntry, NetworkRequestEntry } from './types';\n\n// ── Ring buffer ─────────────────────────────────────────────────────────────\n\n/** A simple ring buffer that drops oldest on overflow. */\nclass RingBuffer<T extends { timestamp: number }> {\n private items: T[] = [];\n\n constructor(private readonly capacity: number) {}\n\n push(entry: T): void {\n this.items.push(entry);\n if (this.items.length > this.capacity) {\n this.items.splice(0, this.items.length - this.capacity);\n }\n }\n\n /**\n * Return entries optionally filtered by `since` (timestamp ms) and capped\n * at `limit`. Newest-end is preserved when `limit` would otherwise truncate.\n */\n entries(opts: { since?: number; limit?: number } = {}): T[] {\n const { since, limit } = opts;\n let filtered = this.items;\n if (typeof since === 'number') {\n filtered = filtered.filter((e) => e.timestamp >= since);\n }\n if (typeof limit === 'number' && limit >= 0 && filtered.length > limit) {\n filtered = filtered.slice(filtered.length - limit);\n }\n return filtered.slice();\n }\n\n size(): number {\n return this.items.length;\n }\n\n clear(): void {\n this.items.length = 0;\n }\n}\n\n// ── Console error buffer ────────────────────────────────────────────────────\n\ninterface PatchedConsole {\n error: (...args: unknown[]) => void;\n warn: (...args: unknown[]) => void;\n}\n\n/**\n * Format console arguments the same way `console.log` would (joined by\n * spaces, with errors stringified to their `message`).\n */\nfunction formatConsoleArgs(args: unknown[]): string {\n return args\n .map((a) => {\n if (a instanceof Error) return a.message;\n if (typeof a === 'string') return a;\n try {\n return JSON.stringify(a);\n } catch {\n return String(a);\n }\n })\n .join(' ');\n}\n\n/** Pull the first `Error` from the args, if any, and return its `.stack`. */\nfunction extractStack(args: unknown[]): string | undefined {\n for (const a of args) {\n if (a instanceof Error && a.stack) return a.stack;\n }\n return undefined;\n}\n\nexport class ConsoleErrorBuffer {\n private buffer: RingBuffer<ConsoleErrorEntry>;\n private installed = false;\n private originalError?: PatchedConsole['error'];\n private originalWarn?: PatchedConsole['warn'];\n\n constructor(capacity = 100) {\n this.buffer = new RingBuffer<ConsoleErrorEntry>(capacity);\n }\n\n install(): void {\n if (this.installed) return;\n if (typeof console === 'undefined') return;\n\n // Capture the originals as-is (no .bind) so `uninstall()` restores the\n // exact reference callers had before we touched the global.\n this.originalError = console.error as PatchedConsole['error'];\n this.originalWarn = console.warn as PatchedConsole['warn'];\n\n const buffer = this.buffer;\n const origError = this.originalError;\n const origWarn = this.originalWarn;\n\n console.error = (...args: unknown[]): void => {\n try {\n buffer.push({\n timestamp: Date.now(),\n level: 'error',\n message: formatConsoleArgs(args),\n stack: extractStack(args),\n });\n } catch {\n // Never let the patch throw — fall through to the original.\n }\n origError.apply(console, args);\n };\n\n console.warn = (...args: unknown[]): void => {\n try {\n buffer.push({\n timestamp: Date.now(),\n level: 'warn',\n message: formatConsoleArgs(args),\n stack: extractStack(args),\n });\n } catch {\n // ignore\n }\n origWarn.apply(console, args);\n };\n\n this.installed = true;\n }\n\n uninstall(): void {\n if (!this.installed) return;\n if (typeof console === 'undefined') return;\n\n if (this.originalError) console.error = this.originalError;\n if (this.originalWarn) console.warn = this.originalWarn;\n\n this.originalError = undefined;\n this.originalWarn = undefined;\n this.installed = false;\n }\n\n entries(opts: { since?: number; limit?: number } = {}): ConsoleErrorEntry[] {\n return this.buffer.entries(opts);\n }\n\n size(): number {\n return this.buffer.size();\n }\n\n clear(): void {\n this.buffer.clear();\n }\n\n isInstalled(): boolean {\n return this.installed;\n }\n}\n\n// ── Network request buffer ──────────────────────────────────────────────────\n\ntype FetchFn = (input: RequestInfo | URL, init?: RequestInit) => Promise<Response>;\n\n/**\n * Best-effort URL extraction from a `fetch` first-arg. Mirrors what RN's\n * polyfill accepts (string | URL | Request).\n */\nfunction extractUrl(input: unknown): string {\n if (typeof input === 'string') return input;\n if (input && typeof input === 'object') {\n const obj = input as { url?: unknown; toString?: () => string };\n if (typeof obj.url === 'string') return obj.url;\n try {\n return String(input);\n } catch {\n return '';\n }\n }\n return '';\n}\n\n/**\n * Best-effort method extraction. `fetch(url, {method})` overrides the\n * Request's method, so we check `init` first and fall back to the Request.\n */\nfunction extractMethod(input: unknown, init?: RequestInit): string {\n if (init && typeof init.method === 'string') return init.method.toUpperCase();\n if (input && typeof input === 'object') {\n const obj = input as { method?: unknown };\n if (typeof obj.method === 'string') return obj.method.toUpperCase();\n }\n return 'GET';\n}\n\n/** Minimal shape of `globalThis` we patch. Avoids depending on DOM types. */\ninterface PatchableGlobal {\n fetch?: FetchFn;\n XMLHttpRequest?: typeof XMLHttpRequest;\n}\n\n/**\n * An XHR instance, plus the markers the patches hang on it.\n *\n * `__uiBridgeMethod` / `__uiBridgeUrl` carry method+url from `open` to `send`.\n * `__uiBridgeFromFetch` marks an XHR that the `fetch` polyfill created for\n * itself — see {@link NetworkRequestBuffer.install}.\n */\ntype MarkedXhr = XMLHttpRequest & {\n __uiBridgeMethod?: string;\n __uiBridgeUrl?: string;\n __uiBridgeFromFetch?: boolean;\n};\n\nexport class NetworkRequestBuffer {\n private buffer: RingBuffer<NetworkRequestEntry>;\n private installed = false;\n private originalFetch?: FetchFn;\n private originalXhrOpen?: typeof XMLHttpRequest.prototype.open;\n private originalXhrSend?: typeof XMLHttpRequest.prototype.send;\n /**\n * Synchronous re-entrancy depth: non-zero while the ORIGINAL `fetch` is\n * executing, which is exactly the window in which React Native's whatwg-fetch\n * polyfill constructs and opens its internal `XMLHttpRequest`.\n *\n * A counter rather than a boolean so a `fetch` called from inside a `fetch`\n * (an interceptor, a retry wrapper) still unwinds to zero. Safe as a plain\n * number: JS is single-threaded and the only writes are the paired\n * increment/decrement around one synchronous call.\n */\n private fetchDepth = { value: 0 };\n\n constructor(capacity = 100) {\n this.buffer = new RingBuffer<NetworkRequestEntry>(capacity);\n }\n\n /**\n * Patch `fetch` and `XMLHttpRequest` so `GET /sdk/network-requests` can\n * report what the app talked to.\n *\n * ONE REQUEST MUST PRODUCE ONE ENTRY. React Native implements `fetch` **on\n * top of** XHR (whatwg-fetch), so both patches observe the same request and\n * the buffer used to carry every call twice — same url, timestamps ~1ms\n * apart, and on failure one `\"Network request failed\"` beside one\n * `\"XMLHttpRequest error\"`. A tester reads that as a double-fetch bug in the\n * app and chases a defect that does not exist.\n *\n * The de-dup: `fetchDepth` is raised across the synchronous call into the\n * original `fetch`, which is when the polyfill builds its XHR; `open` stamps\n * any XHR created in that window with `__uiBridgeFromFetch`, and `send`\n * skips recording those. The `fetch` patch keeps the entry, because it is\n * the layer the app actually called and the only one that sees `Response.ok`.\n *\n * Uninstalling both patches together keeps this sound: an XHR can only be\n * marked while the fetch patch is live.\n *\n * KNOWN LIMIT — it is coupled to the polyfill building its XHR SYNCHRONOUSLY,\n * which whatwg-fetch does (its work happens in the Promise executor). If the\n * host's `fetch` is wrapped by an interceptor that defers the real call to a\n * microtask or `setTimeout`, the depth is back to 0 by the time `open` runs\n * and every request duplicates again — the original symptom, with no signal\n * that the mechanism disengaged. Duplicates in `/sdk/network-requests` are\n * the thing to look for; they mean this assumption stopped holding, not that\n * the app double-fetched.\n */\n install(): void {\n if (this.installed) return;\n const g = globalThis as PatchableGlobal;\n\n if (typeof g.fetch === 'function') {\n // Capture the original reference as-is so `uninstall()` restores the\n // exact function callers had before we patched.\n this.originalFetch = g.fetch;\n const buffer = this.buffer;\n const original = this.originalFetch;\n const fetchDepth = this.fetchDepth;\n\n const patched: FetchFn = async (input, init) => {\n const start = Date.now();\n const url = extractUrl(input);\n const method = extractMethod(input, init);\n\n try {\n // The polyfill's `new XMLHttpRequest()` / `open` / `send` all happen\n // synchronously inside this call (whatwg-fetch does its work in the\n // Promise executor), so raising the depth across just the invocation\n // — not the await — covers exactly that window and nothing else.\n let pending: Promise<Response>;\n fetchDepth.value += 1;\n try {\n pending = original.call(globalThis, input, init);\n } finally {\n fetchDepth.value -= 1;\n }\n const res = await pending;\n buffer.push({\n timestamp: start,\n method,\n url,\n status: res.status,\n durationMs: Date.now() - start,\n ok: res.ok,\n });\n return res;\n } catch (err) {\n buffer.push({\n timestamp: start,\n method,\n url,\n status: 0,\n durationMs: Date.now() - start,\n ok: false,\n error: err instanceof Error ? err.message : String(err),\n });\n throw err;\n }\n };\n\n g.fetch = patched;\n }\n\n // Patch XMLHttpRequest if present (RN ships it; node doesn't unless polyfilled).\n if (typeof g.XMLHttpRequest === 'function') {\n const Xhr = g.XMLHttpRequest;\n this.originalXhrOpen = Xhr.prototype.open;\n this.originalXhrSend = Xhr.prototype.send;\n\n const buffer = this.buffer;\n const fetchDepth = this.fetchDepth;\n\n // Stash method+url on the instance so `send` can record them.\n const origOpen = this.originalXhrOpen;\n Xhr.prototype.open = function (\n this: MarkedXhr,\n method: string,\n url: string | URL,\n ...rest: unknown[]\n ) {\n this.__uiBridgeMethod = method.toUpperCase();\n this.__uiBridgeUrl = typeof url === 'string' ? url : String(url);\n // Opened while the original `fetch` was running: this XHR belongs to\n // the fetch polyfill, and the fetch patch already records it.\n //\n // KNOWN LIMIT — the window, not the identity, is what's tested, so an\n // UNRELATED xhr opened synchronously inside another wrapper's `fetch`\n // (an analytics beacon, an error-reporter transport) is dropped too.\n // Narrowing this to the polyfill's own XHR means matching on url, and\n // whatwg-fetch normalises the url it opens with — a mismatch there\n // would silently restore the duplicate-every-request bug rather than\n // lose one beacon. Pinned by a test in network-buffer-dedup.test.ts.\n if (fetchDepth.value > 0) {\n this.__uiBridgeFromFetch = true;\n }\n // origOpen has overloaded signatures; we forward the original args.\n return (origOpen as (...args: unknown[]) => unknown).call(\n this,\n method,\n url,\n ...rest\n ) as void;\n } as typeof XMLHttpRequest.prototype.open;\n\n const origSend = this.originalXhrSend;\n Xhr.prototype.send = function (\n this: MarkedXhr,\n body?: Document | XMLHttpRequestBodyInit | null\n ) {\n // The fetch patch owns this request's entry. Recording it here too is\n // what made every RN request appear twice in the buffer.\n //\n // The MARKER is the whole test, deliberately. A `fetchDepth > 0` check\n // here as well would also drop any UNRELATED xhr sent synchronously\n // during a `fetch` — an analytics beacon from a library that wrapped\n // `fetch` first, say — and a silently absent request is a worse answer\n // than a visible duplicate.\n if (this.__uiBridgeFromFetch === true) {\n return (origSend as (...args: unknown[]) => unknown).call(this, body) as void;\n }\n\n const start = Date.now();\n const method = this.__uiBridgeMethod ?? 'GET';\n const url = this.__uiBridgeUrl ?? '';\n\n const finalize = (status: number, ok: boolean, error?: string) => {\n buffer.push({\n timestamp: start,\n method,\n url,\n status,\n durationMs: Date.now() - start,\n ok,\n error,\n });\n };\n\n const onLoadEnd = () => {\n this.removeEventListener('loadend', onLoadEnd);\n this.removeEventListener('error', onError);\n finalize(this.status, this.status >= 200 && this.status < 300);\n };\n const onError = () => {\n this.removeEventListener('loadend', onLoadEnd);\n this.removeEventListener('error', onError);\n finalize(0, false, 'XMLHttpRequest error');\n };\n\n this.addEventListener('loadend', onLoadEnd);\n this.addEventListener('error', onError);\n\n return (origSend as (...args: unknown[]) => unknown).call(\n this,\n body\n ) as void;\n } as typeof XMLHttpRequest.prototype.send;\n }\n\n this.installed = true;\n }\n\n uninstall(): void {\n if (!this.installed) return;\n const g = globalThis as PatchableGlobal;\n\n if (this.originalFetch) {\n g.fetch = this.originalFetch;\n this.originalFetch = undefined;\n }\n if (typeof g.XMLHttpRequest === 'function') {\n if (this.originalXhrOpen) {\n g.XMLHttpRequest.prototype.open = this.originalXhrOpen;\n }\n if (this.originalXhrSend) {\n g.XMLHttpRequest.prototype.send = this.originalXhrSend;\n }\n }\n this.originalXhrOpen = undefined;\n this.originalXhrSend = undefined;\n this.installed = false;\n }\n\n entries(opts: { since?: number; limit?: number } = {}): NetworkRequestEntry[] {\n return this.buffer.entries(opts);\n }\n\n size(): number {\n return this.buffer.size();\n }\n\n clear(): void {\n this.buffer.clear();\n }\n\n isInstalled(): boolean {\n return this.installed;\n }\n}\n","/**\n * WebSocket JSON-RPC message types for the UI Bridge protocol.\n */\n\n// ── Client → Server ─────────────────────────────────────────────────────────\n\n/** Standard JSON-RPC request */\nexport interface JsonRpcRequest {\n id: number | string;\n method: string;\n params?: Record<string, unknown>;\n}\n\n/** Batch request — execute multiple requests concurrently */\nexport interface JsonRpcBatchRequest {\n id: number | string;\n batch: JsonRpcRequest[];\n}\n\n/** Subscribe to registry events */\nexport interface JsonRpcSubscribe {\n id: number | string;\n method: 'subscribe';\n params: {\n events: string[];\n /** Optional throttle in ms — batch rapid events within this window */\n throttleMs?: number;\n };\n}\n\n/** Unsubscribe from registry events */\nexport interface JsonRpcUnsubscribe {\n id: number | string;\n method: 'unsubscribe';\n params: { events: string[] };\n}\n\n/** Any client message */\nexport type JsonRpcClientMessage =\n | JsonRpcRequest\n | JsonRpcBatchRequest\n | JsonRpcSubscribe\n | JsonRpcUnsubscribe;\n\n// ── Server → Client ─────────────────────────────────────────────────────────\n\n/** Standard JSON-RPC response */\nexport interface JsonRpcResponse {\n id: number | string;\n result?: {\n success: boolean;\n data?: unknown;\n error?: string;\n code?: string;\n timestamp?: number;\n };\n}\n\n/** Batch response */\nexport interface JsonRpcBatchResponse {\n id: number | string;\n results: JsonRpcResponse[];\n}\n\n/** Server-pushed event (no id — not a response to a request) */\nexport interface JsonRpcEvent {\n event: string;\n data: unknown;\n timestamp: number;\n}\n\n/** Any server message */\nexport type JsonRpcServerMessage = JsonRpcResponse | JsonRpcBatchResponse | JsonRpcEvent;\n\n// ── Helpers ─────────────────────────────────────────────────────────────────\n\n/** Check if a message is a batch request */\nexport function isBatchRequest(msg: unknown): msg is JsonRpcBatchRequest {\n return (\n typeof msg === 'object' &&\n msg !== null &&\n 'batch' in msg &&\n Array.isArray((msg as JsonRpcBatchRequest).batch)\n );\n}\n\n/** Check if a message is a subscribe request */\nexport function isSubscribe(msg: unknown): msg is JsonRpcSubscribe {\n return (\n typeof msg === 'object' && msg !== null && (msg as JsonRpcSubscribe).method === 'subscribe'\n );\n}\n\n/** Check if a message is an unsubscribe request */\nexport function isUnsubscribe(msg: unknown): msg is JsonRpcUnsubscribe {\n return (\n typeof msg === 'object' && msg !== null && (msg as JsonRpcUnsubscribe).method === 'unsubscribe'\n );\n}\n","/**\n * UI Bridge Native HTTP Server\n *\n * Abstract HTTP server implementation for React Native.\n * This provides a framework-agnostic server interface that can be\n * implemented using various React Native HTTP server libraries.\n *\n * Supported libraries:\n * - react-native-http-bridge (recommended)\n * - @aspect/react-native-http-server\n * - Custom implementations\n */\n\nimport type { NativeUIBridgeRegistry } from '../core/registry';\nimport type { NativeActionExecutor, PageNavigationResponse } from '../control/types';\nimport type {\n NativeServerConfig,\n NativeServerHandlers,\n NavigationProvider,\n RouteProvider,\n ScreenshotProvider,\n KeepAwakeProvider,\n APIResponse,\n HandlerContext,\n} from './types';\nimport type { BridgeEvent } from '../core/types';\nimport { createServerHandlers } from './handlers';\nimport { ConsoleErrorBuffer, NetworkRequestBuffer } from './observability';\nimport type { WebSocketEventBridge } from './ws-event-bridge';\nimport type { JsonRpcRequest, JsonRpcResponse } from './ws-types';\nimport { isBatchRequest, isSubscribe, isUnsubscribe } from './ws-types';\n\n// ── HTTP status mapping ─────────────────────────────────────────────────────\n\n/**\n * HTTP status for each `APIResponse.code` that has an honest status of its own.\n *\n * Handlers already distinguish \"this platform will never do that\"\n * (`NOT_SUPPORTED`), \"no such route\" (`NOT_FOUND`) and \"wrong verb\"\n * (`METHOD_NOT_ALLOWED`) in the response envelope. Anything not listed here is\n * a client-input problem and keeps 400, which is what 400 is for.\n *\n * RESOURCE-level misses are deliberately NOT here. `ELEMENT_NOT_FOUND`,\n * `COMPONENT_NOT_FOUND`, `MODAL_NOT_FOUND` and `WORKFLOW_NOT_FOUND`\n * (`handlers.ts`) keep 400: the route resolved and served a request whose\n * *argument* named nothing — a client-input problem, not a routing one.\n * Widening 404 to cover them would make \"this endpoint does not exist\" and\n * \"this id does not exist\" the same status, which is the ambiguity this\n * mapping exists to remove.\n *\n * A `Map` rather than an object literal on purpose: a plain object resolves\n * inherited keys, so a `code` of `\"toString\"` or `\"constructor\"` would return\n * a FUNCTION where a status number is typed, and it would be relayed straight\n * into the cloud tunnel (`transport/CloudRelayClient.ts`). Unreachable today —\n * every `code` in the tree is a hardcoded literal — but a `Map` costs nothing\n * and closes it structurally rather than by audit.\n */\nconst ERROR_CODE_HTTP_STATUS = new Map<string, number>([\n ['NOT_SUPPORTED', 501],\n ['NOT_FOUND', 404],\n ['METHOD_NOT_ALLOWED', 405],\n]);\n\n/**\n * Derive the HTTP status for a completed `APIResponse`.\n *\n * Every unsuccessful response used to be flattened to HTTP 400, which made a\n * deliberately-unimplemented route (`/ai/forms` → `NOT_SUPPORTED`) and a route\n * that does not exist (`NOT_FOUND`) indistinguishable from a malformed request\n * — so callers retried request shapes against endpoints that were never going\n * to answer. The envelope's `code` already carries the distinction; this maps\n * it onto the status line so a caller reading only the status gets the truth.\n */\nexport function httpStatusForResponse(response: APIResponse): number {\n if (response.success) return 200;\n const mapped = response.code ? ERROR_CODE_HTTP_STATUS.get(response.code) : undefined;\n return mapped ?? 400;\n}\n\n// ── Path pattern matching ───────────────────────────────────────────────────\n\n/**\n * Match an actual path against a pattern with :name placeholders.\n * Returns extracted params, or null if the pattern does not match.\n *\n * Example: parsePath('control/element/:id/action', 'control/element/tab-runs/action')\n * → { id: 'tab-runs' }\n */\nfunction parsePath(pattern: string, actual: string): Record<string, string> | null {\n const patternParts = pattern.split('/');\n const actualParts = actual.split('/');\n\n if (patternParts.length !== actualParts.length) {\n return null;\n }\n\n const params: Record<string, string> = {};\n for (let i = 0; i < patternParts.length; i++) {\n if (patternParts[i].startsWith(':')) {\n params[patternParts[i].slice(1)] = actualParts[i];\n } else if (patternParts[i] !== actualParts[i]) {\n return null;\n }\n }\n return params;\n}\n\n// ── WebSocket route table ───────────────────────────────────────────────────\n\n/**\n * Route table for WebSocket JSON-RPC methods.\n *\n * Method strings use the same path structure as HTTP routes (with :id placeholders)\n * but without the /ui-bridge/ prefix. Path params are extracted automatically.\n *\n * Examples:\n * \"health\" → handlers.health\n * \"control/snapshot\" → handlers.getSnapshot\n * \"control/element/tab-runs/action\" → handlers.executeAction ({id: 'tab-runs'})\n * \"control/component/my-comp/action/submit\" → handlers.executeComponentAction\n */\ntype HandlerKey = keyof NativeServerHandlers;\ntype HttpVerb = 'GET' | 'POST' | 'DELETE';\n\ninterface WsRoute {\n pattern: string;\n handler: HandlerKey;\n /**\n * HTTP verbs this route accepts when invoked over HTTP. When absent the\n * route is WS-only (or matches any verb on HTTP). Multiple verbs allow\n * a single pattern to serve GET+POST etc.\n */\n httpMethods?: readonly HttpVerb[];\n /**\n * When true, the route is only mounted (HTTP + WS + manifest) when the\n * server config opts in via `testHooks`. Production builds default to\n * `testHooks: false` so these endpoints simply don't exist in the route\n * table — agents probing `/_routes` won't see them.\n */\n requiresTestHooks?: boolean;\n}\n\nconst WS_ROUTES: readonly WsRoute[] = [\n // Health\n { pattern: 'health', handler: 'health', httpMethods: ['GET'] },\n\n // Elements\n { pattern: 'control/elements', handler: 'getElements', httpMethods: ['GET'] },\n // Flat alias — matches the runner UI Bridge's `/ui-bridge/elements` path so\n // agents can use the same URL across runner + mobile without remembering\n // the `control/` prefix. Delegates to the same handler.\n { pattern: 'elements', handler: 'getElements', httpMethods: ['GET'] },\n { pattern: 'control/element/:id', handler: 'getElement', httpMethods: ['GET'] },\n { pattern: 'control/element/:id/state', handler: 'getElementState', httpMethods: ['GET'] },\n { pattern: 'control/element/:id/action', handler: 'executeAction', httpMethods: ['POST'] },\n\n // Components\n { pattern: 'control/components', handler: 'getComponents', httpMethods: ['GET'] },\n { pattern: 'control/component/:id', handler: 'getComponent', httpMethods: ['GET'] },\n {\n pattern: 'control/component/:id/action/:actionId',\n handler: 'executeComponentAction',\n httpMethods: ['POST'],\n },\n\n // Discovery\n { pattern: 'control/find', handler: 'find', httpMethods: ['POST'] },\n // Runner-parity alias for `control/find`; the runner exposes its\n // AI-powered element search at `/ui-bridge/ai/find`, so mobile mounts the\n // same handler at both paths to keep agents portable across platforms.\n { pattern: 'ai/find', handler: 'find', httpMethods: ['POST'] },\n { pattern: 'control/snapshot', handler: 'getSnapshot', httpMethods: ['GET'] },\n // Discovery alias — web/runner parity with `POST /control/discover` (a\n // legacy alias for snapshot/find). Mounted on HTTP (GET+POST) so mobile\n // doesn't 404 where web returns 200; delegates to the snapshot handler.\n { pattern: 'control/discover', handler: 'getSnapshot', httpMethods: ['GET', 'POST'] },\n // Page health — accepts both GET and POST so the canonical skill invocation\n // (`POST .../control/page-health` with an empty body) and ad-hoc curls both\n // work without a body-shape gotcha.\n { pattern: 'control/page-health', handler: 'getPageHealth', httpMethods: ['GET', 'POST'] },\n\n // Workflows\n { pattern: 'control/workflows', handler: 'getWorkflows', httpMethods: ['GET'] },\n { pattern: 'control/workflow/:id/run', handler: 'runWorkflow', httpMethods: ['POST'] },\n\n // Page Navigation\n { pattern: 'control/page/refresh', handler: 'pageRefresh', httpMethods: ['POST'] },\n { pattern: 'control/page/navigate', handler: 'pageNavigate', httpMethods: ['POST'] },\n { pattern: 'control/page/replace', handler: 'pageReplace', httpMethods: ['POST'] },\n { pattern: 'control/page/back', handler: 'pageGoBack', httpMethods: ['POST'] },\n { pattern: 'control/page/forward', handler: 'pageGoForward', httpMethods: ['POST'] },\n\n // Screenshot — accepts both GET and POST on HTTP\n { pattern: 'control/screenshot', handler: 'getScreenshot', httpMethods: ['GET', 'POST'] },\n\n // Design Review\n { pattern: 'design/element/:id/styles', handler: 'getElementStyles', httpMethods: ['GET'] },\n {\n pattern: 'design/element/:id/state-styles',\n handler: 'getElementStateStyles',\n httpMethods: ['POST'],\n },\n { pattern: 'design/snapshot', handler: 'getDesignSnapshot', httpMethods: ['POST'] },\n { pattern: 'design/responsive', handler: 'getResponsiveSnapshots', httpMethods: ['POST'] },\n { pattern: 'design/audit', handler: 'runDesignAudit', httpMethods: ['POST'] },\n { pattern: 'design/style-guide/load', handler: 'loadStyleGuide', httpMethods: ['POST'] },\n { pattern: 'design/style-guide', handler: 'getStyleGuide', httpMethods: ['GET'] },\n // style-guide/clear: WS uses this pattern; HTTP uses DELETE on /design/style-guide.\n // We keep a WS-only entry for the explicit \"clear\" subpath, and add a DELETE-on-style-guide entry.\n { pattern: 'design/style-guide/clear', handler: 'clearStyleGuide' },\n { pattern: 'design/style-guide', handler: 'clearStyleGuide', httpMethods: ['DELETE'] },\n\n // Quality Evaluation\n { pattern: 'design/evaluate', handler: 'evaluateQuality', httpMethods: ['POST'] },\n { pattern: 'design/evaluate/contexts', handler: 'getQualityContexts', httpMethods: ['GET'] },\n { pattern: 'design/evaluate/baseline', handler: 'saveBaseline', httpMethods: ['POST'] },\n { pattern: 'design/evaluate/diff', handler: 'diffBaseline', httpMethods: ['POST'] },\n\n // Meta / Introspection\n { pattern: 'meta/methods', handler: 'getMethods', httpMethods: ['GET'] },\n\n // AI helpers — mobile parity with the runner's `/ui-bridge/ai/*` family.\n { pattern: 'ai/fill-form', handler: 'fillForm', httpMethods: ['POST'] },\n\n // AI helpers — NOT_SUPPORTED stubs. These endpoints exist on the runner-side\n // UI Bridge surface (and the /manual-test skill's cheatsheet documents them\n // as if they're universally available). Mobile React Native has no DOM, so\n // the mobile bridge mounts explicit stubs so callers get a structured\n // NOT_SUPPORTED envelope (with a hint pointing at the mobile-native\n // replacement) instead of a confusing HTTP 404.\n { pattern: 'ai/forms', handler: 'aiForms', httpMethods: ['GET'] },\n { pattern: 'ai/idle-status', handler: 'aiIdleStatus', httpMethods: ['GET'] },\n {\n pattern: 'ai/change-buffer/enable',\n handler: 'aiChangeBufferEnable',\n httpMethods: ['POST'],\n },\n {\n pattern: 'ai/wait-for-element',\n handler: 'aiWaitForElement',\n httpMethods: ['POST'],\n },\n\n // Coord-based tap — synthesizes a press at the given screen coords by\n // matching against registered elements' layout rects.\n { pattern: 'control/tap', handler: 'tapAt', httpMethods: ['POST'] },\n\n // App-agnostic interaction parity — mirrors the web/runner convenience\n // endpoints (`/control/page/click-by-text` etc.) so the SAME cross-platform\n // contract drives mobile. Text/label-based interactions compose\n // `executor.find` + `executor.executeAction` over the registry; the\n // DOM-selector-only variants (`click-by-selector`, `read-value`) have no RN\n // analog and return a structured NOT_SUPPORTED envelope.\n { pattern: 'control/page/click-by-text', handler: 'clickByText', httpMethods: ['POST'] },\n { pattern: 'control/page/click-by-selector', handler: 'clickBySelector', httpMethods: ['POST'] },\n { pattern: 'control/page/type-into', handler: 'typeInto', httpMethods: ['POST'] },\n { pattern: 'control/page/read-value', handler: 'readValue', httpMethods: ['POST'] },\n { pattern: 'control/page/find-by-text', handler: 'findByText', httpMethods: ['POST'] },\n\n // Test hooks — gated behind `features.testHooks`. Let external runners\n // drive the ModalDetector over HTTP so tests can flip `snapshot.modalStack`\n // without mounting React components.\n {\n pattern: 'control/modal/push',\n handler: 'pushModal',\n httpMethods: ['POST'],\n requiresTestHooks: true,\n },\n {\n pattern: 'control/modal/dismiss/:id',\n handler: 'dismissModal',\n httpMethods: ['POST'],\n requiresTestHooks: true,\n },\n {\n pattern: 'control/keep-awake',\n handler: 'keepAwake',\n httpMethods: ['POST'],\n requiresTestHooks: true,\n },\n\n // Observability — last-N console errors + network requests.\n //\n // Always mounted (not testHooks-gated) so they return a schema-valid 200\n // on every build instead of a 404 that agents can't distinguish from a\n // missing route. The INVASIVE part — monkey-patching `console.error` /\n // `fetch` / `XMLHttpRequest` — stays gated behind `testHooks` (see\n // NativeUIBridgeServer.start → buffer.install()). When the patches aren't\n // installed the handlers report `installed: false` + empty entries, so\n // production builds expose the contract without observing real users'\n // console/network traffic. Set `features.testHooks` (typically on\n // `__DEV__`) to populate the buffers with live data.\n {\n pattern: 'control/console-errors',\n handler: 'getConsoleErrors',\n httpMethods: ['GET'],\n },\n {\n pattern: 'sdk/network-requests',\n handler: 'getNetworkRequests',\n httpMethods: ['GET'],\n },\n];\n\n/**\n * The two discovery endpoints, which `routeRequest` special-cases rather than\n * dispatching through `WS_ROUTES` — there is no handler to dispatch to. Both\n * are GET-only.\n *\n * ⚠️ This is the DISPATCH-adjacent copy, not the only one. The same two path\n * strings are also written out in `buildRoutesPayload` (which appends them to\n * the `_routes` manifest) and in the two serving branches of `routeRequest`,\n * and their `HELP` / `ROUTES` entries live in `types.ts`. Adding a third\n * discovery endpoint means touching all four. Only the `types.ts` ↔\n * `buildRoutesPayload` pair is ratcheted, by `route-table-parity.test.ts`;\n * forgetting THIS set silently downgrades the new endpoint's wrong-verb answer\n * to 404 and nothing fails. Collapsing the four into one declaration is a\n * worthwhile follow-up and is not attempted here.\n */\nconst DISCOVERY_PATHS = new Set(['_help', '_routes']);\n\n/**\n * The verbs this surface serves for a path, in table order.\n *\n * Fills the `Allow` header that RFC 9110 §15.5.6 makes mandatory on a 405, and\n * that the wrong-verb arm answered without: a caller told only \"method not\n * allowed\" has to guess which verb to retry, which is the guessing game the\n * status mapping exists to end. Read off `WS_ROUTES` — the array `routeRequest`\n * itself iterates — plus `DISCOVERY_PATHS`, which is the other thing\n * `routeRequest` dispatches on, so the header cannot come to disagree with the\n * status about what this surface accepts.\n *\n * `testHooks` is honoured for the same reason `routeRequest` honours it: a\n * production build must not advertise a gated verb it will not serve. `path` is\n * the full request path; the `/ui-bridge/` prefix is stripped here. Empty for a\n * path no route matches, in which case no header is set — that path answers\n * 404, where `Allow` would be meaningless.\n */\nfunction allowedMethodsForPath(path: string, testHooks: boolean): string[] {\n const PREFIX = '/ui-bridge/';\n if (!path.startsWith(PREFIX)) return [];\n const stripped = path.slice(PREFIX.length);\n\n const methods: string[] = [];\n if (DISCOVERY_PATHS.has(stripped)) methods.push('GET');\n for (const route of WS_ROUTES) {\n if (!route.httpMethods) continue;\n if (route.requiresTestHooks && !testHooks) continue;\n if (parsePath(route.pattern, stripped) === null) continue;\n for (const verb of route.httpMethods) {\n if (!methods.includes(verb)) methods.push(verb);\n }\n }\n return methods;\n}\n\n// ── _help payload ───────────────────────────────────────────────────────────\n\n/**\n * Short description keyed by handler name — rendered alongside the route\n * list so `_help` is self-documenting. Only needs to cover handlers that\n * appear in WS_ROUTES.\n */\nconst HANDLER_DESCRIPTIONS: Record<string, string> = {\n health: 'Liveness probe; returns app metadata + element count',\n getElements: 'Flat list of registered UI elements',\n getElement: 'Single element by id',\n getElementState: 'Dynamic state (value, focused, checked) for one element',\n executeAction: 'Run an action on an element (see \"actions\" below for names)',\n getComponents: 'Higher-level components with action schemas',\n getComponent: 'Component detail + per-action paramSchema',\n executeComponentAction: 'Invoke a component action directly (preferred over button clicks)',\n find: 'AI-powered element search by natural-language query',\n getSnapshot:\n 'Full snapshot: elements + route + state. Supports ?visibleOnly=true and ?currentRouteOnly=true',\n getPageHealth:\n 'Holistic page health diagnostic over current snapshot elements (spatial coverage, layout regions, text/anomaly signals, heatmap). Optional body: { viewport?: { width, height } } to override Dimensions.get(\"window\").',\n getWorkflows: 'List registered workflows',\n runWorkflow: 'Trigger a workflow by id',\n pageRefresh: 'Reload the current route',\n pageNavigate: 'Imperative router.push(url) — preferred over tapping tab buttons',\n pageReplace: 'router.replace(url)',\n pageGoBack: 'router.back()',\n pageGoForward: 'router.forward()',\n getScreenshot: 'PNG screenshot of the current screen',\n getElementStyles: 'Computed styles for an element (design review)',\n getElementStateStyles: 'Computed styles per interaction state (hover/focus/disabled)',\n getDesignSnapshot: 'Visual + style snapshot for design review',\n getResponsiveSnapshots: 'Screenshots at multiple viewport widths',\n runDesignAudit: 'Accessibility + visual audit',\n loadStyleGuide: 'Load a design system style guide',\n getStyleGuide: 'Fetch the currently loaded style guide',\n clearStyleGuide: 'Unload the style guide',\n evaluateQuality: 'Score the current UI against a quality context',\n getQualityContexts: 'List available quality evaluation contexts',\n saveBaseline: 'Save a quality baseline snapshot',\n diffBaseline: 'Diff current UI against a saved baseline',\n getMethods: 'List every handler name (legacy introspection)',\n fillForm:\n 'Fill multiple inputs in one call: body { fields: [{elementId, value}] } — each field dispatches `type` + `clear:true`',\n aiForms:\n 'STUB — runner-only; mobile returns NOT_SUPPORTED. Use /control/snapshot + filter type===\"input\" instead.',\n aiIdleStatus:\n 'STUB — runner-only; mobile returns NOT_SUPPORTED. Subscribe to registry events over WS for change signals.',\n aiChangeBufferEnable:\n 'STUB — runner-only; mobile returns NOT_SUPPORTED. Use WS event subscriptions for change notifications.',\n aiWaitForElement:\n 'STUB — runner-only; mobile returns NOT_SUPPORTED. Use the WS waitForElement / waitForCondition JSON-RPC methods.',\n tapAt:\n 'Synthesize a press at given screen coords by matching registered element layout rects: body { x, y, action? }',\n clickByText:\n 'App-agnostic: press the first element matching free-text (label/accessibilityLabel/testID): body { text, visibleOnly? }',\n clickBySelector:\n 'STUB — selector-based; NOT_SUPPORTED on native (no DOM). Use clickByText or /control/find + /control/element/:id/action.',\n typeInto:\n 'App-agnostic: type into the input matching a label: body { label, text, clear?, visibleOnly? }. (selector form is web-only)',\n readValue:\n 'STUB — selector-based; NOT_SUPPORTED on native (no DOM). Use /control/element/:id/state to read a value.',\n findByText:\n 'App-agnostic: list elements matching free-text (no press): body { text, visibleOnly? }',\n getConsoleErrors:\n 'Last-N console.error/console.warn entries; ?since=<ms>&limit=<n>. `installed:false` when capture is off (no testHooks) — entries empty but schema-valid.',\n getNetworkRequests:\n 'Last-N fetch/XHR entries with status + duration; ?since=<ms>&limit=<n>. `installed:false` when capture is off (no testHooks) — entries empty but schema-valid.',\n pushModal:\n 'TEST HOOK — push a modal onto the snapshot.modalStack via the registry ModalDetector',\n dismissModal:\n 'TEST HOOK — dismiss a modal by id from the snapshot.modalStack via the registry ModalDetector',\n keepAwake:\n 'TEST HOOK — keep the device screen awake via the injected keepAwakeProvider: body { enabled: boolean, durationMs?: number }',\n};\n\n/** Static reference for common action names + their params. */\nconst ACTION_REFERENCE = [\n { name: 'press', aliases: ['click'], params: 'PressActionParams (optional position)' },\n { name: 'longPress', params: 'PressActionParams (optional position)' },\n { name: 'doubleTap', params: 'none' },\n {\n name: 'type',\n params:\n 'TypeActionParams { text, delay?, clear? | clearFirst? } — `clear:true` replaces content atomically',\n },\n { name: 'clear', params: 'none — empties the input' },\n { name: 'focus', params: 'none' },\n { name: 'blur', params: 'none' },\n { name: 'scroll', params: 'ScrollActionParams { offset? {x,y}, to? }' },\n {\n name: 'scrollIntoView',\n params:\n \"ScrollIntoViewActionParams { padding? (dp, default 16) } — scrolls the element's DECLARED scrollAncestorId ScrollView; returns { alreadyVisible, scrolled }; NOT_SUPPORTED (501) without a usable declared ancestor\",\n },\n { name: 'swipe', params: 'SwipeActionParams { direction, distance }' },\n { name: 'toggle', params: 'none — flips boolean controls' },\n];\n\n/**\n * Minimal `{method, path}` list matching the runner's `/_routes` shape so\n * the same URL works across platforms. Expanded multi-verb routes into one\n * entry per verb. `testHooks` enables the gated `control/modal/*` endpoints.\n */\nfunction buildRoutesPayload(testHooks: boolean) {\n const entries: Array<{ method: string; path: string }> = [];\n for (const r of WS_ROUTES) {\n if (!r.httpMethods) continue;\n if (r.requiresTestHooks && !testHooks) continue;\n for (const m of r.httpMethods) {\n entries.push({ method: m, path: `/ui-bridge/${r.pattern}` });\n }\n }\n // Expose the two discovery endpoints themselves so self-reference is clean.\n entries.push({ method: 'GET', path: '/ui-bridge/_help' });\n entries.push({ method: 'GET', path: '/ui-bridge/_routes' });\n entries.sort((a, b) => a.path.localeCompare(b.path) || a.method.localeCompare(b.method));\n return { routes: entries, count: entries.length };\n}\n\n/**\n * Build the `/_help` payload: route index + action reference.\n * Cheap to compute; we don't cache since it's rarely called.\n * Routes that require `testHooks` are filtered out when the flag is off so\n * agents probing the manifest never see endpoints they can't call.\n */\nfunction buildHelpPayload(testHooks: boolean) {\n return {\n version: 1,\n description: 'UI Bridge Native HTTP surface. Prefix every path with /ui-bridge/.',\n routes: WS_ROUTES.filter((r) => !r.requiresTestHooks || testHooks).map((r) => ({\n pattern: r.pattern,\n httpMethods: r.httpMethods ?? [],\n wsOnly: !r.httpMethods,\n handler: r.handler,\n description: HANDLER_DESCRIPTIONS[r.handler] ?? '',\n })),\n actions: ACTION_REFERENCE,\n tips: [\n 'Start with `GET /ui-bridge/control/snapshot?visibleOnly=true` to see what the user actually sees.',\n 'Prefer `control/component/:id/action/:actionId` over button presses — typed paramSchema, no button-id guessing.',\n 'Use `pageNavigate` for tab switches instead of pressing tab buttons; gesture state often swallows clicks.',\n 'The `type` action supports `clear:true` to replace existing text atomically in one call.',\n ],\n };\n}\n\n/**\n * HTTP Request interface (library-agnostic)\n */\nexport interface HTTPRequest {\n method: string;\n path: string;\n headers: Record<string, string>;\n query: Record<string, string>;\n body?: unknown;\n}\n\n/**\n * HTTP Response interface (library-agnostic)\n */\nexport interface HTTPResponse {\n status: number;\n headers: Record<string, string>;\n body: string;\n}\n\n/**\n * Request handler type\n */\nexport type RequestHandler = (request: HTTPRequest) => Promise<HTTPResponse>;\n\n/**\n * Server adapter interface\n *\n * Implement this interface to integrate with your chosen HTTP server library.\n */\nexport interface ServerAdapter {\n /** Start the server */\n start(port: number, handler: RequestHandler): Promise<void>;\n /** Stop the server */\n stop(): Promise<void>;\n /** Check if server is running */\n isRunning(): boolean;\n}\n\n/**\n * WebSocket-aware server adapter interface.\n *\n * Extends ServerAdapter with callbacks for WebSocket connections.\n * The adapter manages the raw TCP/WS layer; these callbacks let the\n * UI Bridge server handle message routing and event broadcasting.\n */\nexport interface WebSocketServerAdapter extends ServerAdapter {\n /** Called when a JSON text frame is received from a WS client. Returns response string or null. */\n onWebSocketMessage?: (connId: string, message: string) => Promise<string | null>;\n /** Called when a new WS connection is established after the HTTP 101 upgrade. */\n onWebSocketConnect?: (connId: string) => void;\n /** Called when a WS connection is closed or drops. */\n onWebSocketDisconnect?: (connId: string) => void;\n /** Send a message to a specific WS connection by ID. */\n sendToConnection?: (connId: string, message: string) => void;\n /** Send a message to all connected WS clients. */\n broadcast?: (message: string) => void;\n}\n\n/**\n * Native UI Bridge HTTP Server\n */\nexport class NativeUIBridgeServer {\n private config: NativeServerConfig;\n private handlers: NativeServerHandlers;\n private adapter?: ServerAdapter;\n private running = false;\n private keepAwakeProvider?: KeepAwakeProvider;\n /**\n * Per-connection cleanup thunks for in-flight waiters (waitForElement,\n * waitForCondition, ...). Aborted when a client disconnects so the\n * underlying timers/listeners don't leak.\n */\n private pendingWaiters = new Map<string, Set<() => void>>();\n\n /**\n * Observability ring buffers backing `/control/console-errors` and\n * `/sdk/network-requests`. Allocated unconditionally so the handler can\n * always read them, but the global patches (`install()`) only fire on\n * `start()` when observability is enabled (the dedicated `observability`\n * flag, defaulting to `testHooks`) — builds with both off don't\n * monkey-patch.\n */\n private consoleErrorBuffer: ConsoleErrorBuffer;\n private networkRequestBuffer: NetworkRequestBuffer;\n\n /**\n * Whether the console/network capture should be installed. The dedicated\n * `observability` flag wins when set; otherwise falls back to `testHooks`\n * so consumers predating the flag keep their exact behavior.\n */\n private observabilityEnabled(): boolean {\n return this.config.observability ?? this.config.testHooks === true;\n }\n\n constructor(\n private registry: NativeUIBridgeRegistry,\n private executor: NativeActionExecutor,\n config: NativeServerConfig = {}\n ) {\n this.config = {\n serverPort: 8087,\n cors: true,\n ...config,\n };\n this.consoleErrorBuffer = new ConsoleErrorBuffer();\n this.networkRequestBuffer = new NetworkRequestBuffer();\n // Mirror appInfo into the registry so `createSnapshot` includes it\n // automatically — keeps the default `getSnapshot` handler and any other\n // call site (e.g. context.createSnapshot, cloud-relay tunnels) on the\n // same code path without each having to thread `appInfo` through.\n if (this.config.appInfo) {\n this.registry.setAppInfo(this.config.appInfo);\n }\n this.handlers = createServerHandlers(registry, executor, {\n appInfo: this.config.appInfo,\n consoleErrorBuffer: this.consoleErrorBuffer,\n networkRequestBuffer: this.networkRequestBuffer,\n viewportProvider: this.config.viewportProvider,\n });\n\n // Set up method introspection from the route table\n this.handlers.getMethods = async () => {\n const testHooks = this.config.testHooks === true;\n const methods = WS_ROUTES.filter((r) => !r.requiresTestHooks || testHooks).map((r) => ({\n method: r.pattern,\n httpMethods: r.httpMethods ? [...r.httpMethods] : undefined,\n }));\n // Add special WebSocket-only methods not in the route table\n const wsMethods = [\n { method: 'waitForElement', description: 'Wait for an element to be registered' },\n { method: 'waitForCondition', description: 'Wait for an element state predicate' },\n { method: 'sequence', description: 'Execute a sequence of steps in order' },\n { method: 'events/history', description: 'Replay recent registry events' },\n { method: 'subscriptions/list', description: 'List current event subscriptions' },\n ];\n return {\n success: true,\n data: { methods: [...methods, ...wsMethods] },\n timestamp: Date.now(),\n };\n };\n }\n\n /**\n * Set the server adapter\n */\n setAdapter(adapter: ServerAdapter): void {\n this.adapter = adapter;\n }\n\n /**\n * Set a navigation provider for programmatic route navigation.\n * This enables `control/page/navigate` and `control/page/back` on native.\n */\n setNavigationProvider(provider: NavigationProvider): void {\n this.handlers.pageNavigate = async (ctx): Promise<APIResponse<PageNavigationResponse>> => {\n const body = ctx.body as Record<string, unknown> | undefined;\n const url = body?.url;\n if (!url || typeof url !== 'string') {\n return { success: false, error: 'Missing required \"url\" parameter', timestamp: Date.now() };\n }\n try {\n provider.navigate(url);\n return {\n success: true,\n data: { success: true, url, timestamp: Date.now() },\n timestamp: Date.now(),\n };\n } catch (e: unknown) {\n return {\n success: false,\n error: `Navigation failed: ${e instanceof Error ? e.message : String(e)}`,\n timestamp: Date.now(),\n };\n }\n };\n\n this.handlers.pageReplace = async (ctx): Promise<APIResponse<PageNavigationResponse>> => {\n if (!provider.replace) {\n return {\n success: false,\n error: 'Replace navigation not supported by navigation provider',\n timestamp: Date.now(),\n };\n }\n const body = ctx.body as Record<string, unknown> | undefined;\n const url = body?.url;\n if (!url || typeof url !== 'string') {\n return { success: false, error: 'Missing required \"url\" parameter', timestamp: Date.now() };\n }\n try {\n provider.replace(url);\n return {\n success: true,\n data: { success: true, url, timestamp: Date.now() },\n timestamp: Date.now(),\n };\n } catch (e: unknown) {\n return {\n success: false,\n error: `Replace navigation failed: ${e instanceof Error ? e.message : String(e)}`,\n timestamp: Date.now(),\n };\n }\n };\n\n this.handlers.pageGoBack = async (): Promise<APIResponse<PageNavigationResponse>> => {\n if (!provider.back) {\n return { success: false, error: 'Back navigation not supported', timestamp: Date.now() };\n }\n try {\n provider.back();\n return {\n success: true,\n data: { success: true, timestamp: Date.now() },\n timestamp: Date.now(),\n };\n } catch (e: unknown) {\n return {\n success: false,\n error: `Back navigation failed: ${e instanceof Error ? e.message : String(e)}`,\n timestamp: Date.now(),\n };\n }\n };\n\n this.handlers.pageRefresh = async (): Promise<APIResponse<PageNavigationResponse>> => {\n if (!provider.refresh) {\n return {\n success: false,\n error: 'Page refresh not supported by navigation provider',\n timestamp: Date.now(),\n };\n }\n try {\n provider.refresh();\n return {\n success: true,\n data: { success: true, timestamp: Date.now() },\n timestamp: Date.now(),\n };\n } catch (e: unknown) {\n return {\n success: false,\n error: `Refresh failed: ${e instanceof Error ? e.message : String(e)}`,\n timestamp: Date.now(),\n };\n }\n };\n }\n\n /**\n * Set a route provider for reporting the current navigation route.\n * When set, `control/snapshot` responses include `currentRoute` and\n * `segments`, plus the canonical `route` / `activeTab` aliases the web SDK's\n * `BridgeSnapshot` spells the same way.\n *\n * Also forwards the provider into the registry so the *default*\n * `getSnapshot` handler (and any other call site of\n * `registry.createSnapshot`) reads the route too — without this the\n * cloud-relay/bare-server path returned `currentRoute: null` even when\n * a `RouteTracker` was wired, because that path never installed the\n * server-level handler override below.\n */\n setRouteProvider(provider: RouteProvider): void {\n this.registry.setRouteProvider(provider);\n // Override getElements to support currentRouteOnly filtering with real route data\n const baseGetElements = this.handlers.getElements;\n this.handlers.getElements = async (ctx: HandlerContext) => {\n const currentRouteOnly =\n ctx.query?.currentRouteOnly === 'true' ||\n (ctx.body as Record<string, unknown>)?.currentRouteOnly === true;\n\n // If currentRouteOnly requested and no explicit route param, inject the current route\n if (currentRouteOnly && !ctx.query?.route && !(ctx.body as Record<string, unknown>)?.route) {\n // Defensive for the same reason as `getSnapshot` below: a throwing\n // provider must degrade to \"no route filter\", not 500 the route.\n let currentRoute: string | null;\n try {\n currentRoute = provider.getCurrentRoute();\n } catch {\n currentRoute = null;\n }\n if (currentRoute) {\n // Inject route into query so the base handler can filter by it\n ctx.query = { ...ctx.query, route: currentRoute };\n }\n }\n return baseGetElements(ctx);\n };\n\n this.handlers.getSnapshot = async (ctx: HandlerContext) => {\n const visibleOnly =\n ctx?.query?.visibleOnly === 'true' ||\n (ctx?.body as Record<string, unknown>)?.visibleOnly === true;\n const currentRouteOnly =\n ctx?.query?.currentRouteOnly === 'true' ||\n (ctx?.body as Record<string, unknown>)?.currentRouteOnly === true;\n // Read the provider defensively. The registry's own fallback path wraps\n // these same calls in a try/catch and degrades to a null route; without\n // the same guard here a host whose provider throws mid-navigation turns\n // the whole `control/snapshot` response into a 500 instead of a snapshot\n // that simply does not know its route.\n //\n // THREE separate guards, not one, because the three facts fail\n // independently and `currentRoute` is load-bearing: `createSnapshot`\n // applies the `currentRouteOnly` filter only when `currentRoute` is\n // truthy, so letting an optional `getSegments()` throw discard a route we\n // successfully read would answer `?currentRouteOnly=true` with EVERY\n // registered element in the app, labelled as the current route's. That\n // turns a loud 500 into a silent wrong answer a runner would act on.\n let currentRoute: string | null;\n try {\n currentRoute = provider.getCurrentRoute() ?? null;\n } catch {\n currentRoute = null;\n }\n let segments: string[] | undefined;\n try {\n segments = provider.getSegments?.();\n } catch {\n segments = undefined;\n }\n // Passed explicitly rather than left to the registry to resolve. The\n // registry's `resolveActiveTab` reads whatever provider is registered on\n // IT, which is not necessarily this one — a host that detaches with\n // `registry.setRouteProvider(null)` (the documented HMR/teardown escape\n // hatch) would leave this closure still reporting the right `route` while\n // `activeTab` silently reverted to the segment derivation. Reading our own\n // provider keeps the emitted snapshot internally consistent.\n let activeTab: string | null | undefined;\n try {\n activeTab = provider.getActiveTab?.();\n } catch {\n activeTab = undefined;\n }\n const snapshot = this.registry.createSnapshot(\n { currentRoute, segments, activeTab },\n { visibleOnly, currentRouteOnly }\n );\n return { success: true, data: snapshot, timestamp: Date.now() };\n };\n }\n\n /**\n * Set a screenshot provider for native screen capture.\n * This enables `control/screenshot` on native.\n */\n setScreenshotProvider(provider: ScreenshotProvider): void {\n const SCREENSHOT_TIMEOUT_MS = 10_000;\n this.handlers.getScreenshot = async () => {\n try {\n const result = await Promise.race([\n provider.capture(),\n new Promise<never>((_, reject) =>\n setTimeout(\n () =>\n reject(new Error(`Screenshot capture timed out after ${SCREENSHOT_TIMEOUT_MS}ms`)),\n SCREENSHOT_TIMEOUT_MS\n )\n ),\n ]);\n return {\n success: true,\n data: { screenshot: result.base64, width: result.width, height: result.height },\n timestamp: Date.now(),\n };\n } catch (e: unknown) {\n return {\n success: false,\n error: `Screenshot capture failed: ${e instanceof Error ? e.message : String(e)}`,\n timestamp: Date.now(),\n };\n }\n };\n }\n\n /**\n * Set a keep-awake provider for native screen-wake control.\n * This enables `control/keep-awake` and arms the auto-arm hook in\n * handleRequest (every request keeps the screen alive for 60s).\n */\n setKeepAwakeProvider(provider: KeepAwakeProvider): void {\n this.keepAwakeProvider = provider;\n this.handlers.keepAwake = async (ctx) => {\n const { enabled, durationMs } = (ctx.body ?? {}) as {\n enabled?: unknown;\n durationMs?: unknown;\n };\n if (typeof enabled !== 'boolean') {\n return {\n success: false,\n error: 'enabled must be boolean',\n code: 'INVALID_REQUEST',\n timestamp: Date.now(),\n };\n }\n if (enabled) {\n provider.request('ui-bridge', typeof durationMs === 'number' ? durationMs : undefined);\n } else {\n provider.release('ui-bridge');\n }\n return {\n success: true,\n data: { enabled, durationMs: typeof durationMs === 'number' ? durationMs : null },\n timestamp: Date.now(),\n };\n };\n }\n\n /**\n * Start the HTTP server\n */\n async start(): Promise<void> {\n if (this.running) {\n console.warn('[ui-bridge-native] Server already running');\n return;\n }\n\n if (!this.adapter) {\n console.warn('[ui-bridge-native] No server adapter configured. Call setAdapter() first.');\n console.warn('[ui-bridge-native] See documentation for supported adapters.');\n return;\n }\n\n // Install observability patches before binding the port — gated behind\n // the dedicated `observability` flag, which defaults to `testHooks` so\n // existing consumers are unchanged. Decoupling the two lets release\n // builds capture console/network evidence without also exposing the\n // testHooks-gated control surface (`control/modal/*` etc.).\n if (this.observabilityEnabled()) {\n this.consoleErrorBuffer.install();\n this.networkRequestBuffer.install();\n }\n\n await this.adapter.start(this.config.serverPort!, this.handleRequest.bind(this));\n this.running = true;\n\n console.log(`[ui-bridge-native] HTTP server started on port ${this.config.serverPort}`);\n }\n\n /**\n * Stop the HTTP server\n */\n async stop(): Promise<void> {\n if (!this.running || !this.adapter) {\n return;\n }\n\n await this.adapter.stop();\n this.running = false;\n\n // Restore the original globals; idempotent if never installed.\n this.consoleErrorBuffer.uninstall();\n this.networkRequestBuffer.uninstall();\n\n console.log('[ui-bridge-native] HTTP server stopped');\n }\n\n /**\n * Check if server is running\n */\n isRunning(): boolean {\n return this.running;\n }\n\n // ── WebSocket Support ───────────────────────────────────────────────────\n\n private eventBridge?: WebSocketEventBridge;\n\n /**\n * Set the event bridge for WebSocket event broadcasting and subscriptions.\n */\n setEventBridge(bridge: WebSocketEventBridge): void {\n this.eventBridge = bridge;\n }\n\n /**\n * Handle a JSON-RPC message from a WebSocket client.\n * Parses the message, routes to the appropriate handler, and returns\n * a JSON string response (or null for events that need no response).\n */\n async handleWebSocketMessage(connId: string, rawMessage: string): Promise<string | null> {\n let msg: unknown;\n try {\n msg = JSON.parse(rawMessage);\n } catch {\n return JSON.stringify({\n error: 'Invalid JSON',\n timestamp: Date.now(),\n });\n }\n\n if (typeof msg !== 'object' || msg === null) {\n return JSON.stringify({\n error: 'Message must be a JSON object',\n timestamp: Date.now(),\n });\n }\n\n const message = msg as Record<string, unknown>;\n const id = (message.id as string | number | undefined) ?? 0;\n\n // Handle batch requests\n if (isBatchRequest(message)) {\n const results = await this.handleBatchRequest(message.batch);\n return JSON.stringify({ id, results });\n }\n\n // Handle subscribe\n if (isSubscribe(message)) {\n const events = message.params?.events || [];\n const throttleMs = message.params?.throttleMs;\n const ok = this.eventBridge?.handleSubscribe(connId, events, throttleMs) ?? false;\n return JSON.stringify({\n id,\n result: {\n success: ok,\n data: { subscribed: events },\n timestamp: Date.now(),\n },\n } satisfies JsonRpcResponse);\n }\n\n // Handle unsubscribe\n if (isUnsubscribe(message)) {\n const events = message.params?.events || [];\n const ok = this.eventBridge?.handleUnsubscribe(connId, events) ?? false;\n return JSON.stringify({\n id,\n result: {\n success: ok,\n data: { unsubscribed: events },\n timestamp: Date.now(),\n },\n } satisfies JsonRpcResponse);\n }\n\n const method = message.method as string;\n const params = (message.params || {}) as Record<string, unknown>;\n\n // ── Connection-aware special methods ──────────────────────────────────\n\n // subscriptions/list — return current subscriptions + throttle for this connection\n if (method === 'subscriptions/list') {\n const events = this.eventBridge?.getSubscriptions(connId) ?? [];\n const throttleMs = this.eventBridge?.getThrottleMs(connId);\n return JSON.stringify({\n id,\n result: {\n success: true,\n data: { events, throttleMs: throttleMs ?? null },\n timestamp: Date.now(),\n },\n } satisfies JsonRpcResponse);\n }\n\n // waitForElement — resolve when element is registered, or timeout\n if (method === 'waitForElement') {\n return this.handleWaitForElement(connId, id, params);\n }\n\n // waitForCondition — resolve when an element state predicate becomes true\n if (method === 'waitForCondition') {\n return this.handleWaitForCondition(connId, id, params);\n }\n\n // sequence — execute steps in order, stop on first failure\n if (method === 'sequence') {\n return this.handleSequence(id, params);\n }\n\n // events/history — replay recent events matching optional filter\n if (method === 'events/history') {\n const eventsFilter = Array.isArray(params.events) ? (params.events as string[]) : undefined;\n const since = typeof params.since === 'number' ? params.since : undefined;\n const limit = typeof params.limit === 'number' ? params.limit : undefined;\n const history = this.eventBridge?.getHistory({ events: eventsFilter, since }) ?? [];\n const sliced =\n limit !== undefined && limit > 0 && history.length > limit\n ? history.slice(history.length - limit)\n : history;\n return JSON.stringify({\n id,\n result: {\n success: true,\n data: { events: sliced },\n timestamp: Date.now(),\n },\n } satisfies JsonRpcResponse);\n }\n\n // Standard JSON-RPC request\n\n if (!method) {\n return JSON.stringify({\n id,\n result: {\n success: false,\n error: 'Missing \"method\" field',\n code: 'INVALID_REQUEST',\n timestamp: Date.now(),\n },\n } satisfies JsonRpcResponse);\n }\n\n try {\n const apiResponse = await this.routeMethodToHandler(method, params);\n return JSON.stringify({ id, result: apiResponse } satisfies JsonRpcResponse);\n } catch (error) {\n return JSON.stringify({\n id,\n result: {\n success: false,\n error: error instanceof Error ? error.message : 'Internal error',\n code: 'INTERNAL_ERROR',\n timestamp: Date.now(),\n },\n } satisfies JsonRpcResponse);\n }\n }\n\n /**\n * Execute a batch of JSON-RPC requests concurrently.\n */\n async handleBatchRequest(batch: JsonRpcRequest[]): Promise<JsonRpcResponse[]> {\n return Promise.all(\n batch.map(async (req) => {\n try {\n const result = await this.routeMethodToHandler(\n req.method,\n (req.params || {}) as Record<string, unknown>\n );\n return { id: req.id, result } as JsonRpcResponse;\n } catch (error) {\n return {\n id: req.id,\n result: {\n success: false,\n error: error instanceof Error ? error.message : 'Internal error',\n code: 'INTERNAL_ERROR',\n timestamp: Date.now(),\n },\n } satisfies JsonRpcResponse;\n }\n })\n );\n }\n\n /**\n * Register an in-flight waiter's cleanup thunk under the given connection.\n * Returns an `unregister` thunk that the natural-resolution path should\n * call so the cleanup isn't re-invoked on disconnect.\n */\n private registerWaiter(connId: string, cleanup: () => void): () => void {\n let set = this.pendingWaiters.get(connId);\n if (!set) {\n set = new Set();\n this.pendingWaiters.set(connId, set);\n }\n set.add(cleanup);\n return () => {\n const s = this.pendingWaiters.get(connId);\n if (!s) return;\n s.delete(cleanup);\n if (s.size === 0) this.pendingWaiters.delete(connId);\n };\n }\n\n /**\n * Abort all pending waiters associated with a connection. Called by the\n * provider's WS disconnect handler so timers/listeners don't leak after\n * the client goes away.\n */\n abortWaitersForConnection(connId: string): void {\n const set = this.pendingWaiters.get(connId);\n if (!set) return;\n for (const cleanup of set) {\n try {\n cleanup();\n } catch (err) {\n console.warn('[ui-bridge-native] waiter cleanup threw:', err);\n }\n }\n this.pendingWaiters.delete(connId);\n }\n\n /**\n * Wait for an element to be registered, or resolve immediately if it already exists.\n * Returns a JsonRpcResponse JSON string.\n */\n private async handleWaitForElement(\n connId: string,\n id: string | number,\n params: Record<string, unknown>\n ): Promise<string> {\n const targetId = params.id;\n const timeout = typeof params.timeout === 'number' ? params.timeout : 10000;\n\n if (!targetId || typeof targetId !== 'string') {\n return JSON.stringify({\n id,\n result: {\n success: false,\n error: 'Missing or invalid \"id\" parameter',\n code: 'INVALID_REQUEST',\n timestamp: Date.now(),\n },\n } satisfies JsonRpcResponse);\n }\n\n // Already registered — return immediately\n const existing = this.registry.getElement(targetId);\n if (existing) {\n return JSON.stringify({\n id,\n result: {\n success: true,\n data: {\n id: targetId,\n state: existing.getState(),\n identifier: existing.getIdentifier(),\n waited: false,\n },\n timestamp: Date.now(),\n },\n } satisfies JsonRpcResponse);\n }\n\n // Wait for element:registered event with matching id, or timeout\n return new Promise<string>((resolve) => {\n let settled = false;\n let unsub: (() => void) | null = null;\n let timer: ReturnType<typeof setTimeout> | null = null;\n let unregister: (() => void) | null = null;\n\n const cleanup = () => {\n if (settled) return;\n settled = true;\n if (unsub) {\n unsub();\n unsub = null;\n }\n if (timer) {\n clearTimeout(timer);\n timer = null;\n }\n if (unregister) {\n unregister();\n unregister = null;\n }\n };\n\n // Track this waiter so it can be aborted if the connection closes.\n unregister = this.registerWaiter(connId, () => {\n cleanup();\n resolve(\n JSON.stringify({\n id,\n result: {\n success: false,\n error: 'Connection closed before element was registered',\n code: 'CONNECTION_CLOSED',\n timestamp: Date.now(),\n },\n } satisfies JsonRpcResponse)\n );\n });\n\n unsub = this.registry.on('element:registered', (event: BridgeEvent) => {\n if (settled) return;\n const data = event.data as { id?: string } | undefined;\n if (data?.id !== targetId) return;\n\n cleanup();\n const el = this.registry.getElement(targetId);\n resolve(\n JSON.stringify({\n id,\n result: {\n success: true,\n data: {\n id: targetId,\n state: el?.getState() ?? null,\n identifier: el?.getIdentifier() ?? null,\n waited: true,\n },\n timestamp: Date.now(),\n },\n } satisfies JsonRpcResponse)\n );\n });\n\n timer = setTimeout(() => {\n if (settled) return;\n cleanup();\n resolve(\n JSON.stringify({\n id,\n result: {\n success: false,\n error: `Timeout waiting for element: ${targetId}`,\n code: 'TIMEOUT',\n timestamp: Date.now(),\n },\n } satisfies JsonRpcResponse)\n );\n }, timeout);\n });\n }\n\n /**\n * Wait for an arbitrary element-state predicate to become true.\n *\n * Supported `condition` shapes:\n * {field: \"mounted\"|\"visible\"|\"enabled\"|\"focused\", equals: boolean}\n * {field: \"layout\", exists: true}\n * {field: string, equals: unknown} // generic: state[field] === equals\n *\n * Resolves immediately with `waited:false` if the predicate already\n * holds. Otherwise subscribes to `element:registered` and\n * `element:stateChanged` until the predicate matches or timeout fires.\n */\n private async handleWaitForCondition(\n connId: string,\n id: string | number,\n params: Record<string, unknown>\n ): Promise<string> {\n const targetId = params.elementId;\n const condition = params.condition as\n | { field?: string; equals?: unknown; exists?: boolean }\n | undefined;\n const timeout = typeof params.timeout === 'number' ? params.timeout : 10000;\n\n if (!targetId || typeof targetId !== 'string') {\n return JSON.stringify({\n id,\n result: {\n success: false,\n error: 'Missing or invalid \"elementId\" parameter',\n code: 'INVALID_REQUEST',\n timestamp: Date.now(),\n },\n } satisfies JsonRpcResponse);\n }\n if (!condition || typeof condition.field !== 'string') {\n return JSON.stringify({\n id,\n result: {\n success: false,\n error: 'Missing or invalid \"condition.field\"',\n code: 'INVALID_REQUEST',\n timestamp: Date.now(),\n },\n } satisfies JsonRpcResponse);\n }\n\n const evaluate = (state: Record<string, unknown> | null | undefined): boolean => {\n if (!state) return false;\n const value = state[condition.field as string];\n if (condition.exists === true) return value !== null && value !== undefined;\n if ('equals' in condition) return value === condition.equals;\n return false;\n };\n\n const makeResult = (state: Record<string, unknown> | null, waited: boolean) =>\n JSON.stringify({\n id,\n result: {\n success: true,\n data: { id: targetId, state, waited },\n timestamp: Date.now(),\n },\n } satisfies JsonRpcResponse);\n\n // Fast path: already holds.\n const existing = this.registry.getElement(targetId);\n if (existing) {\n const state = existing.getState() as unknown as Record<string, unknown> | null;\n if (evaluate(state)) {\n return makeResult(state, false);\n }\n }\n\n return new Promise<string>((resolve) => {\n let settled = false;\n let unsubRegistered: (() => void) | null = null;\n let unsubStateChanged: (() => void) | null = null;\n let timer: ReturnType<typeof setTimeout> | null = null;\n let unregister: (() => void) | null = null;\n\n const cleanup = () => {\n if (settled) return;\n settled = true;\n if (unsubRegistered) {\n unsubRegistered();\n unsubRegistered = null;\n }\n if (unsubStateChanged) {\n unsubStateChanged();\n unsubStateChanged = null;\n }\n if (timer) {\n clearTimeout(timer);\n timer = null;\n }\n if (unregister) {\n unregister();\n unregister = null;\n }\n };\n\n unregister = this.registerWaiter(connId, () => {\n cleanup();\n resolve(\n JSON.stringify({\n id,\n result: {\n success: false,\n error: 'Connection closed before condition was met',\n code: 'CONNECTION_CLOSED',\n timestamp: Date.now(),\n },\n } satisfies JsonRpcResponse)\n );\n });\n\n const checkAndResolve = () => {\n if (settled) return;\n const el = this.registry.getElement(targetId);\n if (!el) return;\n const state = el.getState() as unknown as Record<string, unknown> | null;\n if (evaluate(state)) {\n cleanup();\n resolve(makeResult(state, true));\n }\n };\n\n unsubRegistered = this.registry.on('element:registered', (event: BridgeEvent) => {\n if (settled) return;\n const data = event.data as { id?: string } | undefined;\n if (data?.id !== targetId) return;\n checkAndResolve();\n });\n\n unsubStateChanged = this.registry.on('element:stateChanged', (event: BridgeEvent) => {\n if (settled) return;\n const data = event.data as { id?: string } | undefined;\n if (data?.id !== targetId) return;\n checkAndResolve();\n });\n\n timer = setTimeout(() => {\n if (settled) return;\n cleanup();\n resolve(\n JSON.stringify({\n id,\n result: {\n success: false,\n error: `Timeout waiting for condition on element: ${targetId}`,\n code: 'TIMEOUT',\n timestamp: Date.now(),\n },\n } satisfies JsonRpcResponse)\n );\n }, timeout);\n });\n }\n\n /**\n * Execute a sequence of JSON-RPC steps in order, stopping on first failure.\n * Returns a JsonRpcResponse JSON string with per-step results.\n */\n private async handleSequence(\n id: string | number,\n params: Record<string, unknown>\n ): Promise<string> {\n const rawSteps = params.steps;\n\n if (!Array.isArray(rawSteps) || rawSteps.length === 0) {\n return JSON.stringify({\n id,\n result: {\n success: false,\n error: 'Missing or empty \"steps\" array',\n code: 'INVALID_REQUEST',\n timestamp: Date.now(),\n },\n } satisfies JsonRpcResponse);\n }\n\n const steps = rawSteps as Array<{ method: string; params?: Record<string, unknown> }>;\n const results: Array<{ step: number; method: string; result: APIResponse }> = [];\n let allSuccess = true;\n\n for (let i = 0; i < steps.length; i++) {\n const step = steps[i];\n\n if (!step || typeof step.method !== 'string') {\n results.push({\n step: i,\n method: String(step?.method ?? ''),\n result: {\n success: false,\n error: 'Step is missing \"method\" field',\n code: 'INVALID_REQUEST',\n timestamp: Date.now(),\n },\n });\n allSuccess = false;\n break;\n }\n\n try {\n const stepResult = await this.routeMethodToHandler(step.method, step.params ?? {});\n results.push({ step: i, method: step.method, result: stepResult });\n if (!stepResult.success) {\n allSuccess = false;\n break;\n }\n } catch (err) {\n results.push({\n step: i,\n method: step.method,\n result: {\n success: false,\n error: err instanceof Error ? err.message : 'Step execution failed',\n code: 'STEP_FAILED',\n timestamp: Date.now(),\n },\n });\n allSuccess = false;\n break;\n }\n }\n\n return JSON.stringify({\n id,\n result: {\n success: allSuccess,\n data: {\n completedSteps: results.length,\n totalSteps: steps.length,\n results,\n },\n timestamp: Date.now(),\n },\n } satisfies JsonRpcResponse);\n }\n\n /**\n * Route a JSON-RPC method string to the appropriate handler using path-style matching.\n *\n * Method strings mirror HTTP routes but without the /ui-bridge/ prefix.\n * Path params are extracted from :name placeholders in the route pattern.\n *\n * Examples:\n * \"health\" → handlers.health\n * \"control/snapshot\" → handlers.getSnapshot\n * \"control/element/tab-runs/action\" → handlers.executeAction ({id:'tab-runs'})\n * \"control/component/my-comp/action/submit\" → handlers.executeComponentAction\n */\n private async routeMethodToHandler(\n method: string,\n params: Record<string, unknown>\n ): Promise<APIResponse> {\n const testHooks = this.config.testHooks === true;\n for (const route of WS_ROUTES) {\n const pathParams = parsePath(route.pattern, method);\n if (!pathParams) continue;\n\n // Test-hook routes are invisible over WS too when the flag is off.\n if (route.requiresTestHooks && !testHooks) continue;\n\n const ctx: HandlerContext = {\n params: pathParams,\n query:\n params.query && typeof params.query === 'object'\n ? (params.query as Record<string, string>)\n : {},\n body: params,\n };\n\n return this.handlers[route.handler](ctx);\n }\n\n return {\n success: false,\n error: `Unknown method: ${method}`,\n code: 'NOT_FOUND',\n timestamp: Date.now(),\n };\n }\n\n /**\n * Handle incoming HTTP request\n *\n * Exposed as public so that CloudRelayClient can call it directly (without\n * loopback TCP overhead) when processing tunneled requests.\n */\n async handleRequest(request: HTTPRequest): Promise<HTTPResponse> {\n // Add CORS headers if enabled\n const headers: Record<string, string> = {\n 'Content-Type': 'application/json',\n };\n\n if (this.config.cors) {\n headers['Access-Control-Allow-Origin'] = this.config.allowedOrigins\n ? this.config.allowedOrigins.join(',')\n : '*';\n headers['Access-Control-Allow-Methods'] = 'GET, POST, PUT, DELETE, OPTIONS';\n headers['Access-Control-Allow-Headers'] = 'Content-Type, Authorization';\n }\n\n // Handle CORS preflight\n if (request.method === 'OPTIONS') {\n return { status: 204, headers, body: '' };\n }\n\n // Auto-arm: when test hooks are enabled and a keep-awake provider is\n // wired, every incoming request keeps the screen alive for 60s so an\n // external runner driving the device never loses it to a screen lock.\n // Best-effort — must never throw and break the request. This is the\n // single chokepoint for HTTP, WS-tunnelled, and cloud-relay paths\n // (CloudRelayClient calls handleRequest directly).\n if (this.config.testHooks === true && this.keepAwakeProvider) {\n try {\n this.keepAwakeProvider.request('auto-arm', 60_000);\n } catch {\n /* keep-awake is best-effort; never break a request */\n }\n }\n\n try {\n const response = await this.routeRequest(request);\n // A 405 must name the verbs that ARE accepted, or the caller is left\n // guessing exactly as it was under the blanket 400. `Allow` is not a\n // CORS-safelisted response header, so without `Access-Control-Expose-\n // Headers` a cross-origin browser caller — a web page or a browser-based\n // agent — reads `null` from it and gets nothing from this at all.\n if (response.code === 'METHOD_NOT_ALLOWED') {\n const allow = allowedMethodsForPath(request.path, this.config.testHooks === true);\n if (allow.length > 0) {\n headers['Allow'] = allow.join(', ');\n if (this.config.cors) headers['Access-Control-Expose-Headers'] = 'Allow';\n }\n }\n return {\n status: httpStatusForResponse(response),\n headers,\n body: JSON.stringify(response),\n };\n } catch (error) {\n const errorResponse: APIResponse = {\n success: false,\n error: error instanceof Error ? error.message : 'Internal server error',\n code: 'INTERNAL_ERROR',\n timestamp: Date.now(),\n };\n return {\n status: 500,\n headers,\n body: JSON.stringify(errorResponse),\n };\n }\n }\n\n /**\n * Route an HTTP request to the appropriate handler using WS_ROUTES.\n *\n * Strips the `/ui-bridge/` prefix from the path, then iterates the shared\n * WS_ROUTES table. Each route's `pattern` is matched against the stripped\n * path via the module-level `parsePath` helper; path params are merged\n * with the request body into a HandlerContext.\n *\n * `httpMethods` disambiguates routes that share a pattern but differ\n * by verb (e.g. GET vs DELETE on `design/style-guide`). A route without\n * `httpMethods` is WS-only and will not be matched on HTTP.\n */\n private async routeRequest(request: HTTPRequest): Promise<APIResponse> {\n const { method, path, query, body } = request;\n\n const PREFIX = '/ui-bridge/';\n if (!path.startsWith(PREFIX)) {\n return {\n success: false,\n error: `Route not found: ${method} ${path}`,\n code: 'NOT_FOUND',\n timestamp: Date.now(),\n };\n }\n\n const stripped = path.slice(PREFIX.length);\n\n // Discoverability:\n // - `_help` (rich) — routes + action reference + tips\n // - `_routes` (minimal) — runner-compatible shape for parity\n // Lets agents fetch a single URL on either runner or mobile to see what\n // they can do without reading docs.\n const testHooks = this.config.testHooks === true;\n\n if (method === 'GET' && stripped === '_help') {\n return {\n success: true,\n data: buildHelpPayload(testHooks),\n timestamp: Date.now(),\n };\n }\n if (method === 'GET' && stripped === '_routes') {\n return {\n success: true,\n data: buildRoutesPayload(testHooks),\n timestamp: Date.now(),\n };\n }\n\n // Reaching here with a discovery path means the PATH was right and the VERB\n // was not — the two branches above are the only ones that serve them, and\n // both are GET-only. They live outside `WS_ROUTES` (there is no handler to\n // dispatch to), so the loop below cannot notice them, and `POST\n // /ui-bridge/_routes` used to answer \"no such route\" about a route\n // `buildRoutesPayload` publishes one line up. Seeding the flag here keeps\n // \"wrong verb on a path we publish → 405\" true for every entry in\n // `UI_BRIDGE_NATIVE_ROUTES`, including these two.\n let patternMatchedButWrongVerb = DISCOVERY_PATHS.has(stripped);\n\n for (const route of WS_ROUTES) {\n const pathParams = parsePath(route.pattern, stripped);\n if (!pathParams) continue;\n\n // Pattern matches — now filter on HTTP verb.\n if (!route.httpMethods) {\n // WS-only route; don't serve on HTTP.\n continue;\n }\n // Route gated by `testHooks`: behave as if it isn't registered when\n // the flag is off so production builds get a vanilla NOT_FOUND.\n if (route.requiresTestHooks && !testHooks) {\n continue;\n }\n if (!route.httpMethods.includes(method as HttpVerb)) {\n patternMatchedButWrongVerb = true;\n continue;\n }\n\n const ctx: HandlerContext = { params: pathParams, query, body };\n return this.handlers[route.handler](ctx);\n }\n\n // The verbs go in the ENVELOPE as well as the `Allow` header, because\n // almost nothing in this tree reads headers: `CloudRelayClient` relays the\n // whole response, but the skills, the cheatsheets and every documented\n // probe read the JSON body (`curl … | jq .error`). A caller doing that saw\n // \"Method not allowed: POST /ui-bridge/health\" and still had to guess.\n const allowed = patternMatchedButWrongVerb\n ? allowedMethodsForPath(path, testHooks)\n : ([] as string[]);\n\n return {\n success: false,\n error: patternMatchedButWrongVerb\n ? `Method not allowed: ${method} ${path}${\n allowed.length > 0 ? ` (allowed: ${allowed.join(', ')})` : ''\n }`\n : `Route not found: ${method} ${path}`,\n code: patternMatchedButWrongVerb ? 'METHOD_NOT_ALLOWED' : 'NOT_FOUND',\n timestamp: Date.now(),\n };\n }\n}\n\n/**\n * Create a UI Bridge Native server\n */\nexport function createNativeServer(\n registry: NativeUIBridgeRegistry,\n executor: NativeActionExecutor,\n config?: NativeServerConfig\n): NativeUIBridgeServer {\n return new NativeUIBridgeServer(registry, executor, config);\n}\n\n/**\n * Example adapter using react-native-http-bridge\n *\n * To use this adapter:\n * 1. Install: npm install react-native-http-bridge\n * 2. Link native modules\n * 3. Create adapter and pass to server\n *\n * ```tsx\n * import httpBridge from 'react-native-http-bridge';\n *\n * const adapter: ServerAdapter = {\n * start: async (port, handler) => {\n * httpBridge.start(port, 'ui-bridge', async (request) => {\n * const response = await handler({\n * method: request.type,\n * path: request.url,\n * headers: request.headers || {},\n * query: parseQuery(request.url),\n * body: request.postData ? JSON.parse(request.postData) : undefined,\n * });\n * httpBridge.respond(\n * request.requestId,\n * response.status,\n * response.headers['Content-Type'],\n * response.body\n * );\n * });\n * },\n * stop: async () => {\n * httpBridge.stop();\n * },\n * isRunning: () => true,\n * };\n *\n * server.setAdapter(adapter);\n * await server.start();\n * ```\n */\n","/**\n * Bridges NativeUIBridgeRegistry events to WebSocket clients.\n *\n * Subscribes to all registry event types and broadcasts them as\n * JsonRpcEvent messages to connected WebSocket clients based on\n * their per-connection subscription sets.\n */\n\nimport type { NativeUIBridgeRegistry } from '../core/registry';\nimport type { BridgeEventType, BridgeEvent } from '../core/types';\nimport type { WebSocketConnection } from './ws-connection';\nimport type { JsonRpcEvent } from './ws-types';\n\n/** All event types the bridge can subscribe to */\nconst BRIDGE_EVENT_TYPES: BridgeEventType[] = [\n 'element:registered',\n 'element:unregistered',\n 'element:stateChanged',\n 'component:registered',\n 'component:unregistered',\n 'action:started',\n 'action:completed',\n 'action:failed',\n 'workflow:started',\n 'workflow:stepCompleted',\n 'workflow:completed',\n 'workflow:failed',\n 'render:snapshot',\n 'error',\n];\n\n/** Per-connection throttle state for batching rapid events */\ninterface ThrottleState {\n ms: number;\n pending: JsonRpcEvent[];\n timer: ReturnType<typeof setTimeout> | null;\n}\n\n// ── Glob pattern matching ───────────────────────────────────────────────────\n\n/** Cache of compiled glob→RegExp to avoid recompiling hot patterns. */\nconst GLOB_CACHE = new Map<string, RegExp>();\n\n/**\n * Convert a glob-style pattern (supports `*` / `**` wildcards) to a RegExp.\n * All other regex metacharacters are escaped, so colons and other\n * event-name characters pass through literally.\n *\n * globToRegex(\"*\") → /^.*$/\n * globToRegex(\"element:*\") → /^element:.*$/\n * globToRegex(\"*:stateChanged\") → /^.*:stateChanged$/\n */\nexport function globToRegex(pattern: string): RegExp {\n const cached = GLOB_CACHE.get(pattern);\n if (cached) return cached;\n\n // Normalize ** → * (same semantics for flat event names)\n const normalized = pattern.replace(/\\*\\*/g, '*');\n // Escape regex metacharacters except '*'\n const escaped = normalized.replace(/[.+?^${}()|[\\]\\\\]/g, '\\\\$&');\n // Replace '*' with '.*'\n const body = escaped.replace(/\\*/g, '.*');\n const regex = new RegExp(`^${body}$`);\n GLOB_CACHE.set(pattern, regex);\n return regex;\n}\n\n/** Options for the WebSocketEventBridge constructor. */\nexport interface WebSocketEventBridgeOptions {\n /** Heartbeat ping interval in ms (default 30000) */\n heartbeatIntervalMs?: number;\n /** Max number of events to retain in the replay history buffer (default 100, 0 disables) */\n maxHistory?: number;\n}\n\nexport class WebSocketEventBridge {\n private connections = new Map<string, WebSocketConnection>();\n private throttles = new Map<string, ThrottleState>();\n private unsubscribers: Array<() => void> = [];\n private heartbeatTimer: ReturnType<typeof setInterval> | null = null;\n private registry: NativeUIBridgeRegistry;\n private heartbeatIntervalMs: number;\n /**\n * True ring buffer for event replay history.\n *\n * `historyBuf` is a fixed-capacity slot array; `historyHead` points at the\n * NEXT write position; `historyCount` is the number of valid slots\n * (clamped to capacity). Append is O(1) — no array shifting.\n */\n private historyBuf: (JsonRpcEvent | undefined)[] = [];\n private historyHead = 0;\n private historyCount = 0;\n\n constructor(\n registry: NativeUIBridgeRegistry,\n optionsOrHeartbeatMs: WebSocketEventBridgeOptions | number = {}\n ) {\n this.registry = registry;\n // Accept legacy positional number form\n const opts: WebSocketEventBridgeOptions =\n typeof optionsOrHeartbeatMs === 'number'\n ? { heartbeatIntervalMs: optionsOrHeartbeatMs }\n : optionsOrHeartbeatMs;\n this.heartbeatIntervalMs = opts.heartbeatIntervalMs ?? 30000;\n const cap = Math.max(0, (opts.maxHistory ?? 100) | 0);\n this.historyBuf = cap > 0 ? new Array(cap) : [];\n }\n\n /** Effective ring buffer capacity. 0 means history is disabled. */\n private get historyCapacity(): number {\n return this.historyBuf.length;\n }\n\n /**\n * Start listening to registry events and broadcasting to WS clients.\n * Also starts the heartbeat timer.\n */\n start(): void {\n for (const eventType of BRIDGE_EVENT_TYPES) {\n const unsub = this.registry.on(eventType, (event: BridgeEvent) => {\n this.broadcastEvent(eventType, event.data);\n });\n this.unsubscribers.push(unsub);\n }\n\n this.startHeartbeat();\n }\n\n /** Stop listening to registry events and clear connections. */\n stop(): void {\n for (const unsub of this.unsubscribers) {\n unsub();\n }\n this.unsubscribers = [];\n\n if (this.heartbeatTimer) {\n clearInterval(this.heartbeatTimer);\n this.heartbeatTimer = null;\n }\n\n // Clean up throttle timers\n for (const throttle of this.throttles.values()) {\n if (throttle.timer) clearTimeout(throttle.timer);\n }\n this.throttles.clear();\n\n // Close all connections\n for (const conn of this.connections.values()) {\n conn.close(1001, 'Server shutting down');\n }\n this.connections.clear();\n this.historyBuf.fill(undefined);\n this.historyHead = 0;\n this.historyCount = 0;\n }\n\n /** Register a new WebSocket connection. */\n addConnection(conn: WebSocketConnection): void {\n this.connections.set(conn.id, conn);\n }\n\n /** Remove a WebSocket connection (called on disconnect). */\n removeConnection(connId: string): void {\n this.connections.delete(connId);\n const throttle = this.throttles.get(connId);\n if (throttle?.timer) clearTimeout(throttle.timer);\n this.throttles.delete(connId);\n }\n\n /** Get the number of active connections. */\n get connectionCount(): number {\n return this.connections.size;\n }\n\n /**\n * Add event subscriptions for a connection.\n *\n * Event names are stored as glob patterns. Supported forms:\n * - Exact: \"element:registered\"\n * - Prefix: \"element:*\"\n * - Suffix: \"*:stateChanged\"\n * - All: \"*\"\n *\n * @param throttleMs — if >0, batch rapid events within this window before sending\n */\n handleSubscribe(connId: string, events: string[], throttleMs?: number): boolean {\n const conn = this.connections.get(connId);\n if (!conn) return false;\n for (const event of events) {\n conn.subscriptions.add(event);\n }\n if (throttleMs && throttleMs > 0) {\n this.throttles.set(connId, { ms: throttleMs, pending: [], timer: null });\n }\n return true;\n }\n\n /**\n * Remove event subscriptions for a connection.\n * If all subscriptions are cleared, also drops the throttle entry\n * (and any pending flush timer) so a subsequent resubscribe starts clean.\n */\n handleUnsubscribe(connId: string, events: string[]): boolean {\n const conn = this.connections.get(connId);\n if (!conn) return false;\n for (const event of events) {\n conn.subscriptions.delete(event);\n }\n if (conn.subscriptions.size === 0) {\n const throttle = this.throttles.get(connId);\n if (throttle?.timer) clearTimeout(throttle.timer);\n this.throttles.delete(connId);\n }\n return true;\n }\n\n /**\n * Get the subscription set for a connection.\n * Returns the original pattern strings (not compiled regexes).\n */\n getSubscriptions(connId: string): string[] {\n const conn = this.connections.get(connId);\n return conn ? Array.from(conn.subscriptions) : [];\n }\n\n /**\n * Check if a connection is subscribed to a specific event.\n * Matches exact names first (fast path), then tests each stored\n * pattern as a glob against the event type.\n */\n isSubscribed(connId: string, eventType: string): boolean {\n const conn = this.connections.get(connId);\n if (!conn) return false;\n // Fast path: exact match\n if (conn.subscriptions.has(eventType)) return true;\n // Glob path: test each pattern\n for (const pattern of conn.subscriptions) {\n // Skip exact names with no wildcard — already tested above\n if (!pattern.includes('*')) continue;\n if (globToRegex(pattern).test(eventType)) return true;\n }\n return false;\n }\n\n /** Get the throttle window (in ms) configured for a connection, or undefined if none. */\n getThrottleMs(connId: string): number | undefined {\n return this.throttles.get(connId)?.ms;\n }\n\n /**\n * Get recent events from the replay history buffer.\n *\n * @param filter.events — optional list of glob patterns to match event types against\n * @param filter.since — optional timestamp (ms); only events at or after this time\n */\n getHistory(filter?: { events?: string[]; since?: number }): JsonRpcEvent[] {\n const cap = this.historyCapacity;\n if (cap === 0 || this.historyCount === 0) return [];\n\n const since = filter?.since;\n const regexes = filter?.events?.map((p) => globToRegex(p));\n\n // Walk the ring buffer in chronological (oldest → newest) order.\n const start = (this.historyHead - this.historyCount + cap) % cap;\n const out: JsonRpcEvent[] = [];\n for (let i = 0; i < this.historyCount; i++) {\n const e = this.historyBuf[(start + i) % cap];\n if (!e) continue;\n if (since !== undefined && e.timestamp < since) continue;\n if (regexes && regexes.length > 0 && !regexes.some((r) => r.test(e.event))) continue;\n out.push(e);\n }\n return out;\n }\n\n /**\n * Configure the max history buffer size at runtime. 0 disables history.\n * Reallocates the ring buffer, preserving the most recent\n * min(historyCount, newCapacity) events in chronological order.\n */\n setMaxHistory(maxHistory: number): void {\n const newCap = Math.max(0, maxHistory | 0);\n if (newCap === this.historyCapacity) return;\n\n if (newCap === 0) {\n this.historyBuf = [];\n this.historyHead = 0;\n this.historyCount = 0;\n return;\n }\n\n // Preserve the latest min(count, newCap) events.\n const oldCap = this.historyCapacity;\n const keep = Math.min(this.historyCount, newCap);\n const newBuf: (JsonRpcEvent | undefined)[] = new Array(newCap);\n if (keep > 0 && oldCap > 0) {\n // Source range: the last `keep` events ending just before historyHead.\n const start = (this.historyHead - keep + oldCap) % oldCap;\n for (let i = 0; i < keep; i++) {\n newBuf[i] = this.historyBuf[(start + i) % oldCap];\n }\n }\n this.historyBuf = newBuf;\n this.historyCount = keep;\n this.historyHead = keep % newCap;\n }\n\n // ── Internal ────────────────────────────────────────────────────────────\n\n private broadcastEvent(eventType: string, data: unknown): void {\n const event: JsonRpcEvent = {\n event: eventType,\n data,\n timestamp: Date.now(),\n };\n\n // Append to ring buffer — O(1), no shifting.\n const cap = this.historyCapacity;\n if (cap > 0) {\n this.historyBuf[this.historyHead] = event;\n this.historyHead = (this.historyHead + 1) % cap;\n if (this.historyCount < cap) this.historyCount++;\n }\n\n for (const [connId, conn] of this.connections) {\n const throttle = this.throttles.get(connId);\n if (throttle) {\n this.enqueueThrottled(connId, conn, throttle, event);\n } else {\n conn.sendEvent(event);\n }\n }\n }\n\n /** Queue an event for throttled delivery, flushing after the throttle window. */\n private enqueueThrottled(\n connId: string,\n conn: WebSocketConnection,\n throttle: ThrottleState,\n event: JsonRpcEvent\n ): void {\n throttle.pending.push(event);\n if (throttle.timer) return; // Flush already scheduled\n\n throttle.timer = setTimeout(() => {\n const events = throttle.pending.splice(0);\n throttle.timer = null;\n // Verify connection still exists\n if (!this.connections.has(connId)) return;\n for (const e of events) {\n conn.sendEvent(e);\n }\n }, throttle.ms);\n }\n\n private startHeartbeat(): void {\n this.heartbeatTimer = setInterval(() => {\n for (const [id, conn] of this.connections) {\n if (!conn.isOpen) {\n this.connections.delete(id);\n continue;\n }\n\n if (!conn.alive) {\n // Missed previous ping — connection is dead\n console.warn(`[ws-event-bridge] Connection ${id} missed heartbeat, closing`);\n conn.close(1001, 'Heartbeat timeout');\n this.connections.delete(id);\n continue;\n }\n\n // Mark as not-alive, send ping. If pong arrives, alive is set back to true.\n conn.alive = false;\n conn.ping();\n }\n }, this.heartbeatIntervalMs);\n }\n}\n","/**\n * Minimal logger for the UI Bridge Native transport layer.\n *\n * Wraps console so callers go through a single controlled point. Log output\n * can be suppressed globally by setting:\n *\n * import { transportLogger } from './logger';\n * transportLogger.silent = true;\n *\n * In production builds you can also tree-shake the verbose log() calls by\n * checking `__DEV__` in your Metro bundler config, but the silent flag is\n * simpler and works without build-time configuration.\n */\n\nexport interface TransportLogger {\n log(message: string, ...args: unknown[]): void;\n warn(message: string, ...args: unknown[]): void;\n error(message: string, ...args: unknown[]): void;\n /** Set to true to suppress all log output (warn/error are always emitted). */\n silent: boolean;\n}\n\nfunction createTransportLogger(): TransportLogger {\n return {\n silent: false,\n log(message: string, ...args: unknown[]): void {\n if (!this.silent) {\n console.log(message, ...args);\n }\n },\n warn(message: string, ...args: unknown[]): void {\n console.warn(message, ...args);\n },\n error(message: string, ...args: unknown[]): void {\n console.error(message, ...args);\n },\n };\n}\n\n/** Shared logger instance for the transport layer. */\nexport const transportLogger = createTransportLogger();\n","/**\n * Shared log hygiene for the two WebSocket clients that dial the cloud relay.\n *\n * `CloudRelayClient` and `DeviceAnnouncer` build the SAME URL from the SAME\n * credential — `<relayUrl>?token=<authToken>` — and both hand their diagnostics\n * to `transportLogger`, whose sink (the observability ring buffer behind\n * `GET /control/console-errors`) is readable by anything that can reach the\n * bridge. When these helpers lived as file-private functions inside\n * `CloudRelayClient`, fixing that client's token leak left the announcer's\n * identical `transportLogger.log('… connecting to', url)` untouched: one secret,\n * two sinks, one of them redacted.\n *\n * They live here so a third dialler cannot repeat that, and so the redaction\n * rule has exactly one definition to test.\n */\n\n/**\n * Query-parameter names whose VALUE is a credential and must never be logged.\n *\n * Both diallers build `<relayUrl>?token=<authToken>` today, so `token` is the\n * only name that matters right now. The rest are here because this function's\n * whole purpose is to be the one place the rule lives: a relay URL that later\n * spells the credential `access_token` or signs with `sig` would otherwise sail\n * through a redactor that everything else trusts. Over-redacting a log line\n * costs nothing; under-redacting one costs a device credential.\n */\nconst CREDENTIAL_PARAMS = ['token', 'access_token', 'auth', 'authorization', 'key', 'sig'];\n\nconst CREDENTIAL_PARAM_RE = new RegExp(`([?&](?:${CREDENTIAL_PARAMS.join('|')})=)[^&#]*`, 'gi');\n\n/** `wss://user:secret@host/…` — credentials in the URL's userinfo component. */\nconst USERINFO_RE = /^([a-z][a-z0-9+.-]*:\\/\\/)[^/?#@]*@/i;\n\n/**\n * Replace credential values in a relay URL with a marker.\n *\n * The relay URL is built as `<relayUrl>?token=<authToken>`; every log line that\n * names the target URL goes through here first so the device auth token never\n * lands in a log file, a console-error ring buffer, or a bug report.\n *\n * Redacts every {@link CREDENTIAL_PARAMS} query value plus any `user:pass@`\n * userinfo. It does NOT attempt to find secrets in a path segment or a fragment\n * — a URL that puts one there needs a different fix, not a cleverer regex.\n */\nexport function redactRelayUrl(url: string): string {\n return url.replace(USERINFO_RE, '$1<redacted>@').replace(CREDENTIAL_PARAM_RE, '$1<redacted>');\n}\n\n/**\n * Render a WebSocket close event as `code=… reason=… wasClean=…`.\n *\n * Read defensively: React Native's WebSocket delivers a plain object rather\n * than a DOM `CloseEvent`, and a missing field must read `unknown` rather than\n * silently print `undefined` as if the relay had told us something.\n *\n * The close CODE is the whole diagnosis — 1006 is \"no close frame\"\n * (network/TLS died), 1008/4001-class codes are the relay rejecting our token,\n * 1001 is the backend going away. Logging the raw event instead says nothing: a\n * DOM `CloseEvent` has no own enumerable properties, so the observability\n * capture's `JSON.stringify` renders it as `{}`.\n */\nexport function describeCloseEvent(event: unknown): string {\n const e = (event ?? {}) as { code?: unknown; reason?: unknown; wasClean?: unknown };\n const code = typeof e.code === 'number' ? String(e.code) : 'unknown';\n const reason = typeof e.reason === 'string' && e.reason.length > 0 ? e.reason : '(none)';\n const wasClean = typeof e.wasClean === 'boolean' ? String(e.wasClean) : 'unknown';\n return `code=${code} reason=${reason} wasClean=${wasClean}`;\n}\n\n/**\n * Render a WebSocket error event. React Native puts the useful text on\n * `message`; some transports also carry an `Error` on `error`, and a few\n * surface a close `code` on the error event itself.\n *\n * Same `{}`-stringification trap as {@link describeCloseEvent}.\n */\nexport function describeErrorEvent(event: unknown): string {\n const e = (event ?? {}) as { message?: unknown; error?: unknown; code?: unknown };\n const parts: string[] = [];\n if (typeof e.message === 'string' && e.message.length > 0) parts.push(`message=${e.message}`);\n if (e.error instanceof Error) parts.push(`error=${e.error.message}`);\n else if (typeof e.error === 'string' && e.error.length > 0) parts.push(`error=${e.error}`);\n if (typeof e.code === 'number') parts.push(`code=${e.code}`);\n if (parts.length === 0) parts.push('message=(none reported by the transport)');\n return parts.join(' ');\n}\n","/**\n * Device Announcer — mDNS + Cloud registration for physical device discovery\n *\n * Announces the UI Bridge service on the local network via mDNS (when\n * react-native-zeroconf is available) and optionally registers with the\n * cloud relay backend.\n */\n\nimport { Platform } from 'react-native';\nimport { transportLogger } from './logger';\nimport { describeCloseEvent, describeErrorEvent, redactRelayUrl } from './relay-logging';\n\nexport interface AnnouncerConfig {\n /** Stable device identifier */\n deviceId: string;\n /** App bundle/package ID */\n appId: string;\n /** UI Bridge server port (default 8087) */\n port?: number;\n /** Cloud relay WebSocket URL for registration */\n cloudRelayUrl?: string;\n /** Auth token for cloud relay */\n cloudToken?: string;\n /** UI Bridge SDK version */\n version?: string;\n}\n\nexport interface DeviceAnnouncerState {\n mdnsActive: boolean;\n cloudConnected: boolean;\n}\n\n/** Minimal interface for the react-native-zeroconf Zeroconf instance */\ninterface ZeroconfService {\n publishService(\n type: string,\n protocol: string,\n domain: string,\n name: string,\n port: number,\n txtRecord: Record<string, string>\n ): void;\n unpublishService(name: string): void;\n}\n\n/** Possible messages received over the cloud relay WebSocket */\ninterface RelayMessage {\n type: string;\n [key: string]: unknown;\n}\n\nconst DEFAULT_PORT = 8087;\nconst RECONNECT_INITIAL_DELAY_MS = 2_000;\nconst RECONNECT_MAX_DELAY_MS = 60_000;\n\n/**\n * Announces the UI Bridge server on the local network (mDNS) and optionally\n * registers with the qontinui.io cloud relay for remote discovery.\n */\nexport class DeviceAnnouncer {\n private config: Required<Pick<AnnouncerConfig, 'deviceId' | 'appId'>> & AnnouncerConfig;\n private state: DeviceAnnouncerState = {\n mdnsActive: false,\n cloudConnected: false,\n };\n private cloudWs: WebSocket | null = null;\n private reconnectTimer: ReturnType<typeof setTimeout> | null = null;\n private reconnectDelay = RECONNECT_INITIAL_DELAY_MS;\n private stopped = false;\n /** Zeroconf instance, set when mDNS is successfully started */\n private zeroconf: ZeroconfService | null = null;\n /** Rotated pairing token for mDNS TXT records */\n private pairingToken: string;\n\n constructor(config: AnnouncerConfig) {\n this.config = config;\n this.pairingToken = generateHex(16);\n }\n\n // ── mDNS ──────────────────────────────────────────────────────────────────\n\n /**\n * Start mDNS advertisement.\n *\n * The consumer must pass the `Zeroconf` constructor (from `react-native-zeroconf`)\n * explicitly; otherwise this is a no-op.\n *\n * Rationale: Metro's `require()` throws an uncatchable module-load error if the\n * bundle doesn't include the named package. That error escapes async try/catch\n * boundaries and crashes the app. We avoid it by never calling `require()`\n * ourselves — the consumer imports the package when they know it's installed.\n *\n * @param ZeroconfCtor - constructor from `import Zeroconf from 'react-native-zeroconf'`\n */\n async startMdnsAdvertise(ZeroconfCtor?: new () => ZeroconfService): Promise<void> {\n if (!ZeroconfCtor) {\n transportLogger.log(\n '[DeviceAnnouncer] mDNS advertisement skipped (no Zeroconf constructor provided). ' +\n 'Pass one to enable mDNS.'\n );\n return;\n }\n try {\n this.zeroconf = new ZeroconfCtor();\n\n const port = this.config.port ?? DEFAULT_PORT;\n const serviceName = `UIBridge-${this.config.deviceId.slice(0, 8)}`;\n\n this.zeroconf.publishService('_uibridge', '_tcp.', 'local.', serviceName, port, {\n device_id: this.config.deviceId,\n app_id: this.config.appId,\n version: this.config.version ?? 'unknown',\n pairing_token: this.pairingToken,\n });\n\n this.state = { ...this.state, mdnsActive: true };\n transportLogger.log(`[DeviceAnnouncer] mDNS: advertising \"${serviceName}\" on port ${port}`);\n } catch (err) {\n transportLogger.warn('[DeviceAnnouncer] mDNS start failed:', err);\n }\n }\n\n // ── Cloud relay ───────────────────────────────────────────────────────────\n\n /**\n * Connect to the cloud relay WebSocket and send a device_register message.\n *\n * Reconnects automatically with exponential backoff (2 s → 60 s) if the\n * connection drops.\n */\n async connectCloudRelay(): Promise<void> {\n if (!this.config.cloudRelayUrl || !this.config.cloudToken) {\n return;\n }\n if (this.stopped) return;\n\n const url = `${this.config.cloudRelayUrl}?token=${encodeURIComponent(this.config.cloudToken)}`;\n // Same credential, same sink, same rule as `CloudRelayClient`: the relay URL\n // carries the device auth token in its query string and `transportLogger`\n // feeds the ring buffer behind `/control/console-errors`, so nothing that\n // reaches a log sink may name the raw URL.\n const safeUrl = redactRelayUrl(url);\n\n transportLogger.log('[DeviceAnnouncer] Cloud relay: connecting to', safeUrl);\n\n const ws = new WebSocket(url);\n this.cloudWs = ws;\n\n ws.onopen = () => {\n if (this.stopped) {\n ws.close();\n return;\n }\n this.reconnectDelay = RECONNECT_INITIAL_DELAY_MS;\n this.state = { ...this.state, cloudConnected: true };\n transportLogger.log('[DeviceAnnouncer] Cloud relay: connected');\n\n // Register this device with the backend\n ws.send(\n JSON.stringify({\n type: 'device_register',\n device_id: this.config.deviceId,\n app_id: this.config.appId,\n platform: getPlatform(),\n display_name: this.config.deviceId,\n ui_bridge_version: this.config.version ?? 'unknown',\n })\n );\n };\n\n ws.onmessage = (event: MessageEvent) => {\n try {\n const msg = JSON.parse(event.data as string) as RelayMessage;\n transportLogger.log('[DeviceAnnouncer] Cloud relay message:', msg.type);\n // Tunneled HTTP requests are handled by CloudRelayClient when wired up\n } catch {\n // ignore malformed messages\n }\n };\n\n ws.onclose = (event: CloseEvent) => {\n this.state = { ...this.state, cloudConnected: false };\n const detail = describeCloseEvent(event);\n if (this.stopped) {\n // Expected: `stop()` asked for this close. Defensive rather than\n // reachable in the normal lifecycle — `stop()` nulls this handler\n // before calling `close()`, and `connectCloudRelay()` early-returns\n // once stopped — so this arm only fires if a transport delivers a\n // close to a handler captured before `stop()` ran. Kept because\n // \"logged nothing\" is what made the pre-fix behaviour undiagnosable.\n transportLogger.log(`[DeviceAnnouncer] Cloud relay closed ${detail} url=${safeUrl}`);\n } else {\n // Unexpected: the registration socket died and we are about to\n // reconnect. Logging the bare event said nothing — a DOM `CloseEvent`\n // has no own enumerable properties, so the observability capture's\n // `JSON.stringify` rendered it as `{}`. The close code is the whole\n // diagnosis: 1008/4001-class means the relay rejected this device's\n // token, which is otherwise indistinguishable from a flaky network.\n transportLogger.warn(\n `[DeviceAnnouncer] Cloud relay closed unexpectedly ${detail} url=${safeUrl}`\n );\n this.scheduleReconnect();\n }\n };\n\n ws.onerror = (err: Event) => {\n transportLogger.warn(\n `[DeviceAnnouncer] Cloud relay error: ${describeErrorEvent(err)} url=${safeUrl}`\n );\n // onclose will fire after this and trigger reconnect\n };\n }\n\n // ── Lifecycle ─────────────────────────────────────────────────────────────\n\n /** Stop all advertising and registration. */\n async stop(): Promise<void> {\n this.stopped = true;\n\n // Cancel any pending reconnect\n if (this.reconnectTimer !== null) {\n clearTimeout(this.reconnectTimer);\n this.reconnectTimer = null;\n }\n\n // Unpublish mDNS service\n if (this.zeroconf) {\n try {\n const serviceName = `UIBridge-${this.config.deviceId.slice(0, 8)}`;\n this.zeroconf.unpublishService(serviceName);\n } catch {\n // ignore\n }\n this.zeroconf = null;\n }\n this.state = { ...this.state, mdnsActive: false };\n\n // Close cloud WebSocket\n if (this.cloudWs) {\n this.cloudWs.onclose = null; // prevent reconnect loop\n this.cloudWs.close();\n this.cloudWs = null;\n }\n this.state = { ...this.state, cloudConnected: false };\n }\n\n /** Return a copy of the current announcer state. */\n getState(): DeviceAnnouncerState {\n return { ...this.state };\n }\n\n // ── Private ───────────────────────────────────────────────────────────────\n\n private scheduleReconnect(): void {\n if (this.stopped) return;\n const delay = this.reconnectDelay;\n transportLogger.log(`[DeviceAnnouncer] Cloud relay: reconnecting in ${delay}ms`);\n this.reconnectTimer = setTimeout(() => {\n this.reconnectTimer = null;\n if (!this.stopped) {\n void this.connectCloudRelay();\n }\n }, delay);\n // Exponential backoff\n this.reconnectDelay = Math.min(this.reconnectDelay * 2, RECONNECT_MAX_DELAY_MS);\n }\n}\n\n// ── Utilities ─────────────────────────────────────────────────────────────────\n\nfunction generateHex(bytes: number): string {\n const arr = new Uint8Array(bytes);\n // In React Native, Math.random() is fine for a non-security pairing token\n for (let i = 0; i < bytes; i++) {\n arr[i] = Math.floor(Math.random() * 256);\n }\n return Array.from(arr)\n .map((b) => b.toString(16).padStart(2, '0'))\n .join('');\n}\n\nfunction getPlatform(): string {\n return Platform?.OS ?? 'unknown';\n}\n","/**\n * Cloud Relay Client — WebSocket tunnel from mobile device to backend\n *\n * Maintains a persistent WebSocket connection to the qontinui.io backend.\n * Receives tunneled HTTP requests from runners, calls the local NativeUIBridgeServer,\n * and sends responses back through the tunnel.\n */\n\nimport type { NativeUIBridgeServer } from '../server/http-server';\nimport { transportLogger } from './logger';\nimport { describeCloseEvent, describeErrorEvent, redactRelayUrl } from './relay-logging';\n\nexport interface CloudRelayConfig {\n /** WebSocket URL for the device bridge endpoint */\n relayUrl: string;\n /** Stable device identifier */\n deviceId: string;\n /** Authentication token */\n authToken: string;\n /** Reference to the local UI Bridge server for processing requests */\n uiBridgeServer: NativeUIBridgeServer;\n}\n\ninterface TunnelRequest {\n id: string;\n method: string;\n path: string;\n headers: Record<string, string>;\n body?: unknown;\n}\n\ninterface TunnelResponse {\n id: string;\n status: number;\n headers: Record<string, string>;\n body?: unknown;\n}\n\nconst INITIAL_RECONNECT_DELAY_MS = 2_000;\nconst MAX_RECONNECT_DELAY_MS = 60_000;\n\n/**\n * Manages a WebSocket tunnel from the mobile device to the qontinui.io backend.\n *\n * When a runner sends an HTTP request to a cloud device it is serialised as a\n * `TunnelRequest` JSON frame by the backend and forwarded here. This client\n * deserializes it, calls `NativeUIBridgeServer.handleRequest()` directly\n * (avoiding loopback TCP overhead), and sends the `TunnelResponse` back.\n */\nexport class CloudRelayClient {\n private ws: WebSocket | null = null;\n private config: CloudRelayConfig;\n private reconnectDelay = INITIAL_RECONNECT_DELAY_MS;\n private maxReconnectDelay = MAX_RECONNECT_DELAY_MS;\n private stopped = false;\n private _isConnected = false;\n private reconnectTimer: ReturnType<typeof setTimeout> | null = null;\n\n constructor(config: CloudRelayConfig) {\n this.config = config;\n }\n\n /** Whether the relay WebSocket is currently connected */\n get isConnected(): boolean {\n return this._isConnected;\n }\n\n // ── Lifecycle ─────────────────────────────────────────────────────────────\n\n /** Connect to the relay and start processing tunneled requests. */\n start(): void {\n this.stopped = false;\n this.connect();\n }\n\n /** Disconnect and stop reconnecting. */\n stop(): void {\n this.stopped = true;\n this._isConnected = false;\n\n if (this.reconnectTimer !== null) {\n clearTimeout(this.reconnectTimer);\n this.reconnectTimer = null;\n }\n\n if (this.ws) {\n this.ws.onclose = null; // prevent reconnect loop\n this.ws.close();\n this.ws = null;\n }\n }\n\n // ── Private ───────────────────────────────────────────────────────────────\n\n private connect(): void {\n if (this.stopped) return;\n\n const url = `${this.config.relayUrl}?token=${encodeURIComponent(this.config.authToken)}`;\n // Everything that reaches a log sink uses the redacted spelling — the\n // relay URL carries the device auth token in its query string, and\n // `/control/console-errors` is readable by anything that can reach the\n // bridge.\n const safeUrl = redactRelayUrl(url);\n\n transportLogger.log('[CloudRelayClient] Connecting to', safeUrl);\n\n const ws = new WebSocket(url);\n this.ws = ws;\n\n ws.onopen = () => {\n if (this.stopped) {\n ws.close();\n return;\n }\n this._isConnected = true;\n this.reconnectDelay = INITIAL_RECONNECT_DELAY_MS;\n\n transportLogger.log('[CloudRelayClient] Connected to relay');\n\n // Register as a device\n ws.send(\n JSON.stringify({\n type: 'device_register',\n device_id: this.config.deviceId,\n })\n );\n };\n\n ws.onmessage = (event: MessageEvent) => {\n void this.onMessage(event.data as string);\n };\n\n ws.onclose = (event: CloseEvent) => {\n this._isConnected = false;\n const detail = describeCloseEvent(event);\n if (this.stopped) {\n // Expected: we asked for this close (or `stop()` raced the handshake).\n transportLogger.log(`[CloudRelayClient] WebSocket closed ${detail} url=${safeUrl}`);\n } else {\n // Unexpected: the tunnel died under us and we are about to reconnect.\n // The close CODE is the whole diagnosis here — 1006 is \"no close frame\"\n // (network/TLS died), 1008/4001-class codes are the relay rejecting our\n // token, 1001 is the backend going away. Logging the raw event instead\n // said nothing: a DOM CloseEvent has no own enumerable properties, so\n // the observability capture's `JSON.stringify` rendered it as `{}`.\n transportLogger.warn(\n `[CloudRelayClient] WebSocket closed unexpectedly ${detail} url=${safeUrl}`\n );\n this.scheduleReconnect();\n }\n };\n\n ws.onerror = (err: Event) => {\n // Same trap as onclose: the bare event stringifies to `{}`. Pull the\n // fields that exist across React Native's event shape and the DOM one.\n transportLogger.warn(\n `[CloudRelayClient] WebSocket error: ${describeErrorEvent(err)} url=${safeUrl}`\n );\n // onclose will fire next and handle reconnect\n };\n }\n\n private async onMessage(raw: string): Promise<void> {\n let msg: Record<string, unknown>;\n try {\n msg = JSON.parse(raw) as Record<string, unknown>;\n } catch {\n transportLogger.warn('[CloudRelayClient] Received non-JSON message');\n return;\n }\n\n // Only handle tunnel_request frames\n if (msg['type'] !== 'tunnel_request') return;\n\n // Validate required fields\n if (\n typeof msg['id'] !== 'string' ||\n typeof msg['method'] !== 'string' ||\n typeof msg['path'] !== 'string'\n ) {\n transportLogger.warn('[CloudRelayClient] Malformed tunnel_request — missing required fields');\n return;\n }\n\n const req: TunnelRequest = {\n id: msg['id'],\n method: msg['method'],\n path: msg['path'],\n headers: (msg['headers'] as Record<string, string>) ?? {},\n body: msg['body'],\n };\n\n const resp = await this.handleTunneledRequest(req);\n\n // Send response back through the WebSocket\n if (this.ws && this.ws.readyState === WebSocket.OPEN) {\n this.ws.send(JSON.stringify({ type: 'tunnel_response', ...resp }));\n }\n }\n\n /**\n * Process a tunneled HTTP request by calling the local NativeUIBridgeServer\n * directly (no loopback TCP involved).\n */\n private async handleTunneledRequest(req: TunnelRequest): Promise<TunnelResponse> {\n try {\n const httpResp = await this.config.uiBridgeServer.handleRequest({\n method: req.method,\n path: req.path,\n headers: req.headers,\n query: parseQueryParams(req.path),\n body: req.body,\n });\n\n // Parse the JSON body back to an object so it can be re-serialised as a\n // proper JSON value in the tunnel response (avoids double-encoding).\n let bodyValue: unknown;\n try {\n bodyValue = httpResp.body ? (JSON.parse(httpResp.body) as unknown) : undefined;\n } catch {\n bodyValue = httpResp.body || undefined;\n }\n\n return {\n id: req.id,\n status: httpResp.status,\n headers: httpResp.headers,\n body: bodyValue,\n };\n } catch (err) {\n transportLogger.error('[CloudRelayClient] Error handling tunneled request:', err);\n return {\n id: req.id,\n status: 500,\n headers: { 'content-type': 'application/json' },\n body: {\n success: false,\n error: err instanceof Error ? err.message : 'Internal server error',\n },\n };\n }\n }\n\n private scheduleReconnect(): void {\n if (this.stopped) return;\n const delay = this.reconnectDelay;\n transportLogger.log(`[CloudRelayClient] Reconnecting in ${delay}ms`);\n this.reconnectTimer = setTimeout(() => {\n this.reconnectTimer = null;\n if (!this.stopped) {\n this.connect();\n }\n }, delay);\n this.reconnectDelay = Math.min(this.reconnectDelay * 2, this.maxReconnectDelay);\n }\n}\n\n// ── Utilities ─────────────────────────────────────────────────────────────────\n\n/**\n * Extract query-string parameters from a URL path.\n * e.g. `/ui-bridge/control/elements?visibleOnly=true` → `{ visibleOnly: 'true' }`\n */\nfunction parseQueryParams(path: string): Record<string, string> {\n const qIdx = path.indexOf('?');\n if (qIdx === -1) return {};\n const qs = path.slice(qIdx + 1);\n const result: Record<string, string> = {};\n for (const pair of qs.split('&')) {\n const [k, v] = pair.split('=');\n if (k) {\n result[decodeURIComponent(k)] = decodeURIComponent(v ?? '');\n }\n }\n return result;\n}\n","import type { NativeModalInfo, NativeSnapshotModalContext } from '../core/types';\n\nexport interface ModalPushInput {\n id: string;\n title?: string;\n type?: NativeModalInfo['type'];\n blocking?: boolean;\n dismissible?: boolean;\n}\n\n/**\n * Declarative modal store. Components/hooks call pushModal/dismissModal directly\n * — there is no DOM/tree scanner. The detector is the single source of truth for\n * the snapshot's modalStack context.\n */\nexport class ModalDetector {\n /** Map preserves O(1) idempotent replace by id; ordering comes from detectedAt. */\n private modals = new Map<string, NativeModalInfo>();\n\n pushModal(modal: ModalPushInput): void {\n const existing = this.modals.get(modal.id);\n const detectedAt = existing ? existing.detectedAt : Date.now();\n const next: NativeModalInfo = {\n id: modal.id,\n title: modal.title,\n type: modal.type ?? 'modal',\n blocking: modal.blocking ?? true,\n dismissible: modal.dismissible ?? true,\n detectedAt,\n };\n this.modals.set(modal.id, next);\n }\n\n /**\n * Remove a modal from the stack. Returns `true` if a modal with that id\n * was actually deleted, `false` if nothing matched (idempotent so repeated\n * calls don't throw, but callers — e.g. the HTTP test-hook endpoint — can\n * surface the miss to clients).\n */\n dismissModal(id: string): boolean {\n return this.modals.delete(id);\n }\n\n getSnapshotModalContext(): NativeSnapshotModalContext {\n const active = this.getActive();\n const ctx: NativeSnapshotModalContext = {\n modals: active,\n hasBlockingModal: active.some((m) => m.blocking),\n count: active.length,\n };\n if (active.length > 0) {\n ctx.topModal = active[active.length - 1];\n }\n return ctx;\n }\n\n getActive(): NativeModalInfo[] {\n return Array.from(this.modals.values()).sort((a, b) => a.detectedAt - b.detectedAt);\n }\n\n clear(): void {\n this.modals.clear();\n }\n}\n","import type { NativeCapturedToast, NativeSnapshotToastContext } from '../core/types';\n\nexport interface ToastRecordInput {\n id: string;\n message: string;\n level?: NativeCapturedToast['level'];\n appearedAt?: number;\n}\n\nexport interface ToastCaptureConfig {\n maxRecent?: number;\n}\n\nconst DEFAULT_MAX_RECENT = 50;\n\n/**\n * Declarative toast/snackbar tracker. Components call recordToast/dismissToast\n * directly — there is no DOM/tree scanner. The active map plus a fixed-size\n * recent ring buffer feed the snapshot's toasts context.\n */\nexport class ToastCapture {\n private active = new Map<string, NativeCapturedToast>();\n private recent: NativeCapturedToast[] = [];\n private totalCaptured = 0;\n private maxRecent: number;\n\n constructor(config: ToastCaptureConfig = {}) {\n this.maxRecent = config.maxRecent ?? DEFAULT_MAX_RECENT;\n }\n\n recordToast(toast: ToastRecordInput): void {\n if (this.active.has(toast.id)) {\n return;\n }\n const appearedAt = toast.appearedAt ?? Date.now();\n const entry: NativeCapturedToast = {\n id: toast.id,\n message: toast.message,\n level: toast.level ?? 'info',\n appearedAt,\n visible: true,\n durationMs: 0,\n };\n this.active.set(toast.id, entry);\n this.totalCaptured += 1;\n }\n\n dismissToast(id: string): void {\n const entry = this.active.get(id);\n if (!entry) {\n return;\n }\n this.active.delete(id);\n const dismissedAt = Date.now();\n const dismissed: NativeCapturedToast = {\n ...entry,\n dismissedAt,\n visible: false,\n durationMs: dismissedAt - entry.appearedAt,\n };\n this.recent.push(dismissed);\n if (this.recent.length > this.maxRecent) {\n this.recent.shift();\n }\n }\n\n getSnapshotToastContext(): NativeSnapshotToastContext {\n const now = Date.now();\n const active = Array.from(this.active.values()).map((entry) => ({\n ...entry,\n durationMs: now - entry.appearedAt,\n }));\n return {\n active,\n recent: [...this.recent],\n totalCaptured: this.totalCaptured,\n };\n }\n\n clear(): void {\n this.active.clear();\n this.recent = [];\n this.totalCaptured = 0;\n }\n}\n","import type { NativeSnapshotUndoContext } from '../core/types';\n\n/**\n * A single bridge action recorded for undo correlation. Action-correlation\n * only — RN has no DOM/execCommand probe, so we rely on developer\n * declaration plus this rolling history of recent actions.\n */\nexport interface ActionRecord {\n id: string;\n type: string;\n targetId?: string;\n description?: string;\n timestamp: number;\n /** Default true — set false for actions that aren't reversible (e.g. navigation, network calls) */\n reversible?: boolean;\n}\n\n/**\n * Developer-declared undo/redo state. When set, this is authoritative and\n * overrides any heuristic inference from action history.\n */\nexport interface DeclaredUndoState {\n canUndo: boolean;\n canRedo: boolean;\n undoDescription?: string;\n redoDescription?: string;\n undoDepth?: number;\n redoDepth?: number;\n}\n\nexport interface UndoTrackerConfig {\n maxHistory?: number;\n}\n\nconst DEFAULT_MAX_HISTORY = 50;\n\nfunction buildSummary(ctx: {\n canUndo: boolean;\n canRedo: boolean;\n undoDescription?: string;\n redoDescription?: string;\n}): string {\n if (!ctx.canUndo && !ctx.canRedo) {\n return 'no undo available';\n }\n const parts: string[] = [];\n if (ctx.canUndo) {\n parts.push(`undo: '${ctx.undoDescription ?? 'available'}'`);\n }\n if (ctx.canRedo) {\n parts.push(`redo: '${ctx.redoDescription ?? 'available'}'`);\n }\n return parts.join(' / ');\n}\n\n/**\n * Action-correlation undo tracker for React Native.\n *\n * Maintains a rolling buffer of recent actions and a developer-declared\n * undo state slot. The declared state is authoritative when set; otherwise\n * we infer `canUndo` from whether any reversible action has been recorded.\n * `executeUndo`/`executeRedo` are placeholders pending an IPC path through\n * ui-bridge-native to the runner's `/control/undo`.\n */\nexport class UndoTracker {\n private readonly maxHistory: number;\n private actions: ActionRecord[] = [];\n private declaredState: DeclaredUndoState | null = null;\n\n constructor(config: UndoTrackerConfig = {}) {\n this.maxHistory = config.maxHistory ?? DEFAULT_MAX_HISTORY;\n }\n\n recordAction(record: ActionRecord): void {\n this.actions.push(record);\n if (this.actions.length > this.maxHistory) {\n this.actions = this.actions.slice(-this.maxHistory);\n }\n }\n\n setDeclaredState(state: DeclaredUndoState): void {\n this.declaredState = state;\n }\n\n getActionHistory(): ActionRecord[] {\n return this.actions.slice();\n }\n\n getSnapshotUndoContext(): NativeSnapshotUndoContext {\n const declared = this.declaredState;\n if (declared) {\n const summary = buildSummary({\n canUndo: declared.canUndo,\n canRedo: declared.canRedo,\n undoDescription: declared.undoDescription,\n redoDescription: declared.redoDescription,\n });\n return {\n canUndo: declared.canUndo,\n canRedo: declared.canRedo,\n undoDescription: declared.undoDescription,\n redoDescription: declared.redoDescription,\n undoDepth: declared.undoDepth,\n redoDepth: declared.redoDepth,\n summary,\n };\n }\n\n const canUndo = this.actions.some((a) => a.reversible !== false);\n const canRedo = false;\n // Surface the most recent reversible action's description as the inferred undo target\n const lastReversible = [...this.actions].reverse().find((a) => a.reversible !== false);\n const undoDescription = lastReversible?.description;\n const summary = buildSummary({ canUndo, canRedo, undoDescription });\n return {\n canUndo,\n canRedo,\n undoDescription,\n summary,\n };\n }\n\n executeUndo(): { ok: boolean; reason?: string } {\n return { ok: false, reason: 'Not implemented in native' };\n }\n\n executeRedo(): { ok: boolean; reason?: string } {\n return { ok: false, reason: 'Not implemented in native' };\n }\n\n clear(): void {\n this.actions = [];\n this.declaredState = null;\n }\n}\n","/**\n * UI Bridge Native Provider\n *\n * React context provider for UI Bridge Native functionality.\n */\n\nimport React, {\n createContext,\n use,\n useMemo,\n useEffect,\n useCallback,\n useRef,\n useState,\n} from 'react';\nimport { Dimensions, PixelRatio } from 'react-native';\nimport type {\n NativeUIBridgeFeatures,\n NativeUIBridgeConfig,\n RegisteredNativeElement,\n RegisteredNativeComponent,\n NativeBridgeSnapshot,\n BridgeEventType,\n BridgeEventListener,\n} from '../core/types';\nimport { NativeUIBridgeRegistry, setGlobalRegistry, resetGlobalRegistry } from '../core/registry';\nimport { createNativeActionExecutor } from '../control/action-executor';\nimport type { NativeActionExecutor } from '../control/types';\nimport {\n createNativeServer,\n type NativeUIBridgeServer,\n type ServerAdapter,\n type WebSocketServerAdapter,\n} from '../server/http-server';\nimport type { RouteProvider, KeepAwakeProvider } from '../server/types';\nimport { WebSocketEventBridge } from '../server/ws-event-bridge';\nimport { DeviceAnnouncer } from '../transport/DeviceAnnouncer';\nimport { CloudRelayClient, type CloudRelayConfig } from '../transport/CloudRelayClient';\nimport { ModalDetector } from '../modal/modal-detector';\nimport { ToastCapture } from '../toast/toast-capture';\nimport { UndoTracker } from '../undo/undo-tracker';\n\n/**\n * UI Bridge Native context value\n */\nexport interface UIBridgeNativeContextValue {\n /** Feature flags */\n features: NativeUIBridgeFeatures;\n /** Configuration */\n config: NativeUIBridgeConfig;\n /** Element registry */\n registry: NativeUIBridgeRegistry;\n /** Action executor */\n executor: NativeActionExecutor;\n /** Modal stack tracker (declarative pushModal/dismissModal) */\n modalDetector: ModalDetector;\n /** Toast/snackbar tracker (declarative recordToast/dismissToast) */\n toastCapture: ToastCapture;\n /** Undo/redo action-correlation tracker */\n undoTracker: UndoTracker;\n /** Get all registered elements */\n getElements: () => RegisteredNativeElement[];\n /** Get all registered components */\n getComponents: () => RegisteredNativeComponent[];\n /** Create a snapshot */\n createSnapshot: () => NativeBridgeSnapshot;\n /** Subscribe to events */\n on: <T = unknown>(type: BridgeEventType, listener: BridgeEventListener<T>) => () => void;\n /** Unsubscribe from events */\n off: <T = unknown>(type: BridgeEventType, listener: BridgeEventListener<T>) => void;\n /** Whether the provider is initialized */\n initialized: boolean;\n /** Server running status */\n serverRunning: boolean;\n /** Start the HTTP server */\n startServer: () => Promise<void>;\n /** Stop the HTTP server */\n stopServer: () => void;\n /** Get the current navigation route (if a RouteProvider is configured) */\n getCurrentRoute: () => string | null;\n}\n\n/**\n * UI Bridge Native context\n */\nconst UIBridgeNativeContext = createContext<UIBridgeNativeContextValue | null>(null);\n\n/**\n * Stable defaults for the two optional object props.\n *\n * Written as `features = {}` these were fresh literals on every render, so\n * `Object.is` failed for both entries of the `contextValue` `useMemo` deps below\n * and the context value was NEW on every provider render. `useUIElement`'s\n * auto-register effect has deps `[autoRegister, bridge, id]` where `bridge` IS\n * that context value, and its cleanup runs a real `registry.unregisterElement`\n * followed by a full `registerElement` — not an in-place mutate. So a host that\n * re-renders its provider (any `useState` in the root layout) churned the entire\n * element registry every time. `useUIComponent` (deps `[autoRegister, bridge]`)\n * had the identical exposure.\n *\n * The two sibling providers in this repo — `packages/ui-bridge/src/react/\n * UIBridgeProvider.tsx` and `packages/ui-bridge/src/native/react/\n * UIBridgeNativeProvider.tsx` — already carry exactly this idiom. Plain\n * literals, not `Object.freeze`d, to match them verbatim.\n */\nconst EMPTY_FEATURES: NativeUIBridgeFeatures = {};\nconst EMPTY_CONFIG: NativeUIBridgeConfig = {};\n\n/**\n * Hold an options object's identity steady for as long as its VALUE is\n * unchanged.\n *\n * Stable defaults alone only fix the host that OMITS the prop. This component's\n * own usage example passes inline literals —\n * `features={{ server: __DEV__, debug: __DEV__ }} config={{ serverPort: 8087 }}`\n * — which are freshly allocated on every render of the host's layout, so\n * `Object.is` fails and the context value churns exactly as before. That is the\n * documented pattern, so it is the one that has to work.\n *\n * Keyed on a JSON signature rather than an enumerated field list: both\n * `NativeUIBridgeFeatures` and `NativeUIBridgeConfig` are small, plain,\n * JSON-serialisable bags (booleans, a number, strings, and one nested `appInfo`\n * of strings — no functions, no cycles), and a field list would silently stop\n * covering a field the day one is added, with nothing to catch it. Cost is one\n * `JSON.stringify` of a handful of scalars per render.\n *\n * Two honest limits: a host that reorders its object's keys between renders\n * produces a different signature, and a host that MUTATES the object in place\n * without changing the reference will now be noticed rather than ignored. Both\n * degrade to the previous behaviour (a new context value), never to a stale one.\n */\nfunction useValueStable<T>(value: T): T {\n const signature = JSON.stringify(value);\n // Keyed on the VALUE signature on purpose: `value`'s identity is precisely\n // what this hook exists to discard, so listing it as a dep would defeat it.\n // eslint-disable-next-line react-hooks/exhaustive-deps\n return useMemo(() => value, [signature]);\n}\n\n/**\n * UI Bridge Native provider props\n */\nexport interface UIBridgeNativeProviderProps {\n /** Child components */\n children: React.ReactNode;\n /** Feature flags */\n features?: NativeUIBridgeFeatures;\n /** Configuration */\n config?: NativeUIBridgeConfig;\n /** Event handler */\n onEvent?: BridgeEventListener;\n /**\n * A ServerAdapter instance for the HTTP server.\n * The app is responsible for creating this using its preferred native TCP/HTTP library.\n * @see ServerAdapter interface in server/http-server.ts\n */\n serverAdapter?: ServerAdapter;\n /**\n * Navigation provider for programmatic route navigation via UI Bridge.\n * Pass Expo Router's push/back functions to enable `control/page/navigate`.\n */\n navigationProvider?: { navigate: (url: string) => void; back?: () => void };\n /**\n * Screenshot provider for native screen capture via UI Bridge.\n * Pass a function that captures the current screen as base64 PNG.\n */\n screenshotProvider?: {\n capture: () => Promise<{ base64: string; width: number; height: number }>;\n };\n /**\n * Keep-awake provider for native screen-wake control via UI Bridge.\n * Pass expo-keep-awake's activateKeepAwakeAsync/deactivateKeepAwake (wrapped\n * to the request/release shape) so an external runner never loses the device\n * to a screen lock. The SDK never imports expo-keep-awake directly.\n */\n keepAwakeProvider?: KeepAwakeProvider;\n /**\n * Route provider for exposing the current navigation route in snapshots.\n * Wire this to Expo Router's `usePathname()` / `useSegments()` via a module-level ref.\n */\n routeProvider?: RouteProvider;\n /**\n * Configuration for the cloud relay tunnel (enables remote device verification\n * when USB/LAN are not available). Omit `uiBridgeServer` — the provider wires\n * that automatically after the server starts.\n */\n cloudRelayConfig?: Omit<CloudRelayConfig, 'uiBridgeServer'>;\n /**\n * Enable mDNS advertisement so that runners on the same LAN can discover this\n * device automatically (requires react-native-zeroconf).\n */\n enableMdnsAnnounce?: boolean;\n /**\n * Stable device identifier used for mDNS TXT records and cloud relay\n * registration. Typically sourced from expo-device or a UUID stored in\n * AsyncStorage.\n */\n deviceId?: string;\n}\n\n/**\n * UI Bridge Native Provider\n *\n * Provides UI Bridge Native context to child components.\n *\n * @example\n * ```tsx\n * // app/_layout.tsx\n * import { UIBridgeNativeProvider } from '@qontinui/ui-bridge-native';\n *\n * export default function RootLayout() {\n * return (\n * <UIBridgeNativeProvider\n * features={{ server: __DEV__, debug: __DEV__ }}\n * config={{ serverPort: 8087 }}\n * >\n * <Stack>{children}</Stack>\n * </UIBridgeNativeProvider>\n * );\n * }\n * ```\n */\n/**\n * The device window size in logical dp — the single definition, shared by every\n * consumer that needs it.\n *\n * Read through `react-native` HERE rather than inside the core registry or the\n * server: the require/import pattern there crashed the host RN app in\n * 0.6.3/0.6.4 (Metro/Hermes raised `unknownModuleError` past every try/catch).\n * This file already has a live react-native import, so it is the safe\n * injection point. See feedback_metro_require_gotcha for the full incident.\n *\n * Injected as a FUNCTION, not a value, so a rotation or split-screen resize is\n * picked up on the next read with nothing to keep in sync. Its three sinks —\n * `getPageHealth`, the design handlers, and the registry's visibility clipping\n * — must not each carry their own copy of this fact and drift apart.\n */\nfunction readWindowViewport(): { width: number; height: number } {\n const win = Dimensions.get('window');\n return { width: win.width, height: win.height };\n}\n\nexport function UIBridgeNativeProvider({\n children,\n features: featuresProp = EMPTY_FEATURES,\n config: configProp = EMPTY_CONFIG,\n onEvent,\n serverAdapter,\n navigationProvider,\n screenshotProvider,\n keepAwakeProvider,\n routeProvider,\n cloudRelayConfig,\n enableMdnsAnnounce,\n deviceId,\n}: UIBridgeNativeProviderProps) {\n // Identity held steady by VALUE — see `useValueStable`. Everything below,\n // including the `contextValue` memo, reads these rather than the raw props.\n const features = useValueStable(featuresProp);\n const config = useValueStable(configProp);\n\n const registryRef = useRef<NativeUIBridgeRegistry | null>(null);\n const executorRef = useRef<NativeActionExecutor | null>(null);\n const modalDetectorRef = useRef<ModalDetector | null>(null);\n const toastCaptureRef = useRef<ToastCapture | null>(null);\n const undoTrackerRef = useRef<UndoTracker | null>(null);\n const [serverRunning, setServerRunning] = useState(false);\n\n // Initialize on first render\n if (!registryRef.current) {\n registryRef.current = new NativeUIBridgeRegistry({\n verbose: config.verbose,\n onEvent,\n });\n // Inject the device pixel ratio so `createSnapshot` can project each\n // element's `state.layout` (logical dp) into a physical-pixel `bbox` the\n // runner's vision pipeline accepts. Done here (a React file that already\n // imports react-native) rather than inside the core registry, which must\n // stay free of react-native imports — see the `projectBbox` doc comment.\n registryRef.current.setPixelRatio(PixelRatio.get());\n // Inject the window bounds so reported `visibility` is clipped against the\n // viewport instead of meaning \"mounted and measured somewhere\". Same\n // injection rationale as `setPixelRatio` above — the core registry must\n // stay free of react-native imports. A PROVIDER rather than a value so a\n // rotation or a split-screen resize is picked up on the next read.\n registryRef.current.setViewportProvider(readWindowViewport);\n setGlobalRegistry(registryRef.current);\n }\n\n const registry = registryRef.current;\n\n // Create executor (memoized)\n if (!executorRef.current) {\n executorRef.current = createNativeActionExecutor(registry);\n }\n\n const executor = executorRef.current;\n\n // Trackers — lazy-init the same way as registry/executor so each provider\n // lifecycle has exactly one stable instance.\n if (!modalDetectorRef.current) modalDetectorRef.current = new ModalDetector();\n if (!toastCaptureRef.current) toastCaptureRef.current = new ToastCapture();\n if (!undoTrackerRef.current) undoTrackerRef.current = new UndoTracker();\n\n const modalDetector = modalDetectorRef.current;\n const toastCapture = toastCaptureRef.current;\n const undoTracker = undoTrackerRef.current;\n\n // Server instance (persisted across renders)\n const serverRef = useRef<NativeUIBridgeServer | null>(null);\n const eventBridgeRef = useRef<WebSocketEventBridge | null>(null);\n\n // Cloud / mDNS transport references\n const announcerRef = useRef<DeviceAnnouncer | null>(null);\n const cloudRelayRef = useRef<CloudRelayClient | null>(null);\n\n // Server management — uses injected serverAdapter if provided\n const startServer = useCallback(async () => {\n if (!features.server) return;\n\n if (!serverAdapter) {\n console.warn(\n `[ui-bridge-native] HTTP server not available: no serverAdapter prop provided. ` +\n `Pass a serverAdapter to UIBridgeNativeProvider to enable the HTTP server.`\n );\n return;\n }\n\n const server = createNativeServer(registry, executor, {\n serverPort: config.serverPort || 8087,\n cors: true,\n appInfo: config.appInfo,\n testHooks: features.testHooks === true,\n // Dedicated console/network-capture flag; the server defaults it to\n // the `testHooks` value when undefined, so passing it through verbatim\n // keeps existing consumers unchanged.\n observability: features.observability,\n // Injected device-viewport getter for POST /control/page-health and the\n // design handlers. Same source as the registry's clipping bounds — see\n // `readWindowViewport`.\n viewportProvider: readWindowViewport,\n });\n\n server.setAdapter(serverAdapter);\n\n // Wire navigation provider if supplied\n if (navigationProvider) {\n server.setNavigationProvider(navigationProvider);\n }\n\n // Wire screenshot provider if supplied\n if (screenshotProvider) {\n server.setScreenshotProvider(screenshotProvider);\n }\n\n // Wire keep-awake provider if supplied\n if (keepAwakeProvider) {\n server.setKeepAwakeProvider(keepAwakeProvider);\n }\n\n // Wire route provider if supplied (must be set AFTER navigationProvider\n // since both may override getSnapshot / pageNavigate handlers)\n if (routeProvider) {\n server.setRouteProvider(routeProvider);\n }\n\n // Wire up WebSocket event bridge if adapter supports it\n const wsAdapter = serverAdapter as WebSocketServerAdapter;\n if (typeof wsAdapter.broadcast === 'function') {\n const eventBridge = new WebSocketEventBridge(registry);\n server.setEventBridge(eventBridge);\n\n wsAdapter.onWebSocketConnect = (connId: string) => {\n // Create a lightweight connection proxy for the event bridge\n // The actual WebSocketConnection lives in the adapter\n eventBridge.addConnection({\n id: connId,\n subscriptions: new Set(),\n alive: true,\n isOpen: true,\n send: (msg: string) => wsAdapter.sendToConnection?.(connId, msg),\n sendEvent: (event: { event: string }) => {\n if (!eventBridge.isSubscribed(connId, event.event)) return;\n wsAdapter.sendToConnection?.(connId, JSON.stringify(event));\n },\n ping: () => {\n /* adapter handles heartbeat */\n },\n close: () => {\n /* adapter handles close */\n },\n destroy: () => {\n /* adapter handles destroy */\n },\n } as any); // eslint-disable-line @typescript-eslint/no-explicit-any\n };\n\n wsAdapter.onWebSocketDisconnect = (connId: string) => {\n // Abort any pending waiters (waitForElement / waitForCondition)\n // for this connection BEFORE removing it — stops leaked timers\n // and registry listeners.\n server.abortWaitersForConnection(connId);\n eventBridge.removeConnection(connId);\n };\n\n wsAdapter.onWebSocketMessage = async (connId: string, message: string) => {\n return server.handleWebSocketMessage(connId, message);\n };\n\n eventBridge.start();\n eventBridgeRef.current = eventBridge;\n }\n\n try {\n await server.start();\n serverRef.current = server;\n setServerRunning(true);\n } catch (err) {\n console.warn('[ui-bridge-native] Failed to start HTTP server:', err);\n }\n }, [\n features.server,\n features.testHooks,\n features.observability,\n config.serverPort,\n config.appInfo,\n registry,\n executor,\n serverAdapter,\n navigationProvider,\n screenshotProvider,\n keepAwakeProvider,\n routeProvider,\n ]);\n\n const stopServer = useCallback(() => {\n if (eventBridgeRef.current) {\n eventBridgeRef.current.stop();\n eventBridgeRef.current = null;\n }\n if (serverRef.current) {\n serverRef.current.stop().catch(() => {});\n serverRef.current = null;\n }\n setServerRunning(false);\n }, []);\n\n // Auto-start server if enabled\n useEffect(() => {\n if (features.server) {\n startServer();\n return () => stopServer();\n }\n }, [features.server, startServer, stopServer]);\n\n // Start mDNS announcement and cloud relay.\n //\n // The cloud relay path does NOT require the HTTP server to be running —\n // it calls `server.handleRequest()` directly, bypassing HTTP. This matters\n // for preview/production builds where `features.server` is typically\n // false (no native TCP server adapter available). We still need a\n // NativeUIBridgeServer instance to handle tunneled requests, so we create\n // a bare instance here if startServer() didn't already make one.\n //\n // mDNS also doesn't need the HTTP server — it just advertises on the\n // network so remote devices can discover this phone's address.\n useEffect(() => {\n // Everything here is best-effort — any exception must not crash the app.\n try {\n const needsBareServer = !serverRef.current && !!cloudRelayConfig;\n if (needsBareServer) {\n try {\n // Create a server instance for handleRequest() use only; no adapter,\n // no HTTP listener. This is safe without features.server.\n const bareServer = createNativeServer(registry, executor, {\n serverPort: config.serverPort || 8087,\n cors: true,\n appInfo: config.appInfo,\n testHooks: features.testHooks === true,\n observability: features.observability,\n viewportProvider: readWindowViewport,\n });\n if (navigationProvider) bareServer.setNavigationProvider(navigationProvider);\n if (screenshotProvider) bareServer.setScreenshotProvider(screenshotProvider);\n if (keepAwakeProvider) bareServer.setKeepAwakeProvider(keepAwakeProvider);\n if (routeProvider) bareServer.setRouteProvider(routeProvider);\n serverRef.current = bareServer;\n } catch (err) {\n console.warn('[ui-bridge-native] Failed to create bare server:', err);\n }\n }\n\n // mDNS advertisement\n if (enableMdnsAnnounce && deviceId) {\n try {\n const announcer = new DeviceAnnouncer({\n deviceId,\n appId: config.appInfo?.appId ?? 'unknown',\n port: config.serverPort ?? 8087,\n cloudRelayUrl: cloudRelayConfig?.relayUrl,\n cloudToken: cloudRelayConfig?.authToken,\n });\n announcerRef.current = announcer;\n void announcer.startMdnsAdvertise().catch((err) => {\n console.warn('[ui-bridge-native] mDNS advertise failed:', err);\n });\n } catch (err) {\n console.warn('[ui-bridge-native] Failed to start DeviceAnnouncer:', err);\n }\n }\n\n // Cloud relay tunnel (works without HTTP server)\n if (cloudRelayConfig && serverRef.current) {\n try {\n const relayClient = new CloudRelayClient({\n ...cloudRelayConfig,\n uiBridgeServer: serverRef.current,\n });\n cloudRelayRef.current = relayClient;\n relayClient.start();\n } catch (err) {\n console.warn('[ui-bridge-native] Failed to start CloudRelayClient:', err);\n }\n }\n } catch (err) {\n console.warn('[ui-bridge-native] Transport effect failed:', err);\n }\n\n return () => {\n try {\n if (announcerRef.current) {\n void announcerRef.current.stop().catch(() => {});\n announcerRef.current = null;\n }\n if (cloudRelayRef.current) {\n cloudRelayRef.current.stop();\n cloudRelayRef.current = null;\n }\n } catch {\n // cleanup must never throw\n }\n };\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [\n serverRunning,\n cloudRelayConfig?.relayUrl,\n cloudRelayConfig?.authToken,\n enableMdnsAnnounce,\n deviceId,\n ]);\n\n // Cleanup on unmount\n useEffect(() => {\n return () => {\n stopServer();\n resetGlobalRegistry();\n };\n }, [stopServer]);\n\n // Context methods\n const getElements = useCallback(() => registry.getAllElements(), [registry]);\n\n const getComponents = useCallback(() => registry.getAllComponents(), [registry]);\n\n const createSnapshot = useCallback(() => registry.createSnapshot(), [registry]);\n\n const getCurrentRoute = useCallback(() => {\n return routeProvider?.getCurrentRoute() ?? null;\n }, [routeProvider]);\n\n // Mark the previous route's elements offscreen when the active route changes.\n // Without this, React Navigation's persistent-mount behavior leaves stale\n // layouts in the registry for tabs the user has left. Elements on the new\n // route re-fire `onLayout` and repopulate their layout.\n useEffect(() => {\n if (!routeProvider) return;\n\n let lastRoute: string | null = routeProvider.getCurrentRoute();\n\n return routeProvider.subscribe((current: string | null) => {\n if (current !== lastRoute && lastRoute != null) {\n registry.markRouteOffscreen(lastRoute);\n }\n lastRoute = current;\n });\n }, [routeProvider, registry]);\n\n // Wire trackers into the registry's snapshot enricher slots. Trackers are\n // stable refs, so this effect runs exactly once per provider lifecycle.\n useEffect(() => {\n registry.setEnrichers({ modalDetector, toastCapture, undoTracker });\n }, [registry, modalDetector, toastCapture, undoTracker]);\n\n // Mirror successful bridge actions into UndoTracker's rolling history so\n // snapshots can surface action-correlation undo context without each\n // action site needing to call recordAction manually.\n useEffect(() => {\n const unsubscribe = executor.onActionExecuted((event) => {\n if (!event.success) return;\n undoTracker.recordAction({\n id: event.requestId ?? `action-${event.timestamp}`,\n type: event.action,\n targetId: event.elementId,\n timestamp: event.timestamp,\n reversible: true,\n });\n });\n return unsubscribe;\n }, [executor, undoTracker]);\n\n const on = useCallback(\n <T = unknown,>(type: BridgeEventType, listener: BridgeEventListener<T>) =>\n registry.on(type, listener),\n [registry]\n );\n\n const off = useCallback(\n <T = unknown,>(type: BridgeEventType, listener: BridgeEventListener<T>) =>\n registry.off(type, listener),\n [registry]\n );\n\n const contextValue = useMemo<UIBridgeNativeContextValue>(\n () => ({\n features,\n config,\n registry,\n executor,\n modalDetector,\n toastCapture,\n undoTracker,\n getElements,\n getComponents,\n createSnapshot,\n on,\n off,\n initialized: true,\n serverRunning,\n startServer,\n stopServer,\n getCurrentRoute,\n }),\n [\n features,\n config,\n registry,\n executor,\n modalDetector,\n toastCapture,\n undoTracker,\n getElements,\n getComponents,\n createSnapshot,\n on,\n off,\n serverRunning,\n startServer,\n stopServer,\n getCurrentRoute,\n ]\n );\n\n return <UIBridgeNativeContext value={contextValue}>{children}</UIBridgeNativeContext>;\n}\n\n/**\n * useUIBridgeNative hook\n *\n * Access the UI Bridge Native context. Throws if used outside provider.\n */\nexport function useUIBridgeNative(): UIBridgeNativeContextValue {\n const context = use(UIBridgeNativeContext);\n if (!context) {\n throw new Error('useUIBridgeNative must be used within a UIBridgeNativeProvider');\n }\n return context;\n}\n\n/**\n * useUIBridgeNativeOptional hook\n *\n * Access the UI Bridge Native context, returning null if outside provider.\n */\nexport function useUIBridgeNativeOptional(): UIBridgeNativeContextValue | null {\n return use(UIBridgeNativeContext);\n}\n\n/**\n * useUIBridgeNativeRequired hook\n *\n * Alias for useUIBridgeNative (throws if outside provider).\n */\nexport const useUIBridgeNativeRequired = useUIBridgeNative;\n","/**\n * useUIElement Hook for React Native\n *\n * Register a native element with UI Bridge for control and observation.\n */\n\nimport { useRef, useEffect, useCallback, useMemo, useState } from 'react';\nimport { StyleSheet } from 'react-native';\nimport type {\n NativeElementType,\n NativeStandardAction,\n NativeCustomAction,\n NativeElementState,\n NativeElementIdentifier,\n RegisteredNativeElement,\n NativeElementRef,\n NativeLayout,\n} from '../core/types';\nimport { useUIBridgeNativeOptional } from './UIBridgeNativeProvider';\n\n/**\n * Flatten an RN style prop into a plain object.\n * Uses StyleSheet.flatten which handles arrays, IDs, and nested objects.\n */\nfunction flattenStyle(style: unknown): Record<string, unknown> | undefined {\n if (style == null) return undefined;\n try {\n const flat = StyleSheet.flatten(style as Parameters<typeof StyleSheet.flatten>[0]);\n return flat ? (flat as Record<string, unknown>) : undefined;\n } catch {\n return undefined;\n }\n}\n\n/**\n * Flatten state style overrides into plain objects.\n */\nfunction flattenStateStyles(stateStyles?: {\n pressed?: unknown;\n focused?: unknown;\n disabled?: unknown;\n}):\n | {\n pressed?: Record<string, unknown>;\n focused?: Record<string, unknown>;\n disabled?: Record<string, unknown>;\n }\n | undefined {\n if (!stateStyles) return undefined;\n const result: {\n pressed?: Record<string, unknown>;\n focused?: Record<string, unknown>;\n disabled?: Record<string, unknown>;\n } = {};\n if (stateStyles.pressed != null) result.pressed = flattenStyle(stateStyles.pressed);\n if (stateStyles.focused != null) result.focused = flattenStyle(stateStyles.focused);\n if (stateStyles.disabled != null) result.disabled = flattenStyle(stateStyles.disabled);\n return Object.keys(result).length > 0 ? result : undefined;\n}\n\n/**\n * Local type definition for the layout data we extract from LayoutChangeEvent.\n * We use this internally to avoid type conflicts between different react-native versions\n * (e.g., when ui-bridge-native is used as a file: dependency with a different RN version).\n */\ninterface LayoutEventData {\n nativeEvent: {\n layout: {\n x: number;\n y: number;\n width: number;\n height: number;\n };\n };\n}\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\ntype AnyHandler = (...args: any[]) => any;\n\n/**\n * A press handler for `button`/`pressable` types. Matches the loose RN\n * `Pressable` `onPress` shape (no required argument), so consumers can pass\n * either a no-arg callback or one that consumes the gesture event.\n */\nexport type PressHandler = (event?: unknown) => void;\n\n/**\n * Element types that require a press handler at registration. The TS\n * signature on `useUIElement` rejects these types unless `handlers.onPress`\n * is provided in options.\n *\n * Picked from the action-executor in `control/action-executor.ts` — the\n * `press` action looks up `props.onPress` (or `onPressIn` /\n * `onResponderRelease`); registering a button without one is a guaranteed\n * dead-button per the 2026-05-20 manual-test session.\n */\nexport type PressNeedingNativeElementType = 'button' | 'pressable';\n\n/**\n * Base options for `useUIElement`. The discriminated union below layers\n * `handlers` requirements on top of this — see {@link UseUIElementOptions}.\n */\nexport interface UseUIElementOptionsBase<T extends NativeElementType = NativeElementType> {\n /** Unique identifier for the element */\n id: string;\n /** Element type (defaults to 'custom') */\n type?: T;\n /** Human-readable label */\n label?: string;\n /** Override available actions */\n actions?: NativeStandardAction[];\n /** Custom actions */\n customActions?: Record<string, NativeCustomAction>;\n /**\n * Current controlled value for text inputs. When provided, it is threaded\n * into the registered element's `state.value` so a `GET /control/element/:id`\n * (or `/state`) reflects what the user sees — without this, the input\n * registers with `value: undefined` and a bridge read returns null even\n * though the field is populated. Pass the same value you bind to the RN\n * `<TextInput value={...} />` prop; the hook keeps the registry in sync as\n * it changes.\n */\n value?: string;\n /** Whether to automatically register on mount */\n autoRegister?: boolean;\n /** Callback when state changes */\n onStateChange?: (state: NativeElementState) => void;\n /** Parent component path for tree path generation */\n parentPath?: string;\n /**\n * Id of the registered scrollable container (`type: 'scroll' | 'list'`) this\n * element is rendered inside.\n *\n * Supplying it makes the bridge clip this element's reported `visibility`\n * against that container's measured frame, so a row scrolled past the fold\n * reports `visibility: 'hidden'` with `visibilityReason: 'off-screen'`\n * instead of claiming to be on screen. Without it, the device window is the\n * only clip region.\n *\n * It has to be declared: `useUIElement` is a hook, so it never wraps its\n * element's children and cannot publish itself to them as an ancestor. See\n * `RegisterElementOptions.scrollAncestorId` for why guessing geometrically\n * would be worse than not clipping.\n *\n * It is also what the `scrollIntoView` action scrolls, and declaring it is\n * what advertises that action — but only when `actions` is left to be\n * inferred. An explicit `actions` list is taken as written; include\n * `'scrollIntoView'` in it yourself if you want the action advertised.\n */\n scrollAncestorId?: string;\n /** RN style prop — will be flattened for design review */\n style?: unknown;\n /** State-specific style overrides for design review (pressed, focused, disabled) */\n stateStyles?: {\n pressed?: unknown;\n focused?: unknown;\n disabled?: unknown;\n };\n}\n\n/**\n * Options shape for press-needing types — `handlers.onPress` is REQUIRED.\n * Registering a `button`/`pressable` without an `onPress` produces a\n * \"No press handler found on element\" error when the bridge fires\n * `POST /control/element/:id/action {\"action\":\"press\"}`. Phase 1 of plan\n * `2026-05-20-manual-test-remediation` makes that a compile-time error.\n *\n * Consumers that wire `onPress` lazily (e.g. computed from props during\n * render) should use {@link useUIElementWithProps} + `captureProps({ onPress })`\n * instead. The runtime guard in this hook also warns once per id when\n * `onPress` never reaches the registry.\n */\nexport interface UseUIElementOptionsHandlersRequired<\n T extends PressNeedingNativeElementType = PressNeedingNativeElementType,\n> extends UseUIElementOptionsBase<T> {\n /**\n * Handler props to auto-register with the bridge for action execution.\n * For `button`/`pressable`, `onPress` is required — UI Bridge invokes it\n * when a `press` action is dispatched.\n *\n * @example\n * ```tsx\n * const { ref, onLayout, bridgeProps } = useUIElement({\n * id: 'my-button',\n * type: 'pressable',\n * handlers: { onPress: handlePress },\n * });\n * ```\n */\n handlers: {\n /** Required — UI Bridge invokes this on `press`/`click` actions. */\n onPress: PressHandler;\n /** Additional handlers (`onLongPress`, `onPressIn`, etc.) */\n [key: string]: AnyHandler | undefined;\n };\n}\n\n/**\n * Options shape for non-press-needing types — `handlers` is optional.\n * Applies to `input`, `text`, `view`, `list`, etc. — anything where a\n * missing `onPress` doesn't indicate a dead button.\n */\nexport interface UseUIElementOptionsHandlersOptional<\n T extends NativeElementType = NativeElementType,\n> extends UseUIElementOptionsBase<T> {\n /**\n * Handler props to auto-register with the bridge for action execution.\n * Optional for non-press-needing types.\n */\n handlers?: Record<string, AnyHandler | undefined>;\n}\n\n/**\n * useUIElement options — discriminated union over element type.\n *\n * For `type: 'button' | 'pressable'`, `handlers.onPress` is required.\n * For all other types, `handlers` is optional.\n */\nexport type UseUIElementOptions<T extends NativeElementType = NativeElementType> =\n T extends PressNeedingNativeElementType\n ? UseUIElementOptionsHandlersRequired<T>\n : UseUIElementOptionsHandlersOptional<T>;\n\n/**\n * Bridge props to spread onto the component\n */\nexport interface UIBridgeProps {\n /** Test ID for automation */\n testID: string;\n /** Accessibility label */\n accessibilityLabel?: string;\n}\n\n/**\n * useUIElement return value\n */\nexport interface UseUIElementReturn {\n /** Ref to attach to the element */\n ref: React.RefObject<NativeElementRef>;\n /** onLayout handler to spread onto the element - uses generic type for RN version compatibility */\n onLayout: (event: {\n nativeEvent: { layout: { x: number; y: number; width: number; height: number } };\n }) => void;\n /** Props to spread onto the element for identification */\n bridgeProps: UIBridgeProps;\n /** Whether the element is registered */\n registered: boolean;\n /** Get current state */\n getState: () => NativeElementState | null;\n /** Get element identifier */\n getIdentifier: () => NativeElementIdentifier | null;\n /** Trigger an action on this element */\n trigger: (\n action: NativeStandardAction | string,\n params?: Record<string, unknown>\n ) => Promise<void>;\n /** Manually register the element */\n register: () => void;\n /** Manually unregister the element */\n unregister: () => void;\n /** The registered element info */\n registeredElement: RegisteredNativeElement | null;\n /** Update style for design review (flattens and stores in registry) */\n updateStyle: (\n style: unknown,\n stateStyles?: { pressed?: unknown; focused?: unknown; disabled?: unknown }\n ) => void;\n /**\n * Re-publish the element's label (and the mirrored `accessibilityLabel` /\n * `testId` so spec-check and a11y stay in sync). Idempotent — no-op when\n * the new label equals the current registered value.\n *\n * NOT required for the common case any more. The `label` OPTION passed to\n * `useUIElement({ id, label })` is now auto-re-published whenever its value\n * changes, so a state-derived label (a tab's active suffix, a card's\n * `${title}: ${loading ? 'loading' : value}`, a list's \"N events\" count)\n * stays in sync with zero call-site ceremony. Existing consumers that still\n * drive `updateLabel(label)` from their own `useEffect` keep working — the\n * second publish is inert, not a flicker.\n *\n * Reach for this only when the string you want in the registry is NOT the\n * `label` option — e.g. a label owned by an imperative handler, or one\n * computed outside the render path.\n *\n * @example\n * ```tsx\n * // No `updateLabel` needed — the option is republished automatically.\n * const { ref } = useUIElement({ id: 'events-list', label: `${events.length} events`, type: 'list' });\n * ```\n */\n updateLabel: (newLabel: string) => void;\n}\n\n/**\n * useUIElement hook for React Native\n *\n * Registers a native element with UI Bridge for programmatic control.\n *\n * @example\n * ```tsx\n * function SubmitButton() {\n * const { ref, onLayout, bridgeProps, trigger } = useUIElement({\n * id: 'submit-btn',\n * type: 'button',\n * label: 'Submit Form',\n * });\n *\n * return (\n * <Pressable\n * ref={ref}\n * onLayout={onLayout}\n * {...bridgeProps}\n * onPress={() => handleSubmit()}\n * >\n * <Text>Submit</Text>\n * </Pressable>\n * );\n * }\n * ```\n */\n/**\n * Module-scoped set of ids we've already warned about so the dead-button\n * `console.warn` only fires once per id even if the component re-mounts.\n */\nconst warnedDeadButtonIds = new Set<string>();\n\n/**\n * Module-scoped set of ids that have already received a no-op-updateLabel\n * warning. Mirrors {@link warnedDeadButtonIds} — one warn per id per process\n * lifetime, so a hot loop calling `updateLabel(sameString)` doesn't spam\n * the console while still surfacing the case during development.\n */\nconst warnedRedundantUpdateLabelIds = new Set<string>();\n\n/**\n * Schedule a deferred check: after one microtask + one macrotask, look up\n * the registered element. If it's a press-needing type AND no `onPress`\n * (or fallback press handler) is on the registry's `props`, emit a\n * `console.warn` pointing at the fix. Deferred so consumers using\n * {@link useUIElementWithProps} + synchronous `captureProps({ onPress })`\n * still pass the check.\n */\nfunction scheduleDeadButtonWarning(\n bridge: ReturnType<typeof useUIBridgeNativeOptional>,\n id: string,\n type: NativeElementType\n): void {\n if (type !== 'button' && type !== 'pressable') return;\n if (warnedDeadButtonIds.has(id)) return;\n if (!bridge) return;\n\n // Defer via macrotask so `useUIElementWithProps` consumers that call\n // `captureProps({ onPress })` from their render body land their props\n // into the registry first. queueMicrotask alone runs before the next\n // render commit on some React schedulers; setTimeout(0) is a safer\n // \"after next paint\" boundary without bringing in `requestAnimationFrame`.\n setTimeout(() => {\n if (warnedDeadButtonIds.has(id)) return;\n const element = bridge.registry.getElement(id);\n if (!element) return;\n const props = (element.props ?? {}) as Record<string, unknown>;\n const hasPress =\n typeof props.onPress === 'function' ||\n typeof props.onPressIn === 'function' ||\n typeof props.onResponderRelease === 'function';\n if (hasPress) return;\n warnedDeadButtonIds.add(id);\n console.warn(\n `[UI Bridge] Registered \\`${type}\\` element \"${id}\" without an \\`onPress\\` handler — UI Bridge \\`press\\` actions on this element will fail with \"No press handler found on element\". Use \\`useUIElementWithProps\\` and \\`captureProps({onPress})\\` instead.`\n );\n }, 0);\n}\n\n// Public overload — narrow signature. External callers see ONLY this; the\n// discriminated union forces `handlers.onPress` for press-needing types.\nexport function useUIElement<T extends NativeElementType = NativeElementType>(\n options: UseUIElementOptions<T>\n): UseUIElementReturn;\n// Implementation signature — wide. Not visible to external callers (TS\n// hides the impl sig); used internally by `useUIElementWithProps` via the\n// narrow public sig with a structural cast.\nexport function useUIElement(options: UseUIElementOptionsHandlersOptional): UseUIElementReturn {\n const bridge = useUIBridgeNativeOptional();\n const [registered, setRegistered] = useState(false);\n const [_layout, setLayout] = useState<NativeLayout | null>(null);\n const propsRef = useRef<Record<string, unknown>>({});\n // Authoritative registration tracking. See the web `useUIElement` for\n // rationale: consumers commonly pass inline `style`/`stateStyles` objects,\n // and threading the `registered` state into the register useCallback's deps\n // creates a cleanup/run feedback loop past React's 50-update ceiling.\n const registeredRef = useRef(false);\n const registeredIdRef = useRef<string | null>(null);\n // Last label value the SDK's OWN auto-publisher wrote to the registry\n // (seeded by `register()`). Only the auto-publish paths write it — a manual\n // `updateLabel(...)` deliberately does not, so the redundant-call warning\n // below can still tell \"the SDK already published this\" apart from \"this\n // call site republishes the same string on its own\".\n const autoPublishedLabelRef = useRef<string | undefined>(undefined);\n\n // Latest bridge for the ref interceptor below. React attaches/detaches\n // refs during the commit phase — outside any effect closure — so the\n // interceptor reads the live bridge through this ref.\n const bridgeRef = useRef(bridge);\n bridgeRef.current = bridge;\n\n // Element ref with attach/detach interception.\n //\n // The registry seeds `visible: true` at registration (see\n // `registerElement`) so unmeasured-but-mounted elements still appear in\n // `visibleOnly` snapshots. That seed is wrong for refs that DETACH after\n // render: conditional branches (e.g. a status element rendered only in an\n // error branch) leave stale `visible: true` + layout in the registry when\n // the branch unmounts, because RN fires no event on detach. React's only\n // detach signal for object refs is the `ref.current = null` write it\n // performs on unmount — so instead of a plain `useRef`, we hand consumers\n // a stable RefObject whose `current` setter mirrors attach/detach into the\n // registry's `visible` flag:\n // - detach (node → null) while registered ⇒ `visible: false`\n // - (re)attach (null → node) while registered ⇒ `visible: true`\n // (restores the registration seed; onLayout / measureInWindow refine\n // it with real dimensions as usual)\n // Reads (`ref.current`) behave exactly like a normal ref.\n const nodeRef = useRef<NativeElementRef>(null);\n const refInterceptorRef = useRef<React.RefObject<NativeElementRef> | null>(null);\n if (refInterceptorRef.current === null) {\n refInterceptorRef.current = {\n get current(): NativeElementRef {\n return nodeRef.current;\n },\n set current(node: NativeElementRef) {\n const prev = nodeRef.current;\n nodeRef.current = node;\n const liveBridge = bridgeRef.current;\n const registeredId = registeredIdRef.current;\n if (!liveBridge || !registeredRef.current || registeredId === null) return;\n if (node == null && prev != null) {\n // Detached after render — the element left the tree while the hook\n // (and its registration) stayed mounted. Without this write the\n // registry keeps reporting the registration-seeded `visible: true`.\n const state = liveBridge.registry.getElement(registeredId)?.getState();\n if (state && state.visible !== false) {\n liveBridge.registry.updateElementState(registeredId, { visible: false });\n }\n } else if (node != null && prev == null) {\n // (Re)attached — restore the seed's \"mounted, should be visible\"\n // optimism; layout measurement refines it from here.\n const state = liveBridge.registry.getElement(registeredId)?.getState();\n if (state && state.visible !== true) {\n liveBridge.registry.updateElementState(registeredId, { visible: true });\n }\n }\n },\n } as React.RefObject<NativeElementRef>;\n }\n const ref = refInterceptorRef.current;\n\n const {\n id,\n type = 'custom',\n label,\n actions,\n customActions,\n autoRegister = true,\n onStateChange,\n parentPath,\n scrollAncestorId,\n style,\n stateStyles: stateStylesProp,\n handlers: handlersProp,\n value: valueProp,\n } = options;\n\n // Build tree path\n const treePath = parentPath ? `${parentPath}/${id}` : id;\n\n // Bridge props to spread onto the element\n const bridgeProps: UIBridgeProps = useMemo(\n () => ({\n testID: id,\n accessibilityLabel: label,\n }),\n [id, label]\n );\n\n // Register the element\n const register = useCallback(() => {\n if (!bridge || registeredRef.current) return;\n\n bridge.registry.registerElement(id, ref, {\n type,\n label,\n actions,\n customActions,\n treePath,\n testId: id,\n accessibilityLabel: label,\n registrationRoute: bridge.getCurrentRoute(),\n scrollAncestorId,\n flatStyle: flattenStyle(style),\n stateStyles: flattenStateStyles(stateStylesProp),\n });\n registeredRef.current = true;\n registeredIdRef.current = id;\n autoPublishedLabelRef.current = typeof label === 'string' ? label : undefined;\n\n // Seed the controlled value into the element state so a bridge read\n // reflects what the user sees immediately on mount — before any `type`/\n // `setValue` action runs. Only write when a value was actually supplied\n // so non-input elements aren't given a spurious empty `value`.\n if (typeof valueProp === 'string') {\n bridge.registry.updateElementState(id, { value: valueProp });\n }\n\n setRegistered(true);\n\n // Runtime backstop for the type-tightening: warns once per id when a\n // press-needing type is registered without an `onPress` reaching the\n // registry. Catches JS consumers and `as any` escape hatches that\n // bypass the discriminated-union signature above. Deferred so consumers\n // using `useUIElementWithProps` + `captureProps({ onPress })` from the\n // render body still pass.\n scheduleDeadButtonWarning(bridge, id, type);\n // `ref` (the interceptor object) is created exactly once per hook\n // instance, so listing it is identity-stable — included to satisfy\n // exhaustive-deps now that it isn't a direct useRef result.\n }, [\n bridge,\n id,\n type,\n label,\n actions,\n customActions,\n treePath,\n scrollAncestorId,\n style,\n stateStylesProp,\n valueProp,\n ref,\n ]);\n\n // Unregister the element\n const unregister = useCallback(() => {\n if (!bridge || !registeredRef.current) return;\n\n bridge.registry.unregisterElement(registeredIdRef.current ?? id);\n registeredRef.current = false;\n registeredIdRef.current = null;\n autoPublishedLabelRef.current = undefined;\n setRegistered(false);\n }, [bridge, id]);\n\n // Keep `onStateChange` in a ref so the layout callback doesn't get\n // re-created (and thereby miss the first layout event) when the consumer\n // passes an inline arrow function.\n const onStateChangeRef = useRef(onStateChange);\n useEffect(() => {\n onStateChangeRef.current = onStateChange;\n }, [onStateChange]);\n\n // Handle layout changes.\n //\n // Registry write gating uses `registeredRef.current` (not the React\n // `registered` state) so the very first `onLayout` event — which can fire\n // before `setRegistered(true)` has been committed by React — still pushes\n // layout into the registry. Without this, snapshots show layout `(?, ?)`\n // until the element is interacted with, because the initial onLayout's\n // closure captured `registered === false` and silently dropped the write.\n // updateElementState itself is also no-op when the id isn't registered,\n // so this is safe even when `onLayout` fires before mount.\n const onLayout = useCallback(\n (event: LayoutEventData) => {\n const { x, y, width, height } = event.nativeEvent.layout;\n\n const writeLayout = (newLayout: NativeLayout) => {\n setLayout(newLayout);\n if (!bridge) return;\n const newState: NativeElementState = {\n mounted: true,\n visible: width > 0 && height > 0,\n enabled: true,\n focused: false,\n layout: newLayout,\n };\n bridge.registry.updateElementState(id, newState);\n onStateChangeRef.current?.(newState);\n };\n\n // Get absolute position using measureInWindow when available.\n if (ref.current && 'measureInWindow' in ref.current) {\n (\n ref.current as {\n measureInWindow: (\n callback: (pageX: number, pageY: number, w: number, h: number) => void\n ) => void;\n }\n ).measureInWindow((pageX: number, pageY: number) => {\n writeLayout({ x, y, width, height, pageX, pageY });\n });\n } else {\n // Fallback when measureInWindow isn't on the ref (test fixtures, web).\n // `pageX`/`pageY` are PARENT-RELATIVE here, not window coordinates —\n // flagged so visibility clipping declines to compare them against the\n // window rather than mixing coordinate spaces. See `NativeLayout`.\n writeLayout({ x, y, width, height, pageX: x, pageY: y, pageOriginUnmeasured: true });\n }\n },\n // `ref` is the once-per-hook interceptor object — identity-stable.\n [bridge, id, ref]\n );\n\n // Keep latest register/unregister in refs so the auto-register effect does\n // not re-run when consumers pass inline `style`/`stateStyles` options.\n const registerRef = useRef(register);\n const unregisterRef = useRef(unregister);\n useEffect(() => {\n registerRef.current = register;\n unregisterRef.current = unregister;\n }, [register, unregister]);\n\n // Auto-register on mount, and RE-register when `id` changes.\n //\n // `id` is a real dependency even though the effect body never reads it:\n // recycled virtualized-list cells (FlashList) re-render the same hook\n // instance with a NEW id. Without `id` in the deps, the effect never\n // re-ran, so the OLD id stayed registered forever (a stale entry no\n // re-measure can fix) and the NEW id was never registered at all.\n //\n // Ordering on an id-change render: the cleanup runs first and closes over\n // the PREVIOUS `unregisterRef.current`, whose `unregister` removes\n // `registeredIdRef.current` — i.e. the OLD id — and resets the guard\n // flags. The ref-sync effect above is declared before this one, so by the\n // time this effect's body re-runs, `registerRef.current` is the fresh\n // closure that registers the NEW id. Invariant: after a rerender that\n // changes `id` from A to B, the registry has no entry for A and a live\n // entry for B.\n useEffect(() => {\n if (autoRegister) {\n registerRef.current();\n }\n\n return () => {\n if (registeredRef.current) {\n unregisterRef.current();\n }\n };\n }, [autoRegister, bridge, id]);\n\n // Layout-on-mount fallback with backoff retry.\n //\n // Bug being addressed: the registry's `layout` field shows `(?, ?)` until\n // the element is actioned. Three compounding causes:\n // 1. The first `onLayout` event used to drop its write because the\n // callback's closure captured `registered === false` (fixed above by\n // switching to a registry-only write path).\n // 2. Some consumers don't actually thread `onLayout={onLayout}` onto\n // their RN component, so the layout never measures.\n // 3. Elements registered while their subtree is mounted-but-not-laid-out\n // (Expo Router lazy tabs; routes hidden behind an overlay like a\n // Connect/login screen) return zero dims from the first\n // `measureInWindow` call. RN doesn't re-fire `onLayout` on visibility\n // changes when intrinsic dimensions don't change, so a single-shot\n // measure leaves the registry entry at `visible:false, layout:null`\n // permanently — even after the user navigates to the screen.\n //\n // Schedule a `measureInWindow` immediately after registration, and retry\n // with backoff (50/200/500/1000/2500 ms) whenever the call returns zeros.\n // Stops on first non-zero result or after the last retry. All pending\n // timers are cleared on unmount / re-register.\n useEffect(() => {\n if (!bridge || !registered) return;\n const node = ref.current as\n | (NativeElementRef & {\n measureInWindow?: (\n callback: (pageX: number, pageY: number, w: number, h: number) => void\n ) => void;\n })\n | null;\n if (!node) {\n // Never attached: the hook registered the element but no rendered node\n // ever received the ref (refs attach during commit, BEFORE effects run\n // — so a null ref here means the element isn't in the tree, e.g. a\n // status element only rendered in an error branch). The registration\n // seed optimistically reports `visible: true`; correct it so snapshots\n // don't claim never-rendered elements are on screen. Mounted nodes\n // that merely haven't measured yet keep the seeded `true` (the\n // lazy-tab rationale above), and the ref interceptor flips this back\n // to `true` if the element attaches later.\n const seeded = bridge.registry.getElement(id)?.getState();\n if (seeded && seeded.visible !== false) {\n bridge.registry.updateElementState(id, { visible: false });\n }\n return;\n }\n if (typeof node.measureInWindow !== 'function') return;\n\n let cancelled = false;\n let pendingTimer: ReturnType<typeof setTimeout> | null = null;\n const backoffMs = [50, 200, 500, 1000, 2500];\n let attempt = 0;\n\n const tryMeasure = () => {\n if (cancelled || !node.measureInWindow) return;\n node.measureInWindow((pageX: number, pageY: number, w: number, h: number) => {\n if (cancelled) return;\n if (w > 0 && h > 0) {\n const newLayout: NativeLayout = {\n x: pageX,\n y: pageY,\n width: w,\n height: h,\n pageX,\n pageY,\n };\n setLayout(newLayout);\n const newState: NativeElementState = {\n mounted: true,\n visible: true,\n enabled: true,\n focused: false,\n layout: newLayout,\n };\n bridge.registry.updateElementState(id, newState);\n onStateChangeRef.current?.(newState);\n return;\n }\n if (attempt >= backoffMs.length) return;\n pendingTimer = setTimeout(tryMeasure, backoffMs[attempt++]);\n });\n };\n\n tryMeasure();\n\n return () => {\n cancelled = true;\n if (pendingTimer != null) clearTimeout(pendingTimer);\n };\n // `ref` is the once-per-hook interceptor object — identity-stable.\n }, [bridge, registered, id, ref]);\n\n // Auto-register handler props (onPress, onChangeText, etc.) when provided.\n // We use a ref to track which keys were last registered so we can clear\n // stale handlers on cleanup or when the handlers object changes.\n const registeredHandlerKeysRef = useRef<string[]>([]);\n\n useEffect(() => {\n if (!bridge || !registered || !handlersProp) return;\n\n // Filter to only function values\n const fnProps: Record<string, unknown> = {};\n for (const [key, value] of Object.entries(handlersProp)) {\n if (typeof value === 'function') {\n fnProps[key] = value;\n }\n }\n\n const newKeys = Object.keys(fnProps);\n\n // Clear any previously registered keys that are no longer present\n const removedKeys = registeredHandlerKeysRef.current.filter((k) => !newKeys.includes(k));\n if (removedKeys.length > 0) {\n const cleared: Record<string, unknown> = {};\n for (const key of removedKeys) {\n cleared[key] = undefined;\n }\n bridge.registry.updateElementProps(id, cleared);\n }\n\n if (newKeys.length > 0) {\n bridge.registry.updateElementProps(id, fnProps);\n }\n registeredHandlerKeysRef.current = newKeys;\n\n return () => {\n // On unmount or re-run, clear all registered handlers\n if (registeredHandlerKeysRef.current.length > 0) {\n const cleared: Record<string, unknown> = {};\n for (const key of registeredHandlerKeysRef.current) {\n cleared[key] = undefined;\n }\n bridge.registry.updateElementProps(id, cleared);\n registeredHandlerKeysRef.current = [];\n }\n };\n }, [bridge, registered, id, handlersProp]);\n\n // Keep the registry's `state.value` in sync with the controlled `value`\n // prop. RN controlled inputs re-render with a new `value` on every\n // keystroke; mirroring it here means a bridge read (`/control/element/:id`)\n // always reflects the live field contents, not just the value at mount or\n // the last bridge-driven `type`/`setValue`. Guarded on `registered` so the\n // write lands after registration; `updateElementState` is a no-op for\n // unknown ids anyway.\n useEffect(() => {\n if (!bridge || !registered) return;\n if (typeof valueProp !== 'string') return;\n const current = bridge.registry.getElement(id)?.getState().value;\n if (current === valueProp) return;\n bridge.registry.updateElementState(id, { value: valueProp });\n }, [bridge, registered, id, valueProp]);\n\n // Keep the registry's label in sync with the `label` OPTION — automatically.\n //\n // ROOT CAUSE this closes: `register()` publishes `label` exactly once and is\n // guarded by `registeredRef.current`, while the auto-register effect only\n // re-runs on `[autoRegister, bridge, id]`. A consumer whose label is derived\n // from state — `${title}: ${error ? 'error' : loading ? 'loading' : value}` —\n // therefore left the registry holding the MOUNT-TIME string forever unless it\n // also remembered to call `updateLabel(...)` by hand. Measured consequence:\n // five `operations-card-*` elements reporting `Fleet: loading` /\n // `Questions: loading` indefinitely while the screen beside them rendered the\n // real numbers. That is both an a11y defect (TalkBack reads \"loading\"\n // forever) and a test-surface defect (any bridge assertion on those labels\n // reads a fossil). `updateLabel` stays as the escape hatch for labels that\n // are NOT the `label` option; it is no longer something a call site has to\n // remember.\n //\n // Identity trap, handled twice over:\n // 1. `label` is a STRING, so React's `Object.is` dependency compare IS a\n // value compare. An inline template literal rebuilt on every render but\n // producing the same text does NOT re-run this effect — no publish per\n // render, per element.\n // 2. `updateElementMeta` compares each field by value before mutating and\n // returns `false` without emitting when nothing changed. So even when\n // the effect DOES re-run for another reason (`registered` flipping,\n // `bridge`/`id` changing), a same-value publish is inert.\n //\n // Publishes the LABEL ONLY. `registerElement` is never called a second time,\n // so the registry entry is mutated in place: no churn, no duplicate entry, and\n // no reset of state / props / layout / handler registration. Double-publishing\n // alongside a consumer that still calls `updateLabel(label)` itself is\n // therefore idempotent rather than a flicker.\n useEffect(() => {\n if (!bridge || !registered) return;\n if (typeof label !== 'string') return;\n autoPublishedLabelRef.current = label;\n bridge.registry.updateElementMeta(id, {\n label,\n accessibilityLabel: label,\n testId: id,\n });\n }, [bridge, registered, id, label]);\n\n // Update props for action execution (allows accessing onPress, onChangeText, etc.)\n const _updateProps = useCallback(\n (props: Record<string, unknown>) => {\n propsRef.current = { ...propsRef.current, ...props };\n if (bridge && registered) {\n bridge.registry.updateElementProps(id, props);\n }\n },\n [bridge, registered, id]\n );\n\n // Get state\n const getState = useCallback((): NativeElementState | null => {\n if (!bridge) return null;\n const element = bridge.registry.getElement(id);\n return element?.getState() || null;\n }, [bridge, id]);\n\n // Get identifier\n const getIdentifier = useCallback((): NativeElementIdentifier | null => {\n if (!bridge) return null;\n const element = bridge.registry.getElement(id);\n return element?.getIdentifier() || null;\n }, [bridge, id]);\n\n // Trigger action\n const trigger = useCallback(\n async (action: NativeStandardAction | string, params?: Record<string, unknown>) => {\n if (!bridge) {\n throw new Error('UI Bridge Native not available');\n }\n\n const response = await bridge.executor.executeAction(id, {\n action,\n params,\n });\n\n if (!response.success) {\n throw new Error(response.error || 'Action failed');\n }\n },\n [bridge, id]\n );\n\n // Re-publish label / a11y label / testId for state-driven labels.\n //\n // The bug being addressed: `useUIElement({id, label})` registers the label\n // exactly once on mount. Consumers that compute a label from state\n // (e.g. `Tab: Actions${active ? ' (active)' : ''}`, `${events.length} events`)\n // see the registry permanently stuck at the mount-time string.\n //\n // Idempotent — the registry's `updateElementMeta` returns false when no\n // field actually changed, so a hot render loop calling `updateLabel(sameString)`\n // costs one Map lookup + three equality checks. To surface obviously-redundant\n // call sites during development, we emit a one-time `console.warn` per id on\n // the first observed no-op.\n const updateLabel = useCallback(\n (newLabel: string) => {\n if (!bridge || !registered) return;\n const changed = bridge.registry.updateElementMeta(id, {\n label: newLabel,\n accessibilityLabel: newLabel,\n testId: id,\n });\n // The hook now auto-publishes the `label` option (see the effect above),\n // so a consumer that ALSO drives `updateLabel(label)` from its own\n // `useEffect` will legitimately observe a no-op every time. Warning there\n // would fire on every correct pre-existing call site, so the warning is\n // scoped to the case it was written for: a redundant publish of a string\n // the SDK did NOT just publish itself.\n const alreadyPublishedBySdk = newLabel === autoPublishedLabelRef.current;\n if (!changed && !alreadyPublishedBySdk && !warnedRedundantUpdateLabelIds.has(id)) {\n warnedRedundantUpdateLabelIds.add(id);\n console.warn(\n `[UI Bridge] updateLabel(\"${newLabel}\") on element \"${id}\" was a no-op (label unchanged). Gate the call behind a useEffect with [label] deps to avoid redundant publishes.`\n );\n }\n },\n [bridge, registered, id]\n );\n\n // Update style for design review\n const updateStyle = useCallback(\n (\n newStyle: unknown,\n newStateStyles?: { pressed?: unknown; focused?: unknown; disabled?: unknown }\n ) => {\n if (!bridge || !registered) return;\n const flat = flattenStyle(newStyle);\n if (flat) {\n bridge.registry.updateElementStyle(id, flat, flattenStateStyles(newStateStyles));\n }\n },\n [bridge, registered, id]\n );\n\n // Get registered element\n const registeredElement = useMemo(() => {\n if (!bridge) return null;\n return bridge.registry.getElement(id) || null;\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [bridge, id, registered]);\n\n return {\n ref,\n onLayout,\n bridgeProps,\n registered,\n getState,\n getIdentifier,\n trigger,\n register,\n unregister,\n registeredElement,\n updateStyle,\n updateLabel,\n };\n}\n\n/**\n * useUIElementWithProps hook\n *\n * Extended version that also captures component props for action execution.\n * Useful when you need the bridge to be able to call onPress, onChangeText, etc.\n *\n * @example\n * ```tsx\n * function TextInputField({ onChangeText, value }) {\n * const { ref, onLayout, bridgeProps, captureProps } = useUIElementWithProps({\n * id: 'email-input',\n * type: 'input',\n * });\n *\n * // Capture props so bridge can call onChangeText\n * captureProps({ onChangeText, value });\n *\n * return (\n * <TextInput\n * ref={ref}\n * onLayout={onLayout}\n * {...bridgeProps}\n * value={value}\n * onChangeText={onChangeText}\n * />\n * );\n * }\n * ```\n */\nexport interface UseUIElementWithPropsReturn extends UseUIElementReturn {\n /** Capture props for action execution */\n captureProps: (props: Record<string, unknown>) => void;\n}\n\n/**\n * Loose options for `useUIElementWithProps` — `handlers` is optional for ALL\n * element types because the consumer will later call `captureProps({ onPress,\n * ... })` from the render body. The runtime warning in {@link useUIElement}\n * still backstops the \"captured but never called with onPress\" case.\n */\nexport type UseUIElementWithPropsOptions<T extends NativeElementType = NativeElementType> =\n UseUIElementOptionsHandlersOptional<T>;\n\nexport function useUIElementWithProps<T extends NativeElementType = NativeElementType>(\n options: UseUIElementWithPropsOptions<T>\n): UseUIElementWithPropsReturn {\n // `useUIElement`'s narrow public signature demands `handlers.onPress` for\n // press-needing types, but the whole point of this hook is to capture\n // props after the fact (via `captureProps` returned below) — so we widen\n // through `unknown`. The runtime warning in `useUIElement` still fires if\n // no onPress ever lands in the registry, regardless of the cast.\n const elementReturn = useUIElement(options as unknown as UseUIElementOptions<'view'>);\n const bridge = useUIBridgeNativeOptional();\n\n const captureProps = useCallback(\n (props: Record<string, unknown>) => {\n if (bridge && elementReturn.registered) {\n bridge.registry.updateElementProps(options.id, props);\n }\n },\n [bridge, elementReturn.registered, options.id]\n );\n\n return {\n ...elementReturn,\n captureProps,\n };\n}\n","/**\n * useUIComponent Hook for React Native\n *\n * Register a component with UI Bridge for component-level actions.\n */\n\nimport { useEffect, useCallback, useRef, useState } from 'react';\nimport type { IREffect, RegisteredNativeComponent } from '../core/types';\nimport { useUIBridgeNativeOptional } from './UIBridgeNativeProvider';\n\n/**\n * Action definition for useUIComponent\n */\nexport interface ComponentActionDef<TParams = unknown, TResult = unknown> {\n /** Action identifier */\n id: string;\n /** Human-readable label */\n label?: string;\n /** Description */\n description?: string;\n /**\n * Parameter schema — **serialized, published to agents, and VALIDATED.**\n *\n * It is spread onto `/control/components` and `/control/component/:id`, and\n * four `qontinui-runner` consumers read it from there — including the LLM\n * router that generates a slash command's args from it. Since Phase 2 of\n * plan `2026-08-20-ui-bridge-action-declaration-shape` the invocation seam\n * checks `params` against it BEFORE your handler runs, so a schema declared\n * here is a promise the runtime keeps.\n *\n * (The doc this replaces promised both halves of a contradiction: the schema\n * is \"surfaced verbatim on `/control/component/:id`\" AND \"No runtime\n * validation is performed.\" The first half was always true; the second is no\n * longer.)\n *\n * Two accepted shapes:\n *\n * - **Object-schema form** — `{ type: 'object', properties: { ... },\n * required: ['...'], additionalProperties: false }`. The only form that can\n * express *requiredness*. `paramSchemaOf()` from\n * `@qontinui/ui-bridge-wrapper` emits it for you.\n * - **Map form** — `{ paramName: 'string', other: { type: 'number' } }`. A\n * TYPE hint only: it cannot mark anything required, and a string that is\n * not one of the seven JSON Schema primitive names (`string`, `number`,\n * `integer`, `boolean`, `object`, `array`, `null`) is read as prose and\n * constrains nothing — which is what keeps the fleet's many\n * `{ count: 'number (>= 1, defaults to 1)' }` hint maps working.\n *\n * Recognised keywords: `type`, `enum`, `const`, `properties`, `required`,\n * `additionalProperties: false`, `items`, `minimum`/`maximum`,\n * `minLength`/`maxLength`, `pattern`. **Anything else is ignored, never\n * rejected** — a schema richer than the subset is still valid JSON Schema,\n * it just expresses fewer enforced constraints. No type coercion: `\"5\"` does\n * not satisfy `{ type: 'number' }`.\n *\n * Enforcement is a deployment setting and defaults to `'warn'` — violations\n * are logged and the handler still runs until someone calls\n * `setDefaultParamValidationMode('enforce')`. The full grammar, and why warn\n * is the default, are documented at `core/param-schema.ts`.\n */\n paramSchema?: Record<string, unknown>;\n /**\n * Safety annotation — `'read' | 'write' | 'destructive'` (Phase 4 of plan\n * `2026-08-20-ui-bridge-action-declaration-shape`).\n *\n * **Declare `'destructive'` on anything irreversible** — a delete, a send, a\n * charge, a deploy. It is the one value nothing can infer for you: the\n * static verb map behind this field never produces `'destructive'`, because\n * destructiveness depends on what your control does, not on what it is\n * called. An autonomous walk excludes destructive actions and walks\n * everything else, so an unmarked delete control gets pressed.\n *\n * **Precedence:** what you write here wins, and it is the **only** thing\n * that reaches the wire. `NATIVE_STANDARD_ACTION_EFFECTS` supplies a default\n * when the action `id` happens to be one of the native standard verbs\n * (`press`, `longPress`, `swipe`, …), but that default is applied **by the\n * consumer**, via the exported `resolveActionEffect()` — the SDK does *not*\n * stamp it onto the response. Leave this undefined and the field is simply\n * **absent** from every projection, which is the honest encoding of \"nobody\n * classified this action\" (see `core/action-effect.ts` for why a\n * server-applied default would fail open).\n */\n effect?: IREffect;\n /**\n * Handler function.\n *\n * The second argument is the `ActionHandlerOptions` bag whose `signal` is\n * aborted when the caller cancels or the request's `timeoutMs` elapses\n * (Phase 3 of plan `2026-08-20-ui-bridge-action-declaration-shape`).\n * Observing it is optional: the executor races this promise against the\n * abort, so an unobservant handler is abandoned anyway — observing it is how\n * a handler releases its own in-flight work instead of leaving it detached.\n */\n handler: (params?: TParams, options?: { signal?: AbortSignal }) => TResult | Promise<TResult>;\n}\n\n/**\n * useUIComponent options\n */\nexport interface UseUIComponentOptions {\n /** Unique identifier for the component */\n id: string;\n /** Human-readable name */\n name: string;\n /** Description */\n description?: string;\n /** Actions available on this component */\n actions?: ComponentActionDef[];\n /** Child element IDs owned by this component */\n elementIds?: string[];\n /** Whether to automatically register on mount */\n autoRegister?: boolean;\n}\n\n/**\n * useUIComponent return value\n */\nexport interface UseUIComponentReturn {\n /** Whether the component is registered */\n registered: boolean;\n /** Execute an action on this component */\n executeAction: <TParams = unknown, TResult = unknown>(\n actionId: string,\n params?: TParams\n ) => Promise<TResult>;\n /** Manually register the component */\n register: () => void;\n /** Manually unregister the component */\n unregister: () => void;\n /**\n * Publish an action list that is NOT the `actions` option.\n *\n * **Not required for the common case any more.** The `actions` OPTION passed\n * to `useUIComponent({ id, actions })` is now auto-re-published whenever its\n * published shape changes, so a state-derived action list — a label carrying\n * a count, an action that only exists while a row is selected, a\n * `paramSchema` that widens once options load — reaches\n * `/control/components` without a call site doing anything. This is the\n * escape hatch for actions the hook does not own, the same role `updateLabel`\n * plays for `useUIElement`.\n *\n * If you pass BOTH the `actions` option and call this, the option wins on the\n * next render that changes its signature: the declarative lane is the one the\n * republish effect re-asserts.\n */\n updateActions: (actions: ComponentActionDef[]) => void;\n /**\n * Add an element ID to this component. Published to the registry\n * immediately — this used to write to a private ref and stop there, so the\n * ownership list an agent read never moved.\n *\n * Survives re-renders. It is replaced only when the DECLARED `elementIds`\n * option itself changes value, which is the point at which the call site has\n * said something newer than the imperative edit.\n */\n addElement: (elementId: string) => void;\n /** Remove an element ID from this component. Same publishing rules as {@link addElement}. */\n removeElement: (elementId: string) => void;\n /**\n * The registered component as the registry currently holds it — `null` until\n * registration commits, then refreshed on every republish that changes the\n * published shape.\n */\n registeredComponent: RegisteredNativeComponent | null;\n}\n\n/**\n * useUIComponent hook for React Native\n *\n * Registers a component with UI Bridge for component-level control.\n * Components can expose high-level actions that may orchestrate multiple element interactions.\n *\n * @example\n * ```tsx\n * function LoginForm() {\n * const [email, setEmail] = useState('');\n * const [password, setPassword] = useState('');\n *\n * useUIComponent({\n * id: 'login-form',\n * name: 'Login Form',\n * actions: [\n * {\n * id: 'login',\n * label: 'Submit Login',\n * handler: async ({ email, password }) => {\n * setEmail(email);\n * setPassword(password);\n * await submitLogin();\n * },\n * },\n * {\n * id: 'clear',\n * label: 'Clear Form',\n * handler: () => {\n * setEmail('');\n * setPassword('');\n * },\n * },\n * ],\n * });\n *\n * return (\n * <View>\n * <TextInput value={email} onChangeText={setEmail} />\n * <TextInput value={password} onChangeText={setPassword} secureTextEntry />\n * <Button title=\"Login\" onPress={handleSubmit} />\n * </View>\n * );\n * }\n * ```\n */\nexport function useUIComponent(options: UseUIComponentOptions): UseUIComponentReturn {\n const bridge = useUIBridgeNativeOptional();\n // `registeredRef` is authoritative for the register/unregister guard (same\n // rationale as `useUIElement`: threading the state into the register\n // callback's deps builds a cleanup/run feedback loop). `registered` is the\n // rendered mirror — the value this hook RETURNS, which used to be\n // `registeredRef.current` and so was read during render before any effect had\n // set it: it was `false` on the first render and only ever changed if\n // something unrelated re-rendered the consumer.\n const [registered, setRegistered] = useState(false);\n // Bumped whenever the registry's copy of this component demonstrably changed,\n // to force the render-phase read of `registeredComponent` below to re-run.\n //\n // A version counter rather than holding the entry itself in state, and that is\n // load-bearing. `registerComponent` returns a FRESH object every call, so\n // storing it would re-render on every registration — and a provider whose\n // context value churns per render re-registers every element on every render,\n // which would then be an unbounded loop instead of the bounded registry churn\n // it is today. PR #179 fixed that churn at the provider, but this hook should\n // not be the thing that turns a provider bug into a hang. Hence\n // `publishedIdRef`: a re-registration under an UNCHANGED id bumps nothing.\n const [publishVersion, setPublishVersion] = useState(0);\n const publishedIdRef = useRef<string | null>(null);\n const registeredRef = useRef(false);\n const registeredIdRef = useRef<string | null>(null);\n const actionsRef = useRef(options.actions || []);\n const elementIdsRef = useRef(options.elementIds || []);\n\n const { id, name, description, autoRegister = true } = options;\n\n // Value signatures of the DECLARED lists. The arrays themselves are freshly\n // allocated on essentially every render at every call site, so their identity\n // says nothing; these say whether anything a bridge consumer can SEE moved.\n // `handler` is excluded for the same reason the registry excludes it (see\n // `publishedActionSignature`) — it is never published, and it changes every\n // render.\n const actionsSignature = JSON.stringify(\n (options.actions ?? []).map((a) => [a.id, a.label, a.description, a.paramSchema, a.effect])\n );\n const elementIdsSignature = JSON.stringify(options.elementIds ?? []);\n\n // Track the declared `actions` on every render, so the trampoline below always\n // resolves to the CURRENT closure. Only when the option is actually SUPPLIED:\n // overwriting unconditionally — which is what `options.actions || []` did —\n // wipes an action list installed through the imperative `updateActions` lane\n // on the very next render of a call site that declares no `actions` option.\n useEffect(() => {\n if (options.actions !== undefined) actionsRef.current = options.actions;\n }, [options.actions]);\n\n // `elementIds` carries no closures, so it is re-asserted only when the\n // DECLARED value actually changes. Doing it every render instead would undo\n // `addElement` / `removeElement` on the next render of any call site that\n // declares an `elementIds` option AND adds to it — the two lanes would fight,\n // and the imperative one would appear to work and then silently revert.\n useEffect(() => {\n if (options.elementIds !== undefined) elementIdsRef.current = options.elementIds;\n // Keyed on the value signature, not the array identity, which is freshly\n // allocated on every render at every call site.\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [elementIdsSignature]);\n\n // Map the declared actions into the registry's shape.\n //\n // The handler is a trampoline that resolves through `actionsRef.current` at\n // INVOKE time. Without it the registry holds the closure from the render that\n // registered the component, for the life of the mount — so an action handler\n // reading component state read that state as it was at mount, and\n // `updateActions` was the only escape from a staleness nothing announced.\n //\n // Everything else is spread rather than re-listed field by field. The\n // hand-rolled list this replaces is the exact silent-drop trap this file's own\n // comments recorded twice (`paramSchema` in Phase 2, `effect` in Phase 4): a\n // field added to `ComponentActionDef` stayed assignable here and simply never\n // arrived. The registry closes the field list once, on the way in; a second\n // closed list here is only a second place to forget.\n const toRegistryActions = useCallback(\n () =>\n actionsRef.current.map(({ handler: declaredHandler, ...rest }) => ({\n ...rest,\n handler: (params?: unknown, handlerOptions?: { signal?: AbortSignal }) => {\n const latest = actionsRef.current.find((a) => a.id === rest.id);\n return (latest?.handler ?? declaredHandler)(params, handlerOptions);\n },\n })),\n []\n );\n\n // Register the component\n const register = useCallback(() => {\n if (!bridge || registeredRef.current) return;\n\n bridge.registry.registerComponent(id, {\n name,\n description,\n actions: toRegistryActions(),\n elementIds: elementIdsRef.current,\n });\n registeredRef.current = true;\n registeredIdRef.current = id;\n setRegistered(true);\n // Only when the id this hook has PUBLISHED actually moved. A re-registration\n // under the same id produces an entry a consumer cannot tell apart from the\n // one it already has, so it is not worth a render — and skipping it is what\n // keeps a churning provider from spinning this hook forever.\n if (publishedIdRef.current !== id) {\n publishedIdRef.current = id;\n setPublishVersion((v) => v + 1);\n }\n }, [bridge, id, name, description, toRegistryActions]);\n\n // Unregister the component\n const unregister = useCallback(() => {\n if (!bridge || !registeredRef.current) return;\n\n bridge.registry.unregisterComponent(registeredIdRef.current ?? id);\n registeredRef.current = false;\n registeredIdRef.current = null;\n setRegistered(false);\n // `publishedIdRef` is deliberately NOT cleared here. It records the id whose\n // registration the render-phase read has already been told about, and\n // clearing it would re-arm the bump in `register()` � which is exactly the\n // unbounded loop this guard exists to prevent, since a provider with a\n // churning context value runs unregister+register on every render. Going\n // un-registered is already visible through `registered` flipping to false.\n }, [bridge, id]);\n\n // Execute an action\n const executeAction = useCallback(\n async <TParams = unknown, TResult = unknown>(\n actionId: string,\n params?: TParams\n ): Promise<TResult> => {\n if (!bridge) {\n throw new Error('UI Bridge Native not available');\n }\n\n const response = await bridge.executor.executeComponentAction(id, {\n action: actionId,\n params: params as Record<string, unknown>,\n });\n\n if (!response.success) {\n throw new Error(response.error || 'Action failed');\n }\n\n return response.result as TResult;\n },\n [bridge, id]\n );\n\n // Publish whatever `elementIdsRef` now holds. Shared by `addElement` and\n // `removeElement`, which BOTH used to mutate the ref and stop there — the\n // registry kept its mount-time `elementIds` and the component's ownership\n // list, as read from `/control/components`, was a fossil. The hook returned\n // two functions that did nothing observable.\n const publishElementIds = useCallback(() => {\n if (!registeredRef.current || !bridge) return;\n const changed = bridge.registry.updateComponentMeta(registeredIdRef.current ?? id, {\n elementIds: elementIdsRef.current,\n });\n if (changed) {\n setPublishVersion((v) => v + 1);\n }\n }, [bridge, id]);\n\n // Update actions dynamically\n const updateActions = useCallback(\n (actions: ComponentActionDef[]) => {\n actionsRef.current = actions;\n\n // Publish in place. This used to unregister and re-register, which emitted\n // a spurious `component:unregistered`/`component:registered` pair and left\n // the component ABSENT from the registry for the width of the call — a\n // snapshot taken in that window reported a component the app had not\n // stopped rendering.\n if (registeredRef.current && bridge) {\n const targetId = registeredIdRef.current ?? id;\n const changed = bridge.registry.updateComponentMeta(targetId, {\n actions: toRegistryActions(),\n });\n if (changed) {\n setPublishVersion((v) => v + 1);\n }\n }\n },\n [bridge, id, toRegistryActions]\n );\n\n // Add element ID\n const addElement = useCallback(\n (elementId: string) => {\n if (!elementIdsRef.current.includes(elementId)) {\n elementIdsRef.current = [...elementIdsRef.current, elementId];\n publishElementIds();\n }\n },\n [publishElementIds]\n );\n\n // Remove element ID\n const removeElement = useCallback(\n (elementId: string) => {\n if (!elementIdsRef.current.includes(elementId)) return;\n elementIdsRef.current = elementIdsRef.current.filter((eid) => eid !== elementId);\n publishElementIds();\n },\n [publishElementIds]\n );\n\n // Keep latest register/unregister in refs so the auto-register effect does\n // not re-run when consumers pass inline options.\n const registerRef = useRef(register);\n const unregisterRef = useRef(unregister);\n useEffect(() => {\n registerRef.current = register;\n unregisterRef.current = unregister;\n }, [register, unregister]);\n\n // Auto-register on mount, and RE-register when `id` changes.\n //\n // `id` is a real dependency even though the effect body never reads it, for\n // the same reason `useUIElement`'s effect lists it: without it the effect\n // never re-ran on an id change, so the OLD id stayed registered forever and\n // the NEW id was never registered at all. `registeredIdRef` existed to name\n // the old id during teardown and could never actually differ from `id`,\n // because nothing re-ran the effect — the field was dead for want of this dep.\n //\n // Ordering on an id-change render: the cleanup runs first, closing over the\n // PREVIOUS `unregisterRef.current`, which removes `registeredIdRef.current` —\n // the OLD id — and resets the guard. The ref-sync effect above is declared\n // first, so by the time this body re-runs, `registerRef.current` registers the\n // NEW id.\n useEffect(() => {\n if (autoRegister) {\n registerRef.current();\n }\n\n return () => {\n if (registeredRef.current) {\n unregisterRef.current();\n }\n };\n }, [autoRegister, bridge, id]);\n\n // Keep the registry's copy of the declaration in step with the OPTIONS —\n // automatically.\n //\n // ROOT CAUSE this closes, and it is PR #176's defect one level up:\n // `register()` publishes name / description / actions / elementIds exactly\n // once and is guarded by `registeredRef`, while the auto-register effect\n // re-runs only on `[autoRegister, bridge, id]`. So a component whose\n // declaration is derived from state — an action label carrying a count, an\n // action that exists only while a row is selected, a `paramSchema` that widens\n // once options load — published its mount-time shape to `/control/components`\n // for the life of the mount. `updateActions` was the manual escape hatch, the\n // same shape `updateLabel` was for elements before #176 auto-published the\n // `label` option.\n //\n // Only the fields the call site actually DECLARES are re-asserted: a hook used\n // purely imperatively (no `actions` / `elementIds` option) must not have its\n // `updateActions` / `addElement` work overwritten by an empty declarative\n // lane.\n //\n // Gated on `registered` rather than `registeredRef` so it runs on the commit\n // that FOLLOWS registration, and keyed on the value signatures rather than the\n // arrays, whose identity churns every render.\n useEffect(() => {\n if (!bridge || !registered) return;\n const targetId = registeredIdRef.current ?? id;\n const changed = bridge.registry.updateComponentMeta(targetId, {\n name,\n description,\n ...(options.actions !== undefined ? { actions: toRegistryActions() } : {}),\n ...(options.elementIds !== undefined ? { elementIds: elementIdsRef.current } : {}),\n });\n if (changed) {\n setPublishVersion((v) => v + 1);\n }\n // `actionsSignature` / `elementIdsSignature` stand in for the arrays they\n // summarise; the arrays themselves are deliberately NOT deps, since their\n // identity changes on every render at every call site.\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [\n bridge,\n registered,\n id,\n name,\n description,\n actionsSignature,\n elementIdsSignature,\n toRegistryActions,\n ]);\n\n // Read straight out of the registry during render, rather than mirroring the\n // entry into state.\n //\n // The registry is the owner; a copy held in state is a second one that can\n // disagree. `publishVersion` is what makes this read re-run � it is bumped\n // exactly when the registry's copy demonstrably changed, so this value is as\n // fresh as the last publish and costs one `Map.get` per render.\n //\n // Pre-fix this was a `useMemo` on `[bridge, id]`, which ran BEFORE the\n // register effect on the first render and never recomputed: permanently\n // `null` for every consumer that read it.\n void publishVersion;\n const registeredComponent =\n registered && bridge ? (bridge.registry.getComponent(id) ?? null) : null;\n\n return {\n registered,\n executeAction,\n register,\n unregister,\n updateActions,\n addElement,\n removeElement,\n registeredComponent,\n };\n}\n\n/**\n * useUIComponentAction hook\n *\n * Create a stable action handler that can be used with useUIComponent.\n * Useful for memoizing action handlers.\n */\nexport function useUIComponentAction<TParams = unknown, TResult = unknown>(\n handler: (params?: TParams, options?: { signal?: AbortSignal }) => TResult | Promise<TResult>,\n deps: React.DependencyList\n): (params?: TParams, options?: { signal?: AbortSignal }) => TResult | Promise<TResult> {\n // eslint-disable-next-line react-hooks/exhaustive-deps\n return useCallback(handler, deps);\n}\n","/**\n * useUIBridge Hook for React Native\n *\n * Provides a simplified interface for common UI Bridge operations.\n */\n\nimport { useCallback, useMemo } from 'react';\nimport type {\n NativeActionRequest,\n NativeActionResponse,\n NativeFindRequest,\n NativeFindResponse,\n NativeBridgeSnapshot,\n RegisteredNativeElement,\n RegisteredNativeComponent,\n Workflow,\n} from '../core/types';\nimport type { ComponentActionRequest, ComponentActionResponse } from '../control/types';\nimport { useUIBridgeNativeOptional } from './UIBridgeNativeProvider';\n\n/**\n * Component action request / response.\n *\n * Re-exported from `../control/types` rather than re-declared. These were a\n * fifth and sixth copy of a shape that already existed there, and the copy had\n * already drifted: it carried neither `requestId` nor `timeoutMs`, so a React\n * Native caller reaching an action through this hook could not set a timeout\n * even though `DefaultNativeActionExecutor` has honoured one since Phase 3 of\n * plan `2026-08-20-ui-bridge-action-declaration-shape`. The executor accepted\n * it; the hook's own type refused to express it.\n *\n * `timeoutMs` is the only cancellation this seam can carry — an `AbortSignal`\n * is not JSON-serializable, and the hook does not forward the executor's\n * in-process `{ signal }` option bag.\n *\n * Collapsing rather than adding the two fields is the plan's stated direction:\n * \"collapse before you extend\", because eight copies drift and two already\n * had.\n */\nexport type {\n ComponentActionRequest,\n ComponentActionResponse,\n} from '../control/types';\n\n/**\n * useUIBridge return type\n */\nexport interface UseUIBridgeReturn {\n /** Whether UI Bridge is available */\n available: boolean;\n /** Whether UI Bridge is initialized */\n initialized: boolean;\n /** All registered elements */\n elements: RegisteredNativeElement[];\n /** All registered components */\n components: RegisteredNativeComponent[];\n /** All registered workflows */\n workflows: Workflow[];\n /** Create a snapshot of the current state */\n createSnapshot: () => NativeBridgeSnapshot;\n /** Execute an action on an element */\n executeAction: (elementId: string, request: NativeActionRequest) => Promise<NativeActionResponse>;\n /** Execute a component action */\n executeComponentAction: (\n componentId: string,\n request: ComponentActionRequest\n ) => Promise<ComponentActionResponse>;\n /** Find elements */\n find: (request?: NativeFindRequest) => Promise<NativeFindResponse>;\n /** Get an element by ID */\n getElement: (id: string) => RegisteredNativeElement | undefined;\n /** Get a component by ID */\n getComponent: (id: string) => RegisteredNativeComponent | undefined;\n /** Get element state by ID */\n getElementState: (id: string) => ReturnType<RegisteredNativeElement['getState']> | null;\n /** Register a workflow */\n registerWorkflow: (workflow: Workflow) => void;\n /** Unregister a workflow */\n unregisterWorkflow: (id: string) => void;\n}\n\n/**\n * useUIBridge hook\n *\n * Provides a simplified interface for accessing UI Bridge functionality.\n *\n * @example\n * ```tsx\n * function MyComponent() {\n * const { available, elements, executeAction, find } = useUIBridge();\n *\n * if (!available) {\n * return <Text>UI Bridge not available</Text>;\n * }\n *\n * const handlePress = async () => {\n * // Find all buttons\n * const result = await find({ types: ['button'] });\n * console.log('Found buttons:', result.elements);\n *\n * // Execute action on specific element\n * await executeAction('submit-btn', { action: 'press' });\n * };\n *\n * return (\n * <View>\n * <Text>Elements: {elements.length}</Text>\n * <Button title=\"Press\" onPress={handlePress} />\n * </View>\n * );\n * }\n * ```\n */\nexport function useUIBridge(): UseUIBridgeReturn {\n const bridge = useUIBridgeNativeOptional();\n\n const available = bridge !== null;\n const initialized = bridge?.initialized ?? false;\n\n // Get elements\n const elements = useMemo(() => (bridge ? bridge.getElements() : []), [bridge]);\n\n // Get components\n const components = useMemo(() => (bridge ? bridge.getComponents() : []), [bridge]);\n\n // Get workflows\n const workflows = useMemo(() => (bridge ? bridge.registry.getAllWorkflows() : []), [bridge]);\n\n // Create snapshot\n const createSnapshot = useCallback((): NativeBridgeSnapshot => {\n if (!bridge) {\n return {\n timestamp: Date.now(),\n elements: [],\n components: [],\n workflows: [],\n };\n }\n return bridge.createSnapshot();\n }, [bridge]);\n\n // Execute action\n const executeAction = useCallback(\n async (elementId: string, request: NativeActionRequest): Promise<NativeActionResponse> => {\n if (!bridge) {\n return {\n success: false,\n error: 'UI Bridge not available',\n durationMs: 0,\n timestamp: Date.now(),\n };\n }\n return bridge.executor.executeAction(elementId, request);\n },\n [bridge]\n );\n\n // Execute component action\n const executeComponentAction = useCallback(\n async (\n componentId: string,\n request: ComponentActionRequest\n ): Promise<ComponentActionResponse> => {\n if (!bridge) {\n return {\n success: false,\n error: 'UI Bridge not available',\n durationMs: 0,\n timestamp: Date.now(),\n };\n }\n return bridge.executor.executeComponentAction(componentId, request);\n },\n [bridge]\n );\n\n // Find elements\n const find = useCallback(\n async (request?: NativeFindRequest): Promise<NativeFindResponse> => {\n if (!bridge) {\n return {\n elements: [],\n total: 0,\n durationMs: 0,\n timestamp: Date.now(),\n };\n }\n return bridge.executor.find(request || {});\n },\n [bridge]\n );\n\n // Get element\n const getElement = useCallback((id: string) => bridge?.registry.getElement(id), [bridge]);\n\n // Get component\n const getComponent = useCallback((id: string) => bridge?.registry.getComponent(id), [bridge]);\n\n // Get element state\n const getElementState = useCallback(\n (id: string) => {\n const element = bridge?.registry.getElement(id);\n return element?.getState() ?? null;\n },\n [bridge]\n );\n\n // Register workflow\n const registerWorkflow = useCallback(\n (workflow: Workflow) => {\n bridge?.registry.registerWorkflow(workflow);\n },\n [bridge]\n );\n\n // Unregister workflow\n const unregisterWorkflow = useCallback(\n (id: string) => {\n bridge?.registry.unregisterWorkflow(id);\n },\n [bridge]\n );\n\n return {\n available,\n initialized,\n elements,\n components,\n workflows,\n createSnapshot,\n executeAction,\n executeComponentAction,\n find,\n getElement,\n getComponent,\n getElementState,\n registerWorkflow,\n unregisterWorkflow,\n };\n}\n\n/**\n * useUIBridgeRequired hook\n *\n * Same as useUIBridge but throws if not available.\n */\nexport function useUIBridgeRequired(): UseUIBridgeReturn {\n const result = useUIBridge();\n if (!result.available) {\n throw new Error('useUIBridgeRequired must be used within a UIBridgeNativeProvider');\n }\n return result;\n}\n","import { useEffect } from 'react';\nimport { useUIBridgeNative } from './UIBridgeNativeProvider';\nimport type { NativeModalInfo } from '../core/types';\n\nexport interface UseUIBridgeModalOptions {\n id: string;\n title?: string;\n type?: NativeModalInfo['type'];\n blocking?: boolean;\n dismissible?: boolean;\n}\n\n/**\n * Declarative hook: while mounted, registers a modal entry on the active\n * stack so UI Bridge snapshots reflect that a modal is open.\n */\nexport function useUIBridgeModal(opts: UseUIBridgeModalOptions): void {\n const { modalDetector } = useUIBridgeNative();\n const { id, title, type, blocking, dismissible } = opts;\n\n useEffect(() => {\n modalDetector.pushModal({ id, title, type, blocking, dismissible });\n return () => {\n modalDetector.dismissModal(id);\n };\n }, [modalDetector, id, title, type, blocking, dismissible]);\n}\n","import { useCallback, useEffect } from 'react';\nimport { useUIBridgeNative } from './UIBridgeNativeProvider';\nimport type { NativeCapturedToast } from '../core/types';\n\nexport interface UseUIBridgeToastOptions {\n id: string;\n message: string;\n level?: NativeCapturedToast['level'];\n}\n\n/**\n * Declarative hook: while mounted, surfaces a toast via the snapshot enricher.\n * Best for explicit-lifecycle toast components.\n */\nexport function useUIBridgeToast(opts: UseUIBridgeToastOptions): void {\n const { toastCapture } = useUIBridgeNative();\n const { id, message, level } = opts;\n\n useEffect(() => {\n toastCapture.recordToast({ id, message, level });\n return () => {\n toastCapture.dismissToast(id);\n };\n }, [toastCapture, id, message, level]);\n}\n\nexport interface ToastRecorderInput {\n id: string;\n message: string;\n level?: NativeCapturedToast['level'];\n}\n\n/**\n * Imperative hook: returns a `recordToast` callback for code that fires\n * toasts outside React (catch blocks, library callbacks, etc.).\n */\nexport function useToastRecorder(): {\n recordToast: (toast: ToastRecorderInput) => void;\n dismissToast: (id: string) => void;\n} {\n const { toastCapture } = useUIBridgeNative();\n const recordToast = useCallback(\n (toast: ToastRecorderInput) => {\n toastCapture.recordToast(toast);\n },\n [toastCapture]\n );\n const dismissToast = useCallback((id: string) => toastCapture.dismissToast(id), [toastCapture]);\n return { recordToast, dismissToast };\n}\n","import type { ReactElement, ReactNode } from 'react';\n\nexport interface StateAnnotationRequiredElement {\n role?: string;\n text?: string;\n testID?: string;\n [key: string]: unknown;\n}\n\nexport interface StateProps {\n id: string;\n name?: string;\n description?: string;\n requiredElements?: StateAnnotationRequiredElement[];\n blocking?: boolean;\n children?: ReactNode;\n [key: string]: unknown;\n}\n\nexport function State(props: StateProps): ReactElement {\n return <>{props.children}</>;\n}\n\nexport interface TransitionToProps {\n id: string;\n name?: string;\n fromStates?: string[];\n activateStates?: string[];\n exitStates?: string[];\n effect?: string;\n description?: string;\n children?: ReactNode;\n [key: string]: unknown;\n}\n\nexport function TransitionTo(props: TransitionToProps): ReactElement {\n return <>{props.children}</>;\n}\n","/**\n * UI Bridge Native Server Types\n *\n * Types for the embedded HTTP server.\n */\n\nimport type {\n NativeUIBridgeConfig,\n NativeActionResponse,\n NativeFindResponse,\n NativeBridgeSnapshot,\n} from '../core/types';\nimport type { ComponentActionResponse, PageNavigationResponse } from '../control/types';\nimport type { ElementDesignData, StateStyles, ResponsiveSnapshot } from '../design/design-types';\n\n/**\n * Navigation provider for React Native apps.\n *\n * Apps supply this to enable programmatic navigation via the UI Bridge\n * (e.g., `control/page/navigate` and `control/page/back`).\n * For Expo Router: pass `router.push` and `router.back`.\n */\nexport interface NavigationProvider {\n navigate: (url: string) => void;\n back?: () => void;\n /** Replace current route (no back-stack entry). For Expo Router: router.replace */\n replace?: (url: string) => void;\n /** Refresh the current route. For Expo Router: router.replace(currentPath) */\n refresh?: () => void;\n}\n\n/**\n * Screenshot provider for React Native apps.\n *\n * Apps supply this to enable screen capture via the UI Bridge\n * (`control/screenshot`). For react-native-view-shot: pass a function\n * that calls `captureRef` on the root view and returns base64 PNG data.\n */\nexport interface ScreenshotProvider {\n /** Capture the current screen and return base64-encoded PNG data (no data: prefix). */\n capture: () => Promise<{ base64: string; width: number; height: number }>;\n}\n\n/** Device keep-awake capability, injected by the host app (expo-keep-awake is mobile-only). */\nexport interface KeepAwakeProvider {\n request(source: string, durationMs?: number): void;\n release(source: string): void;\n}\n\n/**\n * Route provider for React Native apps.\n *\n * Apps supply this to expose the current navigation route in UI Bridge snapshots.\n * For Expo Router: render a RouteTracker component inside the router context that\n * calls `usePathname()` / `useSegments()` and writes the result to a module-level ref.\n */\nexport interface RouteProvider {\n /** Return the current route path (e.g. \"/(tabs)/runs\"), or null if unknown. */\n getCurrentRoute: () => string | null;\n /** Return the current route segments (e.g. [\"(tabs)\", \"runs\"]), if available. */\n getSegments?: () => string[];\n /**\n * Optionally return the currently-active tab id for the snapshot's\n * `activeTab` field. Only needed when the visible pane is decoupled from the\n * router; Expo Router apps can omit it and let the registry derive the value\n * from `getSegments()`.\n */\n getActiveTab?: () => string | null | undefined;\n /**\n * Subscribe to route changes. Required so the UI Bridge can clear stale\n * layouts on route changes with zero lag.\n *\n * Implementers must invoke `listener` synchronously whenever the route\n * changes, passing the new route (or null if unknown). The returned function\n * must unsubscribe the listener.\n *\n * For Expo Router: wrap your RouteTracker component in a module-level\n * listener set and call each listener from within the tracker's effect.\n */\n subscribe: (listener: (route: string | null) => void) => () => void;\n}\n\n/**\n * Server configuration\n */\nexport interface NativeServerConfig extends NativeUIBridgeConfig {\n /** Enable CORS */\n cors?: boolean;\n /** Allowed origins for CORS */\n allowedOrigins?: string[];\n /**\n * Enable test-only HTTP endpoints (currently `control/modal/push` and\n * `control/modal/dismiss/:id`) so external runners can drive registry\n * state. Default `false`; the React provider mirrors\n * `features.testHooks` into this slot.\n */\n testHooks?: boolean;\n /**\n * Enable the read-only observability capture (console.error/warn +\n * fetch/XHR ring buffers backing `GET /control/console-errors` and\n * `GET /sdk/network-requests`). When omitted, falls back to the\n * `testHooks` value so existing consumers are unchanged; set explicitly\n * to decouple release-build capture from the testHooks-gated control\n * surface. The React provider mirrors `features.observability` into\n * this slot.\n */\n observability?: boolean;\n /**\n * Viewport getter for `POST /control/page-health`.\n *\n * Injected by `UIBridgeNativeProvider` from `Dimensions.get('window')`.\n * Lives at config-injection level because importing react-native from\n * `handlers.ts` (or even `require('react-native')` with try/catch) crashed\n * the host RN app in 0.6.3/0.6.4: Metro/Hermes raised\n * `unknownModuleError` past every local try/catch and tore down the JS\n * thread (blank screen, React tree destroyed). The provider already has\n * a live import of `react-native`, so it's the safe injection point.\n *\n * When absent: `page-health` falls back to `body.viewport`, then `{0,0}`\n * (degenerate coverage report — no crash).\n */\n viewportProvider?: () => { width: number; height: number };\n}\n\n/**\n * Route definition\n */\nexport interface RouteDefinition {\n method: 'GET' | 'POST' | 'PUT' | 'DELETE';\n path: string;\n description: string;\n /**\n * True when the route is mounted only if the server config sets\n * `testHooks`. A production build (the default, `testHooks: false`) does not\n * serve it at all — `routeRequest` and `buildRoutesPayload` both drop it, so\n * the honest answer there is a bare 404 with no `Allow`.\n *\n * This field exists because the table is a static constant with no config to\n * consult, so it published the gated routes unconditionally and the only\n * signal was the free-text `(testHooks)` in `description` — which a consumer\n * code-generating a client from this table cannot read. It would call\n * `POST /ui-bridge/control/keep-awake` against a release build, get a bare\n * 404, and have no way to tell it from a typo. `route-table-parity.test.ts`\n * asserts this flag against the flag-off route set, so a fourth gated route —\n * or one of these three accidentally un-gated — cannot change the production\n * surface with the tests still green.\n */\n requiresTestHooks?: boolean;\n}\n\n/**\n * Every HTTP route this package serves.\n *\n * This is the contract an external consumer reads off the package root\n * (`src/index.ts` exports it) to learn what `@qontinui/ui-bridge-native`\n * answers. It is a SECOND declaration of a surface whose single source of\n * truth is `WS_ROUTES` in `./http-server.ts`, which is what `routeRequest`\n * iterates and what `/ui-bridge/_routes` publishes at runtime. Nothing in this\n * package reads the constant below, so nothing made the two agree.\n *\n * They had stopped agreeing. Measured 2026-08-31 against `_routes` with\n * `testHooks: true`: the router served **56** method+path pairs and this table\n * published **36** — every entry here was reachable, but twenty routes the\n * package serves were absent, among them `control/tap`, `control/screenshot`,\n * `ai/find`, the five `control/page/*` interaction endpoints (`click-by-text`,\n * `click-by-selector`, `type-into`, `read-value`, `find-by-text`), the four\n * `design/evaluate*` endpoints and the two discovery endpoints (`_help`,\n * `_routes`) a consumer would use to find the rest. The twenty were added and\n * `route-table-parity.test.ts` now asserts SET EQUALITY with `_routes` in both\n * directions, so neither declaration can move without the other.\n *\n * KEEP IN SYNC with `WS_ROUTES`. That comment used to be the whole mechanism;\n * it is now a pointer to the test that enforces it.\n *\n * The sibling surface (`@qontinui/ui-bridge/native`) exports a constant of the\n * same name over a smaller route set, and there `routeRequest` READS it — the\n * wrong-verb arm derives its 405 from it (qontinui/ui-bridge#189). Do not\n * assume an entry present in one is present in the other; the two packages\n * publish different surfaces and only the status mapping is pinned equal\n * (`packages/ui-bridge/src/native/server/http-status-parity.test.ts`).\n *\n * Multi-verb routes appear once PER VERB, because `RouteDefinition.method` is\n * singular — `control/discover`, `control/page-health` and `control/screenshot`\n * each take GET and POST, and `design/style-guide` takes GET and DELETE.\n */\nexport const UI_BRIDGE_NATIVE_ROUTES: Record<string, RouteDefinition> = {\n // Discovery / introspection — the two endpoints an agent hits first to learn\n // the rest of this table without reading docs. Special-cased in\n // `routeRequest` rather than living in `WS_ROUTES`, and appended by\n // `buildRoutesPayload` so `_routes` describes itself.\n HELP: {\n method: 'GET',\n path: '/ui-bridge/_help',\n description: 'Route index + action reference + tips (rich discovery payload)',\n },\n ROUTES: {\n method: 'GET',\n path: '/ui-bridge/_routes',\n description: 'Minimal {method, path} route list, matching the runner /_routes shape',\n },\n\n // Control - Elements\n GET_ELEMENTS: {\n method: 'GET',\n path: '/ui-bridge/control/elements',\n description: 'List all registered elements',\n },\n GET_ELEMENTS_FLAT: {\n method: 'GET',\n path: '/ui-bridge/elements',\n description: 'List all registered elements (flat alias matching the runner path)',\n },\n GET_ELEMENT: {\n method: 'GET',\n path: '/ui-bridge/control/element/:id',\n description: 'Get element details',\n },\n GET_ELEMENT_STATE: {\n method: 'GET',\n path: '/ui-bridge/control/element/:id/state',\n description: 'Get element state',\n },\n EXECUTE_ACTION: {\n method: 'POST',\n path: '/ui-bridge/control/element/:id/action',\n description: 'Execute action on element',\n },\n\n // Control - Components\n GET_COMPONENTS: {\n method: 'GET',\n path: '/ui-bridge/control/components',\n description: 'List all registered components',\n },\n GET_COMPONENT: {\n method: 'GET',\n path: '/ui-bridge/control/component/:id',\n description: 'Get component details',\n },\n EXECUTE_COMPONENT_ACTION: {\n method: 'POST',\n path: '/ui-bridge/control/component/:id/action/:actionId',\n description: 'Execute component action',\n },\n\n // Discovery\n FIND: {\n method: 'POST',\n path: '/ui-bridge/control/find',\n description: 'Find elements matching criteria',\n },\n AI_FIND: {\n method: 'POST',\n path: '/ui-bridge/ai/find',\n description: 'Find elements matching criteria (runner-parity alias for /control/find)',\n },\n GET_SNAPSHOT: {\n method: 'GET',\n path: '/ui-bridge/control/snapshot',\n description: 'Get full bridge snapshot',\n },\n DISCOVER: {\n method: 'GET',\n path: '/ui-bridge/control/discover',\n description: 'Discover elements (alias for snapshot; web/runner parity)',\n },\n DISCOVER_POST: {\n method: 'POST',\n path: '/ui-bridge/control/discover',\n description: 'Discover elements over POST (same handler as the GET form; web/runner parity)',\n },\n PAGE_HEALTH: {\n method: 'POST',\n path: '/ui-bridge/control/page-health',\n description:\n 'Holistic page health diagnostic: spatial coverage, layout regions, text signals, interactive readiness, anomalies + ASCII heatmap',\n },\n PAGE_HEALTH_GET: {\n method: 'GET',\n path: '/ui-bridge/control/page-health',\n description: 'Page health diagnostic over GET, for ad-hoc curls with no body',\n },\n\n // Screenshots — GET and POST both accepted so a curl works either way.\n //\n // Both keys carry an explicit verb suffix. The pre-existing multi-verb pairs\n // do not agree on what an UNSUFFIXED key means — `DISCOVER` is the GET and\n // `PAGE_HEALTH` is the POST — so a consumer reading `ROUTES.<NAME>.method`\n // off a bare name gets opposite verbs from equally unmarked keys. Those two\n // names are load-bearing for existing consumers and are left alone; new\n // multi-verb entries name their verb rather than entrenching the ambiguity.\n SCREENSHOT_GET: {\n method: 'GET',\n path: '/ui-bridge/control/screenshot',\n description: 'PNG screenshot of the current screen',\n },\n SCREENSHOT_POST: {\n method: 'POST',\n path: '/ui-bridge/control/screenshot',\n description: 'PNG screenshot of the current screen (POST form)',\n },\n\n // Coordinate-based interaction\n CONTROL_TAP: {\n method: 'POST',\n path: '/ui-bridge/control/tap',\n description:\n 'Synthesize a press at screen coords by matching registered element layout rects: body { x, y, action? }',\n },\n\n // App-agnostic interaction parity with the web/runner surface. The\n // selector-based pair has no RN analog and answers NOT_SUPPORTED (501).\n PAGE_CLICK_BY_TEXT: {\n method: 'POST',\n path: '/ui-bridge/control/page/click-by-text',\n description: 'Press the first element matching free text: body { text, visibleOnly? }',\n },\n PAGE_CLICK_BY_SELECTOR: {\n method: 'POST',\n path: '/ui-bridge/control/page/click-by-selector',\n description: 'Selector-based press (web-only; mobile returns NOT_SUPPORTED)',\n },\n PAGE_TYPE_INTO: {\n method: 'POST',\n path: '/ui-bridge/control/page/type-into',\n description: 'Type into the input matching a label: body { label, text, clear?, visibleOnly? }',\n },\n PAGE_READ_VALUE: {\n method: 'POST',\n path: '/ui-bridge/control/page/read-value',\n description: 'Selector-based value read (web-only; mobile returns NOT_SUPPORTED)',\n },\n PAGE_FIND_BY_TEXT: {\n method: 'POST',\n path: '/ui-bridge/control/page/find-by-text',\n description: 'List elements matching free text without pressing: body { text, visibleOnly? }',\n },\n\n // Meta\n META_METHODS: {\n method: 'GET',\n path: '/ui-bridge/meta/methods',\n description: 'List every handler name (legacy introspection; prefer /_routes)',\n },\n\n // Workflows\n GET_WORKFLOWS: {\n method: 'GET',\n path: '/ui-bridge/control/workflows',\n description: 'List all workflows',\n },\n RUN_WORKFLOW: {\n method: 'POST',\n path: '/ui-bridge/control/workflow/:id/run',\n description: 'Run a workflow',\n },\n\n // Page Navigation\n PAGE_REFRESH: {\n method: 'POST',\n path: '/ui-bridge/control/page/refresh',\n description: 'Refresh the current page',\n },\n PAGE_NAVIGATE: {\n method: 'POST',\n path: '/ui-bridge/control/page/navigate',\n description: 'Navigate to a URL',\n },\n PAGE_REPLACE: {\n method: 'POST',\n path: '/ui-bridge/control/page/replace',\n description: 'Replace current route without adding to back stack',\n },\n PAGE_GO_BACK: {\n method: 'POST',\n path: '/ui-bridge/control/page/back',\n description: 'Go back in navigation history',\n },\n PAGE_GO_FORWARD: {\n method: 'POST',\n path: '/ui-bridge/control/page/forward',\n description: 'Go forward in navigation history',\n },\n\n // Design Review\n DESIGN_ELEMENT_STYLES: {\n method: 'GET',\n path: '/ui-bridge/design/element/:id/styles',\n description: 'Get computed styles for an element',\n },\n DESIGN_ELEMENT_STATE_STYLES: {\n method: 'POST',\n path: '/ui-bridge/design/element/:id/state-styles',\n description: 'Get state-specific styles for an element',\n },\n DESIGN_SNAPSHOT: {\n method: 'POST',\n path: '/ui-bridge/design/snapshot',\n description: 'Get design data for all or selected elements',\n },\n DESIGN_RESPONSIVE: {\n method: 'POST',\n path: '/ui-bridge/design/responsive',\n description: 'Get responsive snapshots (current device only on native)',\n },\n DESIGN_AUDIT: {\n method: 'POST',\n path: '/ui-bridge/design/audit',\n description: 'Run style guide audit on elements',\n },\n DESIGN_STYLE_GUIDE_LOAD: {\n method: 'POST',\n path: '/ui-bridge/design/style-guide/load',\n description: 'Load a style guide for audit',\n },\n DESIGN_STYLE_GUIDE_GET: {\n method: 'GET',\n path: '/ui-bridge/design/style-guide',\n description: 'Get currently loaded style guide',\n },\n DESIGN_STYLE_GUIDE_CLEAR: {\n method: 'DELETE',\n path: '/ui-bridge/design/style-guide',\n description: 'Clear loaded style guide',\n },\n\n // Quality Evaluation\n DESIGN_EVALUATE: {\n method: 'POST',\n path: '/ui-bridge/design/evaluate',\n description: 'Score the current UI against a quality context',\n },\n DESIGN_EVALUATE_CONTEXTS: {\n method: 'GET',\n path: '/ui-bridge/design/evaluate/contexts',\n description: 'List available quality evaluation contexts',\n },\n DESIGN_EVALUATE_BASELINE: {\n method: 'POST',\n path: '/ui-bridge/design/evaluate/baseline',\n description: 'Save a quality baseline snapshot',\n },\n DESIGN_EVALUATE_DIFF: {\n method: 'POST',\n path: '/ui-bridge/design/evaluate/diff',\n description: 'Diff the current UI against a saved baseline',\n },\n\n // AI helpers\n AI_FILL_FORM: {\n method: 'POST',\n path: '/ui-bridge/ai/fill-form',\n description: 'Fill multiple input elements in a single call',\n },\n\n // AI helpers (NOT_SUPPORTED stubs) — these endpoints exist on the runner-side\n // UI Bridge surface but have no analog on mobile React Native. The mobile\n // bridge registers explicit stubs so callers get a structured NOT_SUPPORTED\n // envelope instead of a confusing HTTP 404. The mobile bridge's snapshot +\n // `/control/find` already cover what an operator would reach for these for.\n AI_FORMS: {\n method: 'GET',\n path: '/ui-bridge/ai/forms',\n description: 'Discover forms (runner-only; mobile returns NOT_SUPPORTED)',\n },\n AI_IDLE_STATUS: {\n method: 'GET',\n path: '/ui-bridge/ai/idle-status',\n description: 'Get page-idle signal (runner-only; mobile returns NOT_SUPPORTED)',\n },\n AI_CHANGE_BUFFER_ENABLE: {\n method: 'POST',\n path: '/ui-bridge/ai/change-buffer/enable',\n description: 'Enable DOM change buffer (runner-only; mobile returns NOT_SUPPORTED)',\n },\n AI_WAIT_FOR_ELEMENT: {\n method: 'POST',\n path: '/ui-bridge/ai/wait-for-element',\n description: 'Wait for element predicate via HTTP (runner-only; mobile returns NOT_SUPPORTED — use WS waitForElement instead)',\n },\n\n // Test hooks — drive ModalDetector state and the screen lock from outside\n // the React tree (gated by `features.testHooks`). Mirrors `pushModal` /\n // `dismissModal` calls that components normally make in-process.\n //\n // These are LISTED unconditionally — this table is a static constant with no\n // config to consult — but each carries `requiresTestHooks: true`, which is\n // the machine-readable form of the `(testHooks)` in its description. With the\n // flag off `routeRequest` and `buildRoutesPayload` both drop them and the\n // route answers a bare 404. `route-table-parity.test.ts` compares the whole\n // table against `_routes` at `testHooks: true`, and the flagged subset\n // against `_routes` at `testHooks: false`, so both surfaces are pinned.\n PUSH_MODAL: {\n method: 'POST',\n path: '/ui-bridge/control/modal/push',\n description: 'Push a modal onto the modal stack (testHooks)',\n requiresTestHooks: true,\n },\n DISMISS_MODAL: {\n method: 'POST',\n path: '/ui-bridge/control/modal/dismiss/:id',\n description: 'Dismiss a modal by id (testHooks)',\n requiresTestHooks: true,\n },\n KEEP_AWAKE: {\n method: 'POST',\n path: '/ui-bridge/control/keep-awake',\n description:\n 'Keep the device screen awake via the injected keepAwakeProvider: body { enabled, durationMs? } (testHooks)',\n requiresTestHooks: true,\n },\n\n // Observability — last-N ring buffers (always mounted; `installed:false`\n // when the console/network patches are off, i.e. no testHooks).\n CONSOLE_ERRORS: {\n method: 'GET',\n path: '/ui-bridge/control/console-errors',\n description: 'Last-N captured console.error/console.warn entries',\n },\n NETWORK_REQUESTS: {\n method: 'GET',\n path: '/ui-bridge/sdk/network-requests',\n description: 'Last-N captured fetch/XHR requests with status + duration',\n },\n\n // Health\n HEALTH: {\n method: 'GET',\n path: '/ui-bridge/health',\n description: 'Health check',\n },\n};\n\n/**\n * Request body for `POST /ai/fill-form`.\n *\n * The mobile native bridge has no `setValue` action — text inputs are driven\n * via the `type` action (which calls `onChangeText`). The fillForm handler\n * dispatches each field as `executor.executeAction(elementId, { action: 'type',\n * params: { text: value, clear: true } })` so existing values are atomically\n * replaced (matching the web bridge's \"setValue\" semantics).\n *\n * Shape mirrors the runner's `POST /ui-bridge/ai/fill-form` documented in\n * docs-site/api/runner-features.md (array-of-pairs form), so callers can use\n * the same JSON across mobile and web/runner without special-casing.\n */\nexport interface FillFormFieldInput {\n /** Target element id (registered id, testID, accessibilityLabel, etc.) */\n elementId: string;\n /** Text value to write into the input. */\n value: string;\n}\n\nexport interface FillFormRequest {\n fields: FillFormFieldInput[];\n}\n\n/**\n * Per-field outcome returned by `POST /ai/fill-form`.\n */\nexport interface FillFormFieldResult {\n /** Element id from the request, echoed back. */\n elementId: string;\n /** Whether `executor.executeAction` reported success for this field. */\n success: boolean;\n /** Error message when `success === false`. Omitted on success. */\n error?: string;\n}\n\n/**\n * Response payload returned in `APIResponse.data` for `POST /ai/fill-form`.\n */\nexport interface FillFormResponse {\n results: FillFormFieldResult[];\n succeededCount: number;\n failedCount: number;\n}\n\n/**\n * Request body for `POST /control/tap` — synthesize a press at given screen\n * coordinates by searching registered elements whose layout rect contains the\n * point.\n *\n * The handler picks the topmost (smallest-area) match — usually the innermost\n * child — then dispatches the requested action via the standard executor.\n * `action` defaults to `'press'`.\n */\nexport interface TapAtRequest {\n x: number;\n y: number;\n action?: 'press' | 'longPress' | 'doubleTap';\n}\n\n/**\n * Response payload returned in `APIResponse.data` for `POST /control/tap`.\n */\nexport interface TapAtResponse {\n /** Element id whose rect contained the tap coords. */\n elementId: string;\n /** Action that was dispatched. */\n action: 'press' | 'longPress' | 'doubleTap';\n /** The element's layout rect at dispatch time (best-effort). */\n layout: {\n x: number;\n y: number;\n width: number;\n height: number;\n pageX?: number;\n pageY?: number;\n } | null;\n}\n\n/**\n * Single console error/warn entry captured by the observability ring buffer.\n * Returned by `GET /control/console-errors`.\n */\nexport interface ConsoleErrorEntry {\n /** ms since epoch when the entry was captured. */\n timestamp: number;\n /** `'error'` or `'warn'`. */\n level: 'error' | 'warn';\n /** Joined message string (matches what console would have printed). */\n message: string;\n /** Captured stack trace if any of the args was an Error. */\n stack?: string;\n}\n\n/**\n * Response payload for `GET /control/console-errors`.\n */\nexport interface ConsoleErrorsResponse {\n entries: ConsoleErrorEntry[];\n /** Number of entries returned (post `since`/`limit` filtering). */\n count: number;\n /** Total entries currently held in the ring buffer (pre-filter). */\n bufferSize: number;\n /**\n * Whether the console capture patch is actively installed. `false` means\n * the endpoint is mounted and schema-valid but not observing — typically\n * because `features.testHooks` is off (production builds don't patch\n * `console.error`/`console.warn`). When `false`, `entries` is always empty.\n */\n installed: boolean;\n}\n\n/**\n * Single network request entry captured by the observability ring buffer.\n * Returned by `GET /sdk/network-requests`.\n */\nexport interface NetworkRequestEntry {\n /** ms since epoch at request start. */\n timestamp: number;\n /** HTTP method (uppercased). */\n method: string;\n /** Resolved request URL. */\n url: string;\n /** HTTP status code, or 0 if the request errored before a response. */\n status: number;\n /** Wall-clock duration in ms from start to settlement. */\n durationMs: number;\n /** Whether the request settled with a 2xx response. */\n ok: boolean;\n /** Error message when the request rejected before a response. */\n error?: string;\n}\n\n/**\n * Response payload for `GET /sdk/network-requests`.\n */\nexport interface NetworkRequestsResponse {\n entries: NetworkRequestEntry[];\n count: number;\n bufferSize: number;\n /**\n * Whether the network capture patch is actively installed. `false` means\n * the endpoint is mounted and schema-valid but not observing — typically\n * because `features.testHooks` is off (production builds don't patch\n * `fetch`/`XMLHttpRequest`). When `false`, `entries` is always empty.\n */\n installed: boolean;\n}\n\n/**\n * Request body for `POST /control/modal/push`.\n *\n * Mirrors `ModalDetector.pushModal`'s `ModalPushInput` shape; `metadata` is\n * a free-form object the test runner can stash for later assertions but is\n * not currently surfaced in the snapshot.\n */\nexport interface PushModalRequest {\n id: string;\n title?: string;\n type?: string;\n blocking?: boolean;\n dismissible?: boolean;\n metadata?: Record<string, unknown>;\n}\n\n/**\n * Response payload for `POST /control/modal/push`.\n */\nexport interface PushModalResponse {\n pushed: boolean;\n id: string;\n title?: string;\n type?: string;\n blocking?: boolean;\n dismissible?: boolean;\n pushedAt: number;\n}\n\n/**\n * Response payload for `POST /control/modal/dismiss/:id`.\n */\nexport interface DismissModalResponse {\n dismissed: string;\n}\n\n/**\n * API response wrapper\n */\nexport interface APIResponse<T = unknown> {\n success: boolean;\n data?: T;\n error?: string;\n code?: string;\n timestamp: number;\n}\n\n/**\n * Handler context\n */\nexport interface HandlerContext {\n params: Record<string, string>;\n query: Record<string, string>;\n body: unknown;\n}\n\n/**\n * Handler function type\n */\nexport type HandlerFunction<T = unknown> = (context: HandlerContext) => Promise<APIResponse<T>>;\n\n/**\n * Server handlers interface\n */\nexport interface NativeServerHandlers {\n // Elements\n getElements: HandlerFunction<{ elements: unknown[] }>;\n getElement: HandlerFunction<{ element: unknown }>;\n getElementState: HandlerFunction<{ state: unknown }>;\n executeAction: HandlerFunction<NativeActionResponse>;\n\n // Components\n getComponents: HandlerFunction<{ components: unknown[] }>;\n getComponent: HandlerFunction<{ component: unknown }>;\n executeComponentAction: HandlerFunction<ComponentActionResponse>;\n\n // Discovery\n find: HandlerFunction<NativeFindResponse>;\n getSnapshot: HandlerFunction<NativeBridgeSnapshot>;\n // Page health — structured diagnostic over the snapshot's elements +\n // device viewport. Output shape mirrors the runner/web analyzer so the\n // `page-health` skill is platform-neutral.\n getPageHealth: HandlerFunction<unknown>;\n\n // Workflows\n getWorkflows: HandlerFunction<{ workflows: unknown[] }>;\n runWorkflow: HandlerFunction<{\n runId: string;\n status: string;\n steps: Array<{\n stepId: string;\n type: string;\n status: string;\n result?: unknown;\n error?: string;\n durationMs: number;\n }>;\n totalSteps: number;\n completedSteps: number;\n failedSteps: number;\n skippedSteps: number;\n durationMs: number;\n }>;\n\n // Page Navigation\n pageRefresh: HandlerFunction<PageNavigationResponse>;\n pageNavigate: HandlerFunction<PageNavigationResponse>;\n pageReplace: HandlerFunction<PageNavigationResponse>;\n pageGoBack: HandlerFunction<PageNavigationResponse>;\n pageGoForward: HandlerFunction<PageNavigationResponse>;\n\n // Screenshot\n getScreenshot: HandlerFunction<{ screenshot: string; width: number; height: number }>;\n\n // Design Review\n getElementStyles: HandlerFunction<ElementDesignData>;\n getElementStateStyles: HandlerFunction<{ elementId: string; stateStyles: StateStyles[] }>;\n getDesignSnapshot: HandlerFunction<{ elements: ElementDesignData[]; timestamp: number }>;\n getResponsiveSnapshots: HandlerFunction<ResponsiveSnapshot[]>;\n runDesignAudit: HandlerFunction<unknown>;\n loadStyleGuide: HandlerFunction<{ loaded: boolean }>;\n getStyleGuide: HandlerFunction<unknown>;\n clearStyleGuide: HandlerFunction<{ cleared: boolean }>;\n\n // Quality Evaluation\n evaluateQuality: HandlerFunction<unknown>;\n getQualityContexts: HandlerFunction<Array<{ name: string; description: string }>>;\n saveBaseline: HandlerFunction<{ saved: boolean; elementCount: number }>;\n diffBaseline: HandlerFunction<unknown>;\n\n // Meta / Introspection\n getMethods: HandlerFunction<{\n methods: Array<{ method: string; httpMethods?: string[]; description?: string }>;\n }>;\n\n // AI helpers\n fillForm: HandlerFunction<FillFormResponse>;\n\n // App-agnostic interaction parity — cross-platform contract shared with the\n // web/runner bridge (`/control/page/*`). Text/label-based interactions\n // compose find + executeAction over the registry; selector-only variants\n // return NOT_SUPPORTED on native (no DOM).\n clickByText: HandlerFunction<{ clicked: boolean; element?: unknown }>;\n clickBySelector: HandlerFunction<never>;\n typeInto: HandlerFunction<{ typed: boolean; element?: unknown }>;\n readValue: HandlerFunction<never>;\n findByText: HandlerFunction<\n Array<{ index: number; id: string; type: string; label?: string }>\n >;\n\n // AI helpers — NOT_SUPPORTED stubs (runner-only endpoints; see route table).\n // These return `error(..., 'NOT_SUPPORTED')` and exist so the mobile bridge\n // never 404s on cheatsheet endpoints that work on the runner.\n aiForms: HandlerFunction<never>;\n aiIdleStatus: HandlerFunction<never>;\n aiChangeBufferEnable: HandlerFunction<never>;\n aiWaitForElement: HandlerFunction<never>;\n\n // Coord-based tap — synthesizes a press at the given screen coords by\n // searching registered elements whose layout rect contains the point.\n tapAt: HandlerFunction<TapAtResponse>;\n\n // Observability — last-N ring buffers for console + network. Both are\n // gated behind `features.testHooks` at the route layer; the handlers\n // themselves return empty buffers when the buffers aren't installed.\n getConsoleErrors: HandlerFunction<ConsoleErrorsResponse>;\n getNetworkRequests: HandlerFunction<NetworkRequestsResponse>;\n\n // Test hooks — modal stack manipulation\n pushModal: HandlerFunction<PushModalResponse>;\n dismissModal: HandlerFunction<DismissModalResponse>;\n\n // Test hooks — device keep-awake (screen stays on for the duration)\n keepAwake: HandlerFunction<{ enabled: boolean; durationMs: number | null }>;\n\n // Health\n health: HandlerFunction<Record<string, unknown>>;\n}\n","/**\n * Pure-JS RFC 6455 WebSocket protocol implementation.\n *\n * Provides frame encoding/decoding and handshake utilities for running\n * a WebSocket server on react-native-tcp-socket without native crypto deps.\n */\n\n// ── Constants ───────────────────────────────────────────────────────────────\n\nconst WS_GUID = '258EAFA5-E914-47DA-95CA-C5AB0DC85B11';\n\nexport const OPCODE_CONTINUATION = 0x00;\nexport const OPCODE_TEXT = 0x01;\nexport const OPCODE_BINARY = 0x02;\nexport const OPCODE_CLOSE = 0x08;\nexport const OPCODE_PING = 0x09;\nexport const OPCODE_PONG = 0x0a;\n\n// ── Types ───────────────────────────────────────────────────────────────────\n\nexport interface DecodedFrame {\n opcode: number;\n fin: boolean;\n payload: Uint8Array;\n masked: boolean;\n}\n\nexport interface DecodeResult {\n frames: DecodedFrame[];\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n remainder: Uint8Array<any>;\n}\n\n// ── SHA-1 (Pure JS) ─────────────────────────────────────────────────────────\n// Minimal inline SHA-1 per FIPS 180-4. Used only for the WS handshake.\n\nfunction sha1Bytes(input: Uint8Array): Uint8Array {\n const ml = input.length * 8;\n\n // Pre-processing: pad to 512-bit blocks\n const padLen = 64 - ((input.length + 9) % 64);\n const total = input.length + 1 + (padLen === 64 ? 0 : padLen) + 8;\n const msg = new Uint8Array(total);\n msg.set(input);\n msg[input.length] = 0x80;\n // Length in bits as 64-bit big-endian (we only use 32-bit since messages are small)\n const dv = new DataView(msg.buffer);\n dv.setUint32(total - 4, ml, false);\n\n // Initialize hash values\n let h0 = 0x67452301;\n let h1 = 0xefcdab89;\n let h2 = 0x98badcfe;\n let h3 = 0x10325476;\n let h4 = 0xc3d2e1f0;\n\n const w = new Uint32Array(80);\n\n for (let offset = 0; offset < total; offset += 64) {\n const block = new DataView(msg.buffer, offset, 64);\n\n for (let i = 0; i < 16; i++) {\n w[i] = block.getUint32(i * 4, false);\n }\n for (let i = 16; i < 80; i++) {\n const x = w[i - 3] ^ w[i - 8] ^ w[i - 14] ^ w[i - 16];\n w[i] = (x << 1) | (x >>> 31);\n }\n\n let a = h0,\n b = h1,\n c = h2,\n d = h3,\n e = h4;\n\n for (let i = 0; i < 80; i++) {\n let f: number, k: number;\n if (i < 20) {\n f = (b & c) | (~b & d);\n k = 0x5a827999;\n } else if (i < 40) {\n f = b ^ c ^ d;\n k = 0x6ed9eba1;\n } else if (i < 60) {\n f = (b & c) | (b & d) | (c & d);\n k = 0x8f1bbcdc;\n } else {\n f = b ^ c ^ d;\n k = 0xca62c1d6;\n }\n\n const temp = (((a << 5) | (a >>> 27)) + f + e + k + w[i]) | 0;\n e = d;\n d = c;\n c = (b << 30) | (b >>> 2);\n b = a;\n a = temp;\n }\n\n h0 = (h0 + a) | 0;\n h1 = (h1 + b) | 0;\n h2 = (h2 + c) | 0;\n h3 = (h3 + d) | 0;\n h4 = (h4 + e) | 0;\n }\n\n const result = new Uint8Array(20);\n const rdv = new DataView(result.buffer);\n rdv.setUint32(0, h0, false);\n rdv.setUint32(4, h1, false);\n rdv.setUint32(8, h2, false);\n rdv.setUint32(12, h3, false);\n rdv.setUint32(16, h4, false);\n return result;\n}\n\nconst B64_CHARS = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';\n\n/**\n * Manual base64 encoder — avoids Hermes btoa() which can silently corrupt\n * binary strings containing bytes > 127 (common in SHA-1 output).\n */\nfunction bytesToBase64(bytes: Uint8Array): string {\n let result = '';\n const len = bytes.length;\n for (let i = 0; i < len; i += 3) {\n const b0 = bytes[i];\n const b1 = i + 1 < len ? bytes[i + 1] : 0;\n const b2 = i + 2 < len ? bytes[i + 2] : 0;\n const triplet = (b0 << 16) | (b1 << 8) | b2;\n\n result += B64_CHARS[(triplet >> 18) & 0x3f];\n result += B64_CHARS[(triplet >> 12) & 0x3f];\n result += i + 1 < len ? B64_CHARS[(triplet >> 6) & 0x3f] : '=';\n result += i + 2 < len ? B64_CHARS[triplet & 0x3f] : '=';\n }\n return result;\n}\n\n// ── Handshake ───────────────────────────────────────────────────────────────\n\n/**\n * Compute the Sec-WebSocket-Accept value from the client's Sec-WebSocket-Key.\n */\nexport function computeAcceptKey(clientKey: string): string {\n const input = clientKey + WS_GUID;\n const encoder = new TextEncoder();\n const hash = sha1Bytes(encoder.encode(input));\n return bytesToBase64(hash);\n}\n\n/**\n * Build the HTTP 101 Switching Protocols response for a WebSocket upgrade.\n */\nexport function buildUpgradeResponse(clientKey: string): string {\n const accept = computeAcceptKey(clientKey);\n return (\n 'HTTP/1.1 101 Switching Protocols\\r\\n' +\n 'Upgrade: websocket\\r\\n' +\n 'Connection: Upgrade\\r\\n' +\n `Sec-WebSocket-Accept: ${accept}\\r\\n` +\n '\\r\\n'\n );\n}\n\n// ── Frame Encoding (Server → Client, unmasked) ─────────────────────────────\n\nfunction encodeFrame(opcode: number, payload: Uint8Array): Uint8Array {\n const len = payload.length;\n let headerLen: number;\n\n if (len < 126) {\n headerLen = 2;\n } else if (len < 65536) {\n headerLen = 4;\n } else {\n headerLen = 10;\n }\n\n const frame = new Uint8Array(headerLen + len);\n frame[0] = 0x80 | opcode; // FIN + opcode\n\n if (len < 126) {\n frame[1] = len; // No mask bit (server → client)\n } else if (len < 65536) {\n frame[1] = 126;\n frame[2] = (len >> 8) & 0xff;\n frame[3] = len & 0xff;\n } else {\n frame[1] = 127;\n // For payloads > 65535, use 8-byte length (upper 4 bytes zero for practical sizes)\n const dv = new DataView(frame.buffer, 2, 8);\n dv.setUint32(0, 0, false);\n dv.setUint32(4, len, false);\n }\n\n frame.set(payload, headerLen);\n return frame;\n}\n\n/** Encode a text message as a WebSocket frame. */\nexport function encodeTextFrame(text: string): Uint8Array {\n const payload = new TextEncoder().encode(text);\n return encodeFrame(OPCODE_TEXT, payload);\n}\n\n/** Encode a PING frame with optional payload. */\nexport function encodePingFrame(payload?: Uint8Array): Uint8Array {\n return encodeFrame(OPCODE_PING, payload ?? new Uint8Array(0));\n}\n\n/** Encode a PONG frame with the payload from the PING. */\nexport function encodePongFrame(payload: Uint8Array): Uint8Array {\n return encodeFrame(OPCODE_PONG, payload);\n}\n\n/** Encode a CLOSE frame with optional status code and reason. */\nexport function encodeCloseFrame(code?: number, reason?: string): Uint8Array {\n if (code === undefined) {\n return encodeFrame(OPCODE_CLOSE, new Uint8Array(0));\n }\n const reasonBytes = reason ? new TextEncoder().encode(reason) : new Uint8Array(0);\n const payload = new Uint8Array(2 + reasonBytes.length);\n payload[0] = (code >> 8) & 0xff;\n payload[1] = code & 0xff;\n payload.set(reasonBytes, 2);\n return encodeFrame(OPCODE_CLOSE, payload);\n}\n\n// ── Frame Decoding (Client → Server, masked) ───────────────────────────────\n\n/**\n * Decode one or more WebSocket frames from a byte buffer.\n * Returns decoded frames and any unconsumed bytes (for partial frames).\n */\nexport function decodeFrames(buffer: Uint8Array): DecodeResult {\n const frames: DecodedFrame[] = [];\n let offset = 0;\n\n while (offset < buffer.length) {\n // Need at least 2 bytes for the header\n if (buffer.length - offset < 2) break;\n\n const byte0 = buffer[offset];\n const byte1 = buffer[offset + 1];\n\n const fin = (byte0 & 0x80) !== 0;\n const opcode = byte0 & 0x0f;\n const masked = (byte1 & 0x80) !== 0;\n let payloadLen = byte1 & 0x7f;\n\n let headerLen = 2;\n\n if (payloadLen === 126) {\n if (buffer.length - offset < 4) break;\n payloadLen = (buffer[offset + 2] << 8) | buffer[offset + 3];\n headerLen = 4;\n } else if (payloadLen === 127) {\n if (buffer.length - offset < 10) break;\n const dv = new DataView(buffer.buffer, buffer.byteOffset + offset + 2, 8);\n payloadLen = dv.getUint32(4, false); // Use lower 32 bits only\n headerLen = 10;\n }\n\n if (masked) {\n headerLen += 4; // 4-byte masking key\n }\n\n const totalLen = headerLen + payloadLen;\n if (buffer.length - offset < totalLen) break; // Partial frame\n\n // Extract and unmask payload\n const payload = new Uint8Array(payloadLen);\n const dataStart = offset + headerLen;\n\n if (masked) {\n const maskOffset = offset + headerLen - 4;\n const mask = buffer.slice(maskOffset, maskOffset + 4);\n for (let i = 0; i < payloadLen; i++) {\n payload[i] = buffer[dataStart + i] ^ mask[i % 4];\n }\n } else {\n payload.set(buffer.slice(dataStart, dataStart + payloadLen));\n }\n\n frames.push({ opcode, fin, payload, masked });\n offset += totalLen;\n }\n\n return {\n frames,\n remainder: new Uint8Array(buffer.slice(offset)),\n };\n}\n\n/**\n * Decode a text payload from a Uint8Array.\n */\nexport function decodeTextPayload(payload: Uint8Array): string {\n return new TextDecoder().decode(payload);\n}\n","/**\n * Resilient TCP-bind helper for native UI Bridge server adapters.\n *\n * Background: the on-device bridge binds a TCP server on a fixed port (8087).\n * On hot-reload, app foreground/background cycles, or a crash-restart, the OS\n * can leave the previous socket in a lingering state, so the fresh bind fails\n * with `EADDRINUSE`. The original adapter gave up after 3 fixed retries\n * (~5s total), after which the bridge was permanently dead until the app was\n * fully restarted — a single transient stale socket bricked automation.\n *\n * This helper centralises a robust bind loop so every adapter (and a unit\n * test) shares one implementation:\n * - SO_REUSEADDR is requested on bind where the platform/library supports it\n * (passed through to the caller's `attempt` via `reuseAddress: true`), so\n * a lingering TIME_WAIT socket doesn't block rebind.\n * - On `EADDRINUSE` it retries with exponential backoff (capped) for at\n * least `minTotalMs` (default 30s) instead of bailing after a fixed count.\n * - Every retry is logged so operators can see the bridge recovering.\n * - Non-`EADDRINUSE` errors fail fast (a wrong-permission / bad-host error\n * won't fix itself by waiting).\n *\n * The helper is transport-agnostic: the caller supplies an `attempt` thunk\n * that performs ONE bind attempt and resolves on `listening` / rejects on\n * error. This keeps the package free of any concrete TCP library dependency\n * (the same reason `ServerAdapter` is an interface).\n */\n\n/** True when an error looks like an address-already-in-use bind failure. */\nexport function isAddrInUseError(err: unknown): boolean {\n const message =\n err instanceof Error ? err.message : typeof err === 'string' ? err : String(err);\n // Some RN TCP libraries surface a `.code` instead of (or alongside) the\n // message — check both.\n const code = (err as { code?: unknown })?.code;\n return (\n message.includes('EADDRINUSE') ||\n message.toLowerCase().includes('address already in use') ||\n code === 'EADDRINUSE'\n );\n}\n\nexport interface BindWithRetryOptions {\n /**\n * Minimum total wall-clock time to keep retrying `EADDRINUSE` before giving\n * up, in milliseconds. The loop always makes at least one attempt and keeps\n * retrying until this budget is exhausted. Default 30_000 (30s).\n *\n * Pass `Infinity` to retry indefinitely (with capped backoff) — appropriate\n * for an always-on device bridge that should self-heal whenever the stale\n * socket finally clears.\n */\n minTotalMs?: number;\n /** Initial backoff delay between retries, in ms. Default 500. */\n initialDelayMs?: number;\n /** Maximum backoff delay (cap for exponential growth), in ms. Default 5_000. */\n maxDelayMs?: number;\n /** Multiplier applied to the delay after each retry. Default 2. */\n backoffFactor?: number;\n /** Logger for retry diagnostics. Defaults to `console`. */\n logger?: Pick<Console, 'warn' | 'error'>;\n /** Injectable sleep — overridable in tests to avoid real timers. */\n sleep?: (ms: number) => Promise<void>;\n /** Injectable clock — overridable in tests. Defaults to `Date.now`. */\n now?: () => number;\n}\n\nconst defaultSleep = (ms: number): Promise<void> =>\n new Promise((resolve) => setTimeout(resolve, ms));\n\n/**\n * Run `attempt()` repeatedly until it resolves, retrying on `EADDRINUSE` with\n * exponential backoff for at least `minTotalMs`. Non-address-in-use errors\n * reject immediately. Resolves once a bind attempt succeeds.\n *\n * @param attempt One bind attempt. Receives the attempt index (0-based) and\n * MUST resolve on a successful `listening` event or reject on error. The\n * caller is responsible for tearing down any half-bound server before the\n * next attempt (see the adapter's `recreate` thunk).\n */\nexport async function bindWithRetry(\n attempt: (attemptIndex: number) => Promise<void>,\n options: BindWithRetryOptions = {}\n): Promise<void> {\n const {\n minTotalMs = 30_000,\n initialDelayMs = 500,\n maxDelayMs = 5_000,\n backoffFactor = 2,\n logger = console,\n sleep = defaultSleep,\n now = Date.now,\n } = options;\n\n const startedAt = now();\n let delay = initialDelayMs;\n let attemptIndex = 0;\n\n for (;;) {\n try {\n await attempt(attemptIndex);\n return; // bound successfully\n } catch (err) {\n const elapsed = now() - startedAt;\n const budgetExhausted = elapsed + delay >= minTotalMs;\n\n if (!isAddrInUseError(err) || budgetExhausted) {\n // Either a non-recoverable error, or we've spent our retry budget.\n throw err;\n }\n\n logger.warn(\n `[ui-bridge-native] bind failed with EADDRINUSE (attempt ${attemptIndex + 1}); ` +\n `retrying in ${delay}ms (elapsed ${elapsed}ms / budget ${\n minTotalMs === Infinity ? '∞' : minTotalMs\n }ms)`\n );\n\n await sleep(delay);\n delay = Math.min(delay * backoffFactor, maxDelayMs);\n attemptIndex += 1;\n }\n }\n}\n","/**\n * WebSocket connection wrapper for the UI Bridge server.\n *\n * Manages a single WebSocket connection after the HTTP upgrade handshake,\n * handling frame-level I/O, heartbeat, and event subscriptions.\n */\n\nimport {\n decodeFrames,\n decodeTextPayload,\n encodeTextFrame,\n encodePingFrame,\n encodePongFrame,\n encodeCloseFrame,\n OPCODE_TEXT,\n OPCODE_CLOSE,\n OPCODE_PING,\n OPCODE_PONG,\n OPCODE_CONTINUATION,\n type DecodedFrame,\n} from './ws-protocol';\nimport type { JsonRpcEvent } from './ws-types';\nimport { globToRegex } from './ws-event-bridge';\n\n/**\n * Callback for text messages received from the client.\n * Returns a response string to send back, or null for no response.\n */\nexport type WebSocketMessageHandler = (connId: string, message: string) => Promise<string | null>;\n\nexport class WebSocketConnection {\n readonly id: string;\n readonly subscriptions = new Set<string>();\n\n /** Heartbeat liveness flag — set false before ping, set true on pong */\n alive = true;\n\n private socket: {\n write: (data: Uint8Array | string, encoding?: string, cb?: () => void) => void;\n destroy: () => void;\n on: (event: string, handler: (...args: unknown[]) => void) => void;\n removeAllListeners: (event?: string) => void;\n setNoDelay?: (noDelay: boolean) => void;\n };\n\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n private buffer: Uint8Array<any> = new Uint8Array(0);\n private fragmentBuffer: Uint8Array[] = [];\n private fragmentOpcode = 0;\n private closed = false;\n private onMessage: WebSocketMessageHandler;\n private onClose: (connId: string) => void;\n\n constructor(\n id: string,\n socket: WebSocketConnection['socket'],\n onMessage: WebSocketMessageHandler,\n onClose: (connId: string) => void\n ) {\n this.id = id;\n this.socket = socket;\n this.onMessage = onMessage;\n this.onClose = onClose;\n\n // Disable Nagle's algorithm for low latency\n if (socket.setNoDelay) {\n socket.setNoDelay(true);\n }\n\n // Wire up data handler\n socket.on('data', (data: unknown) => {\n if (this.closed) return;\n const chunk =\n data instanceof Uint8Array\n ? data\n : typeof data === 'string'\n ? new TextEncoder().encode(data)\n : new Uint8Array(data as ArrayBuffer);\n this.handleData(chunk);\n });\n\n socket.on('error', () => {\n this.destroy();\n });\n\n socket.on('close', () => {\n this.destroy();\n });\n }\n\n /** Send a text message to the client. */\n send(message: string): void {\n if (this.closed) return;\n try {\n const frame = encodeTextFrame(message);\n this.writeRaw(frame);\n } catch {\n // Socket may be closed\n }\n }\n\n /**\n * Send an event if the client is subscribed to it. Subscription patterns\n * may be exact event names, `*` (all), or glob patterns containing `*`\n * (e.g. `element:*`, `*:stateChanged`). Exact matches and `*` are checked\n * via fast Set lookups; glob patterns fall through to a regex test.\n */\n sendEvent(event: JsonRpcEvent): void {\n if (this.closed) return;\n if (!this.matchesSubscription(event.event)) return;\n this.send(JSON.stringify(event));\n }\n\n private matchesSubscription(eventType: string): boolean {\n // Fast paths\n if (this.subscriptions.has(eventType)) return true;\n if (this.subscriptions.has('*')) return true;\n // Glob fallback — only patterns containing `*` (other than the bare `*`\n // already handled above) need the regex test.\n for (const pattern of this.subscriptions) {\n if (!pattern.includes('*')) continue;\n if (globToRegex(pattern).test(eventType)) return true;\n }\n return false;\n }\n\n /** Send a ping frame for heartbeat. */\n ping(): void {\n if (this.closed) return;\n try {\n this.writeRaw(encodePingFrame());\n } catch {\n // Socket may be closed\n }\n }\n\n /** Close the connection gracefully. */\n close(code = 1000, reason = ''): void {\n if (this.closed) return;\n this.closed = true;\n try {\n this.writeRaw(encodeCloseFrame(code, reason));\n // Give the frame time to flush before destroying\n setTimeout(() => this.socket.destroy(), 100);\n } catch {\n this.socket.destroy();\n }\n this.onClose(this.id);\n }\n\n /** Forcefully destroy the connection without a close frame. */\n destroy(): void {\n if (this.closed) return;\n this.closed = true;\n try {\n this.socket.destroy();\n } catch {\n // Already destroyed\n }\n this.onClose(this.id);\n }\n\n /** Whether the connection is still open. */\n get isOpen(): boolean {\n return !this.closed;\n }\n\n // ── Internal ────────────────────────────────────────────────────────────\n\n private writeRaw(data: Uint8Array): void {\n // react-native-tcp-socket write() accepts Buffer/Uint8Array/string.\n // Convert to binary string for compatibility with all socket implementations.\n // Use chunked String.fromCharCode to avoid call-stack limits on large payloads\n // while staying O(n) instead of O(n^2) from single-char concatenation.\n const CHUNK = 8192;\n const parts: string[] = [];\n for (let i = 0; i < data.length; i += CHUNK) {\n const end = Math.min(i + CHUNK, data.length);\n parts.push(String.fromCharCode.apply(null, data.subarray(i, end) as unknown as number[]));\n }\n this.socket.write(parts.join(''), 'binary');\n }\n\n private handleData(chunk: Uint8Array): void {\n // Append to buffer\n const newBuffer = new Uint8Array(this.buffer.length + chunk.length);\n newBuffer.set(this.buffer);\n newBuffer.set(chunk, this.buffer.length);\n this.buffer = newBuffer;\n\n // Decode frames\n const { frames, remainder } = decodeFrames(this.buffer);\n this.buffer = remainder;\n\n for (const frame of frames) {\n this.handleFrame(frame);\n }\n }\n\n private handleFrame(frame: DecodedFrame): void {\n // Handle fragmented messages\n if (!frame.fin && frame.opcode !== OPCODE_CONTINUATION) {\n // Start of fragmented message\n this.fragmentBuffer = [frame.payload];\n this.fragmentOpcode = frame.opcode;\n return;\n }\n\n if (frame.opcode === OPCODE_CONTINUATION) {\n this.fragmentBuffer.push(frame.payload);\n if (!frame.fin) return; // More fragments coming\n\n // Reassemble\n const totalLen = this.fragmentBuffer.reduce((sum, buf) => sum + buf.length, 0);\n const reassembled = new Uint8Array(totalLen);\n let offset = 0;\n for (const buf of this.fragmentBuffer) {\n reassembled.set(buf, offset);\n offset += buf.length;\n }\n this.fragmentBuffer = [];\n\n // Process as the original opcode\n this.handleFrame({\n opcode: this.fragmentOpcode,\n fin: true,\n payload: reassembled,\n masked: true,\n });\n return;\n }\n\n switch (frame.opcode) {\n case OPCODE_TEXT: {\n const text = decodeTextPayload(frame.payload);\n this.onMessage(this.id, text)\n .then((response) => {\n if (response !== null) {\n this.send(response);\n }\n })\n .catch((err) => {\n console.warn(`[ws-connection] message handler error:`, err);\n this.send(\n JSON.stringify({\n error: 'Internal error',\n timestamp: Date.now(),\n })\n );\n });\n break;\n }\n\n case OPCODE_PING:\n // Respond with PONG carrying the same payload\n try {\n this.writeRaw(encodePongFrame(frame.payload));\n } catch {\n // Socket may be closed\n }\n break;\n\n case OPCODE_PONG:\n this.alive = true;\n break;\n\n case OPCODE_CLOSE:\n this.close();\n break;\n }\n }\n}\n","/**\n * UI Bridge Native Debug Inspector\n *\n * An overlay component that shows registered elements and allows\n * inspection of the UI Bridge state.\n */\n\nimport { useState, useCallback, useMemo } from 'react';\nimport {\n View,\n Text,\n StyleSheet,\n TouchableOpacity,\n ScrollView,\n Modal,\n Dimensions,\n} from 'react-native';\nimport { useUIBridgeNativeOptional } from '../react/UIBridgeNativeProvider';\nimport type { RegisteredNativeElement } from '../core/types';\n\n/**\n * Inspector props\n */\nexport interface UIBridgeInspectorProps {\n /** Whether to show the inspector */\n visible?: boolean;\n /** Callback when inspector is closed */\n onClose?: () => void;\n /** Position of the inspector toggle button */\n togglePosition?: 'top-left' | 'top-right' | 'bottom-left' | 'bottom-right';\n}\n\n/**\n * Element info card\n */\nfunction ElementCard({\n element,\n onPress,\n}: {\n element: RegisteredNativeElement;\n onPress: (element: RegisteredNativeElement) => void;\n}) {\n const state = element.getState();\n const identifier = element.getIdentifier();\n\n return (\n <TouchableOpacity style={styles.elementCard} onPress={() => onPress(element)}>\n <View style={styles.elementHeader}>\n <Text style={styles.elementId}>{element.id}</Text>\n <Text style={styles.elementType}>{element.type}</Text>\n </View>\n {element.label && <Text style={styles.elementLabel}>{element.label}</Text>}\n <View style={styles.stateRow}>\n <StateIndicator label=\"Mounted\" value={state.mounted} />\n <StateIndicator label=\"Visible\" value={state.visible} />\n <StateIndicator label=\"Enabled\" value={state.enabled} />\n </View>\n {identifier.testId && <Text style={styles.testId}>testID: {identifier.testId}</Text>}\n </TouchableOpacity>\n );\n}\n\n/**\n * State indicator\n */\nfunction StateIndicator({ label, value }: { label: string; value: boolean }) {\n return (\n <View style={styles.stateIndicator}>\n <View style={[styles.stateDot, { backgroundColor: value ? '#4CAF50' : '#F44336' }]} />\n <Text style={styles.stateLabel}>{label}</Text>\n </View>\n );\n}\n\n/**\n * Element detail view\n */\nfunction ElementDetail({\n element,\n onClose,\n}: {\n element: RegisteredNativeElement;\n onClose: () => void;\n}) {\n const state = element.getState();\n const identifier = element.getIdentifier();\n\n return (\n <View style={styles.detailContainer}>\n <View style={styles.detailHeader}>\n <Text style={styles.detailTitle}>{element.id}</Text>\n <TouchableOpacity onPress={onClose}>\n <Text style={styles.closeButton}>Close</Text>\n </TouchableOpacity>\n </View>\n\n <ScrollView style={styles.detailContent}>\n <Text style={styles.sectionTitle}>Type</Text>\n <Text style={styles.sectionValue}>{element.type}</Text>\n\n {element.label && (\n <>\n <Text style={styles.sectionTitle}>Label</Text>\n <Text style={styles.sectionValue}>{element.label}</Text>\n </>\n )}\n\n <Text style={styles.sectionTitle}>State</Text>\n <View style={styles.stateSection}>\n <Text style={styles.stateText}>Mounted: {String(state.mounted)}</Text>\n <Text style={styles.stateText}>Visible: {String(state.visible)}</Text>\n <Text style={styles.stateText}>Enabled: {String(state.enabled)}</Text>\n <Text style={styles.stateText}>Focused: {String(state.focused)}</Text>\n {state.value !== undefined && <Text style={styles.stateText}>Value: {state.value}</Text>}\n </View>\n\n {state.layout && (\n <>\n <Text style={styles.sectionTitle}>Layout</Text>\n <View style={styles.stateSection}>\n <Text style={styles.stateText}>\n Position: ({state.layout.x}, {state.layout.y})\n </Text>\n <Text style={styles.stateText}>\n Size: {state.layout.width} x {state.layout.height}\n </Text>\n <Text style={styles.stateText}>\n Page: ({state.layout.pageX}, {state.layout.pageY})\n </Text>\n </View>\n </>\n )}\n\n <Text style={styles.sectionTitle}>Identifier</Text>\n <View style={styles.stateSection}>\n {identifier.uiId && <Text style={styles.stateText}>uiId: {identifier.uiId}</Text>}\n {identifier.testId && <Text style={styles.stateText}>testId: {identifier.testId}</Text>}\n {identifier.accessibilityLabel && (\n <Text style={styles.stateText}>a11yLabel: {identifier.accessibilityLabel}</Text>\n )}\n <Text style={styles.stateText}>treePath: {identifier.treePath}</Text>\n </View>\n\n <Text style={styles.sectionTitle}>Actions</Text>\n <View style={styles.actionsSection}>\n {element.actions.map((action) => (\n <View key={action} style={styles.actionBadge}>\n <Text style={styles.actionText}>{action}</Text>\n </View>\n ))}\n </View>\n\n {element.customActions && Object.keys(element.customActions).length > 0 && (\n <>\n <Text style={styles.sectionTitle}>Custom Actions</Text>\n <View style={styles.actionsSection}>\n {Object.keys(element.customActions).map((action) => (\n <View key={action} style={[styles.actionBadge, styles.customActionBadge]}>\n <Text style={styles.actionText}>{action}</Text>\n </View>\n ))}\n </View>\n </>\n )}\n </ScrollView>\n </View>\n );\n}\n\n/**\n * UI Bridge Inspector component\n *\n * Shows an overlay with information about registered elements.\n * Useful for debugging and development.\n *\n * @example\n * ```tsx\n * function App() {\n * const [showInspector, setShowInspector] = useState(false);\n *\n * return (\n * <UIBridgeNativeProvider features={{ debug: __DEV__ }}>\n * <MainContent />\n * {__DEV__ && (\n * <UIBridgeInspector\n * visible={showInspector}\n * onClose={() => setShowInspector(false)}\n * />\n * )}\n * </UIBridgeNativeProvider>\n * );\n * }\n * ```\n */\nexport function UIBridgeInspector({\n visible = false,\n onClose,\n togglePosition = 'bottom-right',\n}: UIBridgeInspectorProps) {\n const bridge = useUIBridgeNativeOptional();\n const [showInspector, setShowInspector] = useState(visible);\n const [selectedElement, setSelectedElement] = useState<RegisteredNativeElement | null>(null);\n\n const elements = useMemo(() => (bridge ? bridge.getElements() : []), [bridge]);\n\n const components = useMemo(() => (bridge ? bridge.getComponents() : []), [bridge]);\n\n const handleToggle = useCallback(() => {\n setShowInspector((prev) => !prev);\n }, []);\n\n const handleClose = useCallback(() => {\n setShowInspector(false);\n onClose?.();\n }, [onClose]);\n\n const handleSelectElement = useCallback((element: RegisteredNativeElement) => {\n setSelectedElement(element);\n }, []);\n\n const handleCloseDetail = useCallback(() => {\n setSelectedElement(null);\n }, []);\n\n // Position style for toggle button\n const toggleStyle = useMemo(() => {\n switch (togglePosition) {\n case 'top-left':\n return { top: 50, left: 10 };\n case 'top-right':\n return { top: 50, right: 10 };\n case 'bottom-left':\n return { bottom: 50, left: 10 };\n case 'bottom-right':\n default:\n return { bottom: 50, right: 10 };\n }\n }, [togglePosition]);\n\n if (!bridge) {\n return null;\n }\n\n return (\n <>\n {/* Toggle button */}\n <TouchableOpacity style={[styles.toggleButton, toggleStyle]} onPress={handleToggle}>\n <Text style={styles.toggleText}>UI</Text>\n </TouchableOpacity>\n\n {/* Inspector modal */}\n <Modal\n visible={showInspector}\n animationType=\"slide\"\n transparent={true}\n onRequestClose={handleClose}\n >\n <View style={styles.modalContainer}>\n <View style={styles.inspectorContainer}>\n {/* Header */}\n <View style={styles.header}>\n <Text style={styles.headerTitle}>UI Bridge Inspector</Text>\n <TouchableOpacity onPress={handleClose}>\n <Text style={styles.closeButton}>X</Text>\n </TouchableOpacity>\n </View>\n\n {/* Stats */}\n <View style={styles.statsRow}>\n <View style={styles.stat}>\n <Text style={styles.statValue}>{elements.length}</Text>\n <Text style={styles.statLabel}>Elements</Text>\n </View>\n <View style={styles.stat}>\n <Text style={styles.statValue}>{components.length}</Text>\n <Text style={styles.statLabel}>Components</Text>\n </View>\n <View style={styles.stat}>\n <Text style={styles.statValue}>{bridge.serverRunning ? 'ON' : 'OFF'}</Text>\n <Text style={styles.statLabel}>Server</Text>\n </View>\n </View>\n\n {/* Element list or detail */}\n {selectedElement ? (\n <ElementDetail element={selectedElement} onClose={handleCloseDetail} />\n ) : (\n <ScrollView style={styles.elementList}>\n {elements.map((element) => (\n <ElementCard key={element.id} element={element} onPress={handleSelectElement} />\n ))}\n {elements.length === 0 && (\n <Text style={styles.emptyText}>No elements registered yet</Text>\n )}\n </ScrollView>\n )}\n </View>\n </View>\n </Modal>\n </>\n );\n}\n\nconst { height: screenHeight } = Dimensions.get('window');\n\nconst styles = StyleSheet.create({\n toggleButton: {\n position: 'absolute',\n width: 44,\n height: 44,\n borderRadius: 22,\n backgroundColor: '#2196F3',\n justifyContent: 'center',\n alignItems: 'center',\n shadowColor: '#000',\n shadowOffset: { width: 0, height: 2 },\n shadowOpacity: 0.25,\n shadowRadius: 4,\n elevation: 5,\n zIndex: 1000,\n },\n toggleText: {\n color: '#fff',\n fontWeight: 'bold',\n fontSize: 14,\n },\n modalContainer: {\n flex: 1,\n backgroundColor: 'rgba(0, 0, 0, 0.5)',\n justifyContent: 'flex-end',\n },\n inspectorContainer: {\n backgroundColor: '#1e1e1e',\n borderTopLeftRadius: 16,\n borderTopRightRadius: 16,\n maxHeight: screenHeight * 0.8,\n },\n header: {\n flexDirection: 'row',\n justifyContent: 'space-between',\n alignItems: 'center',\n padding: 16,\n borderBottomWidth: 1,\n borderBottomColor: '#333',\n },\n headerTitle: {\n color: '#fff',\n fontSize: 18,\n fontWeight: 'bold',\n },\n closeButton: {\n color: '#2196F3',\n fontSize: 16,\n fontWeight: 'bold',\n },\n statsRow: {\n flexDirection: 'row',\n padding: 12,\n borderBottomWidth: 1,\n borderBottomColor: '#333',\n },\n stat: {\n flex: 1,\n alignItems: 'center',\n },\n statValue: {\n color: '#fff',\n fontSize: 20,\n fontWeight: 'bold',\n },\n statLabel: {\n color: '#888',\n fontSize: 12,\n marginTop: 2,\n },\n elementList: {\n padding: 12,\n },\n elementCard: {\n backgroundColor: '#2d2d2d',\n borderRadius: 8,\n padding: 12,\n marginBottom: 8,\n },\n elementHeader: {\n flexDirection: 'row',\n justifyContent: 'space-between',\n alignItems: 'center',\n },\n elementId: {\n color: '#fff',\n fontSize: 14,\n fontWeight: 'bold',\n },\n elementType: {\n color: '#888',\n fontSize: 12,\n backgroundColor: '#444',\n paddingHorizontal: 8,\n paddingVertical: 2,\n borderRadius: 4,\n },\n elementLabel: {\n color: '#aaa',\n fontSize: 12,\n marginTop: 4,\n },\n stateRow: {\n flexDirection: 'row',\n marginTop: 8,\n },\n stateIndicator: {\n flexDirection: 'row',\n alignItems: 'center',\n marginRight: 12,\n },\n stateDot: {\n width: 8,\n height: 8,\n borderRadius: 4,\n marginRight: 4,\n },\n stateLabel: {\n color: '#888',\n fontSize: 10,\n },\n testId: {\n color: '#666',\n fontSize: 10,\n marginTop: 4,\n fontFamily: 'monospace',\n },\n emptyText: {\n color: '#888',\n textAlign: 'center',\n marginTop: 20,\n },\n detailContainer: {\n flex: 1,\n },\n detailHeader: {\n flexDirection: 'row',\n justifyContent: 'space-between',\n alignItems: 'center',\n padding: 12,\n borderBottomWidth: 1,\n borderBottomColor: '#333',\n },\n detailTitle: {\n color: '#fff',\n fontSize: 16,\n fontWeight: 'bold',\n },\n detailContent: {\n padding: 12,\n },\n sectionTitle: {\n color: '#888',\n fontSize: 12,\n marginTop: 12,\n marginBottom: 4,\n textTransform: 'uppercase',\n },\n sectionValue: {\n color: '#fff',\n fontSize: 14,\n },\n stateSection: {\n backgroundColor: '#2d2d2d',\n borderRadius: 8,\n padding: 8,\n },\n stateText: {\n color: '#ddd',\n fontSize: 12,\n fontFamily: 'monospace',\n marginBottom: 2,\n },\n actionsSection: {\n flexDirection: 'row',\n flexWrap: 'wrap',\n },\n actionBadge: {\n backgroundColor: '#2196F3',\n paddingHorizontal: 8,\n paddingVertical: 4,\n borderRadius: 4,\n marginRight: 6,\n marginBottom: 6,\n },\n customActionBadge: {\n backgroundColor: '#9C27B0',\n },\n actionText: {\n color: '#fff',\n fontSize: 12,\n },\n});\n"]}
1
+ {"version":3,"sources":["../src/core/vision-fields.ts","../src/core/element-actions.ts","../src/core/registry.ts","../src/core/action-effect.ts","../src/core/param-schema.ts","../src/core/abortable.ts","../src/core/element-identifier.ts","../src/control/action-executor.ts","../src/design/design-inspector-native.ts","../src/server/design-handlers.ts","../src/server/page-health.ts","../src/server/handlers.ts","../src/server/observability.ts","../src/server/ws-types.ts","../src/server/http-server.ts","../src/server/ws-event-bridge.ts","../src/transport/logger.ts","../src/transport/relay-logging.ts","../src/transport/DeviceAnnouncer.ts","../src/transport/CloudRelayClient.ts","../src/modal/modal-detector.ts","../src/toast/toast-capture.ts","../src/undo/undo-tracker.ts","../src/react/UIBridgeNativeProvider.tsx","../src/react/useUIElement.ts","../src/react/useUIComponent.ts","../src/react/useUIBridge.ts","../src/react/useUIBridgeModal.ts","../src/react/useUIBridgeToast.ts","../src/react/StateAnnotation.tsx","../src/server/types.ts","../src/server/ws-protocol.ts","../src/server/bind-retry.ts","../src/server/ws-connection.ts","../src/debug/inspector.tsx"],"names":["error","INTERACTIVE_TYPES","success","Platform","summary","createContext","useMemo","Dimensions","useRef","useState","PixelRatio","useCallback","useEffect","jsx","use","StyleSheet","Fragment","sleep","jsxs","TouchableOpacity","View","Text","ScrollView","Modal"],"mappings":";;;;;;;;;;;;;;AA+EA,IAAM,yBAAA,uBAAqD,GAAA,CAAI;AAAA,EAC7D,SAAA;AAAA,EACA,WAAA;AAAA,EACA,YAAA;AAAA,EACA,aAAA;AAAA,EACA,cAAA;AAAA,EACA,eAAA;AAAA,EACA,UAAA;AAAA,EACA,iBAAA;AAAA,EACA,SAAA;AAAA,EACA,cAAA;AAAA,EACA;AACF,CAAC,CAAA;AAUD,IAAM,iBAAA,uBAAwD,GAAA,CAAuB;AAAA,EACnF,QAAA;AAAA,EACA,OAAA;AAAA,EACA,QAAA;AAAA,EACA,UAAA;AAAA,EACA,OAAA;AAAA,EACA,WAAA;AAAA,EACA,WAAA;AAAA,EACA;AACF,CAAC,CAAA;AAOM,SAAS,YAAY,IAAA,EAA6C;AACvE,EAAA,QAAQ,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ACnB,eAAA,EAAiB,CAAA;AAAA,IACjB,YAAA,EAAc,CAAA;AAAA,IACd,WAAA,EAAa,CAAA;AAAA,IACb,YAAA,EAAc;AAAA,GAChB;AAAA,EACA,iBAAA,EAAmB;AAAA,IACjB,eAAA,EAAiB;AAAA,GACnB;AAAA,EACA,UAAA,EAAY;AAAA,IACV,KAAA,EAAO,MAAA;AAAA,IACP,QAAA,EAAU;AAAA;AAEd,CAAC,CAAA","file":"index.js","sourcesContent":["/**\n * Vision analyzer field projection.\n *\n * The runner's vision pipeline (`POST /ui-bridge/vision/{analyze,assert}`)\n * deserializes a snapshot's `elements[]` straight into the Rust\n * `qontinui_vision_core::Element` struct. Beyond geometry (`bbox` — see\n * {@link projectBbox}), the analyzers read these per-element fields:\n *\n * - `interactable: bool` — elements analyzer (interactive coverage),\n * layout analyzer (WCAG target size).\n * - `text: Option<String>` — elements (no_text), color (contrast gate).\n * - `role: Option<String>` — elements analyzer role vocabulary.\n * - `fg_color`/`bg_color: Rgb` — color analyzer (WCAG contrast).\n * - `font_size_px: f32` — typography analyzer (size drift).\n * - `font_family: String` — typography analyzer (family drift).\n *\n * The web SDK populates the runner-facing equivalents via `getComputedStyle`\n * (`state.computedStyles.{color,backgroundColor,fontSize,fontFamily}`) and\n * the DOM (`textContent`, aria `role`, event handlers / tag → interactable);\n * the runner projects those into the snake_case Rust shape. React Native has\n * NO `getComputedStyle`, so the native SDK derives the same signals from what\n * the registry already carries:\n *\n * - `interactable` ← the element's `actions` (press/click/tap/...) or its\n * interactive `type` (button/input/switch/...). Mirrors web's\n * \"has a click-type handler OR is an interactive tag\".\n * - `text` ← `state.value` / `state.textContent` / `label` (human-visible).\n * - `role` ← `type` mapped to the ARIA-ish vocabulary the analyzer expects.\n * - `fg_color`/`bg_color` ← parsed from `flatStyle.color` /\n * `flatStyle.backgroundColor` when the host wired styles via\n * `captureStyle`/`updateElementStyle`. Same source the design inspector\n * reads. Absent when no style was wired (analyzer soft-skips).\n * - `font_size_px` ← `flatStyle.fontSize` (RN number is already px).\n * - `font_family` ← `flatStyle.fontFamily`.\n *\n * These fields are emitted directly in the runner-native snake_case shape so a\n * visual-audit caller can post the snapshot through with no transform — same\n * rationale as `bbox` emitting `{x,y,w,h}` (see {@link NativeElementBbox}).\n */\n\nimport type { NativeElementState, NativeElementType } from './types';\n\n/** Linear RGB triple, runner-native shape (`qontinui_vision_core::Rgb`). */\nexport interface VisionRgb {\n r: number;\n g: number;\n b: number;\n}\n\n/**\n * Analyzer-facing fields projected onto a snapshot element. Every field is\n * optional/absent-when-unknown so the Rust deserializer's serde defaults\n * (`interactable: false`, the rest `None`) only kick in when we genuinely\n * couldn't derive the value — matching the \"soft skip on missing field\"\n * contract in `element_snapshot.rs`.\n */\nexport interface VisionElementFields {\n interactable: boolean;\n text?: string;\n role?: string;\n fg_color?: VisionRgb;\n bg_color?: VisionRgb;\n font_size_px?: number;\n font_family?: string;\n}\n\n/**\n * Real React Native handler prop names that imply the element accepts\n * pointer/key input. This is the GENUINE interactivity signal — a prop the host\n * actually wired to a function (surfaced by `extractHandlerNames(props)` as the\n * snapshot's `registeredHandlers`). Mirrors the web SDK's \"has a real\n * click-type event handler\" interactable signal.\n *\n * Deliberately NOT derived from the element's `actions` array: `inferActions`\n * synthesizes `click`/`press` for EVERY element (even plain `text`/`view`/\n * `custom`), so an action-based check marks every node interactive. The real\n * handler names below are only present when the app source actually attached\n * `onPress` (etc.) to that element.\n */\nconst INTERACTIVE_HANDLER_NAMES: ReadonlySet<string> = new Set([\n 'onPress',\n 'onPressIn',\n 'onPressOut',\n 'onLongPress',\n 'onChangeText',\n 'onValueChange',\n 'onChange',\n 'onSubmitEditing',\n 'onClick',\n 'onTouchStart',\n 'onTouchEnd',\n]);\n\n/**\n * Element types that are inherently interactive regardless of which actions\n * were inferred/declared. Mirrors web treating `<button>/<a>/<input>/<select>`\n * as interactive by tag. `text`/`view`/`image` are intentionally absent — a\n * plain Text/View is only interactive if it carries a REAL press handler\n * (handled by the handler check), matching web's \"div is interactive only with\n * a handler\".\n */\nconst INTERACTIVE_TYPES: ReadonlySet<NativeElementType> = new Set<NativeElementType>([\n 'button',\n 'input',\n 'switch',\n 'checkbox',\n 'radio',\n 'touchable',\n 'pressable',\n 'listItem',\n]);\n\n/**\n * Map a native element `type` to the ARIA-ish `role` vocabulary the runner's\n * elements analyzer expects (matches the web SDK's aria/role values). Returns\n * `undefined` for generic containers so the analyzer doesn't over-count roles.\n */\nexport function roleForType(type: NativeElementType): string | undefined {\n switch (type) {\n case 'button':\n case 'touchable':\n case 'pressable':\n return 'button';\n case 'input':\n return 'textbox';\n case 'text':\n return 'text';\n case 'switch':\n return 'switch';\n case 'checkbox':\n return 'checkbox';\n case 'radio':\n return 'radio';\n case 'image':\n return 'img';\n case 'list':\n return 'list';\n case 'listItem':\n return 'listitem';\n case 'modal':\n return 'dialog';\n case 'scroll':\n case 'view':\n case 'custom':\n default:\n return undefined;\n }\n}\n\n/**\n * Derive whether an element accepts input. True when it is an\n * inherently-interactive `type` (button/input/switch/...) OR the host wired a\n * REAL interactive handler to it (`onPress`/`onChangeText`/...). Matches web's\n * \"has a real click-type handler OR is an interactive tag\".\n *\n * The `handlerNames` come from `extractHandlerNames(props)` — the names of the\n * element's props whose values are actually functions (the snapshot's\n * `registeredHandlers`). This is the genuine interactivity signal. The\n * element's inferred `actions` array is deliberately NOT consulted:\n * `inferActions` synthesizes `click`/`press` for plain `text`/`view`/`custom`,\n * so an action-based check would mark every node interactive (the very\n * over-count this function exists to avoid). A plain `text`/`view`/`heading`\n * with no real handler is therefore `interactable: false`, mirroring web.\n */\nexport function deriveInteractable(\n type: NativeElementType,\n handlerNames: readonly string[] | undefined\n): boolean {\n if (INTERACTIVE_TYPES.has(type)) return true;\n if (handlerNames) {\n for (const name of handlerNames) {\n if (INTERACTIVE_HANDLER_NAMES.has(name)) return true;\n }\n }\n return false;\n}\n\n/**\n * Derive the human-visible text for an element, preferring the most\n * \"what the user reads\" source. Mirrors web's `textContent`/accessibleName\n * precedence adapted to RN's registry shape:\n * 1. `state.value` — current input value / text element's mirrored label.\n * 2. `state.textContent` — explicit text content if the host set it.\n * 3. `label` — registration label (often the visible string).\n * Returns `undefined` when none carry a non-empty string so the analyzer's\n * `text.is_none()` gate stays accurate.\n */\nexport function deriveText(\n state: Pick<NativeElementState, 'value' | 'textContent'>,\n label: string | undefined\n): string | undefined {\n const candidates = [state.value, state.textContent, label];\n for (const c of candidates) {\n if (typeof c === 'string') {\n const trimmed = c.trim();\n if (trimmed.length > 0) return trimmed;\n }\n }\n return undefined;\n}\n\n// Common CSS/RN named colors. RN accepts the full CSS named-color set; we\n// cover the ones a design system realistically declares inline. Anything\n// outside this map + the hex/rgb parsers returns undefined (analyzer skips).\nconst NAMED_COLORS: Readonly<Record<string, VisionRgb>> = {\n black: { r: 0, g: 0, b: 0 },\n white: { r: 255, g: 255, b: 255 },\n red: { r: 255, g: 0, b: 0 },\n green: { r: 0, g: 128, b: 0 },\n blue: { r: 0, g: 0, b: 255 },\n gray: { r: 128, g: 128, b: 128 },\n grey: { r: 128, g: 128, b: 128 },\n silver: { r: 192, g: 192, b: 192 },\n transparent: { r: 0, g: 0, b: 0 },\n orange: { r: 255, g: 165, b: 0 },\n yellow: { r: 255, g: 255, b: 0 },\n purple: { r: 128, g: 0, b: 128 },\n navy: { r: 0, g: 0, b: 128 },\n};\n\nconst clamp255 = (n: number): number => Math.max(0, Math.min(255, Math.round(n)));\n\n/**\n * Parse an RN/CSS color string into a runner-native `{r,g,b}` triple, dropping\n * alpha (the runner's `Rgb` has no alpha; the analyzers convert to Lab/sRGB on\n * demand). Supports:\n * - `#rgb`, `#rgba`, `#rrggbb`, `#rrggbbaa`\n * - `rgb(r,g,b)` / `rgba(r,g,b,a)` (integer or %),\n * - named colors (subset).\n * Returns `undefined` for `undefined`, non-strings, or unrecognized formats so\n * the snapshot omits the field and the analyzer soft-skips rather than seeing a\n * bogus color. RN integer colors (e.g. `processColor` output) are not handled —\n * inline styles in app source are strings.\n */\nexport function parseColorToRgb(input: unknown): VisionRgb | undefined {\n if (typeof input !== 'string') return undefined;\n const raw = input.trim().toLowerCase();\n if (raw.length === 0) return undefined;\n\n if (Object.prototype.hasOwnProperty.call(NAMED_COLORS, raw)) {\n return NAMED_COLORS[raw];\n }\n\n // Hex: #rgb, #rgba, #rrggbb, #rrggbbaa\n if (raw.startsWith('#')) {\n const hex = raw.slice(1);\n if (hex.length === 3 || hex.length === 4) {\n const r = parseInt(hex[0] + hex[0], 16);\n const g = parseInt(hex[1] + hex[1], 16);\n const b = parseInt(hex[2] + hex[2], 16);\n if ([r, g, b].every((v) => Number.isFinite(v))) return { r, g, b };\n return undefined;\n }\n if (hex.length === 6 || hex.length === 8) {\n const r = parseInt(hex.slice(0, 2), 16);\n const g = parseInt(hex.slice(2, 4), 16);\n const b = parseInt(hex.slice(4, 6), 16);\n if ([r, g, b].every((v) => Number.isFinite(v))) return { r, g, b };\n return undefined;\n }\n return undefined;\n }\n\n // rgb()/rgba()\n const rgbMatch = raw.match(/^rgba?\\(([^)]+)\\)$/);\n if (rgbMatch) {\n const parts = rgbMatch[1].split(',').map((p) => p.trim());\n if (parts.length < 3) return undefined;\n const channel = (p: string): number | undefined => {\n if (p.endsWith('%')) {\n const pct = parseFloat(p.slice(0, -1));\n if (!Number.isFinite(pct)) return undefined;\n return clamp255((pct / 100) * 255);\n }\n const n = parseFloat(p);\n if (!Number.isFinite(n)) return undefined;\n return clamp255(n);\n };\n const r = channel(parts[0]);\n const g = channel(parts[1]);\n const b = channel(parts[2]);\n if (r === undefined || g === undefined || b === undefined) return undefined;\n return { r, g, b };\n }\n\n return undefined;\n}\n\n/**\n * Parse an RN `fontSize` into CSS pixels. RN `fontSize` is a unitless number\n * already in density-independent pixels (the analyzer compares relative sizes,\n * so dp vs px scaling is consistent across all elements in one snapshot).\n * Accepts a bare number or a `\"16px\"`/`\"16\"` string. Returns `undefined` for\n * anything non-numeric so typography soft-skips.\n */\nexport function parseFontSizePx(input: unknown): number | undefined {\n if (typeof input === 'number') {\n return Number.isFinite(input) && input > 0 ? input : undefined;\n }\n if (typeof input === 'string') {\n const m = input.trim().match(/^(-?\\d*\\.?\\d+)/);\n if (m) {\n const n = parseFloat(m[1]);\n return Number.isFinite(n) && n > 0 ? n : undefined;\n }\n }\n return undefined;\n}\n\n/**\n * Project the analyzer-facing fields for one registered element. Pure — takes\n * the already-resolved state + the element's static metadata, returns the\n * snake_case field bag to spread onto the snapshot element. Visual fields\n * (colors/fonts) are present only when `flatStyle` carried them; the runner's\n * serde defaults handle their absence.\n *\n * Unlike `bbox` (gated on `visibility === 'visible'`), interactable/text/role\n * are populated for ALL elements so the elements analyzer's coverage counts\n * are accurate — matching the web SDK, which emits role/text/interactable for\n * every element it discovers regardless of viewport position.\n */\nexport function projectVisionFields(args: {\n type: NativeElementType;\n label: string | undefined;\n /**\n * Names of the element's props that are real functions (from\n * `extractHandlerNames(props)` — the snapshot's `registeredHandlers`). The\n * genuine interactivity signal; the inferred `actions` array is NOT used here\n * because `inferActions` synthesizes press/click for every element.\n */\n handlerNames: readonly string[] | undefined;\n state: Pick<NativeElementState, 'value' | 'textContent'>;\n flatStyle: Record<string, unknown> | undefined;\n}): VisionElementFields {\n const { type, label, handlerNames, state, flatStyle } = args;\n\n const fields: VisionElementFields = {\n interactable: deriveInteractable(type, handlerNames),\n };\n\n const text = deriveText(state, label);\n if (text !== undefined) fields.text = text;\n\n const role = roleForType(type);\n if (role !== undefined) fields.role = role;\n\n if (flatStyle) {\n const fg = parseColorToRgb(flatStyle.color);\n if (fg !== undefined) fields.fg_color = fg;\n const bg = parseColorToRgb(flatStyle.backgroundColor);\n if (bg !== undefined) fields.bg_color = bg;\n const size = parseFontSizePx(flatStyle.fontSize);\n if (size !== undefined) fields.font_size_px = size;\n if (typeof flatStyle.fontFamily === 'string' && flatStyle.fontFamily.trim().length > 0) {\n fields.font_family = flatStyle.fontFamily;\n }\n }\n\n return fields;\n}\n","/**\n * The ONE wire projection for an element's custom actions.\n *\n * Plan `2026-09-04-effect-calculus-joins-the-component-action-registry`,\n * Design decision 4 step 3.\n *\n * DUPLICATE of `@qontinui/ui-bridge` `src/core/element-actions.ts`, for the same\n * reason the types beside it are duplicated: this package must not import from\n * `@qontinui/ui-bridge` (an optional peer). KEEP IN SYNC — a divergence here is\n * a divergence in what the two channels advertise about the same annotation.\n *\n * ---------------------------------------------------------------------------\n * WHAT THIS DOES NOT DO: default the effect\n * ---------------------------------------------------------------------------\n *\n * `effect` is carried through **verbatim and undefaulted**. An action whose\n * author declared nothing is emitted with `effect` absent, never with a\n * manufactured `'read'` — a default rendered as a declaration is a fail-open lie\n * on exactly the surface the annotation exists to protect. **Absent means\n * UNCLASSIFIED, not safe**, which is what served policy `operating-rules`\n * `what-makes-an-action-destructive` requires of an unestablished effect.\n */\n\nimport type { CustomAction, SerializedElementAction } from './types';\n\ntype ProjectableCustomActions = Record<\n string,\n Pick<CustomAction, 'label' | 'description' | 'effect'> | undefined\n>;\n\n/**\n * Project `RegisteredNativeElement.customActions` to its wire shape.\n *\n * - `undefined` in → `undefined` out (an element with no custom actions must not\n * start emitting `[]`; `JSON.stringify` keeps `[]` and drops `undefined`).\n * - An empty record in → `[]` out, matching what `Object.keys({})` gave before.\n *\n * The emitted `id` is the RECORD KEY — the executor dispatches by key, so the\n * key is the name a caller must send. Nullish entries are skipped: they carry no\n * handler, so advertising them would advertise a capability that does not exist.\n */\nexport function serializeElementCustomActions(\n customActions: ProjectableCustomActions | undefined\n): SerializedElementAction[] | undefined {\n if (!customActions) return undefined;\n\n const out: SerializedElementAction[] = [];\n for (const [id, action] of Object.entries(customActions)) {\n if (!action) continue;\n const entry: SerializedElementAction = { id };\n if (action.label !== undefined) entry.label = action.label;\n if (action.description !== undefined) entry.description = action.description;\n // Undefaulted — see the module header. `undefined` stays `undefined`.\n if (action.effect !== undefined) entry.effect = action.effect;\n out.push(entry);\n }\n return out;\n}\n","/**\n * Native Element and Component Registry\n *\n * Central registry for all UI elements and components registered with UI Bridge Native.\n * Adapted from ui-bridge for React Native environments.\n */\n\nimport type {\n RegisteredNativeElement,\n RegisteredNativeComponent,\n NativeElementState,\n NativeElementType,\n NativeStandardAction,\n NativeCustomAction,\n NativeAppInfo,\n NativeBridgeSnapshot,\n NativeElementBbox,\n NativeElementIdentifier,\n NativeElementRef,\n NativeRegistrationCoverage,\n NativeRouteProviderLike,\n NativeSnapshotEnrichers,\n NativeSnapshotEnricher,\n Workflow,\n BridgeEvent,\n BridgeEventType,\n BridgeEventListener,\n IREffect,\n} from './types';\nimport { projectVisionFields } from './vision-fields';\nimport { serializeElementCustomActions } from './element-actions';\n\n/**\n * Options for registering an element\n */\nexport interface RegisterElementOptions {\n type?: NativeElementType;\n label?: string;\n actions?: NativeStandardAction[];\n customActions?: Record<string, NativeCustomAction>;\n props?: Record<string, unknown>;\n treePath?: string;\n testId?: string;\n accessibilityLabel?: string;\n /** Route path where the element was registered (for page-scoped filtering) */\n registrationRoute?: string | null;\n /**\n * Id of the registered scrollable container this element lives inside.\n *\n * When set, {@link computeVisibility} clips the element against that\n * container's measured frame as well as the window, so a row scrolled out of\n * its `ScrollView` / `FlatList` stops reporting `visibility: 'visible'`.\n *\n * DECLARED, not inferred, and that is deliberate. React Native gives the\n * registry no parent chain — `useUIElement` is a hook, so it never wraps its\n * element's children and cannot publish itself as their ancestor. Guessing\n * the ancestor geometrically is worse than not clipping: a full-width scroll\n * container horizontally contains the tab bar and the header too, and\n * clipping those against it would report on-screen chrome as off-screen.\n * A wrong `hidden` is a worse answer than a coarse `visible`.\n *\n * Unset (the default) leaves the window as the only clip region.\n */\n scrollAncestorId?: string;\n /** Flattened RN style (from StyleSheet.flatten) for design review */\n flatStyle?: Record<string, unknown>;\n /** State-specific style overrides for design review */\n stateStyles?: {\n pressed?: Record<string, unknown>;\n focused?: Record<string, unknown>;\n disabled?: Record<string, unknown>;\n };\n}\n\n/**\n * Options for registering a component\n */\nexport interface RegisterComponentOptions {\n name: string;\n description?: string;\n actions?: Array<{\n id: string;\n label?: string;\n description?: string;\n /**\n * Phase 2 (same plan): the action's published parameter schema. It was\n * ABSENT here and dropped by the object literal in `registerComponent`\n * below, so the field `ComponentAction` declares could never reach a\n * registered native component and the native invocation seam had nothing\n * to validate against. That is the silent-drop trap the plan warns about,\n * already realised.\n */\n paramSchema?: Record<string, unknown>;\n /**\n * Phase 4 (same plan): the safety annotation. Absent here, an author's\n * `effect: 'destructive'` would die at this hop exactly the way\n * `paramSchema` did before Phase 2 — the literal in `registerComponent`\n * has a closed field list and nothing type-checks the omission.\n */\n effect?: IREffect;\n /**\n * Phase 3 (plan 2026-08-20-ui-bridge-action-declaration-shape): the second\n * argument is the `ActionHandlerOptions` bag carrying the cancellation\n * signal. A 1-arity handler stays assignable.\n */\n handler: (params?: unknown, options?: { signal?: AbortSignal }) => unknown | Promise<unknown>;\n }>;\n elementIds?: string[];\n}\n\n/**\n * Options for {@link NativeUIBridgeRegistry.updateComponentMeta}.\n *\n * Every field is optional and `undefined` means \"leave the registered value\n * alone\" — the same partial-update semantics {@link RegisterComponentOptions}'s\n * sister {@link NativeUIBridgeRegistry.updateElementMeta} uses. A consequence\n * worth stating: a `description` cannot be CLEARED through this door, only\n * replaced. Pass `actions: []` to publish an empty action list; that is\n * distinguishable from omitting the field.\n */\nexport interface UpdateComponentMetaOptions {\n name?: string;\n description?: string;\n actions?: RegisterComponentOptions['actions'];\n elementIds?: string[];\n}\n\n/**\n * Map declared component actions into the registry's stored shape.\n *\n * ⚠ CLOSED FIELD LIST. Any `ComponentAction` field not named here is dropped at\n * registration time, silently: the literal stays assignable, the serializer\n * still runs, the field is simply never there. `paramSchema` was exactly that\n * until Phase 2, and `effect` is the Phase 4 addition that would have gone the\n * same way.\n *\n * It lives in ONE place on purpose. `registerComponent` and\n * `updateComponentMeta` both publish actions, and a second hand-rolled copy of\n * this list is precisely how the two Phase-2/Phase-4 drops happened — a field\n * added to the declaration type stays assignable at every re-wrap site and\n * simply never arrives.\n */\nfunction toRegisteredComponentActions(\n actions: NonNullable<RegisterComponentOptions['actions']>\n): RegisteredNativeComponent['actions'] {\n return actions.map((a) => ({\n id: a.id,\n label: a.label,\n description: a.description,\n paramSchema: a.paramSchema,\n effect: a.effect,\n handler: a.handler,\n }));\n}\n\n/**\n * Value signature of everything about an action list that reaches a bridge\n * consumer.\n *\n * `handler` is excluded deliberately: it is a function, so it is not\n * serialisable, it is never published, and call sites pass inline closures that\n * are freshly allocated on every render — including it would make\n * `updateComponentMeta` report a change every single time and defeat its\n * idempotence. Order is significant, because published order is the order an\n * agent reads the actions in.\n */\nfunction publishedActionSignature(actions: RegisteredNativeComponent['actions']): string {\n return JSON.stringify(\n actions.map((a) => [a.id, a.label, a.description, a.paramSchema, a.effect])\n );\n}\n\n/** Positional equality for the optional `elementIds` list. */\nfunction sameElementIds(a: string[] | undefined, b: string[] | undefined): boolean {\n if (a === b) return true;\n if (a === undefined || b === undefined) return false;\n return a.length === b.length && a.every((id, i) => id === b[i]);\n}\n\n/**\n * Registry configuration\n */\nexport interface NativeRegistryConfig {\n verbose?: boolean;\n onEvent?: BridgeEventListener;\n}\n\n/**\n * Extract handler function names from an element's props.\n * Returns names of props whose values are functions (e.g. ['onPress', 'onChangeText']).\n */\nexport function extractHandlerNames(props?: Record<string, unknown>): string[] {\n if (!props) return [];\n return Object.keys(props).filter((k) => typeof props[k] === 'function');\n}\n\n/**\n * `currentRouteOnly` filter predicate for `registrationRoute`.\n *\n * Returns `true` when an element should be INCLUDED in a current-route-only\n * view. Two classes of elements pass the filter:\n *\n * 1. Elements registered on the current route\n * (`registrationRoute === currentRoute`).\n * 2. Route-agnostic elements (`registrationRoute == null` or `''`) — these\n * are typically registered at the app root (tab bars, persistent\n * headers, modal hosts) and apply to every route. Excluding them by\n * default makes `currentRouteOnly=true` return empty on mobile where\n * most apps register chrome at the root and screens via routed stacks.\n *\n * The filter only DROPS elements whose `registrationRoute` is set to a\n * non-matching route — i.e. they belong to a different screen. This matches\n * the runner-side semantics: route-tagged DOM nodes that don't match the\n * active URL are scoped out; untagged nodes are always in scope.\n *\n * Surfaced 2026-05-23 (item 4 of the 0.6.6 robustness pass) — the prior\n * strict equality returned 0 elements on mobile screens that register tabs\n * at the root, because tab elements had `registrationRoute: null`.\n */\nexport function matchesCurrentRoute(\n registrationRoute: string | null | undefined,\n currentRoute: string\n): boolean {\n if (registrationRoute == null || registrationRoute === '') return true;\n return registrationRoute === currentRoute;\n}\n\n/**\n * Derive the snapshot's `activeTab` from an Expo Router segment list.\n *\n * Expo Router spells a layout group as a parenthesised segment and a dynamic\n * route as a bracketed one, so `usePathname()`/`useSegments()` on the \"runs\"\n * tab of a `(tabs)` layout yield `\"/(tabs)/runs\"` and `[\"(tabs)\", \"runs\"]`\n * (the shape the `RouteProvider` doc comment already documents). The tab a user\n * is looking at is therefore the segment immediately following the INNERMOST\n * group.\n *\n * Rules, all deliberately conservative — an unknown tab is reported as absent\n * rather than guessed:\n *\n * - `[\"(tabs)\", \"runs\"]` → `\"runs\"`\n * - `[\"(tabs)\", \"runs\", \"[id]\"]`→ `\"runs\"` (a detail screen is still *on* a tab)\n * - `[\"(tabs)\"]` → `\"index\"` (the group's own index route)\n * - `[\"(tabs)\", \"[id]\"]` → `undefined` (dynamic route, not a tab)\n * - `[\"settings\"]` → `undefined` (no group layout ⇒ no tabs)\n * - `[]` / `undefined` → `undefined`\n *\n * Exported so the rules are unit-testable without standing up a registry.\n */\nexport function deriveActiveTabFromSegments(segments?: string[]): string | undefined {\n if (!segments || segments.length === 0) return undefined;\n\n let innermostGroup = -1;\n for (let i = 0; i < segments.length; i++) {\n const segment = segments[i];\n if (typeof segment === 'string' && segment.startsWith('(') && segment.endsWith(')')) {\n innermostGroup = i;\n }\n }\n // No layout group at all — the app has no tab shell, so claiming an active\n // tab would be an invention.\n if (innermostGroup === -1) return undefined;\n\n const next = segments[innermostGroup + 1];\n // The group IS the leaf: the router is showing that group's index route.\n if (next === undefined) return 'index';\n if (typeof next !== 'string' || next.length === 0) return undefined;\n // A dynamic segment is a detail screen reached from a tab, not a tab itself.\n if (next.startsWith('[') && next.endsWith(']')) return undefined;\n return next;\n}\n\n/**\n * Project an element's runtime state into a runner-native pixel-space `bbox`.\n *\n * Returns `{x, y, w, h}` in PHYSICAL pixels (RN `state.layout` is logical dp;\n * we multiply by `pixelRatio` — `PixelRatio.get()`, injected via\n * `registry.setPixelRatio` — so the box aligns with the runner's adb screencap\n * frame). See {@link NativeElementBbox} for why the shape is `{x,y,w,h}` and\n * not the web SDK's `{x,y,width,height}`.\n *\n * `pixelRatio` is INJECTED rather than read from `react-native` here: this is a\n * non-React core module, and a static `import { PixelRatio } from 'react-native'`\n * breaks both the vitest suite (\"Flow is not supported\") and risks the\n * Metro/Hermes `unknownModuleError` that bit `design-handlers`/`page-health`.\n * The provider wires the real ratio via `setPixelRatio`; callers/tests that\n * never wire it get the `1` default (dp ≈ px, still a usable box).\n *\n * Gating (avoid poisoning the snapshot — the flat registry mixes routes and\n * some elements carry stale off-screen coords):\n * - returns `undefined` unless `visibility === 'visible'` (visible + measured)\n * - returns `undefined` when `state.layout` is null/absent\n * Clamps every component to a non-negative integer.\n *\n * Uses `measureInWindow`'s absolute `pageX`/`pageY` for the origin. Falls back\n * to the layout-relative `x`/`y` only when `pageX`/`pageY` weren't measured\n * (rare; keeps a best-effort box rather than dropping the element).\n */\nexport function projectBbox(\n state: NativeElementState,\n visibility: 'visible' | 'likely-visible' | 'hidden',\n pixelRatio = 1\n): NativeElementBbox | undefined {\n if (visibility !== 'visible') return undefined;\n const layout = state.layout;\n if (!layout) return undefined;\n\n const ratio = pixelRatio > 0 && Number.isFinite(pixelRatio) ? pixelRatio : 1;\n const toPx = (v: number): number => Math.max(0, Math.round(v * ratio));\n\n const hasPage =\n typeof layout.pageX === 'number' &&\n typeof layout.pageY === 'number' &&\n Number.isFinite(layout.pageX) &&\n Number.isFinite(layout.pageY);\n const originX = hasPage ? layout.pageX : layout.x;\n const originY = hasPage ? layout.pageY : layout.y;\n\n if (\n typeof originX !== 'number' ||\n typeof originY !== 'number' ||\n typeof layout.width !== 'number' ||\n typeof layout.height !== 'number' ||\n !Number.isFinite(originX) ||\n !Number.isFinite(originY) ||\n !Number.isFinite(layout.width) ||\n !Number.isFinite(layout.height)\n ) {\n return undefined;\n }\n\n return {\n x: toPx(originX),\n y: toPx(originY),\n w: toPx(layout.width),\n h: toPx(layout.height),\n };\n}\n\n// ── Visibility ──────────────────────────────────────────────────────────────\n\n/**\n * A rectangle in window (page) coordinates, logical dp — the same space\n * `measureInWindow` reports `pageX`/`pageY` in.\n */\nexport interface NativePageRect {\n left: number;\n top: number;\n right: number;\n bottom: number;\n}\n\n/**\n * Why an element is not plainly visible.\n *\n * DUPLICATE of `@qontinui/ui-bridge` `VisibilityReason`\n * (`src/core/types.ts` — `'hidden' | 'off-screen' | 'occluded' | 'no-layout'`),\n * for the same reason the action types above are duplicated: `@qontinui/ui-bridge`\n * is an OPTIONAL peer of this package, so this module must not import from it.\n * KEEP IN SYNC — one vocabulary across both SDKs is the point; do not coin\n * native-only spellings.\n *\n * `'occluded'` is declared but never produced here: React Native gives the\n * registry no hit-test equivalent of `document.elementFromPoint`, so this SDK\n * cannot honestly claim occlusion. It stays in the union so a native reason\n * string is always a valid web reason string.\n */\nexport type NativeVisibilityReason = 'hidden' | 'off-screen' | 'occluded' | 'no-layout';\n\n/** The three-value verdict carried on every snapshot element. */\nexport type NativeVisibility = 'visible' | 'likely-visible' | 'hidden';\n\n/**\n * Convert an element's measured layout into a page-space rect, or `null` when\n * it has no TRUSTWORTHY page-space origin.\n *\n * STRICTER THAN {@link projectBbox} ON PURPOSE. `projectBbox` falls back to the\n * parent-relative `x`/`y` when `pageX`/`pageY` weren't measured, because a\n * slightly-wrong box is still a usable box. Clipping cannot take that trade: a\n * parent-relative origin compared against window coordinates silently mixes two\n * coordinate spaces and yields a wrong `hidden` verdict — the outcome\n * `RegisterElementOptions.scrollAncestorId` calls worse than a coarse\n * `visible`. So a layout flagged `pageOriginUnmeasured` returns `null` here,\n * and {@link computeVisibility} declines to clip rather than guess.\n */\nexport function pageRectOf(state: NativeElementState): NativePageRect | null {\n const layout = state.layout;\n if (!layout) return null;\n // The writer told us `pageX`/`pageY` are a parent-relative stand-in, not a\n // `measureInWindow` result. Not a page-space rect, and not guessable into one.\n if (layout.pageOriginUnmeasured === true) return null;\n\n const hasPage =\n typeof layout.pageX === 'number' &&\n typeof layout.pageY === 'number' &&\n Number.isFinite(layout.pageX) &&\n Number.isFinite(layout.pageY);\n if (!hasPage) return null;\n\n const left = layout.pageX;\n const top = layout.pageY;\n\n if (\n typeof layout.width !== 'number' ||\n typeof layout.height !== 'number' ||\n !Number.isFinite(layout.width) ||\n !Number.isFinite(layout.height)\n ) {\n return null;\n }\n\n return { left, top, right: left + layout.width, bottom: top + layout.height };\n}\n\n/** Do two 1-D spans share any extent? A zero-length span counts as touching. */\nfunction spansOverlap(aMin: number, aMax: number, bMin: number, bMax: number): boolean {\n if (aMin === aMax) return aMin >= bMin && aMin <= bMax;\n return aMin < bMax && aMax > bMin;\n}\n\n/**\n * Is this rect empty — nothing can overlap it?\n *\n * {@link intersectRects} returns an INVERTED rect (`right < left`) when the two\n * inputs are disjoint, which is the honest answer for \"the reachable region\",\n * but `spansOverlap`'s `aMin < bMax && aMax > bMin` reads an inverted span as\n * overlapping. Every consumer of an intersection must ask this first.\n */\nexport function isEmptyRect(rect: NativePageRect): boolean {\n return rect.right <= rect.left || rect.bottom <= rect.top;\n}\n\n/**\n * Intersect two page rects, or `null` when either is absent (`null` means\n * UNKNOWN, so it never narrows the other side).\n *\n * The result may be EMPTY — check {@link isEmptyRect}. That happens whenever\n * the two rects are disjoint, e.g. a scroll container that has itself been\n * scrolled out of the window: nothing inside it can be on screen, and an empty\n * clip is exactly how that is expressed.\n */\nexport function intersectRects(\n a: NativePageRect | null,\n b: NativePageRect | null\n): NativePageRect | null {\n if (!a) return b;\n if (!b) return a;\n return {\n left: Math.max(a.left, b.left),\n top: Math.max(a.top, b.top),\n right: Math.min(a.right, b.right),\n bottom: Math.min(a.bottom, b.bottom),\n };\n}\n\n/**\n * Decide what a snapshot should say about an element being on screen.\n *\n * THE DEFECT THIS CLOSES: visibility used to be derived from mount + `measure()`\n * alone — `state.visible ? (state.layout ? 'visible' : 'likely-visible') : 'hidden'`\n * — with no comparison against any bounds at all. Every mounted, measured\n * element reported `visible`, including rows scrolled far past the fold, so a\n * snapshot claimed things were on screen that were not.\n *\n * SCOPE — read this before citing it. This is a PURE PROJECTION: it reads\n * `state.visible` and never writes it. An off-screen element still carries\n * `state.visible === true`; only the snapshot's `visibility` /\n * `visibilityReason` change. That is a deliberate divergence from the web SDK,\n * which folds off-screen INTO the boolean (`@qontinui/ui-bridge`\n * `src/core/registry.ts` — `if (!inViewport) return { visible: false, reason:\n * 'off-screen' }`), and it means any consumer asserting on `state.visible`\n * alone — `/manual-test`'s \"PRESENT IS NOT VISIBLE\" gate among them — sees no\n * change on mobile and stays as vacuous as it was. Closing that needs either a\n * matching demotion of `state.visible` here or a consumer that reads\n * `visibility`; both are contract decisions beyond this projection, and\n * neither is done. The strings are shared with the web SDK; the SHAPE is not.\n *\n * `clip` is the region the element must reach to count as on screen — the\n * window, intersected with the measured frame of a declared\n * `scrollAncestorId`. **A `null`/absent clip means the bounds are UNKNOWN, and\n * an unknown never demotes**: with no viewport injected (every non-RN caller,\n * including this package's own suite) the answer is exactly what it was before.\n * Absence of evidence is not evidence of off-screen.\n *\n * Any overlap at all counts as visible. A half-scrolled row IS on screen, and\n * a ratio threshold would be a second, unshared policy knob for callers to\n * disagree about.\n */\nexport function computeVisibility(\n state: NativeElementState,\n clip?: NativePageRect | null\n): { visibility: NativeVisibility; visibilityReason?: NativeVisibilityReason } {\n if (!state.visible) {\n return { visibility: 'hidden', visibilityReason: 'hidden' };\n }\n if (state.layout === null) {\n // Registered and mounted but not yet measured. `'likely-visible'` already\n // is this SDK's honest-UNKNOWN value; `'no-layout'` names why.\n return { visibility: 'likely-visible', visibilityReason: 'no-layout' };\n }\n if (!clip) {\n return { visibility: 'visible' };\n }\n const rect = pageRectOf(state);\n if (!rect) {\n // Measured, but with no trustworthy page-space origin (see `pageRectOf`).\n // Report it exactly as before — an unknown must not manufacture a verdict.\n return { visibility: 'visible' };\n }\n // A disjoint intersection (a scroll container itself scrolled off the window)\n // inverts rather than zeroing, and `spansOverlap` would read an inverted span\n // as overlapping. Nothing can be inside an empty clip.\n if (isEmptyRect(clip)) {\n return { visibility: 'hidden', visibilityReason: 'off-screen' };\n }\n const onScreen =\n spansOverlap(rect.left, rect.right, clip.left, clip.right) &&\n spansOverlap(rect.top, rect.bottom, clip.top, clip.bottom);\n\n return onScreen\n ? { visibility: 'visible' }\n : { visibility: 'hidden', visibilityReason: 'off-screen' };\n}\n\n/**\n * Infer available actions based on element type.\n *\n * `scrollIntoView` is advertised only when the element DECLARES a\n * `scrollAncestorId`. It is the one input the action cannot work without (the\n * registry keeps no parent chain, so there is nothing else to scroll), and the\n * runner refuses any action an element does not advertise — so advertising it\n * everywhere would put a verb on every element that answers `NOT_SUPPORTED`\n * for all but the declared few. An ancestor that turns out to be unregistered\n * or not a ScrollView is still answered honestly by the executor\n * (`NOT_SUPPORTED`).\n */\nfunction inferActions(type: NativeElementType, scrollAncestorId?: string): NativeStandardAction[] {\n const baseActions: NativeStandardAction[] = scrollAncestorId\n ? ['focus', 'blur', 'scrollIntoView']\n : ['focus', 'blur'];\n\n switch (type) {\n case 'button':\n case 'touchable':\n case 'pressable':\n return [...baseActions, 'click', 'press', 'longPress', 'doubleTap'];\n case 'input':\n return [...baseActions, 'click', 'press', 'type', 'setValue', 'clear'];\n case 'text':\n return [...baseActions, 'click', 'press', 'longPress'];\n case 'view':\n return [...baseActions, 'click', 'press'];\n case 'scroll':\n return [...baseActions, 'scroll', 'swipe'];\n case 'list':\n return [...baseActions, 'scroll', 'swipe'];\n case 'listItem':\n return [...baseActions, 'click', 'press', 'longPress', 'swipe'];\n case 'switch':\n case 'checkbox':\n return [...baseActions, 'click', 'press', 'toggle'];\n case 'radio':\n return [...baseActions, 'click', 'press'];\n case 'image':\n return [...baseActions, 'click', 'press', 'longPress'];\n case 'modal':\n return ['focus', 'blur'];\n case 'custom':\n default:\n return [...baseActions, 'click', 'press'];\n }\n}\n\n/**\n * Native UI Bridge Registry\n *\n * Manages registration and lookup of native UI elements and components.\n */\nexport class NativeUIBridgeRegistry {\n private elements = new Map<string, RegisteredNativeElement>();\n private components = new Map<string, RegisteredNativeComponent>();\n private workflows = new Map<string, Workflow>();\n private eventListeners = new Map<BridgeEventType, Set<BridgeEventListener>>();\n private config: NativeRegistryConfig;\n private enrichers: NativeSnapshotEnrichers = {};\n private snapshotExtras = new Map<string, NativeSnapshotEnricher>();\n /**\n * App identification metadata (appId/appName/appType/framework). Set via\n * `setAppInfo` — typically wired in the server constructor from the\n * `NativeUIBridgeConfig` the host passes to `UIBridgeNativeProvider`.\n *\n * When set, `createSnapshot` includes it on the resulting snapshot so\n * agents can identify the app from snapshot bytes alone (parity with the\n * `uiBridge` block on the `health` response). Snapshots created before\n * this is wired simply omit the field.\n */\n private appInfo: NativeAppInfo | null = null;\n /**\n * Optional route provider. When set, `createSnapshot` reads\n * `currentRoute`/`segments` from it whenever the caller does not pass an\n * explicit `routeInfo` argument. This lets the default `getSnapshot` HTTP\n * handler — which has no direct reference to the `NativeUIBridgeServer`\n * instance — still emit a populated `currentRoute` field.\n *\n * Wired by `NativeUIBridgeServer.setRouteProvider`, which forwards the\n * provider into the registry alongside the per-handler overrides it\n * already installs.\n */\n private routeProvider: NativeRouteProviderLike | null = null;\n /**\n * Device pixel ratio used to project `state.layout` (logical dp) into the\n * physical-pixel `bbox` emitted on each snapshot element. Defaults to `1`\n * (dp ≈ px) so callers/tests that never inject a ratio still get a usable\n * box; the React provider wires the real `PixelRatio.get()` via\n * {@link setPixelRatio}. Read from a non-React core module on purpose — see\n * the `projectBbox` doc comment for why we don't import `react-native` here.\n */\n private pixelRatio = 1;\n /**\n * Injected getter for the device window size in logical dp, used to clip\n * reported visibility. Injected rather than read here for exactly the reason\n * `pixelRatio` is: a static `import { Dimensions } from 'react-native'` in\n * this non-React core module breaks the vitest suite and risks the\n * Metro/Hermes `unknownModuleError`. It is a PROVIDER, not a value, so a\n * rotation is picked up on the next snapshot with nothing to keep in sync.\n *\n * `null` means the window bounds are UNKNOWN, and {@link computeVisibility}\n * treats unknown bounds as \"cannot demote\" — never as an empty viewport.\n */\n private viewportProvider: (() => { width: number; height: number }) | null = null;\n /**\n * Sticky flag: flips `true` the first time any element is registered and\n * stays `true` even after elements are unregistered. Lets agents distinguish\n * \"this route never wired any elements\" from \"this route registered then\n * unmounted\".\n */\n private everHadRegistrations = false;\n\n constructor(config: NativeRegistryConfig = {}) {\n this.config = config;\n }\n\n // ============================================================================\n // App Info & Route Provider\n // ============================================================================\n\n /**\n * Set the app identification metadata returned alongside snapshots.\n * Idempotent — re-calling with the same shape is a no-op.\n * Pass `null` (or omit a previous call) to clear.\n */\n setAppInfo(info: NativeAppInfo | null | undefined): void {\n this.appInfo = info ?? null;\n }\n\n /** Read-only accessor for the registered app info, if any. */\n getAppInfo(): NativeAppInfo | null {\n return this.appInfo;\n }\n\n /**\n * Set a route provider whose `getCurrentRoute`/`getSegments` are read by\n * `createSnapshot` when no explicit `routeInfo` argument is supplied.\n *\n * Call with `null` to detach (e.g. when the host swaps providers on HMR).\n */\n setRouteProvider(provider: NativeRouteProviderLike | null | undefined): void {\n this.routeProvider = provider ?? null;\n }\n\n /** Read-only accessor for the registered route provider, if any. */\n getRouteProvider(): NativeRouteProviderLike | null {\n return this.routeProvider;\n }\n\n /**\n * Resolve the snapshot's `activeTab`: an explicit `getActiveTab()` on the\n * route provider wins, otherwise derive it from the Expo Router segments the\n * provider already exposes.\n *\n * A throwing or empty-string provider degrades to the derivation rather than\n * to `undefined` — the host's opt-in extra should never be able to make the\n * snapshot WORSE than it was without it. A blank derivation stays blank.\n */\n private resolveActiveTab(segments: string[] | undefined): string | undefined {\n const explicit = (() => {\n if (!this.routeProvider?.getActiveTab) return undefined;\n try {\n const value = this.routeProvider.getActiveTab();\n return typeof value === 'string' && value.length > 0 ? value : undefined;\n } catch (error) {\n if (this.config.verbose) {\n console.warn(`[ui-bridge-native] routeProvider getActiveTab threw:`, error);\n }\n return undefined;\n }\n })();\n return explicit ?? deriveActiveTabFromSegments(segments);\n }\n\n /**\n * Set the device pixel ratio used to project per-element `bbox` geometry\n * into physical pixels. The React provider passes `PixelRatio.get()` here\n * once at startup. Ignores non-finite / non-positive values (keeps the\n * previous ratio) so a bad call can't zero out every bbox.\n */\n setPixelRatio(ratio: number): void {\n if (typeof ratio === 'number' && Number.isFinite(ratio) && ratio > 0) {\n this.pixelRatio = ratio;\n }\n }\n\n /** Read-only accessor for the device pixel ratio used for bbox projection. */\n getPixelRatio(): number {\n return this.pixelRatio;\n }\n\n /**\n * Set the getter for the device window size (logical dp) that reported\n * visibility is clipped against. The React provider passes\n * `() => Dimensions.get('window')` here at construction.\n *\n * Pass `null` to detach. While detached the window bounds are UNKNOWN and no\n * element is ever demoted for being outside them.\n */\n setViewportProvider(\n provider: (() => { width: number; height: number }) | null | undefined\n ): void {\n this.viewportProvider = provider ?? null;\n }\n\n /**\n * The window as a page-space rect, or `null` when it is unknown or the\n * provider returned something unusable (it throws in some RN teardown\n * paths, and a zero-size window would silently hide the entire screen).\n */\n getViewportRect(): NativePageRect | null {\n if (!this.viewportProvider) return null;\n let size: { width: number; height: number };\n try {\n size = this.viewportProvider();\n } catch (error) {\n if (this.config.verbose) {\n console.warn(`[ui-bridge-native] viewportProvider threw:`, error);\n }\n return null;\n }\n const { width, height } = size ?? {};\n if (\n typeof width !== 'number' ||\n typeof height !== 'number' ||\n !Number.isFinite(width) ||\n !Number.isFinite(height) ||\n width <= 0 ||\n height <= 0\n ) {\n return null;\n }\n return { left: 0, top: 0, right: width, bottom: height };\n }\n\n /**\n * The region `element` must reach to count as on screen: the window,\n * intersected with the measured frame of its declared `scrollAncestorId`.\n *\n * Returns `null` when neither bound is known — see {@link computeVisibility}\n * for why that means \"do not demote\" rather than \"nothing is visible\".\n * An ancestor that is not registered, or registered but not yet measured,\n * contributes nothing rather than hiding its subtree.\n */\n getClipRectFor(\n element: RegisteredNativeElement,\n viewport?: NativePageRect | null\n ): NativePageRect | null {\n // `undefined` = not supplied, read it now. `null` = the caller already\n // read it and it was UNKNOWN — don't re-read and disagree with them.\n const bounds = viewport === undefined ? this.getViewportRect() : viewport;\n const ancestorId = element.scrollAncestorId;\n if (!ancestorId) return bounds;\n\n // Single level by design: only the DECLARED ancestor is applied, and its\n // own `scrollAncestorId` is not followed. The window clip already covers\n // most of what a second level would add, and a recursive walk needs a\n // visited set to survive a declaration cycle. Revisit together.\n const ancestor = this.elements.get(ancestorId);\n if (!ancestor || ancestorId === element.id) return bounds;\n\n return intersectRects(bounds, pageRectOf(ancestor.getState()));\n }\n\n // ============================================================================\n // Snapshot Enricher Slots\n // ============================================================================\n\n /**\n * Register/replace canonical enrichers (modal/toast/undo). HMR-safe — calling\n * with a partial set merges into existing slots instead of clobbering them.\n */\n setEnrichers(e: Partial<NativeSnapshotEnrichers>): void {\n this.enrichers = { ...this.enrichers, ...e };\n }\n\n /**\n * Read-only accessor for the canonical enrichers slot. Returned object is\n * the live reference, so callers can detect \"no detector wired\" via\n * `getEnrichers().modalDetector === undefined`. Used by the test-hook HTTP\n * handlers (`control/modal/push`, `control/modal/dismiss/:id`) which need\n * to drive the ModalDetector directly without re-instantiating it.\n */\n getEnrichers(): Readonly<NativeSnapshotEnrichers> {\n return this.enrichers;\n }\n\n /**\n * Register a custom snapshot enricher. The returned object will be\n * `Object.assign`ed onto the snapshot, so use unique top-level keys to avoid\n * clobbering canonical fields. Returns a disposer.\n */\n registerSnapshotEnricher(name: string, fn: NativeSnapshotEnricher): () => void {\n this.snapshotExtras.set(name, fn);\n return () => this.unregisterSnapshotEnricher(name);\n }\n\n /** Remove a custom snapshot enricher by name */\n unregisterSnapshotEnricher(name: string): void {\n this.snapshotExtras.delete(name);\n }\n\n // ============================================================================\n // Element Management\n // ============================================================================\n\n /**\n * Register a native element\n */\n registerElement(\n id: string,\n ref: React.RefObject<NativeElementRef>,\n options: RegisterElementOptions = {}\n ): RegisteredNativeElement {\n const {\n type = 'custom',\n label,\n customActions,\n props,\n treePath = id,\n testId,\n accessibilityLabel,\n registrationRoute,\n scrollAncestorId,\n flatStyle,\n stateStyles,\n } = options;\n const actions = options.actions ?? inferActions(type, scrollAncestorId);\n\n // Create state getter\n const getState = (): NativeElementState => {\n const element = ref.current;\n if (!element) {\n return {\n mounted: false,\n visible: false,\n enabled: false,\n focused: false,\n layout: null,\n };\n }\n\n // State is populated by the element during onLayout\n // Here we return the stored state from the element's metadata\n const stored = this.elements.get(id);\n if (stored && stored.getState !== getState) {\n return stored.getState();\n }\n\n return {\n mounted: true,\n visible: true,\n enabled: true,\n focused: false,\n layout: null,\n };\n };\n\n // Create identifier getter\n const getIdentifier = (): NativeElementIdentifier => ({\n uiId: id,\n testId: testId || id,\n accessibilityLabel,\n treePath,\n });\n\n const registered: RegisteredNativeElement = {\n id,\n ref,\n type,\n label,\n actions,\n customActions,\n props,\n getState,\n getIdentifier,\n registeredAt: Date.now(),\n mounted: true,\n registrationRoute: registrationRoute ?? null,\n scrollAncestorId,\n flatStyle,\n stateStyles,\n };\n\n this.elements.set(id, registered);\n this.everHadRegistrations = true;\n\n this.emit('element:registered', { id, type, label });\n\n if (this.config.verbose) {\n console.log(`[ui-bridge-native] Registered element: ${id} (${type})`);\n }\n\n // Seed a sensible initial state so elements are immediately visible in snapshots\n // even before onLayout fires. Layout-measuring code can overwrite this later.\n //\n // For controlled-input elements (`type:'input'` with a string `props.value`),\n // also seed `state.value` from the prop so bridge consumers can read the\n // default value before the user has typed. See `updateElementProps` for\n // the corresponding re-sync path on prop changes.\n const seededState: Partial<NativeElementState> = {\n mounted: true,\n visible: true,\n enabled: true,\n focused: false,\n layout: null,\n };\n if (type === 'input' && typeof props?.value === 'string') {\n seededState.value = props.value;\n }\n // For `type:'text'` elements, surface the (dynamic) label as `state.value`\n // so bridge consumers can read text content with a uniform `state.value`\n // accessor instead of parsing the `label` field (\"Status: ...\"). The hook\n // already re-publishes the label via `updateElementMeta` when consumers\n // call `updateLabel(newLabel)` — that path also re-syncs `state.value`\n // (see `updateElementMeta`).\n if (type === 'text' && typeof label === 'string') {\n seededState.value = label;\n }\n this.updateElementState(id, seededState);\n\n return registered;\n }\n\n /**\n * Unregister an element\n */\n unregisterElement(id: string): void {\n const element = this.elements.get(id);\n if (element) {\n this.elements.delete(id);\n this.emit('element:unregistered', { id });\n\n if (this.config.verbose) {\n console.log(`[ui-bridge-native] Unregistered element: ${id}`);\n }\n }\n }\n\n /**\n * Get a registered element\n */\n getElement(id: string): RegisteredNativeElement | undefined {\n return this.elements.get(id);\n }\n\n /**\n * Get all registered elements\n */\n getAllElements(): RegisteredNativeElement[] {\n return Array.from(this.elements.values());\n }\n\n /**\n * Get all registered elements that are visible AND have a measured layout.\n *\n * This is the *strict* visibility filter: requires `state.visible === true`\n * AND `state.layout !== null`. Use this when you need both signals\n * (e.g. coord-based tap, where you need an actual rect to hit-test against).\n *\n * Callers driving an LLM agent typically want\n * {@link getMountedVisibleElements} instead — that variant accepts\n * elements that *should* be on screen (visible:true) but whose first\n * `onLayout` has not yet fired. Without it, a snapshot taken in the gap\n * between mount and the first layout pass returns 0 elements on a fully\n * populated screen.\n */\n getVisibleElements(): RegisteredNativeElement[] {\n return this.getAllElements().filter((e) => {\n const state = e.getState();\n return state.visible && state.layout !== null;\n });\n }\n\n /**\n * Get all registered elements marked as visible (regardless of layout).\n *\n * Looser than {@link getVisibleElements}: includes elements whose\n * `onLayout` callback has not yet fired (so `layout === null`). React\n * Native's `onLayout` is async — there's a one-tick window after mount\n * where elements are in the tree, the user *sees* them, but the\n * registry hasn't received their measurements yet. Excluding those\n * elements makes `getSnapshot?visibleOnly=true` return 0 on a populated\n * screen, which is a worse failure mode than including a few elements\n * we can't yet locate spatially.\n *\n * Used by `createSnapshot`'s `visibleOnly` filter and by the\n * `getSnapshot` / `getElements` handlers. Each emitted element carries a\n * `visibility` discriminator (`\"visible\"` / `\"likely-visible\"`) so\n * agents that *do* require a known rect can branch downstream.\n */\n getMountedVisibleElements(): RegisteredNativeElement[] {\n return this.getAllElements().filter((e) => e.getState().visible);\n }\n\n /**\n * Get elements registered on a specific route (for page-scoped filtering)\n */\n getElementsForRoute(route: string): RegisteredNativeElement[] {\n return this.getAllElements().filter((e) => e.registrationRoute === route);\n }\n\n /**\n * Mark elements registered on a route as off-screen (visible: false, layout: null).\n *\n * Use this when a screen loses focus but stays mounted — common in React Navigation\n * tab navigators where inactive tabs remain in the tree. Without this call, stale\n * `layout` data lingers in snapshots and makes off-screen elements look rendered.\n *\n * Does NOT unregister the elements — they stay registered so the user's next visit\n * re-measures them via `onLayout` without re-mount cost. Elements without a\n * `registrationRoute` (app-wide registrations) are untouched.\n */\n markRouteOffscreen(route: string): void {\n // Guard against accidental global wipes. Elements registered without a\n // route have `registrationRoute: null` — passing null/empty here would\n // match every globally-registered element and erase their layouts.\n if (route == null || route === '') {\n if (this.config.verbose) {\n console.warn(\n `[ui-bridge-native] markRouteOffscreen called with null/empty route — ignoring`\n );\n }\n return;\n }\n let cleared = 0;\n for (const element of this.elements.values()) {\n if (element.registrationRoute === route) {\n this.updateElementState(element.id, {\n visible: false,\n layout: null,\n });\n cleared++;\n }\n }\n if (this.config.verbose && cleared > 0) {\n console.log(`[ui-bridge-native] Marked ${cleared} elements offscreen for route: ${route}`);\n }\n }\n\n /**\n * Re-measure every mounted-visible element's geometry via its stored React\n * ref and write the fresh coordinates into the registry (\"measure-on-\n * snapshot\").\n *\n * Why: element geometry is otherwise captured ONCE at mount time\n * (`onLayout` + `measureInWindow` in `useUIElement`) and RN never re-fires\n * `onLayout` on pure translation — scrolling a virtualized list\n * (FlashList), recycling a cell, a keyboard shift or an orientation change\n * all move elements WITHOUT updating the stored `state.layout`. Snapshot\n * consumers (vision analyzers hit-testing `bbox`, coord-based tap) then\n * operate on stale positions. Re-measuring at READ time is correct\n * regardless of what moved the element and needs zero per-consumer wiring:\n * every registry entry already stores its ref (see `registerElement`).\n *\n * Per-element outcomes:\n * - non-zero dims → write a fresh full layout (same state shape as the\n * mount-time measure loop in `useUIElement`); counted as `measured`.\n * - zero dims AND the element previously had a non-null `state.layout` →\n * the view collapsed / left the screen; clear to\n * `{ visible: false, layout: null }` (same shape `markRouteOffscreen`\n * writes); counted as `cleared`.\n * - zero dims and it never had a layout → leave state untouched (element\n * in the mount→first-onLayout gap; don't demote `likely-visible`);\n * counted as `skipped`.\n * - no ref / no callable `measureInWindow` (test fixtures, web) → leave\n * untouched; counted as `skipped`.\n *\n * The whole sweep races an overall timeout (default 250 ms) so a dead ref\n * whose `measureInWindow` never calls back can never hang a snapshot: the\n * returned promise resolves at the deadline with whatever counts have\n * accumulated. Late callbacks may still write state afterwards — harmless,\n * freshest data wins. Never throws.\n *\n * Non-React core module on purpose — `measureInWindow` is duck-typed off\n * the stored ref rather than imported from `react-native` (see the\n * `projectBbox` doc comment for why this file must not import RN).\n */\n async refreshMeasurements(options?: {\n timeoutMs?: number;\n }): Promise<{ measured: number; cleared: number; skipped: number }> {\n const timeoutMs =\n typeof options?.timeoutMs === 'number' &&\n Number.isFinite(options.timeoutMs) &&\n options.timeoutMs > 0\n ? options.timeoutMs\n : 250;\n\n const counts = { measured: 0, cleared: 0, skipped: 0 };\n const pending: Array<Promise<void>> = [];\n\n for (const element of this.getMountedVisibleElements()) {\n const node = element.ref?.current as\n | (NativeElementRef & {\n measureInWindow?: (\n callback: (pageX: number, pageY: number, w: number, h: number) => void\n ) => void;\n })\n | null\n | undefined;\n\n if (!node || typeof node.measureInWindow !== 'function') {\n counts.skipped++;\n continue;\n }\n\n const id = element.id;\n pending.push(\n new Promise<void>((resolve) => {\n let settled = false;\n try {\n node.measureInWindow!((pageX: number, pageY: number, w: number, h: number) => {\n if (settled) return;\n settled = true;\n try {\n if (w > 0 && h > 0) {\n this.updateElementState(id, {\n mounted: true,\n visible: true,\n enabled: true,\n focused: false,\n layout: { x: pageX, y: pageY, width: w, height: h, pageX, pageY },\n });\n counts.measured++;\n } else if (this.elements.get(id)?.getState().layout != null) {\n // Collapsed / off-screen: it HAD a measured rect and now\n // reports zeros. Clear it so stale coords can't poison the\n // snapshot (same shape as markRouteOffscreen).\n this.updateElementState(id, { visible: false, layout: null });\n counts.cleared++;\n } else {\n counts.skipped++;\n }\n } finally {\n resolve();\n }\n });\n } catch {\n // A throwing measureInWindow must never break the sweep.\n if (!settled) {\n settled = true;\n counts.skipped++;\n resolve();\n }\n }\n })\n );\n }\n\n if (pending.length > 0) {\n await new Promise<void>((resolve) => {\n const timer = setTimeout(resolve, timeoutMs);\n void Promise.all(pending).then(() => {\n clearTimeout(timer);\n resolve();\n });\n });\n }\n\n return counts;\n }\n\n /**\n * Update element state\n */\n updateElementState(id: string, state: Partial<NativeElementState>): void {\n const element = this.elements.get(id);\n if (element) {\n // Create a new getState that includes the updated state\n const currentState = element.getState();\n const newState = { ...currentState, ...state };\n\n const updated: RegisteredNativeElement = {\n ...element,\n getState: () => newState,\n };\n\n this.elements.set(id, updated);\n this.emit('element:stateChanged', { id, state: newState });\n }\n }\n\n /**\n * Update an element's descriptive metadata (label / accessibilityLabel /\n * testId). Sister to {@link updateElementState} (which carries layout +\n * visibility) and {@link updateElementProps} (which carries event handlers).\n *\n * Idempotent — if every passed field equals the existing value, the call\n * returns without mutating the entry or emitting an event. This keeps\n * `useUIElement().updateLabel(...)` cheap when consumers re-publish from a\n * render path that produces the same string on every tick.\n *\n * Returns `true` when the entry was mutated, `false` otherwise. Callers\n * that want to gate a `console.warn` on no-op invocations can use the\n * return value instead of recomputing equality.\n */\n updateElementMeta(\n id: string,\n meta: { label?: string; accessibilityLabel?: string; testId?: string }\n ): boolean {\n const element = this.elements.get(id);\n if (!element) return false;\n\n // The `testId` on a registered element lives inside the identifier\n // closure (see registerElement's `getIdentifier`). To rebuild it we\n // need the current value — read it via the existing identifier and\n // overlay the new one if provided.\n const currentIdentifier = element.getIdentifier();\n const nextLabel = meta.label !== undefined ? meta.label : element.label;\n const nextAccessibilityLabel =\n meta.accessibilityLabel !== undefined\n ? meta.accessibilityLabel\n : currentIdentifier.accessibilityLabel;\n const nextTestId = meta.testId !== undefined ? meta.testId : currentIdentifier.testId;\n\n const labelChanged = nextLabel !== element.label;\n const accessibilityLabelChanged =\n nextAccessibilityLabel !== currentIdentifier.accessibilityLabel;\n const testIdChanged = nextTestId !== currentIdentifier.testId;\n\n if (!labelChanged && !accessibilityLabelChanged && !testIdChanged) {\n return false;\n }\n\n const updated: RegisteredNativeElement = {\n ...element,\n label: nextLabel,\n getIdentifier: (): NativeElementIdentifier => ({\n uiId: id,\n testId: nextTestId,\n accessibilityLabel: nextAccessibilityLabel,\n treePath: currentIdentifier.treePath,\n }),\n };\n this.elements.set(id, updated);\n\n // For text-type elements, mirror the new label into `state.value` so\n // bridge consumers can read text content with a uniform `state.value`\n // accessor. Initial seed lives in `registerElement`; this keeps the\n // mirror in sync when consumers call `updateLabel(newLabel)` from a\n // state-driven render path (e.g. `Status: ${connected ? 'online' : 'offline'}`).\n if (element.type === 'text' && labelChanged && typeof nextLabel === 'string') {\n this.updateElementState(id, { value: nextLabel });\n }\n\n // Reuse `element:registered` rather than minting a new event — downstream\n // consumers already subscribe to it for label/identifier diffs, and\n // adding a new BridgeEventType ('element:metaChanged') would force a\n // SemVer-major bump on every snapshot consumer.\n this.emit('element:registered', {\n id,\n type: element.type,\n label: nextLabel,\n });\n\n return true;\n }\n\n /**\n * Update element props (for action execution).\n *\n * Side effect for `type: 'input'` elements: when `props.value` is a string,\n * mirror it into `state.value` so AI drivers reading the registry don't see\n * `state.value === undefined` until the user types. Before this mirror,\n * controlled-input consumers (`<TextInput value={x} onChangeText={setX} />`\n * with `captureProps({ value: x, onChangeText: setX })`) registered an\n * input whose `state.value` only became defined after the FIRST\n * `onChangeText` call — bridge consumers couldn't read the default value\n * (e.g. a pre-populated API-URL input) until someone typed into it.\n *\n * Re-runs on every `updateElementProps` so a parent passing a fresh\n * `value` prop (controlled re-render) keeps the registry in sync. The\n * mirror is gated on `type === 'input'` to avoid touching non-input\n * elements that may carry an unrelated `value` prop (e.g. a Switch's\n * boolean value, which lives on `state.checked`).\n */\n updateElementProps(id: string, props: Record<string, unknown>): void {\n const element = this.elements.get(id);\n if (element) {\n const updated: RegisteredNativeElement = {\n ...element,\n props: { ...element.props, ...props },\n };\n this.elements.set(id, updated);\n\n // Controlled-input value mirror — see doc comment above.\n if (\n element.type === 'input' &&\n Object.prototype.hasOwnProperty.call(props, 'value') &&\n typeof props.value === 'string'\n ) {\n const currentState = updated.getState();\n if (currentState.value !== props.value) {\n this.updateElementState(id, { value: props.value });\n }\n }\n }\n }\n\n /**\n * Update element style for design review\n */\n updateElementStyle(\n id: string,\n flatStyle: Record<string, unknown>,\n stateStyles?: {\n pressed?: Record<string, unknown>;\n focused?: Record<string, unknown>;\n disabled?: Record<string, unknown>;\n }\n ): void {\n const element = this.elements.get(id);\n if (element) {\n const updated: RegisteredNativeElement = {\n ...element,\n flatStyle,\n ...(stateStyles !== undefined ? { stateStyles } : {}),\n };\n this.elements.set(id, updated);\n }\n }\n\n /**\n * Get element style for design review\n */\n getElementStyle(id: string): Record<string, unknown> | null {\n const element = this.elements.get(id);\n return element?.flatStyle ?? null;\n }\n\n /**\n * Find element by testID\n */\n findByTestId(testId: string): RegisteredNativeElement | undefined {\n for (const element of this.elements.values()) {\n const identifier = element.getIdentifier();\n if (identifier.testId === testId) {\n return element;\n }\n }\n return undefined;\n }\n\n /**\n * Find elements by type\n */\n findByType(type: NativeElementType): RegisteredNativeElement[] {\n return Array.from(this.elements.values()).filter((e) => e.type === type);\n }\n\n // ============================================================================\n // Component Management\n // ============================================================================\n\n /**\n * Register a component\n */\n registerComponent(id: string, options: RegisterComponentOptions): RegisteredNativeComponent {\n const { name, description, actions = [], elementIds } = options;\n\n const registered: RegisteredNativeComponent = {\n id,\n name,\n description,\n // Closed field list, applied once — see `toRegisteredComponentActions`.\n actions: toRegisteredComponentActions(actions),\n elementIds,\n registeredAt: Date.now(),\n mounted: true,\n };\n\n this.components.set(id, registered);\n\n this.emit('component:registered', { id, name });\n\n if (this.config.verbose) {\n console.log(`[ui-bridge-native] Registered component: ${id} (${name})`);\n }\n\n return registered;\n }\n\n /**\n * Update a registered component's declaration in place — name, description,\n * actions, elementIds.\n *\n * Sister to {@link updateElementMeta}, and it exists for the same reason one\n * level up. `registerComponent` publishes the declaration exactly once, and\n * `useUIComponent` registers on mount and never again, so an action whose\n * `label` carries a count, an action that only exists while a row is\n * selected, a `paramSchema` that widens once options load, or an `elementIds`\n * list that grows after mount, all published their mount-time shape to\n * `/control/components` forever. PR #176 closed that hole for an ELEMENT's\n * label; this closes it for a COMPONENT's declaration.\n *\n * **Idempotent by VALUE over the PUBLISHED shape.** `handler` identity is\n * excluded from the comparison — call sites pass inline closures that are\n * freshly allocated every render, so including it would report a change on\n * every call and make the door useless for a render-path publisher. The\n * newest handlers are still STORED whenever `actions` is supplied, which is\n * the other half of the same defect: without it the registry keeps the\n * closure from the render that registered the component, so a handler reading\n * component state read the state as it was at mount.\n *\n * Returns `true` when the published shape changed and an event was emitted,\n * `false` otherwise — the same contract as `updateElementMeta`, so a caller\n * can gate a warning or a state write on a real change.\n */\n updateComponentMeta(id: string, meta: UpdateComponentMetaOptions): boolean {\n const component = this.components.get(id);\n if (!component) return false;\n\n const nextName = meta.name !== undefined ? meta.name : component.name;\n const nextDescription =\n meta.description !== undefined ? meta.description : component.description;\n const nextActions =\n meta.actions !== undefined ? toRegisteredComponentActions(meta.actions) : component.actions;\n const nextElementIds = meta.elementIds !== undefined ? meta.elementIds : component.elementIds;\n\n const changed =\n nextName !== component.name ||\n nextDescription !== component.description ||\n !sameElementIds(nextElementIds, component.elementIds) ||\n publishedActionSignature(nextActions) !== publishedActionSignature(component.actions);\n\n // Nothing published changed AND no fresh handlers were offered: leave the\n // stored entry untouched so its identity stays stable for consumers holding\n // a reference.\n if (!changed && meta.actions === undefined) return false;\n\n // Store even when `changed` is false, provided actions were supplied: the\n // handlers in `nextActions` are the CURRENT render's closures. Keeping the\n // old ones is exactly how a component action ends up reading state from the\n // render it was first declared in.\n this.components.set(id, {\n ...component,\n name: nextName,\n description: nextDescription,\n actions: nextActions,\n elementIds: nextElementIds,\n });\n\n if (!changed) return false;\n\n // Reuse `component:registered` rather than minting a\n // 'component:metaChanged' BridgeEventType — same reasoning as\n // `updateElementMeta`'s reuse of `element:registered`: a new event type is a\n // breaking change for every consumer switching exhaustively over the union.\n this.emit('component:registered', { id, name: nextName });\n\n if (this.config.verbose) {\n console.log(`[ui-bridge-native] Updated component: ${id} (${nextName})`);\n }\n\n return true;\n }\n\n /**\n * Unregister a component\n */\n unregisterComponent(id: string): void {\n const component = this.components.get(id);\n if (component) {\n this.components.delete(id);\n this.emit('component:unregistered', { id });\n\n if (this.config.verbose) {\n console.log(`[ui-bridge-native] Unregistered component: ${id}`);\n }\n }\n }\n\n /**\n * Get a registered component\n */\n getComponent(id: string): RegisteredNativeComponent | undefined {\n return this.components.get(id);\n }\n\n /**\n * Get all registered components\n */\n getAllComponents(): RegisteredNativeComponent[] {\n return Array.from(this.components.values());\n }\n\n // ============================================================================\n // Workflow Management\n // ============================================================================\n\n /**\n * Register a workflow\n */\n registerWorkflow(workflow: Workflow): void {\n this.workflows.set(workflow.id, workflow);\n\n if (this.config.verbose) {\n console.log(`[ui-bridge-native] Registered workflow: ${workflow.id}`);\n }\n }\n\n /**\n * Unregister a workflow\n */\n unregisterWorkflow(id: string): void {\n this.workflows.delete(id);\n }\n\n /**\n * Get a workflow\n */\n getWorkflow(id: string): Workflow | undefined {\n return this.workflows.get(id);\n }\n\n /**\n * Get all workflows\n */\n getAllWorkflows(): Workflow[] {\n return Array.from(this.workflows.values());\n }\n\n // ============================================================================\n // Event System\n // ============================================================================\n\n /**\n * Subscribe to events\n */\n on<T = unknown>(type: BridgeEventType, listener: BridgeEventListener<T>): () => void {\n if (!this.eventListeners.has(type)) {\n this.eventListeners.set(type, new Set());\n }\n this.eventListeners.get(type)!.add(listener as BridgeEventListener);\n\n // Return unsubscribe function\n return () => this.off(type, listener);\n }\n\n /**\n * Unsubscribe from events\n */\n off<T = unknown>(type: BridgeEventType, listener: BridgeEventListener<T>): void {\n this.eventListeners.get(type)?.delete(listener as BridgeEventListener);\n }\n\n /**\n * Emit an event\n */\n emit(type: BridgeEventType, data: unknown): void {\n const event: BridgeEvent = {\n type,\n timestamp: Date.now(),\n data,\n };\n\n // Notify listeners\n const listeners = this.eventListeners.get(type);\n if (listeners) {\n for (const listener of listeners) {\n try {\n listener(event);\n } catch (error) {\n console.error(`[ui-bridge-native] Event listener error:`, error);\n }\n }\n }\n\n // Notify global handler\n if (this.config.onEvent) {\n try {\n this.config.onEvent(event);\n } catch (error) {\n console.error(`[ui-bridge-native] Global event handler error:`, error);\n }\n }\n }\n\n // ============================================================================\n // Snapshots\n // ============================================================================\n\n /**\n * Create a snapshot of the current state.\n *\n * Route resolution: `routeInfo` wins when provided. Otherwise — and this\n * is the path the default `getSnapshot` HTTP handler takes — we fall back\n * to the registered `routeProvider`. This means callers that never wire a\n * server-level override (the bare-server / cloud-relay path) still get a\n * populated `currentRoute` field as long as `setRouteProvider` was called\n * on the registry.\n *\n * `activeTab` resolves through {@link resolveActiveTab} on BOTH branches. An\n * explicit `routeInfo.activeTab` wins outright; otherwise a registered\n * provider's `getActiveTab()` answers and the Expo Router derivation is the\n * fallback. Deriving straight from `routeInfo.segments` here instead — which\n * is what this branch did when `activeTab` was introduced — silently ignored\n * `RouteProvider.getActiveTab` on the ONLY path that serves\n * `control/snapshot` once `setRouteProvider` is wired (the server installs a\n * `getSnapshot` override that passes `routeInfo`), so the opt-in hook for an\n * app whose visible pane is decoupled from the router reached no consumer.\n */\n createSnapshot(\n routeInfo?: {\n currentRoute?: string | null;\n segments?: string[];\n /**\n * Explicit active tab for callers that own the answer outright. Omit to\n * let the registered `routeProvider` / the segment derivation resolve it.\n */\n activeTab?: string | null;\n },\n options?: { visibleOnly?: boolean; currentRouteOnly?: boolean }\n ): NativeBridgeSnapshot {\n // Resolve route info: prefer the explicit argument, fall back to a\n // registered route provider. We treat an explicitly-passed `routeInfo`\n // (even if both fields are null/undefined) as \"the caller is in charge\"\n // so server-layer overrides that pass `{currentRoute: null}` keep working.\n const resolvedRoute: {\n currentRoute: string | null;\n segments: string[] | undefined;\n activeTab: string | undefined;\n } = (() => {\n if (routeInfo !== undefined) {\n const explicit =\n typeof routeInfo.activeTab === 'string' && routeInfo.activeTab.length > 0\n ? routeInfo.activeTab\n : undefined;\n return {\n currentRoute: routeInfo.currentRoute ?? null,\n segments: routeInfo.segments,\n activeTab: explicit ?? this.resolveActiveTab(routeInfo.segments),\n };\n }\n if (this.routeProvider) {\n try {\n const segments = this.routeProvider.getSegments?.();\n return {\n currentRoute: this.routeProvider.getCurrentRoute() ?? null,\n segments,\n activeTab: this.resolveActiveTab(segments),\n };\n } catch (error) {\n if (this.config.verbose) {\n console.warn(`[ui-bridge-native] routeProvider getCurrentRoute threw:`, error);\n }\n return { currentRoute: null, segments: undefined, activeTab: undefined };\n }\n }\n return { currentRoute: null, segments: undefined, activeTab: undefined };\n })();\n\n // visibleOnly uses the *looser* mounted-visible filter so a snapshot\n // taken in the gap between mount and the first `onLayout` doesn't\n // return 0 elements on a populated screen. Each element in the\n // payload carries a `visibility` field so agents can branch on\n // measured vs unmeasured.\n let elements = options?.visibleOnly ? this.getMountedVisibleElements() : this.getAllElements();\n\n // Filter to elements that belong on the current route. Route-agnostic\n // elements (no `registrationRoute`) pass through too — see the\n // `matchesCurrentRoute` doc comment for the rationale (tab bars, modal\n // hosts and other app-root registrations have a null route and apply to\n // every screen).\n if (options?.currentRouteOnly && resolvedRoute.currentRoute) {\n const currentRoute = resolvedRoute.currentRoute;\n elements = elements.filter((e) => matchesCurrentRoute(e.registrationRoute, currentRoute));\n }\n\n // Read ONCE per snapshot, not once per element: it is a `Dimensions.get`\n // call behind a try/catch, and a rotation landing mid-map would otherwise\n // give elements in the SAME snapshot different clip regions.\n const viewport = this.getViewportRect();\n\n const snapshot: NativeBridgeSnapshot = {\n timestamp: Date.now(),\n elements: elements.map((e) => {\n const handlers = extractHandlerNames(e.props);\n const state = e.getState();\n const { visibility, visibilityReason } = computeVisibility(\n state,\n this.getClipRectFor(e, viewport)\n );\n const bbox = projectBbox(state, visibility, this.pixelRatio);\n const vision = projectVisionFields({\n type: e.type,\n label: e.label,\n // Real interactivity signal: the names of props that are actually\n // functions (onPress/onChangeText/...). NOT `e.actions`, which\n // `inferActions` synthesizes press/click onto for every element —\n // using it would mark plain text/view nodes interactable.\n handlerNames: handlers,\n state,\n flatStyle: e.flatStyle,\n });\n return {\n id: e.id,\n type: e.type,\n label: e.label,\n identifier: e.getIdentifier(),\n state,\n actions: e.actions,\n customActions: serializeElementCustomActions(e.customActions),\n registeredHandlers: handlers.length > 0 ? handlers : undefined,\n registrationRoute: e.registrationRoute,\n visibility,\n ...(visibilityReason ? { visibilityReason } : {}),\n ...(bbox ? { bbox } : {}),\n ...vision,\n };\n }),\n components: this.getAllComponents().map((c) => ({\n id: c.id,\n name: c.name,\n description: c.description,\n actions: c.actions.map((a) => a.id),\n elementIds: c.elementIds,\n })),\n workflows: this.getAllWorkflows().map((w) => ({\n id: w.id,\n name: w.name,\n description: w.description,\n stepCount: w.steps.length,\n })),\n currentRoute: resolvedRoute.currentRoute,\n segments: resolvedRoute.segments,\n // Canonical aliases, spelled the way the web SDK's `BridgeSnapshot`\n // spells them so a cross-platform consumer reads one field name on both\n // platforms. Omitted rather than nulled when unknown — same convention\n // as the web fields, and it keeps the emitted shape byte-identical for\n // hosts that wire no route provider.\n ...(resolvedRoute.currentRoute ? { route: resolvedRoute.currentRoute } : {}),\n ...(resolvedRoute.activeTab ? { activeTab: resolvedRoute.activeTab } : {}),\n registration: this.getRegistrationCoverage(),\n };\n\n // Include app identification metadata so consumers can identify which\n // app produced this snapshot without a separate health probe.\n if (this.appInfo) {\n snapshot.appInfo = this.appInfo;\n }\n\n // Canonical enrichers — each in its own try/catch so a misbehaving tracker\n // can never break the rest of the snapshot.\n if (this.enrichers.modalDetector) {\n try {\n snapshot.modalStack = this.enrichers.modalDetector.getSnapshotModalContext();\n } catch (error) {\n if (this.config.verbose) {\n console.warn(`[ui-bridge-native] modalDetector enricher threw:`, error);\n }\n }\n }\n if (this.enrichers.toastCapture) {\n try {\n snapshot.toasts = this.enrichers.toastCapture.getSnapshotToastContext();\n } catch (error) {\n if (this.config.verbose) {\n console.warn(`[ui-bridge-native] toastCapture enricher threw:`, error);\n }\n }\n }\n if (this.enrichers.undoTracker) {\n try {\n snapshot.undoRedo = this.enrichers.undoTracker.getSnapshotUndoContext();\n } catch (error) {\n if (this.config.verbose) {\n console.warn(`[ui-bridge-native] undoTracker enricher threw:`, error);\n }\n }\n }\n\n // Custom enrichers — keys assign-merged onto the snapshot\n if (this.snapshotExtras.size > 0) {\n const ctx = { elements, currentRoute: resolvedRoute.currentRoute };\n for (const [name, fn] of this.snapshotExtras) {\n try {\n const extra = fn(ctx);\n if (extra && typeof extra === 'object') {\n Object.assign(snapshot, extra);\n }\n } catch (error) {\n if (this.config.verbose) {\n console.warn(`[ui-bridge-native] snapshot enricher \"${name}\" threw:`, error);\n }\n }\n }\n }\n\n return snapshot;\n }\n\n /**\n * Get registry statistics\n */\n getStats(): { elements: number; components: number; workflows: number } {\n return {\n elements: this.elements.size,\n components: this.components.size,\n workflows: this.workflows.size,\n };\n }\n\n /**\n * Compute registration coverage metadata for the current registry state.\n *\n * Groups currently-registered elements by `registrationRoute`, bucketing\n * elements without a route under `'?'`. `everHadRegistrations` is sticky —\n * once true, it stays true for the lifetime of the registry instance.\n */\n getRegistrationCoverage(): NativeRegistrationCoverage {\n const byRoute: Record<string, number> = {};\n for (const element of this.elements.values()) {\n const key =\n element.registrationRoute == null || element.registrationRoute === ''\n ? '?'\n : element.registrationRoute;\n byRoute[key] = (byRoute[key] ?? 0) + 1;\n }\n return {\n totalRegistered: this.elements.size,\n everHadRegistrations: this.everHadRegistrations,\n byRoute,\n };\n }\n\n /**\n * Clear all registrations\n */\n clear(): void {\n this.elements.clear();\n this.components.clear();\n this.workflows.clear();\n\n if (this.config.verbose) {\n console.log(`[ui-bridge-native] Registry cleared`);\n }\n }\n}\n\n// ============================================================================\n// Global Registry\n// ============================================================================\n\nlet globalRegistry: NativeUIBridgeRegistry | null = null;\n\n/**\n * Set the global registry\n */\nexport function setGlobalRegistry(registry: NativeUIBridgeRegistry): void {\n globalRegistry = registry;\n}\n\n/**\n * Get the global registry\n */\nexport function getGlobalRegistry(): NativeUIBridgeRegistry | null {\n return globalRegistry;\n}\n\n/**\n * Reset the global registry\n */\nexport function resetGlobalRegistry(): void {\n globalRegistry?.clear();\n globalRegistry = null;\n}\n","/**\n * Action effect defaults for `@qontinui/ui-bridge-native`.\n *\n * Plan `2026-08-20-ui-bridge-action-declaration-shape`, Phase 4.\n *\n * `IREffect` (\"read\" | \"write\" | \"destructive\") has exactly one job: **exclude\n * destructive actions from automatic walks.** Two sources feed it, in order:\n *\n * 1. `action.effect` — the author's explicit per-registration declaration.\n * 2. `NATIVE_STANDARD_ACTION_EFFECTS[action.id]` — the static default below.\n *\n * **1 wins.** A static `press → write` map is wrong precisely on a delete\n * control — guaranteed wrong in the one case the annotation exists for — and it\n * fails *open*, so an unmarked destructive action gets walked.\n *\n * DUPLICATE of `@qontinui/ui-bridge` `src/core/action-effect.ts` +\n * `src/native/core/action-effect.ts`, and deliberately not a re-export:\n * `@qontinui/ui-bridge` is an OPTIONAL peer of this package, so a consumer may\n * install `@qontinui/ui-bridge-native` alone. Same constraint that keeps\n * `ActionHandler` / `ComponentAction` / `IREffect` duplicated in\n * `./types` — see the long note there. KEEP IN SYNC.\n */\n\nimport type { IREffect, NativeStandardAction } from './types';\n\n/**\n * Static default effect for each {@link NativeStandardAction} verb.\n *\n * Typed `Record<NativeStandardAction, IREffect>` so adding a verb without\n * classifying it is a compile error — a *map* silently falling behind the\n * *union* it describes is exactly the drift class this plan exists to fix.\n *\n * **No verb maps to `'destructive'`, and none ever should.** Destructiveness\n * is a property of what a control does, not of the verb used to reach it;\n * `'destructive'` is reachable only through an explicit `effect`.\n *\n * The non-obvious calls, justified:\n *\n * - **`longPress` → `read`.** The touch analogue of a right-click: it reveals\n * a context menu / selection affordance. Long-press is *associated* with\n * delete on mobile, but it only surfaces the option — the delete is a\n * separate press with its own effect.\n * - **`swipe` → `write`.** Genuinely ambiguous, and it resolves the other way\n * from `longPress`: a swipe is sometimes just a scroll gesture (read), but\n * swipe-to-delete / swipe-to-archive **commits on the gesture itself**, with\n * nothing in the verb to tell the two apart. It takes the more cautious\n * classification, and a swipe-to-delete row must still declare\n * `effect: 'destructive'`.\n * - **`focus` / `blur` → `read`.** They move focus, which is UI state, not\n * persistent state.\n * - **`scrollIntoView` → `read`.** It moves the declared scroll container's\n * content offset (UI state) and fires no element handler.\n *\n * Note this union carries `click`, `setValue` and `scrollIntoView` that the\n * `@qontinui/ui-bridge` `native/core` copy does not — a real divergence\n * between the two native unions, not a sync error.\n */\nexport const NATIVE_STANDARD_ACTION_EFFECTS: Record<NativeStandardAction, IREffect> = {\n // --- Reads ---------------------------------------------------------------\n focus: 'read',\n blur: 'read',\n scroll: 'read',\n scrollIntoView: 'read',\n longPress: 'read',\n\n // --- Writes --------------------------------------------------------------\n press: 'write',\n click: 'write',\n doubleTap: 'write',\n type: 'write',\n setValue: 'write',\n clear: 'write',\n swipe: 'write',\n toggle: 'write',\n};\n\n/**\n * The static default for a native action id, or `undefined` when the id is not\n * one of the native standard verbs (the normal case for a `ComponentAction`,\n * whose ids are free-form).\n *\n * `undefined` means **unknown**, not \"safe\" — a caller that walks unknown\n * actions is choosing to fail open and should say so.\n */\nexport function nativeStandardActionEffect(actionId: string): IREffect | undefined {\n return Object.prototype.hasOwnProperty.call(NATIVE_STANDARD_ACTION_EFFECTS, actionId)\n ? NATIVE_STANDARD_ACTION_EFFECTS[actionId as NativeStandardAction]\n : undefined;\n}\n\n/**\n * Resolve the effective annotation for a declared action: **explicit\n * declaration first, static verb map second.**\n */\nexport function resolveActionEffect(action: {\n id: string;\n effect?: IREffect;\n}): IREffect | undefined {\n return action.effect ?? nativeStandardActionEffect(action.id);\n}\n","/**\n * Parameter-schema validation for component actions.\n *\n * Plan `2026-08-20-ui-bridge-action-declaration-shape`, Phase 2.\n *\n * `ComponentAction.paramSchema` is **published to agents** — it is spread onto\n * `/control/components` and `/control/component/:id` by\n * `server/handlers.ts` `annotateComponentWithInvocationPaths`, and four live\n * runner consumers read it off the wire. Until Phase 2 nothing enforced it, so\n * an agent that read the schema and sent conforming params had no guarantee\n * the handler agreed. That is worse than publishing nothing: it invites trust\n * it cannot honour. This module is what makes the declaration enforceable.\n *\n * ---------------------------------------------------------------------------\n * THE SUPPORTED SUBSET — this is a CROSS-REPO CONTRACT\n * ---------------------------------------------------------------------------\n *\n * `qontinui-runner` reads these same schemas\n * (`workflow_generation/wrapper_manifest.rs`, `commands/command_interpreter.rs`,\n * `bin/wrappers_mcp.rs`), and `command_interpreter.rs` feeds one to an LLM and\n * asks it to produce conforming args. So the grammar below is not a private\n * implementation detail — changing it changes what those consumers may emit.\n *\n * **No dependency.** `@qontinui/ui-bridge` ships to browsers and has exactly\n * one runtime dependency (`dom-accessibility-api`). A full JSON Schema\n * validator (`ajv` and friends) would be the SDK's first heavyweight runtime\n * dep, which the plan rejected on bundle size. Hence a hand-implemented subset,\n * documented here rather than inferred from the code.\n *\n * **Two accepted top-level shapes**, because `useUIComponent`'s own author-\n * facing doc has always sanctioned both:\n *\n * 1. **Object-schema form** — the shape `paramSchemaOf()`\n * (`@qontinui/ui-bridge-wrapper`) emits:\n *\n * ```jsonc\n * { \"type\": \"object\",\n * \"properties\": { \"username\": { \"type\": \"string\" },\n * \"remember\": { \"type\": \"boolean\" } },\n * \"required\": [\"username\"],\n * \"additionalProperties\": false }\n * ```\n *\n * 2. **Map form** — the lightweight shorthand the doc describes as\n * \"a map of `{ paramName: \"string\" | \"number\" | ... }`\":\n *\n * ```jsonc\n * { \"username\": \"string\", \"count\": { \"type\": \"integer\", \"minimum\": 1 } }\n * ```\n *\n * **Disambiguation rule** (deterministic, no heuristics). The schema is read as\n * form 1 **iff** either:\n *\n * - it carries a `properties` object; or\n * - `type === \"object\"` **and every other top-level key is a JSON Schema\n * object-applicable keyword** ({@link OBJECT_SCHEMA_KEYWORDS}).\n *\n * Everything else is form 2. So `{ \"type\": \"string\" }` is a map declaring one\n * param named `type` of type `string`, not a top-level string schema — a\n * params bag is always an object, so a non-object top-level `type` cannot be\n * describing the bag.\n *\n * ⚠️ **The second clause is load-bearing, and a naive `type === \"object\"` test\n * is a silent-validation-loss bug.** Consider the map form\n * `{ \"type\": \"object\", \"id\": \"string\" }` — an action taking a param literally\n * named `type` whose hint is `\"object\"`, plus an `id`. Reading that as form 1\n * would find no `properties`, express no constraint, and **silently drop every\n * sibling declaration in the map**: `validateActionParams(schema, { id: 12345 })`\n * would answer `{ valid: true }` for a schema that plainly says `id` is a\n * string. `id` is not an object keyword, so the keyword test sends it to form 2\n * and both params validate. A param named `type` is not exotic — it is one of\n * the most common names there is.\n *\n * The one genuinely ambiguous input is a bare `{ \"type\": \"object\" }`: it is\n * both an empty object schema and a one-entry map declaring a param named\n * `type` of type `object`. It is read as form 1 (the empty object schema),\n * which constrains nothing either way, so the choice is unobservable except in\n * combination with `additionalProperties: false` — where form 1 is clearly the\n * intended reading.\n *\n * ### Map form is a TYPE hint, never a REQUIREDNESS hint\n *\n * A bare string value in map form is read as a type name **only when it is one\n * of the seven JSON Schema primitive names** — `string`, `number`, `integer`,\n * `boolean`, `object`, `array`, `null` — which is exactly `paramSchemaOf`'s\n * own `PRIMITIVE_TYPES` set. **Any other string is prose and constrains\n * nothing.**\n *\n * That is not defensive coding, it is the corpus: a census of every literal\n * `paramSchema` in the fleet (2026-08-22) found ~50 map-form declarations in\n * `qontinui-runner` alone whose values are human-readable hints, not types —\n * `{ count: \"number (>= 1, defaults to 1)\", account: \"string — either a Claude\n * account label … or the literal \\\"best\\\"\" }`. Reading `\"number (>= 1,\n * defaults to 1)\"` as a type name would make every one of them unvalidatable\n * noise. The file that declares them says so itself: *\"loose `Record<string,\n * unknown>` with hint strings, no runtime validation\"*.\n *\n * For the same reason, **map form never marks anything required.** It has no\n * `required` array and no other way to express optionality, and most of those\n * ~50 real declarations describe params that are explicitly optional in their\n * own prose (\"defaults to 1\", \"optional initial prompt\"). Requiring by default\n * would report a violation on nearly every real call. An author who needs\n * required params writes form 1, which has a keyword for it.\n *\n * **Optionality in form 1** is exactly `required`: a property is required iff\n * listed there. Note `paramSchemaOf` **omits `required` entirely** when every\n * field is optional, so its absence means \"nothing required\", never \"malformed\".\n *\n * `optional: true` is not a JSON Schema keyword — it is this monorepo's\n * convention on `paramSchemaOf`'s *input* descriptors, and `paramSchemaOf`\n * strips it before the schema reaches the wire. It is honoured here (form 2\n * only) purely so an unstripped input-shaped object is read the same way.\n *\n * **Recognised property keywords** — everything else is IGNORED:\n *\n * | Keyword | Applies to | Meaning |\n * |---|---|---|\n * | `type` | any | `\"string\" \\| \"number\" \\| \"integer\" \\| \"boolean\" \\| \"object\" \\| \"array\" \\| \"null\"`, or an array of those (union — a value matching any member passes). Any OTHER type name constrains nothing (`paramSchemaOf` passes unknown names through verbatim, so they do occur) |\n * | `enum` | any | value must equal one of the listed JSON values |\n * | `const` | any | value must equal this JSON value |\n * | `properties` | objects | per-key sub-schemas, applied recursively |\n * | `required` | objects | array of key names that must be present |\n * | `additionalProperties` | objects | when exactly `false`, keys absent from `properties` are rejected — **including when the schema declares no `properties` at all**, which is the natural spelling of \"takes no params\". Any other value is ignored |\n * | `items` | arrays | one sub-schema applied to every element, recursively |\n * | `minimum` / `maximum` | numbers | inclusive bounds |\n * | `minLength` / `maxLength` | strings | inclusive bounds on `.length` |\n * | `pattern` | strings | ECMAScript regex, unanchored. An uncompilable **or catastrophically-backtracking** pattern is ignored, never a failure — see {@link MAX_PATTERN_LENGTH} |\n *\n * **⚠ Anything outside this table is IGNORED, never rejected.** `description`,\n * `default`, `title`, `format`, `examples`, `$schema`, `$ref`, `oneOf`,\n * `anyOf`, `allOf`, `not`, `patternProperties`, `minItems`, `exclusiveMinimum`\n * … all pass silently. This is deliberate and load-bearing: a schema outside\n * this subset is still *valid JSON Schema*, and rejecting an unrecognised\n * keyword would convert a documentation nicety into a hard invocation failure\n * for every author who wrote a richer schema than this validator reads. An\n * unreadable schema means \"no constraint expressed here\", not \"invalid\".\n * The same rule applies one level up: a `paramSchema` that is not a plain\n * object at all (`null`, an array, a string) expresses no constraint and\n * validates everything.\n *\n * **No coercion.** `\"5\"` does not satisfy `{\"type\":\"number\"}`. The runner's\n * LLM router is already instructed to \"coerce numeric tokens to numbers\"\n * (`command_interpreter.rs`), so coercing here would hide that contract rather\n * than enforce it.\n *\n * ### A validator must return a verdict, never throw\n *\n * {@link validateActionParams} is called at an invocation seam whose only\n * generic failure label is `UB-ACTION-FAILED` — \"the handler failed\". A\n * validator that throws would therefore be reported as a *handler* fault, and\n * the author would go debug code that never ran. Two inputs could do it, and\n * both are **author-supplied schema data**, not caller params:\n *\n * - **A self-referential schema.** `const s = { type: 'object', properties: {} };\n * s.properties.self = s;` recurses until `RangeError: Maximum call stack size\n * exceeded`. Bounded by {@link MAX_SCHEMA_DEPTH}: past that depth the walk\n * stops and expresses no further constraint (the ignore-don't-reject rule,\n * applied to depth).\n * - **A catastrophically-backtracking `pattern`.** This one does not throw at\n * all — it *hangs*, which no `try`/`catch` can rescue. Guarded before\n * compilation by {@link MAX_PATTERN_LENGTH} and a nested-quantifier test,\n * the same pair `control/action-executor.ts` already applies to a\n * caller-supplied `srcPattern`.\n *\n * The seams wrap the call anyway (belt and braces) and report a validator\n * fault distinguishably from a handler fault — see the executors.\n *\n * ---------------------------------------------------------------------------\n * DUPLICATE — deliberately not an import\n * ---------------------------------------------------------------------------\n *\n * DUPLICATE OF `@qontinui/ui-bridge` `src/core/param-schema.ts` — DELIBERATELY\n * NOT AN IMPORT, for the same reason as `core/abortable.ts` beside it:\n * `@qontinui/ui-bridge` is an OPTIONAL peerDependency of this package and is\n * absent from `dependencies`, so a consumer may install\n * `@qontinui/ui-bridge-native` alone; importing from it would resolve inside\n * this monorepo and then fail for that consumer.\n *\n * KEEP IN SYNC with `@qontinui/ui-bridge` `src/core/param-schema.ts`. The\n * module has no imports and touches no DOM or Node API — only `RegExp`,\n * `JSON`, `Set` and `Number`, all present in React Native. The documented\n * subset above is a cross-repo contract, so the two copies drifting is a\n * contract break, not a style nit.\n */\n\n/** Which rule rejected a value. Machine-readable; pairs with `message`. */\nexport type ParamSchemaKeyword =\n | 'required'\n | 'type'\n | 'enum'\n | 'const'\n | 'additionalProperties'\n | 'minimum'\n | 'maximum'\n | 'minLength'\n | 'maxLength'\n | 'pattern';\n\n/**\n * One rejected parameter. `path` is the whole point — an agent told only\n * \"invalid params\" cannot fix anything, so every issue names the param it is\n * about.\n */\nexport interface ParamSchemaIssue {\n /**\n * Location of the offending value, in dotted/bracketed form relative to the\n * params object: `\"username\"`, `\"filter.status\"`, `\"ids[2]\"`. Empty string\n * means the params object itself.\n */\n path: string;\n /** Which rule rejected it. */\n keyword: ParamSchemaKeyword;\n /** What the schema demanded, rendered for a human/agent reader. */\n expected: string;\n /** What was actually supplied, rendered compactly. Absent for `required`. */\n received?: string;\n /** One-line explanation naming both the param and the reason. */\n message: string;\n}\n\n/** Outcome of {@link validateActionParams}. */\nexport interface ParamValidationResult {\n valid: boolean;\n /** Empty iff `valid`. */\n issues: ParamSchemaIssue[];\n}\n\n/**\n * What the executor does with a schema violation.\n *\n * - `'enforce'` — reject the invocation before the handler runs, with\n * `errorCode: 'UB-ACTION-REJECTED'` and the issue list attached.\n * - `'warn'` — log the violation and invoke the handler anyway.\n * - `'off'` — skip validation entirely (no schema walk, no allocation).\n */\nexport type ParamValidationMode = 'enforce' | 'warn' | 'off';\n\n/**\n * **`'warn'`.** Decided on the plan's priority order — *powerful features →\n * scalability → robustness → clean code* — not on backward compatibility,\n * which is explicitly not a factor on this project.\n *\n * The feature Phase 2 delivers is *an enforceable declaration*, and warn mode\n * delivers all of it except the refusal: the schema is walked, the violating\n * param is named, and the violation is reported. Enforcement is one call to\n * {@link setDefaultParamValidationMode} away, per deployment.\n *\n * What arming `'enforce'` by default would buy is the refusal — and the\n * population it would refuse first is not attackers, it is the fleet's own\n * schemas. Nothing has ever validated these declarations, so on the balance of\n * evidence some existing `paramSchema` values are wrong about their own\n * handlers rather than the callers being wrong about the schema; a validator\n * armed on day one reports that as the caller's failure. Worse, the largest\n * live producer of action params is a *model*:\n * `qontinui-runner/src-tauri/src/commands/command_interpreter.rs` asks an LLM\n * for \"args whose keys match the chosen action's `paramSchema`\", and that\n * failure surfaces to a user running a slash command. Defaulting to enforce\n * would convert a documentation defect into a user-visible outage on a\n * population that was never measured.\n *\n * Robustness — third in the order, and the tiebreaker here — argues the same\n * way: the robust move is to collect violations from a validator that has\n * never seen production traffic before letting it refuse anything. A default\n * that fails open and is *observable* beats a default that fails closed and is\n * *unmeasured*.\n */\nexport const DEFAULT_PARAM_VALIDATION_MODE: ParamValidationMode = 'warn';\n\nlet currentDefaultMode: ParamValidationMode = DEFAULT_PARAM_VALIDATION_MODE;\n\n/**\n * Arm or disarm validation process-wide. Call once at app boot; each\n * invocation may still override it via `executeComponentAction`'s\n * `{ paramValidation }` option.\n */\nexport function setDefaultParamValidationMode(mode: ParamValidationMode): void {\n currentDefaultMode = mode;\n}\n\n/** The mode an invocation gets when it does not pass one. */\nexport function getDefaultParamValidationMode(): ParamValidationMode {\n return currentDefaultMode;\n}\n\n/** Test/teardown helper: restore {@link DEFAULT_PARAM_VALIDATION_MODE}. */\nexport function resetDefaultParamValidationMode(): void {\n currentDefaultMode = DEFAULT_PARAM_VALIDATION_MODE;\n}\n\n// ---------------------------------------------------------------------------\n// Implementation\n// ---------------------------------------------------------------------------\n\ntype PlainObject = Record<string, unknown>;\n\n/**\n * The only strings read as type names. Byte-identical to `paramSchemaOf`'s\n * `PRIMITIVE_TYPES` (`@qontinui/ui-bridge-wrapper` `helpers/schema.ts`) —\n * KEEP IN SYNC. Anything else is prose.\n */\nconst PRIMITIVE_TYPE_NAMES = new Set([\n 'string',\n 'number',\n 'integer',\n 'boolean',\n 'object',\n 'array',\n 'null',\n]);\n\n/**\n * Top-level keys that a JSON Schema *object* schema may legitimately carry\n * alongside `type: \"object\"`. Used only by the form-1/form-2 disambiguation\n * (see the module header): a top level whose non-`type` keys are all in here\n * is an object schema; anything else is a map of param declarations.\n *\n * Deliberately generous — it lists keywords this validator does not implement\n * (`oneOf`, `patternProperties`, `$defs`, …) because the question it answers\n * is \"was this written as a schema?\", not \"can we enforce it?\". A schema\n * richer than the subset must still be *recognised* as a schema, or its\n * `properties` would be re-read as param names.\n */\nconst OBJECT_SCHEMA_KEYWORDS = new Set([\n 'type',\n 'properties',\n 'required',\n 'additionalProperties',\n 'patternProperties',\n 'propertyNames',\n 'minProperties',\n 'maxProperties',\n 'dependentRequired',\n 'dependentSchemas',\n 'unevaluatedProperties',\n 'allOf',\n 'anyOf',\n 'oneOf',\n 'not',\n 'if',\n 'then',\n 'else',\n 'enum',\n 'const',\n 'default',\n 'examples',\n 'title',\n 'description',\n 'deprecated',\n 'readOnly',\n 'writeOnly',\n '$schema',\n '$id',\n '$ref',\n '$comment',\n '$defs',\n 'definitions',\n]);\n\n/**\n * Depth ceiling for the recursive schema walk. A schema nested deeper than\n * this expresses no further constraint here (ignore-don't-reject), which is\n * what keeps a self-referential `paramSchema` from becoming a `RangeError` at\n * the invocation seam.\n *\n * 32 is far past any hand-written declaration — the deepest real `paramSchema`\n * in the fleet is 2 levels — and far short of a default stack.\n */\nconst MAX_SCHEMA_DEPTH = 32;\n\n/**\n * Longest `pattern` this validator will compile, and the companion\n * nested-quantifier test below.\n *\n * A `pattern` is author-supplied but it is evaluated against caller-supplied\n * strings, so `(a+)+$` against a long non-matching input is a hang, not an\n * exception — unrescuable by `try`/`catch` because the engine never returns.\n * The pair (length cap + nested-quantifier reject) is the same guard\n * `control/action-executor.ts` applies to a caller-supplied `srcPattern`; over\n * the cap or on a risky construct the keyword is IGNORED, exactly like an\n * uncompilable pattern.\n */\nconst MAX_PATTERN_LENGTH = 200;\n\n/**\n * Nested-quantifier detector — a group that itself contains a quantifier and\n * is then quantified (`(a+)+`, `(a*)*`, `(?:a{2,})+`), the classic\n * catastrophic-backtracking shape.\n *\n * A deliberate duplicate of `@qontinui/ui-bridge` `control/action-executor.ts`\n * `hasNestedQuantifiers`: this module imports nothing so that `src/native/*`\n * and the standalone React Native package can share it (see the header), while\n * `action-executor.ts` pulls in the DOM. KEEP THE COPIES IN SYNC.\n */\nfunction hasNestedQuantifiers(pattern: string): boolean {\n return /(\\((?:[^()]*[+*}])[^()]*\\))[+*?]|\\(\\?:[^()]*[+*}][^()]*\\)[+*?]/.test(pattern);\n}\n\nfunction isPlainObject(value: unknown): value is PlainObject {\n return typeof value === 'object' && value !== null && !Array.isArray(value);\n}\n\n/** `Object.prototype.hasOwnProperty`, safely — see {@link hasOwn}. */\nconst hasOwnProperty = Object.prototype.hasOwnProperty;\n\n/**\n * Own-property test.\n *\n * **Not `key in value`.** `in` walks the prototype chain, so a param named\n * `toString`, `valueOf`, `constructor` or `hasOwnProperty` is never reported\n * missing (it \"exists\" on `Object.prototype`) and is then validated against\n * `Object.prototype`'s member instead of the caller's value — a required\n * param that was never supplied silently passes, and a type constraint on it\n * is checked against a function. `standardActionEffect` already spells this\n * correctly; this is the same rule.\n */\nfunction hasOwn(value: object, key: string): boolean {\n return hasOwnProperty.call(value, key);\n}\n\n/** Compact rendering of a supplied value, for the `received` field. */\nfunction render(value: unknown): string {\n if (value === null) return 'null';\n if (value === undefined) return 'undefined';\n if (Array.isArray(value)) return `array(${value.length})`;\n const t = typeof value;\n if (t === 'string') return JSON.stringify(value);\n if (t === 'number' || t === 'boolean') return String(value);\n if (t === 'object') return 'object';\n return t;\n}\n\n/** Longest JSON rendering {@link renderJson} will emit before truncating. */\nconst MAX_RENDERED_JSON_LENGTH = 120;\n\n/**\n * Rendering for `enum` / `const`, where the *identity* of the value is the\n * whole message.\n *\n * {@link render} collapses every object to the literal string `\"object\"`,\n * which turns a `const` violation into **\"must equal object, received\n * object.\"** — a message that tells an agent nothing, in a module whose stated\n * purpose is that \"invalid params\" tells an agent nothing. So these two\n * keywords render structurally instead, capped so a large schema value cannot\n * blow up a log line.\n */\nfunction renderJson(value: unknown): string {\n if (value === undefined) return 'undefined';\n let text: string;\n try {\n text = JSON.stringify(value) ?? String(value);\n } catch {\n // Cyclic or a BigInt — fall back to the compact rendering.\n return render(value);\n }\n return text.length > MAX_RENDERED_JSON_LENGTH\n ? `${text.slice(0, MAX_RENDERED_JSON_LENGTH)}…`\n : text;\n}\n\n/** The JSON Schema type name a runtime value would be reported as. */\nfunction jsonTypeOf(value: unknown): string {\n if (value === null) return 'null';\n if (Array.isArray(value)) return 'array';\n const t = typeof value;\n if (t === 'number') return Number.isInteger(value) ? 'integer' : 'number';\n if (t === 'string' || t === 'boolean' || t === 'object') return t;\n return t;\n}\n\nfunction matchesType(value: unknown, typeName: string): boolean {\n switch (typeName) {\n case 'string':\n return typeof value === 'string';\n case 'number':\n return typeof value === 'number' && Number.isFinite(value);\n case 'integer':\n return typeof value === 'number' && Number.isInteger(value);\n case 'boolean':\n return typeof value === 'boolean';\n case 'null':\n return value === null;\n case 'array':\n return Array.isArray(value);\n case 'object':\n return isPlainObject(value);\n default:\n // Unrecognised type name — outside the subset, so it constrains nothing.\n return true;\n }\n}\n\n/**\n * Structural equality for JSON `enum` / `const` members.\n *\n * **Not `JSON.stringify(a) === JSON.stringify(b)`.** That comparison is\n * key-order sensitive, so `const: { a: 1, b: 2 }` would reject `{ b: 2, a: 1 }`\n * — two renderings of the same JSON value. Object key order is not semantic in\n * JSON, and the caller does not control it (it is whatever the producing\n * serializer emitted), so an order-sensitive test produces a false failure on\n * a value that IS the declared constant.\n *\n * Depth-bounded for the same reason the schema walk is: a cyclic `const` in a\n * hand-built (non-JSON) schema would otherwise recurse forever. Past the\n * bound the two are treated as unequal rather than throwing.\n */\nfunction jsonEquals(a: unknown, b: unknown, depth = 0): boolean {\n if (a === b) return true;\n if (depth > MAX_SCHEMA_DEPTH) return false;\n if (a === null || b === null || a === undefined || b === undefined) return false;\n if (typeof a !== typeof b) return false;\n if (typeof a !== 'object') return false;\n\n const aIsArray = Array.isArray(a);\n if (aIsArray !== Array.isArray(b)) return false;\n if (aIsArray) {\n const bArr = b as unknown[];\n const aArr = a as unknown[];\n if (aArr.length !== bArr.length) return false;\n return aArr.every((item, i) => jsonEquals(item, bArr[i], depth + 1));\n }\n\n const aObj = a as PlainObject;\n const bObj = b as PlainObject;\n const aKeys = Object.keys(aObj);\n const bKeys = Object.keys(bObj);\n if (aKeys.length !== bKeys.length) return false;\n return aKeys.every((key) => hasOwn(bObj, key) && jsonEquals(aObj[key], bObj[key], depth + 1));\n}\n\nfunction joinPath(base: string, key: string): string {\n return base === '' ? key : `${base}.${key}`;\n}\n\n/**\n * Read a `type` keyword into the list of accepted type names, or `null` when\n * the keyword is absent or shaped outside the subset (in which case it\n * constrains nothing).\n */\nfunction readTypes(schema: PlainObject): string[] | null {\n const raw = schema['type'];\n if (typeof raw === 'string') return [raw];\n if (Array.isArray(raw)) {\n const names = raw.filter((t): t is string => typeof t === 'string');\n return names.length > 0 ? names : null;\n }\n return null;\n}\n\n/** Validate one value against one property schema, appending to `issues`. */\nfunction validateValue(\n value: unknown,\n schema: unknown,\n path: string,\n issues: ParamSchemaIssue[],\n depth: number\n): void {\n // Depth bound — a self-referential `paramSchema` would otherwise recurse to\n // `RangeError`, which the seam can only report as a HANDLER failure. Past\n // the bound the schema expresses no further constraint. See MAX_SCHEMA_DEPTH.\n if (depth > MAX_SCHEMA_DEPTH) return;\n\n // A property schema that is not an object expresses no constraint. A bare\n // PRIMITIVE type-name string IS a constraint though, and is how map form\n // spells one; any other string is prose (see the module header).\n if (typeof schema === 'string') {\n if (PRIMITIVE_TYPE_NAMES.has(schema) && !matchesType(value, schema)) {\n issues.push({\n path,\n keyword: 'type',\n expected: schema,\n received: render(value),\n message: `Parameter \"${path}\" must be of type ${schema}, received ${jsonTypeOf(value)} (${render(value)}).`,\n });\n }\n return;\n }\n if (!isPlainObject(schema)) return;\n\n const types = readTypes(schema);\n if (types !== null && !types.some((t) => matchesType(value, t))) {\n const expected = types.join(' | ');\n issues.push({\n path,\n keyword: 'type',\n expected,\n received: render(value),\n message: `Parameter \"${path}\" must be of type ${expected}, received ${jsonTypeOf(value)} (${render(value)}).`,\n });\n // A wrong-typed value cannot meaningfully fail the type-specific keywords\n // below; reporting those too would bury the one issue that matters.\n return;\n }\n\n if (hasOwn(schema, 'const') && !jsonEquals(value, schema['const'])) {\n // `renderJson`, not `render`: the identity of the value IS the message\n // here, and `render` would collapse both sides to the word \"object\".\n const expected = renderJson(schema['const']);\n const received = renderJson(value);\n issues.push({\n path,\n keyword: 'const',\n expected,\n received,\n message: `Parameter \"${path}\" must equal ${expected}, received ${received}.`,\n });\n return;\n }\n\n const enumValues = schema['enum'];\n if (Array.isArray(enumValues) && !enumValues.some((allowed) => jsonEquals(value, allowed))) {\n const expected = enumValues.map((v) => renderJson(v)).join(', ');\n const received = renderJson(value);\n issues.push({\n path,\n keyword: 'enum',\n expected,\n received,\n message: `Parameter \"${path}\" must be one of [${expected}], received ${received}.`,\n });\n return;\n }\n\n if (typeof value === 'number') {\n const min = schema['minimum'];\n if (typeof min === 'number' && value < min) {\n issues.push({\n path,\n keyword: 'minimum',\n expected: `>= ${min}`,\n received: render(value),\n message: `Parameter \"${path}\" must be >= ${min}, received ${value}.`,\n });\n }\n const max = schema['maximum'];\n if (typeof max === 'number' && value > max) {\n issues.push({\n path,\n keyword: 'maximum',\n expected: `<= ${max}`,\n received: render(value),\n message: `Parameter \"${path}\" must be <= ${max}, received ${value}.`,\n });\n }\n }\n\n if (typeof value === 'string') {\n const minLength = schema['minLength'];\n if (typeof minLength === 'number' && value.length < minLength) {\n issues.push({\n path,\n keyword: 'minLength',\n expected: `length >= ${minLength}`,\n received: `length ${value.length}`,\n message: `Parameter \"${path}\" must be at least ${minLength} characters, received ${value.length}.`,\n });\n }\n const maxLength = schema['maxLength'];\n if (typeof maxLength === 'number' && value.length > maxLength) {\n issues.push({\n path,\n keyword: 'maxLength',\n expected: `length <= ${maxLength}`,\n received: `length ${value.length}`,\n message: `Parameter \"${path}\" must be at most ${maxLength} characters, received ${value.length}.`,\n });\n }\n const pattern = schema['pattern'];\n // ReDoS guard, BEFORE compilation: a catastrophically-backtracking pattern\n // does not throw, it hangs — no `try`/`catch` can rescue it, so the only\n // defence is not to run it. Same pair of tests `action-executor.ts` applies\n // to a caller-supplied `srcPattern`. Over the cap, or a nested-quantifier\n // construct, and the keyword is ignored like an uncompilable one.\n if (\n typeof pattern === 'string' &&\n pattern.length <= MAX_PATTERN_LENGTH &&\n !hasNestedQuantifiers(pattern)\n ) {\n // Declared WITHOUT an initializer on purpose: both arms below assign\n // before any read, so an initializer here would be dead (eslint\n // `no-useless-assignment`). The regex carries no `g` flag and is rebuilt\n // per call, so there is no `lastIndex` state to carry between values.\n let re: RegExp | null;\n try {\n re = new RegExp(pattern);\n } catch {\n // An uncompilable pattern expresses no constraint we can read. Ignored,\n // never a failure — same rule as an unrecognised keyword.\n re = null;\n }\n if (re !== null && !re.test(value)) {\n issues.push({\n path,\n keyword: 'pattern',\n expected: `match /${pattern}/`,\n received: render(value),\n message: `Parameter \"${path}\" must match /${pattern}/, received ${render(value)}.`,\n });\n }\n }\n }\n\n if (Array.isArray(value) && hasOwn(schema, 'items')) {\n const items = schema['items'];\n value.forEach((element, index) => {\n validateValue(element, items, `${path}[${index}]`, issues, depth + 1);\n });\n }\n\n if (\n isPlainObject(value) &&\n (isPlainObject(schema['properties']) ||\n hasOwn(schema, 'required') ||\n schema['additionalProperties'] === false)\n ) {\n validateObject(value, schema, path, issues, depth);\n }\n}\n\n/**\n * Validate a plain object against the `properties` / `required` /\n * `additionalProperties` triple. Shared by the top level and by nested\n * `type: \"object\"` properties.\n */\nfunction validateObject(\n value: PlainObject,\n schema: PlainObject,\n basePath: string,\n issues: ParamSchemaIssue[],\n depth: number\n): void {\n if (depth > MAX_SCHEMA_DEPTH) return;\n\n const properties = isPlainObject(schema['properties']) ? schema['properties'] : {};\n const requiredRaw = schema['required'];\n const required = Array.isArray(requiredRaw)\n ? requiredRaw.filter((k): k is string => typeof k === 'string')\n : [];\n\n for (const key of required) {\n // `hasOwn`, not `key in value` — see `hasOwn`. With `in`, a required param\n // named `toString` is never reported missing.\n if (!hasOwn(value, key) || value[key] === undefined) {\n const at = joinPath(basePath, key);\n issues.push({\n path: at,\n keyword: 'required',\n expected: 'present',\n message: `Required parameter \"${at}\" is missing.`,\n });\n }\n }\n\n if (schema['additionalProperties'] === false) {\n const declared = new Set(Object.keys(properties));\n // With no `properties` at all the schema says \"no params are accepted\" —\n // say that, rather than the empty \"one of []\" the generic phrasing gives.\n const expected = declared.size === 0 ? 'no parameters' : `one of [${[...declared].join(', ')}]`;\n for (const key of Object.keys(value)) {\n if (!declared.has(key)) {\n const at = joinPath(basePath, key);\n issues.push({\n path: at,\n keyword: 'additionalProperties',\n expected,\n received: render(value[key]),\n message: `Parameter \"${at}\" is not declared by the schema, which sets additionalProperties: false.`,\n });\n }\n }\n }\n\n for (const [key, propSchema] of Object.entries(properties)) {\n // `hasOwn`, not `key in value` — with `in`, a declared param named\n // `valueOf` would be \"present\" and validated against `Object.prototype`'s\n // function instead of the caller's (absent) value.\n if (!hasOwn(value, key) || value[key] === undefined) continue;\n validateValue(value[key], propSchema, joinPath(basePath, key), issues, depth + 1);\n }\n}\n\n/**\n * The form-1/form-2 disambiguation, in one place. See the module header for\n * the rule and for why the `type === 'object'` half is not enough on its own.\n *\n * @returns `true` for object-schema form (form 1), `false` for map form.\n */\nfunction isObjectSchemaForm(schema: PlainObject): boolean {\n if (isPlainObject(schema['properties'])) return true;\n if (schema['type'] !== 'object') return false;\n // `type: \"object\"` with NO `properties`. Object schema only if everything\n // else present is a schema keyword; a single non-keyword key (`id`,\n // `username`, …) means this is a map that happens to declare a param called\n // `type`, and reading it as a schema would silently drop every sibling\n // declaration in it.\n return Object.keys(schema).every((key) => OBJECT_SCHEMA_KEYWORDS.has(key));\n}\n\n/**\n * Normalise map form into the object-schema form so one walker serves both.\n * Returns `null` when `schema` is already object form.\n */\nfunction normalizeMapForm(schema: PlainObject): PlainObject | null {\n if (isObjectSchemaForm(schema)) return null;\n\n const properties: PlainObject = {};\n for (const [key, raw] of Object.entries(schema)) {\n if (raw === null || raw === undefined) continue;\n if (typeof raw === 'string') {\n // Type name, or prose? Only the seven primitive names are types. Every\n // other string is a human hint — ~50 live declarations in\n // `qontinui-runner` are exactly that — and expresses no constraint.\n properties[key] = PRIMITIVE_TYPE_NAMES.has(raw) ? { type: raw } : {};\n continue;\n }\n if (isPlainObject(raw)) {\n // `optional` is this monorepo's non-standard marker, not JSON Schema.\n // Nothing in map form is required, so it only needs stripping.\n const { optional: _optional, ...rest } = raw as PlainObject & { optional?: unknown };\n properties[key] = rest;\n continue;\n }\n // A value that is neither a type name nor a schema object expresses no\n // constraint — ignored, per the unrecognised-keyword rule.\n }\n // NO `required`: map form cannot express requiredness. See the module header.\n return { type: 'object', properties };\n}\n\n/**\n * Validate `params` against an action's `paramSchema`.\n *\n * Returns `{ valid: true, issues: [] }` for anything the documented subset\n * cannot read — that is the ignore-don't-reject rule, and it is why a schema\n * this validator does not understand can never fail an invocation.\n *\n * @param schema the action's declared `paramSchema` (any shape; unreadable\n * shapes constrain nothing)\n * @param params the params the caller supplied. `undefined` is treated as an\n * empty object, so a schema with required properties still reports them.\n */\nexport function validateActionParams(\n schema: unknown,\n params: unknown\n): ParamValidationResult {\n if (!isPlainObject(schema)) return { valid: true, issues: [] };\n\n const normalized = normalizeMapForm(schema) ?? schema;\n\n const hasProperties = isPlainObject(normalized['properties']);\n const hasRequired = Array.isArray(normalized['required']);\n // `additionalProperties: false` is a constraint ON ITS OWN, even with no\n // `properties` key: `{ type: 'object', additionalProperties: false }` is the\n // natural way to spell \"this action takes no params at all\", and the keyword\n // table above documents it. Omitting it from this test made that schema\n // accept every payload — the same silent-drop defect as the map-form one.\n const forbidsExtras = normalized['additionalProperties'] === false;\n if (!hasProperties && !hasRequired && !forbidsExtras) {\n // e.g. a bare `{ type: \"object\" }`. No constraint expressed.\n //\n // (The map-form branch cannot reach here: `normalizeMapForm` always\n // returns a `properties` object, empty or not — so `hasProperties` is\n // true for every map form, including one whose every entry was prose.)\n return { valid: true, issues: [] };\n }\n\n const issues: ParamSchemaIssue[] = [];\n\n if (params === undefined || params === null) {\n validateObject({}, normalized, '', issues, 0);\n return { valid: issues.length === 0, issues };\n }\n\n if (!isPlainObject(params)) {\n issues.push({\n path: '',\n keyword: 'type',\n expected: 'object',\n received: render(params),\n message: `Action params must be an object, received ${jsonTypeOf(params)} (${render(params)}).`,\n });\n return { valid: false, issues };\n }\n\n validateObject(params, normalized, '', issues, 0);\n return { valid: issues.length === 0, issues };\n}\n\n/**\n * One-line summary of a violation set, naming the action and every offending\n * param. Used as the `error` / `message` string at every invocation seam so\n * the three trees phrase the rejection identically.\n */\nexport function formatParamValidationFailure(\n componentId: string,\n actionId: string,\n issues: ParamSchemaIssue[]\n): string {\n const detail = issues.map((i) => i.message).join(' ');\n return `Action \"${actionId}\" on component \"${componentId}\" was rejected: params do not match the action's declared paramSchema. ${detail}`;\n}\n","/**\n * Abandonment primitive for action invocation.\n *\n * Plan `2026-08-20-ui-bridge-action-declaration-shape`, Phase 3.\n *\n * `ActionHandler`'s `options.signal` is **cooperative**: a well-behaved handler\n * observes it and returns early. Cooperation cannot be enforced, and a handler\n * that hangs is exactly the case cancellation exists for — so the executor\n * never trusts the handler to observe the signal. It races the handler promise\n * against the abort and reports the outcome either way.\n *\n * DUPLICATE OF `@qontinui/ui-bridge` `src/core/abortable.ts` — DELIBERATELY NOT\n * AN IMPORT. `@qontinui/ui-bridge` is an OPTIONAL peerDependency of this\n * package and is absent from `dependencies`, so a consumer may install\n * `@qontinui/ui-bridge-native` alone; importing from it would resolve inside\n * this monorepo and then fail for that consumer. See the same note on\n * `core/types.ts` `ActionHandler`.\n *\n * KEEP IN SYNC with `@qontinui/ui-bridge` `src/core/abortable.ts` — including\n * `MAX_ACTION_TIMEOUT_MS` and `normalizeActionTimeoutMs` below. The module has\n * no imports and touches no DOM API — only `AbortController` and `setTimeout`,\n * both present in React Native.\n */\n\n/** Which of the two cancellation sources fired. */\nexport type AbortReason = 'signal' | 'timeout';\n\n/**\n * Ceiling applied to a caller-supplied `timeoutMs` — **24 hours**.\n *\n * `ComponentActionRequest.timeoutMs` crosses the wire, so it is attacker- (or\n * typo-) controlled: an HTTP or WebSocket caller can put any JSON number in\n * it and it would otherwise land in `setTimeout` unchecked. Two concrete\n * hazards that ceiling closes:\n *\n * - **`setTimeout`'s 32-bit delay overflow.** Any delay above 2147483647ms\n * wraps to a *negative* 32-bit int in every major runtime and the timer\n * fires **immediately** — so `timeoutMs: 2147483648` (\"about 25 days,\n * effectively no timeout\") would abandon the action on the next tick, the\n * exact opposite of what the caller asked for. Clamping below that boundary\n * makes the semantics monotonic: a bigger number never means a shorter wait.\n * - **A pinned timer per in-flight request.** Nothing here is unbounded work,\n * but a 100-year timeout is indistinguishable from \"no timeout\" while still\n * holding the handler's abandonment machinery alive, so there is nothing to\n * buy above a day.\n *\n * Clamping (rather than rejecting) is right at the top end because the intent\n * is unambiguous — \"effectively forever\" — and the clamped value honours it as\n * closely as the platform can. The malformed cases below are rejected instead,\n * because there the intent is NOT recoverable.\n */\nexport const MAX_ACTION_TIMEOUT_MS = 86_400_000;\n\n/**\n * Outcome of {@link normalizeActionTimeoutMs}. Discriminated on `ok` so a\n * rejected value cannot be read as a timeout by accident.\n */\nexport type TimeoutNormalization =\n | {\n ok: true;\n /** `undefined` ≡ no timeout. Always a finite integer in `[0, MAX]`. */\n timeoutMs: number | undefined;\n /** True iff the caller's value was above {@link MAX_ACTION_TIMEOUT_MS}. */\n clamped: boolean;\n }\n | { ok: false; reason: string };\n\n/**\n * Validate and clamp a wire-supplied `timeoutMs` before it can reach a timer.\n *\n * The policy, stated once so all three executors share it:\n *\n * | Supplied | Result | Why |\n * |---|---|---|\n * | absent / `null` | no timeout | the documented \"omitted ⇒ no timeout\" default |\n * | `0` | abandon on the next tick | a coherent request (\"don't let it run\"), and what `setTimeout(…, 0)` already means |\n * | `1 … MAX` | honoured, floored to an integer | fractional ms is not a thing a timer can express |\n * | `> MAX` | clamped to {@link MAX_ACTION_TIMEOUT_MS} | see that constant — above 2^31-1 the platform timer silently inverts |\n * | negative | **rejected** | `setTimeout` would treat it as `0`, i.e. a sign typo would abandon every call instantly and silently |\n * | `NaN` / `±Infinity` | **rejected** | `setTimeout(NaN)` is `setTimeout(0)` — same silent-instant-abandon trap |\n * | not a number (`\"5000\"`, `{}`, `true`) | **rejected** | JSON has numbers; a string here means the caller built the body wrong, and coercing would hide it |\n *\n * Rejection is loud on purpose: every rejected case is one where *ignoring*\n * the field fails open (the action runs uncancellable) and *coercing* it fails\n * closed at zero. Neither is what the caller asked for, and both are silent —\n * which is the defect class this whole plan exists to remove.\n */\nexport function normalizeActionTimeoutMs(raw: unknown): TimeoutNormalization {\n if (raw === undefined || raw === null) {\n return { ok: true, timeoutMs: undefined, clamped: false };\n }\n if (typeof raw !== 'number') {\n return {\n ok: false,\n reason: `timeoutMs must be a number of milliseconds, received ${typeof raw === 'string' ? JSON.stringify(raw) : typeof raw}`,\n };\n }\n if (!Number.isFinite(raw)) {\n return {\n ok: false,\n reason: `timeoutMs must be a finite number of milliseconds, received ${String(raw)}`,\n };\n }\n if (raw < 0) {\n return {\n ok: false,\n reason: `timeoutMs must not be negative, received ${String(raw)}`,\n };\n }\n if (raw > MAX_ACTION_TIMEOUT_MS) {\n return { ok: true, timeoutMs: MAX_ACTION_TIMEOUT_MS, clamped: true };\n }\n return { ok: true, timeoutMs: Math.floor(raw), clamped: false };\n}\n\n/**\n * Result of {@link runAbortable}. Discriminated on `aborted` so the caller\n * cannot read `result` off an abandoned invocation.\n */\nexport type AbortableOutcome<T> =\n | { aborted: false; result: T }\n | { aborted: true; reason: AbortReason };\n\n/** Cancellation sources composed by {@link runAbortable}. */\nexport interface RunAbortableOptions {\n /**\n * An in-process caller's signal. Cannot cross the wire — that is what\n * `timeoutMs` is for.\n */\n signal?: AbortSignal;\n /**\n * Milliseconds after which the invocation is abandoned. Serializable, so\n * this is the arm an HTTP/WebSocket caller can actually use.\n *\n * Expected to have been through {@link normalizeActionTimeoutMs} already —\n * every executor seam runs it, because this value arrives from the wire.\n * The `Number.isFinite` / `>= 0` guard below is defence in depth for a\n * direct in-process caller, and ignores anything malformed rather than\n * letting it reach `setTimeout`.\n */\n timeoutMs?: number;\n}\n\n/**\n * A fresh `AbortSignal` that is never aborted.\n *\n * `ActionHandlerOptions` promises the bag is *always* supplied, so a handler\n * written the way the docs describe — `(params, { signal }) => …` — must never\n * be called with `undefined` as its second argument. Not every invocation seam\n * has a cancellation source to give it though: an ELEMENT custom action\n * (`ControlActionRequest`) carries no `timeoutMs` and the executor holds no\n * controller for it, so there is nothing that could ever abort. Those seams\n * pass this instead of `undefined`, which keeps the destructure safe and keeps\n * `signal.aborted` honestly `false`.\n *\n * **Fresh per call, deliberately.** A shared singleton would accumulate one\n * listener per handler that calls `signal.addEventListener('abort', …)` and\n * never releases them — a leak on a hot path. A `AbortController` allocation\n * is a few bytes and custom element actions are not a hot path.\n *\n * When element actions grow a cancellation source, replace the call sites with\n * a real `runAbortable` race — the handler contract does not change.\n */\nexport function inertAbortSignal(): AbortSignal {\n return new AbortController().signal;\n}\n\n/**\n * Invoke `invoke` with a derived `AbortSignal`, abandoning it if either the\n * caller's signal aborts or `timeoutMs` elapses.\n *\n * - Returns `{ aborted: true, reason }` **without invoking at all** when the\n * caller's signal is already aborted.\n * - Returns `{ aborted: false, result }` on normal completion.\n * - **Rejects** if `invoke` throws/rejects while the race is still live, so a\n * genuine handler error stays distinguishable from a cancellation.\n * - A rejection that arrives *after* an abort already won is swallowed:\n * `Promise.race` has a rejection handler attached, so the abandoned handler\n * cannot surface as an unhandled rejection.\n */\nexport async function runAbortable<T>(\n invoke: (signal: AbortSignal) => T | Promise<T>,\n options: RunAbortableOptions = {}\n): Promise<AbortableOutcome<T>> {\n const callerSignal = options.signal;\n const timeoutMs = options.timeoutMs;\n\n if (callerSignal?.aborted) {\n return { aborted: true, reason: 'signal' };\n }\n\n const controller = new AbortController();\n // Set before `controller.abort()` in both arms, so the abort listener reads\n // the reason that actually fired.\n let reason: AbortReason = 'signal';\n let timer: ReturnType<typeof setTimeout> | undefined;\n\n const onCallerAbort = (): void => {\n reason = 'signal';\n controller.abort();\n };\n\n callerSignal?.addEventListener('abort', onCallerAbort, { once: true });\n\n if (typeof timeoutMs === 'number' && Number.isFinite(timeoutMs) && timeoutMs >= 0) {\n // The clamp is applied AGAIN here, at the only place a delay actually\n // reaches a timer. `normalizeActionTimeoutMs` already did it for every\n // wire path, but a direct in-process caller reaches `runAbortable`\n // without passing through an executor — and above 2^31-1 `setTimeout`\n // wraps negative and fires immediately, turning \"wait a century\" into\n // \"abandon now\". See MAX_ACTION_TIMEOUT_MS.\n timer = setTimeout(\n () => {\n reason = 'timeout';\n controller.abort();\n },\n Math.min(timeoutMs, MAX_ACTION_TIMEOUT_MS)\n );\n }\n\n try {\n const abandoned = new Promise<AbortableOutcome<T>>((resolve) => {\n controller.signal.addEventListener('abort', () => resolve({ aborted: true, reason }), {\n once: true,\n });\n });\n\n const completed = (async (): Promise<AbortableOutcome<T>> => ({\n aborted: false,\n result: await invoke(controller.signal),\n }))();\n\n return await Promise.race([completed, abandoned]);\n } finally {\n if (timer !== undefined) clearTimeout(timer);\n callerSignal?.removeEventListener('abort', onCallerAbort);\n }\n}\n","/**\n * Native Element Identifier\n *\n * Utilities for identifying and finding native elements.\n * In React Native, we use testID, accessibilityLabel, and tree paths\n * instead of XPath/CSS selectors.\n */\n\nimport type { NativeElementIdentifier, RegisteredNativeElement } from './types';\nimport { getGlobalRegistry } from './registry';\n\n/**\n * Create an element identifier for a native element\n */\nexport function createNativeElementIdentifier(\n id: string,\n options: {\n testId?: string;\n accessibilityLabel?: string;\n accessibilityHint?: string;\n treePath?: string;\n } = {}\n): NativeElementIdentifier {\n return {\n uiId: id,\n testId: options.testId || id,\n accessibilityLabel: options.accessibilityLabel,\n accessibilityHint: options.accessibilityHint,\n treePath: options.treePath || id,\n };\n}\n\n/**\n * Find an element by its identifier in the global registry\n */\nexport function findElementByIdentifier(\n identifier: string | NativeElementIdentifier\n): RegisteredNativeElement | null {\n const registry = getGlobalRegistry();\n if (!registry) return null;\n\n // If string, try different lookup strategies\n if (typeof identifier === 'string') {\n // Try direct ID lookup\n const byId = registry.getElement(identifier);\n if (byId) return byId;\n\n // Try testID lookup\n const byTestId = registry.findByTestId(identifier);\n if (byTestId) return byTestId;\n\n // Try pattern matching\n return findByPattern(registry, identifier);\n }\n\n // If identifier object, try each strategy\n if (identifier.uiId) {\n const byId = registry.getElement(identifier.uiId);\n if (byId) return byId;\n }\n\n if (identifier.testId) {\n const byTestId = registry.findByTestId(identifier.testId);\n if (byTestId) return byTestId;\n }\n\n return null;\n}\n\n/**\n * Find element by pattern (supports wildcards)\n */\nfunction findByPattern(\n registry: ReturnType<typeof getGlobalRegistry>,\n pattern: string\n): RegisteredNativeElement | null {\n if (!registry) return null;\n\n // Convert pattern to regex\n const regexPattern = pattern\n .replace(/[.+^${}()|[\\]\\\\]/g, '\\\\$&') // Escape special chars\n .replace(/\\*/g, '.*') // Convert * to .*\n .replace(/\\?/g, '.'); // Convert ? to .\n\n const regex = new RegExp(`^${regexPattern}$`, 'i');\n\n for (const element of registry.getAllElements()) {\n const identifier = element.getIdentifier();\n\n // Match against testId\n if (identifier.testId && regex.test(identifier.testId)) {\n return element;\n }\n\n // Match against uiId\n if (identifier.uiId && regex.test(identifier.uiId)) {\n return element;\n }\n\n // Match against treePath\n if (identifier.treePath && regex.test(identifier.treePath)) {\n return element;\n }\n\n // Match against accessibilityLabel\n if (identifier.accessibilityLabel && regex.test(identifier.accessibilityLabel)) {\n return element;\n }\n }\n\n return null;\n}\n\n/**\n * Find all elements matching a pattern\n */\nexport function findAllByPattern(pattern: string): RegisteredNativeElement[] {\n const registry = getGlobalRegistry();\n if (!registry) return [];\n\n // Convert pattern to regex\n const regexPattern = pattern\n .replace(/[.+^${}()|[\\]\\\\]/g, '\\\\$&')\n .replace(/\\*/g, '.*')\n .replace(/\\?/g, '.');\n\n const regex = new RegExp(`^${regexPattern}$`, 'i');\n const results: RegisteredNativeElement[] = [];\n\n for (const element of registry.getAllElements()) {\n const identifier = element.getIdentifier();\n\n if (\n (identifier.testId && regex.test(identifier.testId)) ||\n (identifier.uiId && regex.test(identifier.uiId)) ||\n (identifier.treePath && regex.test(identifier.treePath)) ||\n (identifier.accessibilityLabel && regex.test(identifier.accessibilityLabel))\n ) {\n results.push(element);\n }\n }\n\n return results;\n}\n\n/**\n * Build a tree path for an element based on its position in the component tree\n */\nexport function buildTreePath(componentPath: string[], elementIndex?: number): string {\n let path = componentPath.join('/');\n if (elementIndex !== undefined) {\n path += `[${elementIndex}]`;\n }\n return path;\n}\n\n/**\n * Parse a tree path into its components\n */\nexport function parseTreePath(treePath: string): { components: string[]; index?: number } {\n const indexMatch = treePath.match(/\\[(\\d+)\\]$/);\n const index = indexMatch ? parseInt(indexMatch[1], 10) : undefined;\n const pathWithoutIndex = treePath.replace(/\\[\\d+\\]$/, '');\n const components = pathWithoutIndex.split('/').filter(Boolean);\n\n return { components, index };\n}\n\n/**\n * Check if an identifier matches criteria\n */\nexport function matchesIdentifier(\n identifier: NativeElementIdentifier,\n criteria: Partial<NativeElementIdentifier>\n): boolean {\n if (criteria.uiId && identifier.uiId !== criteria.uiId) {\n return false;\n }\n if (criteria.testId && identifier.testId !== criteria.testId) {\n return false;\n }\n if (\n criteria.accessibilityLabel &&\n identifier.accessibilityLabel !== criteria.accessibilityLabel\n ) {\n return false;\n }\n if (criteria.treePath && identifier.treePath !== criteria.treePath) {\n return false;\n }\n return true;\n}\n","/**\n * Native Action Executor\n *\n * Executes actions on registered native elements and components.\n * In React Native, we execute actions by calling prop handlers directly\n * (onPress, onChangeText, etc.) rather than simulating DOM events.\n */\n\nimport type { NativeUIBridgeRegistry } from '../core/registry';\nimport type {\n NativeStandardAction,\n NativeFindRequest,\n NativeFindResponse,\n DiscoveredNativeElement,\n WaitOptions,\n} from '../core/types';\nimport { findElementByIdentifier } from '../core/element-identifier';\nimport { pageRectOf, isEmptyRect, intersectRects } from '../core/registry';\nimport type { NativePageRect } from '../core/registry';\n// Phase 3 (plan 2026-08-20-ui-bridge-action-declaration-shape). A justified\n// duplicate of the web SDK's primitive — see the header of `core/abortable.ts`\n// for why this package cannot import it.\nimport { runAbortable, normalizeActionTimeoutMs, inertAbortSignal } from '../core/abortable';\n// Phase 2 (same plan). A justified duplicate of the web SDK's validator — see\n// the header of `core/param-schema.ts` for why this package cannot import it.\nimport {\n validateActionParams,\n formatParamValidationFailure,\n getDefaultParamValidationMode,\n} from '../core/param-schema';\nimport type {\n ControlActionRequest,\n ControlActionResponse,\n ComponentActionRequest,\n ComponentActionResponse,\n ComponentActionInvokeOptions,\n WaitResult,\n NativeActionExecutor,\n NativeActionEvent,\n NativeActionListener,\n TypeActionParams,\n ScrollActionParams,\n ScrollIntoViewActionParams,\n SwipeActionParams,\n PressActionParams,\n} from './types';\n\n/**\n * Default wait options\n */\nconst DEFAULT_WAIT_OPTIONS: Required<WaitOptions> = {\n visible: true,\n enabled: true,\n focused: false,\n state: {},\n timeout: 10000,\n interval: 100,\n};\n\n/**\n * An action failure that carries a machine-readable code of its own, so the\n * HTTP handler can report it as that code instead of the generic\n * `ACTION_FAILED`. Used for `NOT_SUPPORTED` — \"this element cannot do that\",\n * which a caller must not retry with a different request shape.\n */\nexport class NativeActionError extends Error {\n constructor(\n message: string,\n readonly code: string\n ) {\n super(message);\n this.name = 'NativeActionError';\n }\n}\n\n/** Default gap (logical dp) left above an element scrolled into view. */\nconst DEFAULT_SCROLL_INTO_VIEW_PADDING = 16;\n\n/** Upper bound on waiting for `measureLayout` to call back. */\nconst SCROLL_INTO_VIEW_MEASURE_TIMEOUT_MS = 1000;\n\n/** The slice of a React Native `ScrollView` instance `scrollIntoView` drives. */\ninterface ScrollContainerRef {\n scrollTo: (options: { x?: number; y?: number; animated?: boolean }) => void;\n getInnerViewRef?: () => unknown;\n getInnerViewNode?: () => unknown;\n /** VirtualizedList family (FlatList / SectionList): the underlying ScrollView. */\n getNativeScrollRef?: () => unknown;\n getScrollResponder?: () => unknown;\n}\n\n/** Upper bound on the targeted `measureInWindow` used for the visibility check. */\nconst SCROLL_INTO_VIEW_WINDOW_MEASURE_TIMEOUT_MS = 250;\n\ntype WindowMeasurable = {\n measureInWindow?: (cb: (x: number, y: number, w: number, h: number) => void) => void;\n};\n\n/**\n * The page rect of one registered element, measured NOW where its ref allows.\n *\n * A ref with `measureInWindow` is measured directly (bounded); a timeout,\n * throw, or zero-size answer is UNKNOWN (`null`). A ref without it (a test\n * fixture, a non-host wrapper) falls back to the registry's stored layout —\n * the same evidence the snapshot route would report for it.\n */\nfunction measurePageRectNow(\n element: NonNullable<ReturnType<NativeUIBridgeRegistry['getElement']>>,\n preferred?: unknown\n): Promise<NativePageRect | null> {\n // `preferred` lets a caller measure a better node than the registered ref —\n // the ScrollView a FlatList wraps, whose class instance has no measureInWindow.\n const preferredNode = preferred as WindowMeasurable | null | undefined;\n const node =\n preferredNode && typeof preferredNode.measureInWindow === 'function'\n ? preferredNode\n : (element.ref.current as unknown as WindowMeasurable | null);\n if (!node || typeof node.measureInWindow !== 'function') {\n const state = element.getState();\n return Promise.resolve(state.visible ? pageRectOf(state) : null);\n }\n return new Promise((resolve) => {\n let settled = false;\n const done = (rect: NativePageRect | null) => {\n if (settled) return;\n settled = true;\n clearTimeout(timer);\n resolve(rect);\n };\n const timer = setTimeout(() => done(null), SCROLL_INTO_VIEW_WINDOW_MEASURE_TIMEOUT_MS);\n try {\n node.measureInWindow!((x, y, w, h) =>\n done(\n [x, y, w, h].every(Number.isFinite) && w > 0 && h > 0\n ? { left: x, top: y, right: x + w, bottom: y + h }\n : null\n )\n );\n } catch {\n done(null);\n }\n });\n}\n\n/** The slice of a React Native host view `scrollIntoView` measures with. */\ninterface MeasurableRef {\n measureLayout: (\n relativeTo: unknown,\n onSuccess: (x: number, y: number, width: number, height: number) => void,\n onFail?: () => void\n ) => void;\n}\n\n/**\n * The ScrollView-shaped object behind a container ref: the ref itself when it\n * has `scrollTo`, else the ScrollView a VirtualizedList (FlatList /\n * SectionList) wraps. `null` when neither yields one.\n */\nfunction resolveScrollView(\n current: unknown\n): (Partial<ScrollContainerRef> & Pick<ScrollContainerRef, 'scrollTo'>) | null {\n const c = current as Partial<ScrollContainerRef> | null | undefined;\n if (!c) return null;\n if (typeof c.scrollTo === 'function')\n return c as Partial<ScrollContainerRef> & Pick<ScrollContainerRef, 'scrollTo'>;\n for (const unwrap of [c.getNativeScrollRef, c.getScrollResponder]) {\n if (typeof unwrap !== 'function') continue;\n let inner: Partial<ScrollContainerRef> | null | undefined;\n try {\n inner = unwrap.call(c) as Partial<ScrollContainerRef> | null | undefined;\n } catch {\n inner = null;\n }\n if (inner && typeof inner.scrollTo === 'function')\n return inner as Partial<ScrollContainerRef> & Pick<ScrollContainerRef, 'scrollTo'>;\n }\n return null;\n}\n\n/**\n * Is the container visibly declared `horizontal`? Checks captured registry\n * props, then a class-component ref's own `props` (FlatList / SectionList\n * instances), then the resolved ScrollView's. See the LIMIT note at the call\n * site — an invisible declaration cannot be detected.\n */\nfunction isDeclaredHorizontal(\n registeredProps: Record<string, unknown> | undefined,\n ...refs: unknown[]\n): boolean {\n if (registeredProps?.horizontal === true) return true;\n return refs.some((r) => {\n const props = (r as { props?: { horizontal?: unknown } } | null | undefined)?.props;\n return props !== null && typeof props === 'object' && props.horizontal === true;\n });\n}\n\n/**\n * Sleep for a duration\n */\nfunction sleep(ms: number): Promise<void> {\n return new Promise((resolve) => setTimeout(resolve, ms));\n}\n\n/**\n * Default native action executor implementation\n */\nexport class DefaultNativeActionExecutor implements NativeActionExecutor {\n private actionListeners = new Set<NativeActionListener>();\n\n constructor(private registry: NativeUIBridgeRegistry) {}\n\n onActionExecuted(listener: NativeActionListener): () => void {\n this.actionListeners.add(listener);\n return () => {\n this.actionListeners.delete(listener);\n };\n }\n\n /** Notify listeners out-of-band; isolate each invocation so one bad listener can't poison the rest. */\n private emitActionEvent(event: NativeActionEvent): void {\n for (const listener of this.actionListeners) {\n try {\n listener(event);\n } catch (error) {\n console.warn(`[ui-bridge-native] Action listener error:`, error);\n }\n }\n }\n\n /**\n * Execute an action on an element\n */\n async executeAction(\n elementId: string,\n request: ControlActionRequest\n ): Promise<ControlActionResponse> {\n const startTime = Date.now();\n let waitDurationMs = 0;\n\n try {\n // Find the element\n let registered = this.registry.getElement(elementId);\n\n // If not in registry, try by identifier\n if (!registered) {\n registered = findElementByIdentifier(elementId) ?? undefined;\n }\n\n if (!registered) {\n const failTime = Date.now();\n const errorMsg = `Element not found: ${elementId}`;\n this.emitActionEvent({\n elementId,\n action: request.action,\n params: request.params,\n success: false,\n error: errorMsg,\n timestamp: failTime,\n requestId: request.requestId,\n durationMs: failTime - startTime,\n });\n return {\n success: false,\n error: errorMsg,\n durationMs: failTime - startTime,\n timestamp: failTime,\n requestId: request.requestId,\n };\n }\n\n // Wait for conditions if specified\n if (request.waitOptions) {\n const waitResult = await this.waitForElementInternal(registered.id, request.waitOptions);\n waitDurationMs = waitResult.waitedMs;\n if (!waitResult.met) {\n const failTime = Date.now();\n const errorMsg = waitResult.error || 'Wait condition not met';\n this.emitActionEvent({\n elementId,\n action: request.action,\n params: request.params,\n success: false,\n error: errorMsg,\n timestamp: failTime,\n requestId: request.requestId,\n durationMs: failTime - startTime,\n });\n return {\n success: false,\n error: errorMsg,\n durationMs: failTime - startTime,\n timestamp: failTime,\n requestId: request.requestId,\n waitDurationMs,\n };\n }\n }\n\n // Execute the action\n const result = await this.performAction(registered, request.action, request.params);\n\n const successTime = Date.now();\n this.emitActionEvent({\n elementId,\n action: request.action,\n params: request.params,\n success: true,\n timestamp: successTime,\n requestId: request.requestId,\n durationMs: successTime - startTime,\n });\n // Re-fetch the element from the registry rather than reusing the\n // `registered` reference captured before `performAction`. Mutating\n // actions (`type`/`setValue`/`clear`/`focus`/...) call\n // `registry.updateElementState`, which REPLACES the map entry with a\n // fresh object carrying a new `getState` closure — the captured\n // `registered.getState` is stale and omits the just-set `value`. Without\n // this re-fetch the action response's `elementState` disagrees with a\n // subsequent `GET /control/element/:id` and `/control/snapshot`, which is\n // the inconsistent read-path the manual-test session flagged.\n const fresh = this.registry.getElement(registered.id) ?? registered;\n return {\n success: true,\n elementState: fresh.getState(),\n result,\n durationMs: successTime - startTime,\n timestamp: successTime,\n requestId: request.requestId,\n waitDurationMs,\n };\n } catch (error) {\n const failTime = Date.now();\n const errorMsg = error instanceof Error ? error.message : String(error);\n this.emitActionEvent({\n elementId,\n action: request.action,\n params: request.params,\n success: false,\n error: errorMsg,\n timestamp: failTime,\n requestId: request.requestId,\n durationMs: failTime - startTime,\n });\n return {\n success: false,\n error: errorMsg,\n ...(error instanceof NativeActionError ? { code: error.code } : {}),\n stack: error instanceof Error ? error.stack : undefined,\n durationMs: failTime - startTime,\n timestamp: failTime,\n requestId: request.requestId,\n waitDurationMs,\n };\n }\n }\n\n /**\n * Perform an action on an element\n */\n private async performAction(\n element: ReturnType<NativeUIBridgeRegistry['getElement']>,\n action: NativeStandardAction | string,\n params?: Record<string, unknown>\n ): Promise<unknown> {\n if (!element) {\n throw new Error('Element not found');\n }\n\n const props = element.props || {};\n\n // Check for custom action first\n if (element.customActions && action in element.customActions) {\n // The options bag is ALWAYS supplied — `ActionHandlerOptions` promises\n // it, and a handler written the documented way (`(params, { signal }) =>\n // …`) throws on `undefined`. An element action carries no cancellation\n // source, so the signal is inert; see `inertAbortSignal`.\n return element.customActions[action].handler(params, { signal: inertAbortSignal() });\n }\n\n // Execute standard actions\n switch (action) {\n case 'click': // Web UI Bridge compatibility alias\n case 'press':\n return this.performPress(props, params as PressActionParams | undefined);\n\n case 'longPress':\n return this.performLongPress(props, params as PressActionParams | undefined);\n\n case 'doubleTap':\n return this.performDoubleTap(props);\n\n case 'type':\n return this.performType(element, props, params as unknown as TypeActionParams);\n\n case 'setValue':\n return this.performSetValue(element, props, params as unknown as TypeActionParams);\n\n case 'clear':\n return this.performClear(element, props);\n\n case 'focus':\n return this.performFocus(element);\n\n case 'blur':\n return this.performBlur(element);\n\n case 'scroll':\n return this.performScroll(props, params as ScrollActionParams | undefined);\n\n case 'scrollIntoView':\n return this.performScrollIntoView(\n element,\n params as ScrollIntoViewActionParams | undefined\n );\n\n case 'swipe':\n return this.performSwipe(props, params as unknown as SwipeActionParams);\n\n case 'toggle':\n return this.performToggle(props);\n\n default:\n throw new Error(`Unknown action: ${action}`);\n }\n }\n\n /**\n * Perform press action\n */\n private async performPress(\n props: Record<string, unknown>,\n params?: PressActionParams\n ): Promise<void> {\n // Try different press handlers in order of preference\n const handlers = ['onPress', 'onPressIn', 'onResponderRelease'];\n\n for (const handler of handlers) {\n if (typeof props[handler] === 'function') {\n // Create a synthetic event object\n const event = this.createPressEvent(params);\n (props[handler] as (event: unknown) => void)(event);\n return;\n }\n }\n\n throw new Error('No press handler found on element');\n }\n\n /**\n * Perform long press action\n */\n private async performLongPress(\n props: Record<string, unknown>,\n params?: PressActionParams\n ): Promise<void> {\n if (typeof props.onLongPress === 'function') {\n const event = this.createPressEvent(params);\n (props.onLongPress as (event: unknown) => void)(event);\n return;\n }\n\n throw new Error('No long press handler found on element');\n }\n\n /**\n * Perform double tap action\n */\n private async performDoubleTap(props: Record<string, unknown>): Promise<void> {\n // First try dedicated double tap handler\n if (typeof props.onDoubleTap === 'function') {\n (props.onDoubleTap as () => void)();\n return;\n }\n\n // Fall back to calling press twice\n if (typeof props.onPress === 'function') {\n const event = this.createPressEvent();\n (props.onPress as (event: unknown) => void)(event);\n await sleep(50);\n (props.onPress as (event: unknown) => void)(event);\n return;\n }\n\n throw new Error('No press handler found for double tap');\n }\n\n /**\n * Perform type action\n */\n private async performType(\n element: ReturnType<NativeUIBridgeRegistry['getElement']>,\n props: Record<string, unknown>,\n params: TypeActionParams\n ): Promise<void> {\n if (!params?.text) {\n throw new Error('Type action requires text parameter');\n }\n\n // Clear first if requested. Accept either `clearFirst` (native SDK\n // convention) or `clear` (runner UI Bridge convention) — so agents\n // using the same action across platforms don't hit a naming mismatch.\n if (params.clearFirst || params.clear) {\n await this.performClear(element, props);\n }\n\n // Type character by character if delay specified\n if (params.delay && params.delay > 0) {\n const currentValue = (element?.getState().value || '') as string;\n for (const char of params.text) {\n const newValue = currentValue + char;\n if (typeof props.onChangeText === 'function') {\n (props.onChangeText as (text: string) => void)(newValue);\n }\n await sleep(params.delay);\n }\n } else {\n // Type all at once\n if (typeof props.onChangeText === 'function') {\n (props.onChangeText as (text: string) => void)(params.text);\n } else if (typeof props.onChange === 'function') {\n (props.onChange as (event: { nativeEvent: { text: string } }) => void)({\n nativeEvent: { text: params.text },\n });\n } else {\n throw new Error('No text change handler found on element');\n }\n }\n\n // Update element state\n if (element) {\n this.registry.updateElementState(element.id, { value: params.text });\n }\n }\n\n /**\n * Perform setValue action.\n *\n * Web/runner UI Bridge parity: `setValue` replaces the input's value\n * atomically in a single call (no per-character keystroke simulation),\n * mirroring the web bridge's `setValue` semantics. On native there is no\n * DOM value to assign, so we drive the controlled-input handler\n * (`onChangeText`, falling back to `onChange`) with the full string. The\n * registry's `state.value` is then synced so a subsequent GET on the\n * element reflects the new value.\n *\n * Unlike `type`, this does not append to existing content and ignores\n * `delay` — it is the deterministic \"set the field to exactly this\" action.\n */\n private async performSetValue(\n element: ReturnType<NativeUIBridgeRegistry['getElement']>,\n props: Record<string, unknown>,\n params: TypeActionParams\n ): Promise<void> {\n // `text` is the canonical key; accept `value` as an alias so callers using\n // the web bridge's `{ value }` body shape work without translation.\n const next =\n typeof params?.text === 'string'\n ? params.text\n : typeof (params as { value?: unknown })?.value === 'string'\n ? ((params as { value?: string }).value as string)\n : undefined;\n\n if (typeof next !== 'string') {\n throw new Error('setValue action requires a string \"text\" (or \"value\") parameter');\n }\n\n if (typeof props.onChangeText === 'function') {\n (props.onChangeText as (text: string) => void)(next);\n } else if (typeof props.onChange === 'function') {\n (props.onChange as (event: { nativeEvent: { text: string } }) => void)({\n nativeEvent: { text: next },\n });\n } else {\n throw new Error('No text change handler found on element');\n }\n\n if (element) {\n this.registry.updateElementState(element.id, { value: next });\n }\n }\n\n /**\n * Perform clear action\n */\n private async performClear(\n element: ReturnType<NativeUIBridgeRegistry['getElement']>,\n props: Record<string, unknown>\n ): Promise<void> {\n if (typeof props.onChangeText === 'function') {\n (props.onChangeText as (text: string) => void)('');\n } else if (typeof props.onChange === 'function') {\n (props.onChange as (event: { nativeEvent: { text: string } }) => void)({\n nativeEvent: { text: '' },\n });\n }\n\n // Update element state\n if (element) {\n this.registry.updateElementState(element.id, { value: '' });\n }\n }\n\n /**\n * Perform focus action\n */\n private async performFocus(\n element: ReturnType<NativeUIBridgeRegistry['getElement']>\n ): Promise<void> {\n if (element?.ref.current && 'focus' in element.ref.current) {\n (element.ref.current as { focus: () => void }).focus();\n }\n\n // Update element state\n if (element) {\n this.registry.updateElementState(element.id, { focused: true });\n }\n }\n\n /**\n * Perform blur action\n */\n private async performBlur(\n element: ReturnType<NativeUIBridgeRegistry['getElement']>\n ): Promise<void> {\n if (element?.ref.current && 'blur' in element.ref.current) {\n (element.ref.current as { blur: () => void }).blur();\n }\n\n // Update element state\n if (element) {\n this.registry.updateElementState(element.id, { focused: false });\n }\n }\n\n /**\n * Perform scroll action\n */\n private async performScroll(\n props: Record<string, unknown>,\n params?: ScrollActionParams\n ): Promise<void> {\n if (typeof props.onScroll === 'function') {\n const event = {\n nativeEvent: {\n contentOffset: params?.offset || { x: 0, y: 0 },\n },\n };\n (props.onScroll as (event: unknown) => void)(event);\n }\n }\n\n /**\n * Perform scrollIntoView: scroll the element's DECLARED scroll container so\n * the element sits `padding` dp below the top of its viewport.\n *\n * The container comes from `scrollAncestorId` and nowhere else — the\n * registry keeps no parent chain (`RegisterElementOptions.scrollAncestorId`),\n * so there is no \"nearest ScrollView\" to find. Nothing here tracks a\n * ScrollView's content offset either (`performScroll` only fakes an\n * `onScroll` event), so the target is measured CONTENT-relative with\n * `measureLayout` against the container's inner content view: stateless,\n * and immune to a stale-offset race.\n *\n * Result shape mirrors the web executor's `scrollIntoView`\n * (`@qontinui/ui-bridge` `control/action-executor.ts`):\n * `{ alreadyVisible, scrolled }`, short-circuiting when the element is\n * already fully inside its clip region. \"Fully visible\" is only claimed when\n * it is MEASURED — a page-space rect for the element and a known,\n * non-empty clip (window ∩ declared container), both measured at call\n * time. Anything unknown scrolls.\n *\n * Containers: a ScrollView, or a VirtualizedList (FlatList / SectionList)\n * unwrapped through `getNativeScrollRef()` / `getScrollResponder()`.\n * Vertical only — a `horizontal` container is NOT_SUPPORTED. The action\n * returns once `scrollTo` is dispatched; positions settle on the next frame.\n *\n * Prerequisites are checked BEFORE the visibility short-circuit, so whether\n * the element supports the action does not depend on where it happens to be\n * on screen. Each missing prerequisite is a `NOT_SUPPORTED` failure.\n */\n private async performScrollIntoView(\n element: NonNullable<ReturnType<NativeUIBridgeRegistry['getElement']>>,\n params?: ScrollIntoViewActionParams\n ): Promise<{ alreadyVisible: boolean; scrolled: boolean }> {\n const padding = params?.padding ?? DEFAULT_SCROLL_INTO_VIEW_PADDING;\n if (typeof padding !== 'number' || !Number.isFinite(padding) || padding < 0) {\n throw new Error('scrollIntoView \"padding\" must be a finite, non-negative number');\n }\n\n const ancestorId = element.scrollAncestorId;\n if (!ancestorId) {\n throw new NativeActionError(\n `scrollIntoView is not supported on element \"${element.id}\": it declares no scrollAncestorId, ` +\n 'and the registry keeps no parent chain to find its scroll container from',\n 'NOT_SUPPORTED'\n );\n }\n const ancestor = ancestorId === element.id ? undefined : this.registry.getElement(ancestorId);\n if (!ancestor) {\n throw new NativeActionError(\n `scrollIntoView is not supported on element \"${element.id}\": its declared scrollAncestorId ` +\n `\"${ancestorId}\" is not a registered element`,\n 'NOT_SUPPORTED'\n );\n }\n const container = resolveScrollView(ancestor.ref.current);\n if (!container) {\n throw new NativeActionError(\n `scrollIntoView is not supported on element \"${element.id}\": its scroll ancestor ` +\n `\"${ancestorId}\" has no scrollTo (not a mounted ScrollView, and no ` +\n 'getNativeScrollRef/getScrollResponder yielding one)',\n 'NOT_SUPPORTED'\n );\n }\n if (isDeclaredHorizontal(ancestor.props, ancestor.ref.current, container)) {\n // `scrollTo` here moves only y; RN sends `x || 0`, so on a horizontal\n // ScrollView this would jump the content to its start and still report\n // success. Refuse rather than lie.\n //\n // LIMIT: detected only where `horizontal` is visible to the bridge —\n // captured props (`captureProps({ horizontal: true })` / a direct\n // `registerElement` with `props`) or a class-component ref carrying\n // `props.horizontal` (FlatList / SectionList instances). A horizontal\n // ScrollView registered through `useUIElement` without captured props\n // is NOT detected; the action is documented as vertical-only.\n throw new NativeActionError(\n `scrollIntoView is not supported on element \"${element.id}\": its scroll ancestor ` +\n `\"${ancestorId}\" is horizontal (only vertical containers are supported)`,\n 'NOT_SUPPORTED'\n );\n }\n // `getInnerViewRef()` returns a host instance on both architectures and is\n // the primary path. `getInnerViewNode()` returns a numeric tag, which only\n // the legacy architecture's `measureLayout` accepts (Fabric ignores it and\n // never calls back — the timeout below then names that cause).\n const innerViewRef = container.getInnerViewRef?.();\n const innerView = innerViewRef ?? container.getInnerViewNode?.();\n const innerViewIsTag = innerViewRef == null && typeof innerView === 'number';\n if (innerView === undefined || innerView === null) {\n throw new NativeActionError(\n `scrollIntoView is not supported on element \"${element.id}\": its scroll ancestor ` +\n `\"${ancestorId}\" exposes no inner content view to measure against`,\n 'NOT_SUPPORTED'\n );\n }\n const target = element.ref.current as unknown as Partial<MeasurableRef> | null;\n if (!target || typeof target.measureLayout !== 'function') {\n throw new NativeActionError(\n `scrollIntoView is not supported on element \"${element.id}\": its ref has no measureLayout ` +\n '(not a mounted host view)',\n 'NOT_SUPPORTED'\n );\n }\n\n // Already-visible short-circuit — only on MEASURED evidence: the target\n // AND its declared container are both measured now (targeted, bounded —\n // not a registry-wide sweep), and the target lies fully inside\n // window ∩ container. An unknown container rect must NOT fall back to the\n // window alone: a row below a short ScrollView's bottom edge is still\n // inside the window. Anything unknown scrolls.\n const [rect, ancestorRect] = await Promise.all([\n measurePageRectNow(element),\n measurePageRectNow(ancestor, container),\n ]);\n // With no viewport provider the window is UNKNOWN and only the container\n // bounds the check — the same answer `getClipRectFor` gives.\n const viewport = this.registry.getViewportRect();\n const clip = ancestorRect ? intersectRects(viewport, ancestorRect) : null;\n if (\n rect &&\n clip &&\n !isEmptyRect(clip) &&\n rect.right > rect.left &&\n rect.bottom > rect.top &&\n rect.top >= clip.top &&\n rect.left >= clip.left &&\n rect.bottom <= clip.bottom &&\n rect.right <= clip.right\n ) {\n return { alreadyVisible: true, scrolled: false };\n }\n\n const measured = await new Promise<{ x: number; y: number; width: number }>(\n (resolve, reject) => {\n let settled = false;\n const timer = setTimeout(() => {\n if (settled) return;\n settled = true;\n reject(\n new Error(\n `scrollIntoView: measureLayout did not call back within ${SCROLL_INTO_VIEW_MEASURE_TIMEOUT_MS}ms` +\n (innerViewIsTag\n ? ' (measured against a numeric inner-view tag from getInnerViewNode, which the new architecture does not support)'\n : '')\n )\n );\n }, SCROLL_INTO_VIEW_MEASURE_TIMEOUT_MS);\n const finish = (fn: () => void) => {\n if (settled) return;\n settled = true;\n clearTimeout(timer);\n fn();\n };\n try {\n target.measureLayout!(\n innerView,\n (x, y, width) =>\n finish(() =>\n Number.isFinite(y)\n ? resolve({ x, y, width })\n : reject(new Error('scrollIntoView: measureLayout returned a non-finite y'))\n ),\n () =>\n finish(() =>\n reject(\n new Error(\n `scrollIntoView: measureLayout failed for \"${element.id}\" relative to \"${ancestorId}\"`\n )\n )\n )\n );\n } catch (error) {\n finish(() => reject(error));\n }\n }\n );\n\n // Undeclared-horizontal backstop: content laid out sideways past the\n // container's measured width means scrolling only y cannot reach it (and\n // RN's `x || 0` would reset the x offset). Refuse rather than report a\n // scroll that did not bring the element into view. Skipped when the\n // container width is unknown.\n if (\n ancestorRect &&\n Number.isFinite(measured.x) &&\n Number.isFinite(measured.width) &&\n measured.x + measured.width > ancestorRect.right - ancestorRect.left + 1\n ) {\n throw new NativeActionError(\n `scrollIntoView is not supported on element \"${element.id}\": it is laid out beyond the ` +\n `horizontal extent of its scroll ancestor \"${ancestorId}\" (sideways overflow, a horizontal ` +\n 'container, or a nested horizontal container — declare that inner container as its ' +\n 'scrollAncestorId); only vertical scrolling is supported',\n 'NOT_SUPPORTED'\n );\n }\n\n container.scrollTo({ y: Math.max(0, measured.y - padding), animated: false });\n return { alreadyVisible: false, scrolled: true };\n }\n\n /**\n * Perform swipe action\n */\n private async performSwipe(\n props: Record<string, unknown>,\n params: SwipeActionParams\n ): Promise<void> {\n if (!params?.direction) {\n throw new Error('Swipe action requires direction parameter');\n }\n\n // Try dedicated swipe handlers\n const handlerMap: Record<string, string> = {\n left: 'onSwipeLeft',\n right: 'onSwipeRight',\n up: 'onSwipeUp',\n down: 'onSwipeDown',\n };\n\n const handler = handlerMap[params.direction];\n if (handler && typeof props[handler] === 'function') {\n (props[handler] as () => void)();\n return;\n }\n\n // Fall back to generic swipe handler\n if (typeof props.onSwipe === 'function') {\n (props.onSwipe as (direction: string) => void)(params.direction);\n }\n }\n\n /**\n * Perform toggle action\n */\n private async performToggle(props: Record<string, unknown>): Promise<void> {\n // For Switch components\n if (typeof props.onValueChange === 'function') {\n const currentValue = props.value as boolean;\n (props.onValueChange as (value: boolean) => void)(!currentValue);\n return;\n }\n\n // Fall back to press\n if (typeof props.onPress === 'function') {\n (props.onPress as () => void)();\n return;\n }\n\n throw new Error('No toggle handler found on element');\n }\n\n /**\n * Create a synthetic press event\n */\n private createPressEvent(params?: PressActionParams): object {\n return {\n nativeEvent: {\n locationX: params?.position?.x ?? 0,\n locationY: params?.position?.y ?? 0,\n timestamp: Date.now(),\n },\n persist: () => {},\n };\n }\n\n /**\n * Execute a component action\n */\n async executeComponentAction(\n componentId: string,\n request: ComponentActionRequest,\n options: ComponentActionInvokeOptions = {}\n ): Promise<ComponentActionResponse> {\n const startTime = Date.now();\n\n try {\n const component = this.registry.getComponent(componentId);\n\n if (!component) {\n return {\n success: false,\n error: `Component not found: ${componentId}`,\n durationMs: Date.now() - startTime,\n timestamp: Date.now(),\n requestId: request.requestId,\n };\n }\n\n // Find the action\n const action = component.actions.find((a) => a.id === request.action);\n\n if (!action) {\n return {\n success: false,\n error: `Action not found: ${request.action}`,\n durationMs: Date.now() - startTime,\n timestamp: Date.now(),\n requestId: request.requestId,\n };\n }\n\n // `timeoutMs` is WIRE data — the HTTP entry point forwards it verbatim\n // from a JSON body — so it is validated and clamped here, before it can\n // reach a timer. See `normalizeActionTimeoutMs` for the policy (0\n // abandons on the next tick; negative / NaN / non-numeric are refused;\n // anything above 24h is clamped, because past 2^31-1 `setTimeout` wraps\n // negative and fires immediately).\n const timeout = normalizeActionTimeoutMs(request.timeoutMs);\n if (!timeout.ok) {\n return {\n success: false,\n error: `Action \"${request.action}\" on component \"${componentId}\" was rejected: ${timeout.reason}.`,\n durationMs: Date.now() - startTime,\n timestamp: Date.now(),\n requestId: request.requestId,\n };\n }\n const timeoutMs = timeout.timeoutMs;\n\n // Phase 2: `paramSchema` is published to agents, so it has to mean\n // something. Validate BEFORE the handler runs — a rejection after a\n // side-effect is not a rejection.\n const validationMode = options.paramValidation ?? getDefaultParamValidationMode();\n if (validationMode !== 'off' && action.paramSchema !== undefined) {\n // The validator walks AUTHOR-supplied schema data. It is bounded\n // against both known fault routes (`param-schema.ts` MAX_SCHEMA_DEPTH /\n // MAX_PATTERN_LENGTH), but it is wrapped anyway: without this, a\n // validator fault would fall into the generic catch below and be\n // reported as a HANDLER failure, for a handler that never ran.\n let validation: ReturnType<typeof validateActionParams>;\n try {\n validation = validateActionParams(action.paramSchema, request.params);\n } catch (validatorFault) {\n const detail =\n validatorFault instanceof Error ? validatorFault.message : String(validatorFault);\n const faultMessage = `Action \"${request.action}\" on component \"${componentId}\": its declared paramSchema could not be evaluated (${detail}).`;\n if (validationMode === 'enforce') {\n // A gate that cannot be evaluated has not been cleared. The prose\n // names the SCHEMA, so it is not mistaken for a handler fault.\n return {\n success: false,\n error: faultMessage,\n durationMs: Date.now() - startTime,\n timestamp: Date.now(),\n requestId: request.requestId,\n };\n }\n console.warn(`[ui-bridge-native] ${faultMessage}`);\n validation = { valid: true, issues: [] };\n }\n if (!validation.valid) {\n const message = formatParamValidationFailure(\n componentId,\n request.action,\n validation.issues\n );\n if (validationMode === 'enforce') {\n // Prose `error` rather than structured `failureDetails` — this\n // tree's response type has no such field. See the note on\n // `ComponentActionInvokeOptions.paramValidation`.\n return {\n success: false,\n error: message,\n durationMs: Date.now() - startTime,\n timestamp: Date.now(),\n requestId: request.requestId,\n };\n }\n console.warn(`[ui-bridge-native] ${message}`);\n }\n }\n\n // The handler is *given* a signal (cooperative cancellation) and is\n // *raced* against it (enforced abandonment) — a handler that ignores its\n // signal must still be abandonable at the caller. Phase 3 of plan\n // 2026-08-20-ui-bridge-action-declaration-shape.\n const outcome = await runAbortable((signal) => action.handler(request.params, { signal }), {\n signal: options.signal,\n timeoutMs,\n });\n\n if (outcome.aborted) {\n // NOTE: this tree's `ComponentActionResponse` has no `failureDetails`\n // field and this package ships no diagnostics module, so the\n // cancellation surfaces as a prose `error` rather than through\n // `buildActionFailureDetails('UB-ACTION-FAILED', ...)` the way the web\n // seam does. Giving the native channel structured failure details is a\n // separate change, not Phase 3.\n return {\n success: false,\n error:\n outcome.reason === 'timeout'\n ? `Action \"${request.action}\" on component \"${componentId}\" was abandoned after its ${timeoutMs}ms timeout elapsed.`\n : `Action \"${request.action}\" on component \"${componentId}\" was cancelled by the caller's abort signal.`,\n durationMs: Date.now() - startTime,\n timestamp: Date.now(),\n requestId: request.requestId,\n };\n }\n\n return {\n success: true,\n result: outcome.result,\n durationMs: Date.now() - startTime,\n timestamp: Date.now(),\n requestId: request.requestId,\n };\n } catch (error) {\n return {\n success: false,\n error: error instanceof Error ? error.message : String(error),\n stack: error instanceof Error ? error.stack : undefined,\n durationMs: Date.now() - startTime,\n timestamp: Date.now(),\n requestId: request.requestId,\n };\n }\n }\n\n /**\n * Find elements\n */\n async find(request: NativeFindRequest): Promise<NativeFindResponse> {\n const startTime = Date.now();\n\n const allElements = this.registry.getAllElements();\n let filtered = allElements;\n\n // Filter by type\n if (request.types && request.types.length > 0) {\n filtered = filtered.filter((e) => request.types!.includes(e.type));\n }\n\n // Filter by testID pattern\n if (request.testIdPattern) {\n const regex = new RegExp(request.testIdPattern.replace(/\\*/g, '.*').replace(/\\?/g, '.'));\n filtered = filtered.filter((e) => {\n const identifier = e.getIdentifier();\n return identifier.testId && regex.test(identifier.testId);\n });\n }\n\n // Filter by accessibility label pattern\n if (request.accessibilityLabelPattern) {\n const regex = new RegExp(\n request.accessibilityLabelPattern.replace(/\\*/g, '.*').replace(/\\?/g, '.')\n );\n filtered = filtered.filter((e) => {\n const identifier = e.getIdentifier();\n return identifier.accessibilityLabel && regex.test(identifier.accessibilityLabel);\n });\n }\n\n // Filter by visibility\n if (request.visibleOnly) {\n filtered = filtered.filter((e) => e.getState().visible);\n }\n\n // Apply limit\n if (request.limit && request.limit > 0) {\n filtered = filtered.slice(0, request.limit);\n }\n\n // Map to discovered elements\n const elements: DiscoveredNativeElement[] = filtered.map((e) => ({\n id: e.id,\n type: e.type,\n identifier: e.getIdentifier(),\n state: e.getState(),\n actions: e.actions,\n label: e.label,\n }));\n\n return {\n elements,\n total: elements.length,\n durationMs: Date.now() - startTime,\n timestamp: Date.now(),\n };\n }\n\n /**\n * Wait for element conditions\n */\n async waitForElement(elementId: string, options: WaitOptions): Promise<WaitResult> {\n return this.waitForElementInternal(elementId, options);\n }\n\n /**\n * Internal wait implementation\n */\n private async waitForElementInternal(\n elementId: string,\n options: WaitOptions\n ): Promise<WaitResult> {\n const opts = { ...DEFAULT_WAIT_OPTIONS, ...options };\n const startTime = Date.now();\n\n while (Date.now() - startTime < opts.timeout) {\n const element = this.registry.getElement(elementId);\n\n if (!element) {\n await sleep(opts.interval);\n continue;\n }\n\n const state = element.getState();\n\n // Check conditions\n let conditionsMet = true;\n\n if (opts.visible && !state.visible) {\n conditionsMet = false;\n }\n\n if (opts.enabled && !state.enabled) {\n conditionsMet = false;\n }\n\n if (opts.focused && !state.focused) {\n conditionsMet = false;\n }\n\n // Check custom state conditions\n if (opts.state && Object.keys(opts.state).length > 0) {\n const stateRecord = state as unknown as Record<string, unknown>;\n for (const [key, value] of Object.entries(opts.state)) {\n if (stateRecord[key] !== value) {\n conditionsMet = false;\n break;\n }\n }\n }\n\n if (conditionsMet) {\n return {\n met: true,\n waitedMs: Date.now() - startTime,\n state,\n };\n }\n\n await sleep(opts.interval);\n }\n\n return {\n met: false,\n waitedMs: Date.now() - startTime,\n error: `Timeout waiting for conditions on element: ${elementId}`,\n };\n }\n}\n\n/**\n * Create a native action executor\n */\nexport function createNativeActionExecutor(registry: NativeUIBridgeRegistry): NativeActionExecutor {\n return new DefaultNativeActionExecutor(registry);\n}\n","/**\n * Native Design Inspector\n *\n * Pure TypeScript functions that map flattened React Native styles to the\n * web SDK's ExtendedComputedStyles format. No react-native imports — works\n * with already-flattened style objects from the registry.\n *\n * Key differences from web:\n * - No `window.getComputedStyle()` — styles are declarative objects\n * - No hover/active states — uses pressed/focused/disabled\n * - No pseudo-elements (::before/::after)\n * - No CSS grid, cursor, visibility, transitions, background-image\n * - RN default flexDirection is 'column' (not 'row')\n * - Shadows differ: iOS uses shadow* props, Android uses elevation\n * - Numeric values → \"Npx\" strings\n */\n\nimport type {\n ExtendedComputedStyles,\n ElementDesignData,\n StateStyles,\n StyleDiff,\n ResponsiveSnapshot,\n NativeInteractionStateName,\n} from './design-types';\nimport type { NativeLayout } from '../core/types';\n\n// ============================================================================\n// Helpers\n// ============================================================================\n\n/**\n * Convert a numeric RN value to a CSS px string.\n * String values (like \"50%\") pass through unchanged.\n */\nfunction toCssValue(value: unknown): string {\n if (value == null) return '';\n if (typeof value === 'number') return `${value}px`;\n return String(value);\n}\n\n/**\n * Convert RN transform array to CSS transform string.\n * e.g. [{translateX: 10}, {rotate: '45deg'}] → \"translateX(10px) rotate(45deg)\"\n */\nfunction transformToCss(transform: unknown): string {\n if (!Array.isArray(transform) || transform.length === 0) return '';\n\n return transform\n .map((t: Record<string, unknown>) => {\n const key = Object.keys(t)[0];\n if (!key) return '';\n const val = t[key];\n // Rotation values are already strings like '45deg'\n if (typeof val === 'string') return `${key}(${val})`;\n // Numeric values need px for translate, unitless for scale\n if (typeof val === 'number') {\n const needsPx = key.startsWith('translate') || key === 'perspective';\n return `${key}(${val}${needsPx ? 'px' : ''})`;\n }\n return '';\n })\n .filter(Boolean)\n .join(' ');\n}\n\n/**\n * Convert RN shadow props (iOS) + elevation (Android) to CSS box-shadow string.\n */\nfunction shadowToCss(style: Record<string, unknown>): string {\n const parts: string[] = [];\n\n // iOS shadow\n const shadowColor = style.shadowColor as string | undefined;\n const shadowOffset = style.shadowOffset as { width: number; height: number } | undefined;\n const shadowOpacity = style.shadowOpacity as number | undefined;\n const shadowRadius = style.shadowRadius as number | undefined;\n\n if (shadowColor && shadowOffset && shadowOpacity != null && shadowOpacity > 0) {\n const { width, height } = shadowOffset;\n parts.push(\n `${width}px ${height}px ${shadowRadius ?? 0}px ${shadowColor}` +\n (shadowOpacity < 1 ? ` /* opacity: ${shadowOpacity} */` : '')\n );\n }\n\n // Android elevation\n const elevation = style.elevation as number | undefined;\n if (elevation != null && elevation > 0) {\n parts.push(`elevation(${elevation})`);\n }\n\n return parts.join(', ');\n}\n\n/**\n * Convert RN border props to CSS border shorthand.\n */\nfunction borderToCss(style: Record<string, unknown>): string {\n const width = style.borderWidth as number | undefined;\n const color = style.borderColor as string | undefined;\n\n if (width == null && color == null) return '';\n return `${width ?? 0}px solid ${color ?? 'transparent'}`;\n}\n\n/**\n * Convert RN borderRadius to CSS border-radius string.\n * Handles both uniform radius and per-corner values.\n */\nfunction borderRadiusToCss(style: Record<string, unknown>): string {\n const uniform = style.borderRadius as number | undefined;\n if (uniform != null) return `${uniform}px`;\n\n const tl = style.borderTopLeftRadius as number | undefined;\n const tr = style.borderTopRightRadius as number | undefined;\n const bl = style.borderBottomLeftRadius as number | undefined;\n const br = style.borderBottomRightRadius as number | undefined;\n\n if (tl == null && tr == null && bl == null && br == null) return '';\n return `${tl ?? 0}px ${tr ?? 0}px ${br ?? 0}px ${bl ?? 0}px`;\n}\n\n/**\n * Resolve margin/padding shorthand + Horizontal/Vertical expansions.\n * Returns top, right, bottom, left values.\n */\nfunction resolveSpacing(\n style: Record<string, unknown>,\n prefix: 'margin' | 'padding'\n): { top: string; right: string; bottom: string; left: string; shorthand: string } {\n const all = style[prefix];\n const top = style[`${prefix}Top`] ?? style[`${prefix}Vertical`] ?? all;\n const bottom = style[`${prefix}Bottom`] ?? style[`${prefix}Vertical`] ?? all;\n const right = style[`${prefix}Right`] ?? style[`${prefix}Horizontal`] ?? all;\n const left = style[`${prefix}Left`] ?? style[`${prefix}Horizontal`] ?? all;\n\n const t = toCssValue(top);\n const r = toCssValue(right);\n const b = toCssValue(bottom);\n const l = toCssValue(left);\n\n // Build shorthand\n let shorthand = '';\n if (t || r || b || l) {\n if (t === r && r === b && b === l) {\n shorthand = t || '0px';\n } else if (t === b && r === l) {\n shorthand = `${t || '0px'} ${r || '0px'}`;\n } else {\n shorthand = `${t || '0px'} ${r || '0px'} ${b || '0px'} ${l || '0px'}`;\n }\n }\n\n return {\n top: t,\n right: r,\n bottom: b,\n left: l,\n shorthand,\n };\n}\n\n/**\n * Resolve gap values (gap, rowGap, columnGap).\n */\nfunction resolveGap(style: Record<string, unknown>): string {\n const gap = style.gap as number | undefined;\n const rowGap = style.rowGap as number | undefined;\n const columnGap = style.columnGap as number | undefined;\n\n if (gap != null) return `${gap}px`;\n if (rowGap != null && columnGap != null) return `${rowGap}px ${columnGap}px`;\n if (rowGap != null) return `${rowGap}px`;\n if (columnGap != null) return `${columnGap}px`;\n return '';\n}\n\n// ============================================================================\n// Core mapping function\n// ============================================================================\n\n/**\n * Map a flattened React Native style object to ExtendedComputedStyles.\n *\n * Rules:\n * - Numeric values → \"Npx\"\n * - String values → pass through\n * - textDecorationLine → textDecoration\n * - RN shadow props → boxShadow string\n * - CSS-only properties (cursor, visibility, grid*, etc.) → empty string\n */\nexport function mapNativeStyleToExtended(\n rnStyle: Record<string, unknown> | undefined | null\n): ExtendedComputedStyles {\n const s = rnStyle ?? {};\n\n const margin = resolveSpacing(s, 'margin');\n const padding = resolveSpacing(s, 'padding');\n\n return {\n // Layout\n display: (s.display as string) ?? 'flex',\n position: (s.position as string) ?? 'relative',\n boxSizing: '', // CSS-only\n width: toCssValue(s.width),\n height: toCssValue(s.height),\n minWidth: toCssValue(s.minWidth),\n maxWidth: toCssValue(s.maxWidth),\n minHeight: toCssValue(s.minHeight),\n maxHeight: toCssValue(s.maxHeight),\n margin: margin.shorthand,\n marginTop: margin.top,\n marginRight: margin.right,\n marginBottom: margin.bottom,\n marginLeft: margin.left,\n padding: padding.shorthand,\n paddingTop: padding.top,\n paddingRight: padding.right,\n paddingBottom: padding.bottom,\n paddingLeft: padding.left,\n overflow: (s.overflow as string) ?? '',\n overflowX: '', // CSS-only\n overflowY: '', // CSS-only\n\n // Flex/Grid — RN defaults to column, not row\n flexDirection: (s.flexDirection as string) ?? '',\n flexWrap: (s.flexWrap as string) ?? '',\n justifyContent: (s.justifyContent as string) ?? '',\n alignItems: (s.alignItems as string) ?? '',\n alignSelf: (s.alignSelf as string) ?? '',\n gap: resolveGap(s),\n gridTemplateColumns: '', // CSS-only\n gridTemplateRows: '', // CSS-only\n\n // Typography\n fontFamily: (s.fontFamily as string) ?? '',\n fontSize: toCssValue(s.fontSize),\n fontWeight: (s.fontWeight as string) ?? '',\n lineHeight: toCssValue(s.lineHeight),\n letterSpacing: toCssValue(s.letterSpacing),\n textAlign: (s.textAlign as string) ?? '',\n textTransform: (s.textTransform as string) ?? '',\n textDecoration: (s.textDecorationLine as string) ?? '', // RN name → CSS name\n color: (s.color as string) ?? '',\n\n // Visual\n backgroundColor: (s.backgroundColor as string) ?? '',\n backgroundImage: '', // CSS-only\n border: borderToCss(s),\n borderRadius: borderRadiusToCss(s),\n boxShadow: shadowToCss(s),\n opacity: s.opacity != null ? String(s.opacity) : '',\n outline: '', // CSS-only\n\n // Effects\n transform: transformToCss(s.transform),\n transition: '', // CSS-only\n cursor: '', // CSS-only\n zIndex: s.zIndex != null ? String(s.zIndex) : '',\n visibility: '', // CSS-only\n pointerEvents: (s.pointerEvents as string) ?? '',\n };\n}\n\n// ============================================================================\n// Design data functions\n// ============================================================================\n\n/**\n * Produce ElementDesignData for a single native element.\n */\nexport function getNativeElementDesignData(\n id: string,\n label: string | undefined,\n type: string,\n rnStyle: Record<string, unknown> | undefined | null,\n layout: NativeLayout | null\n): ElementDesignData {\n return {\n elementId: id,\n label,\n type,\n styles: mapNativeStyleToExtended(rnStyle),\n pseudoElements: [], // RN has no pseudo-elements\n rect: layout\n ? {\n x: layout.pageX,\n y: layout.pageY,\n width: layout.width,\n height: layout.height,\n }\n : { x: 0, y: 0, width: 0, height: 0 },\n };\n}\n\n/**\n * Compute style diffs between default and a state variation.\n */\nfunction computeStyleDiff(\n defaultStyles: ExtendedComputedStyles,\n stateStyles: ExtendedComputedStyles\n): StyleDiff[] {\n const diffs: StyleDiff[] = [];\n for (const key of Object.keys(defaultStyles) as Array<keyof ExtendedComputedStyles>) {\n if (defaultStyles[key] !== stateStyles[key]) {\n diffs.push({\n property: key,\n defaultValue: defaultStyles[key],\n stateValue: stateStyles[key],\n });\n }\n }\n return diffs;\n}\n\n/**\n * Merge a base RN style with a state override.\n */\nfunction mergeStyles(\n base: Record<string, unknown>,\n override: Record<string, unknown> | undefined\n): Record<string, unknown> {\n if (!override) return base;\n return { ...base, ...override };\n}\n\n/**\n * Produce StateStyles[] for default/pressed/focused/disabled.\n * Only includes states that have actual overrides or the default state.\n */\nexport function captureNativeStateVariations(\n baseStyle: Record<string, unknown> | undefined | null,\n stateStyles?: {\n pressed?: Record<string, unknown>;\n focused?: Record<string, unknown>;\n disabled?: Record<string, unknown>;\n }\n): StateStyles[] {\n const base = baseStyle ?? {};\n const defaultExtended = mapNativeStyleToExtended(base);\n\n const results: StateStyles[] = [\n {\n state: 'default',\n styles: defaultExtended,\n diffFromDefault: [],\n },\n ];\n\n if (!stateStyles) return results;\n\n const states: Array<{ name: NativeInteractionStateName; override?: Record<string, unknown> }> = [\n { name: 'pressed', override: stateStyles.pressed },\n { name: 'focused', override: stateStyles.focused },\n { name: 'disabled', override: stateStyles.disabled },\n ];\n\n for (const { name, override } of states) {\n if (!override) continue;\n const merged = mergeStyles(base, override);\n const extended = mapNativeStyleToExtended(merged);\n const diff = computeStyleDiff(defaultExtended, extended);\n if (diff.length > 0) {\n results.push({ state: name, styles: extended, diffFromDefault: diff });\n }\n }\n\n return results;\n}\n\n/**\n * Capture a responsive snapshot.\n *\n * Platform limitation: RN cannot constrain screen width at runtime.\n * This returns a single snapshot at the current device dimensions.\n */\nexport function captureNativeResponsiveSnapshot(\n elements: Array<{\n id: string;\n label?: string;\n type: string;\n flatStyle?: Record<string, unknown>;\n layout: NativeLayout | null;\n }>,\n screenDimensions: { width: number; height: number }\n): ResponsiveSnapshot[] {\n const elementData = elements.map((el) =>\n getNativeElementDesignData(el.id, el.label, el.type, el.flatStyle, el.layout)\n );\n\n return [\n {\n viewportWidth: screenDimensions.width,\n viewportLabel: 'current',\n elements: elementData,\n timestamp: Date.now(),\n },\n ];\n}\n","/**\n * UI Bridge Native Design Review Handlers\n *\n * HTTP handlers for the 8 design review endpoints.\n * Maps registered element styles to the web SDK's design data format.\n */\n\nimport type { NativeUIBridgeRegistry } from '../core/registry';\nimport type { APIResponse, HandlerContext } from './types';\nimport type { ElementDesignData, StateStyles, ResponsiveSnapshot } from '../design/design-types';\nimport {\n mapNativeStyleToExtended,\n getNativeElementDesignData,\n captureNativeStateVariations,\n captureNativeResponsiveSnapshot,\n} from '../design/design-inspector-native';\n\n// Style guide and baseline stored in closure (same pattern as web SDK)\nlet loadedStyleGuide: unknown = null;\nlet savedBaseline: unknown = null;\n\n// Try to load the style validator from the web SDK (optional peer dep)\nlet styleValidator: {\n runStyleAudit: (\n elements: Array<{ elementId: string; styles: Record<string, string> }>,\n guide: unknown\n ) => unknown;\n} | null = null;\n\n// Try to load quality evaluator from the web SDK (optional peer dep)\nlet qualityEvaluator: {\n evaluateQuality: (\n elements: ElementDesignData[],\n viewport: { width: number; height: number },\n context?: unknown\n ) => unknown;\n listContexts: () => Array<{ name: string; description: string }>;\n createBaseline: (\n elements: ElementDesignData[],\n viewport: { width: number; height: number },\n label?: string\n ) => unknown;\n diffSnapshots: (baseline: unknown, current: ElementDesignData[]) => unknown;\n} | null = null;\n\ntry {\n // eslint-disable-next-line @typescript-eslint/no-require-imports\n const specs = require('@qontinui/ui-bridge/specs');\n styleValidator = specs;\n qualityEvaluator = specs;\n} catch {\n // Optional dependency not installed — audit/evaluate endpoints will return an error\n}\n\nfunction success<T>(data: T): APIResponse<T> {\n return { success: true, data, timestamp: Date.now() };\n}\n\nfunction error<T = unknown>(message: string, code?: string): APIResponse<T> {\n return { success: false, error: message, code, timestamp: Date.now() };\n}\n\n/**\n * Design handler interface (subset of NativeServerHandlers)\n */\nexport interface NativeDesignHandlers {\n getElementStyles: (ctx: HandlerContext) => Promise<APIResponse<ElementDesignData>>;\n getElementStateStyles: (\n ctx: HandlerContext\n ) => Promise<APIResponse<{ elementId: string; stateStyles: StateStyles[] }>>;\n getDesignSnapshot: (\n ctx: HandlerContext\n ) => Promise<APIResponse<{ elements: ElementDesignData[]; timestamp: number }>>;\n getResponsiveSnapshots: (ctx: HandlerContext) => Promise<APIResponse<ResponsiveSnapshot[]>>;\n runDesignAudit: (ctx: HandlerContext) => Promise<APIResponse<unknown>>;\n loadStyleGuide: (ctx: HandlerContext) => Promise<APIResponse<{ loaded: boolean }>>;\n getStyleGuide: (ctx: HandlerContext) => Promise<APIResponse<unknown>>;\n clearStyleGuide: (ctx: HandlerContext) => Promise<APIResponse<{ cleared: boolean }>>;\n evaluateQuality: (ctx: HandlerContext) => Promise<APIResponse<unknown>>;\n getQualityContexts: (\n ctx: HandlerContext\n ) => Promise<APIResponse<Array<{ name: string; description: string }>>>;\n saveBaseline: (\n ctx: HandlerContext\n ) => Promise<APIResponse<{ saved: boolean; elementCount: number }>>;\n diffBaseline: (ctx: HandlerContext) => Promise<APIResponse<unknown>>;\n}\n\n/**\n * Create design review handlers.\n *\n * @param registry - the registered native element registry\n * @param viewportProvider - optional injected viewport getter. Same shape as\n * the `viewportProvider` consumed by `handlers.ts`/`getPageHealth`. This is\n * injected by `createServerHandlers` from the `NativeServerConfig` the host\n * passes to `UIBridgeNativeProvider`/`NativeUIBridgeServer`, which in turn\n * reads `Dimensions.get('screen')` (or `'window'`). The indirection exists\n * because `require('react-native')` from this file crashes the host RN\n * app the moment any design endpoint is invoked: Metro/Hermes raise\n * `unknownModuleError` past every try/catch and tear down the JS thread.\n * This was the same latent crash that took out 0.6.3/0.6.4 page-health\n * handler — the design handlers had it too, just hiding on unused\n * endpoints until `POST /design/responsive` was first called.\n *\n * When the injected provider is absent (tests, custom hosts) the design\n * handlers fall back to `{width:0, height:0}` — the responsive snapshot\n * degenerates to \"zero-dimension viewport\" rather than crashing.\n */\nexport function createDesignHandlers(\n registry: NativeUIBridgeRegistry,\n viewportProvider?: () => { width: number; height: number }\n): NativeDesignHandlers {\n // Helper to get screen dimensions via the injected provider.\n //\n // The 0.6.3/0.6.4 implementation called `require('react-native')` here\n // inside a try/catch; Metro/Hermes still surfaced `unknownModuleError`\n // up the stack and tore down the JS thread the moment any design endpoint\n // was touched. The fix is to take the viewport as an injected dependency\n // (parity with `getPageHealth`) so this file has no `react-native` dep\n // at all — see the doc comment on `createDesignHandlers` above and the\n // project memory entry `feedback_metro_require_gotcha.md`.\n function getScreenDimensions(): { width: number; height: number } {\n return viewportProvider?.() ?? { width: 0, height: 0 };\n }\n\n return {\n // 1. GET /design/element/:id/styles\n getElementStyles: async (ctx) => {\n const { id } = ctx.params;\n const element = registry.getElement(id);\n\n if (!element) {\n return error('Element not found: ' + id, 'ELEMENT_NOT_FOUND');\n }\n\n const state = element.getState();\n const data = getNativeElementDesignData(\n id,\n element.label,\n element.type,\n element.flatStyle,\n state.layout\n );\n\n return success(data);\n },\n\n // 2. POST /design/element/:id/state-styles\n getElementStateStyles: async (ctx) => {\n const { id } = ctx.params;\n const element = registry.getElement(id);\n\n if (!element) {\n return error('Element not found: ' + id, 'ELEMENT_NOT_FOUND');\n }\n\n const stateStyles = captureNativeStateVariations(element.flatStyle, element.stateStyles);\n\n return success({ elementId: id, stateStyles });\n },\n\n // 3. POST /design/snapshot\n getDesignSnapshot: async (ctx) => {\n const body = ctx.body as\n | {\n elementIds?: string[];\n includePseudoElements?: boolean;\n }\n | undefined;\n\n let elements = registry.getAllElements();\n\n // Filter to requested IDs if specified\n if (body?.elementIds && body.elementIds.length > 0) {\n const idSet = new Set(body.elementIds);\n elements = elements.filter((e) => idSet.has(e.id));\n }\n\n const designData: ElementDesignData[] = elements.map((el) => {\n const state = el.getState();\n return getNativeElementDesignData(el.id, el.label, el.type, el.flatStyle, state.layout);\n });\n\n return success({ elements: designData, timestamp: Date.now() });\n },\n\n // 4. POST /design/responsive\n getResponsiveSnapshots: async () => {\n // Platform limitation: RN cannot constrain screen width at runtime.\n // Returns a single snapshot at current device dimensions.\n const elements = registry.getAllElements();\n const elementData = elements.map((el) => {\n const state = el.getState();\n return {\n id: el.id,\n label: el.label,\n type: el.type,\n flatStyle: el.flatStyle,\n layout: state.layout,\n };\n });\n\n const snapshots = captureNativeResponsiveSnapshot(elementData, getScreenDimensions());\n return success(snapshots);\n },\n\n // 5. POST /design/audit\n runDesignAudit: async (ctx) => {\n const body = ctx.body as\n | {\n guide?: unknown;\n elementIds?: string[];\n }\n | undefined;\n\n const guide = body?.guide ?? loadedStyleGuide;\n\n if (!guide) {\n return error('No style guide loaded or provided', 'NO_STYLE_GUIDE');\n }\n\n if (!styleValidator) {\n return error(\n 'Install @qontinui/ui-bridge for style audit support. ' +\n 'Add it as a dependency: npm install @qontinui/ui-bridge',\n 'VALIDATOR_NOT_AVAILABLE'\n );\n }\n\n let elements = registry.getAllElements();\n if (body?.elementIds && body.elementIds.length > 0) {\n const idSet = new Set(body.elementIds);\n elements = elements.filter((e) => idSet.has(e.id));\n }\n\n // Map elements to the format expected by the validator\n const auditElements = elements.map((el) => ({\n elementId: el.id,\n styles: mapNativeStyleToExtended(el.flatStyle) as unknown as Record<string, string>,\n }));\n\n try {\n const report = styleValidator.runStyleAudit(auditElements, guide);\n return success(report);\n } catch (err) {\n return error(\n 'Audit failed: ' + (err instanceof Error ? err.message : String(err)),\n 'DESIGN_AUDIT_ERROR'\n );\n }\n },\n\n // 6. POST /design/style-guide/load\n loadStyleGuide: async (ctx) => {\n const body = ctx.body as { guide?: unknown } | undefined;\n\n if (!body?.guide) {\n return error('Style guide is required in request body', 'INVALID_REQUEST');\n }\n\n loadedStyleGuide = body.guide;\n return success({ loaded: true });\n },\n\n // 7. GET /design/style-guide\n getStyleGuide: async () => {\n return success(loadedStyleGuide);\n },\n\n // 8. DELETE /design/style-guide\n clearStyleGuide: async () => {\n loadedStyleGuide = null;\n return success({ cleared: true });\n },\n\n // 9. POST /design/evaluate\n evaluateQuality: async (ctx) => {\n if (!qualityEvaluator) {\n return error(\n 'Install @qontinui/ui-bridge for quality evaluation support. ' +\n 'Add it as a dependency: npm install @qontinui/ui-bridge',\n 'EVALUATOR_NOT_AVAILABLE'\n );\n }\n\n const body = ctx.body as\n | {\n context?: string;\n customContext?: unknown;\n elementIds?: string[];\n viewport?: { width: number; height: number };\n }\n | undefined;\n\n let elements = registry.getAllElements();\n if (body?.elementIds && body.elementIds.length > 0) {\n const idSet = new Set(body.elementIds);\n elements = elements.filter((e) => idSet.has(e.id));\n }\n\n const designData: ElementDesignData[] = elements.map((el) => {\n const state = el.getState();\n return getNativeElementDesignData(el.id, el.label, el.type, el.flatStyle, state.layout);\n });\n\n const viewport = body?.viewport ?? getScreenDimensions();\n\n // Resolve context: custom object > style guide context > built-in name\n let context: unknown = body?.customContext ?? body?.context ?? 'general';\n if (typeof context === 'string' && loadedStyleGuide) {\n const guide = loadedStyleGuide as { qualityContexts?: Record<string, unknown> };\n if (guide.qualityContexts?.[context]) {\n context = guide.qualityContexts[context];\n }\n }\n\n try {\n const report = qualityEvaluator.evaluateQuality(designData, viewport, context);\n return success(report);\n } catch (err) {\n return error(\n 'Evaluation failed: ' + (err instanceof Error ? err.message : String(err)),\n 'QUALITY_EVALUATION_ERROR'\n );\n }\n },\n\n // 10. GET /design/evaluate/contexts\n getQualityContexts: async () => {\n if (!qualityEvaluator) {\n return error(\n 'Install @qontinui/ui-bridge for quality evaluation support.',\n 'EVALUATOR_NOT_AVAILABLE'\n );\n }\n return success(qualityEvaluator.listContexts());\n },\n\n // 11. POST /design/evaluate/baseline\n saveBaseline: async (ctx) => {\n if (!qualityEvaluator) {\n return error(\n 'Install @qontinui/ui-bridge for quality evaluation support.',\n 'EVALUATOR_NOT_AVAILABLE'\n );\n }\n\n const body = ctx.body as\n | {\n label?: string;\n elementIds?: string[];\n }\n | undefined;\n\n let elements = registry.getAllElements();\n if (body?.elementIds && body.elementIds.length > 0) {\n const idSet = new Set(body.elementIds);\n elements = elements.filter((e) => idSet.has(e.id));\n }\n\n const designData: ElementDesignData[] = elements.map((el) => {\n const state = el.getState();\n return getNativeElementDesignData(el.id, el.label, el.type, el.flatStyle, state.layout);\n });\n\n const viewport = getScreenDimensions();\n savedBaseline = qualityEvaluator.createBaseline(designData, viewport, body?.label);\n return success({ saved: true, elementCount: designData.length });\n },\n\n // 12. POST /design/evaluate/diff\n diffBaseline: async (ctx) => {\n if (!qualityEvaluator) {\n return error(\n 'Install @qontinui/ui-bridge for quality evaluation support.',\n 'EVALUATOR_NOT_AVAILABLE'\n );\n }\n\n if (!savedBaseline) {\n return error('No baseline saved. Call saveBaseline first.', 'NO_BASELINE');\n }\n\n const body = ctx.body as { elementIds?: string[] } | undefined;\n\n let elements = registry.getAllElements();\n if (body?.elementIds && body.elementIds.length > 0) {\n const idSet = new Set(body.elementIds);\n elements = elements.filter((e) => idSet.has(e.id));\n }\n\n const designData: ElementDesignData[] = elements.map((el) => {\n const state = el.getState();\n return getNativeElementDesignData(el.id, el.label, el.type, el.flatStyle, state.layout);\n });\n\n try {\n const report = qualityEvaluator.diffSnapshots(savedBaseline, designData);\n return success(report);\n } catch (err) {\n return error(\n 'Diff failed: ' + (err instanceof Error ? err.message : String(err)),\n 'DIFF_BASELINE_ERROR'\n );\n }\n },\n };\n}\n","/**\n * Page Health Diagnostics — Mobile (React Native) variant.\n *\n * Mirrors the runner / web analyzer in\n * `ui-bridge/packages/ui-bridge/src/server/page-health.ts`\n * and the canonical Rust implementation in\n * `qontinui-runner/src-tauri/src/mcp/ui_bridge/screenshots.rs::ui_bridge_page_health_handler`\n *\n * Output shape (`summary`/`findings`/`heatmap`/`element_count`/`visible_count`)\n * matches those byte-for-byte so the same `page-health` skill works on web,\n * runner, and mobile without branching per platform.\n *\n * Mobile-specific differences from the web/runner analyzer:\n *\n * • Layout source: React Native elements expose `state.layout` in *pixels*\n * (`{x, y, width, height, pageX, pageY}` relative to the device viewport).\n * We normalize via `Dimensions.get('window')` into the 0-1 space the\n * analyzer expects. The web/runner analyzer reads pre-normalized\n * `state.normalizedRect` directly.\n *\n * • Interactivity detection: mobile elements don't carry a `category` field.\n * We treat `type ∈ {button, input, switch, checkbox, radio, touchable,\n * listItem}` as interactive instead.\n *\n * • CSS class signals: React Native has no class names, so the\n * `class contains spin|pulse|skeleton|...` heuristic is always empty.\n * We still emit the `css_signals` field (as `[]`) so the response shape\n * stays platform-neutral.\n *\n * Fold semantics (see Step 7: Visual anomalies):\n *\n * The `outside_viewport` count tracks only *horizontal* overflow — elements\n * whose normalized x is left of the viewport (`x + width < 0`) or right of\n * it (`x > 1`). Vertical offsets (`y > 1`, `y + height < 0`) are NOT an\n * anomaly on mobile: ScrollView / FlatList content legitimately extends\n * above or below the visible fold, and the user reaches it by scrolling.\n * Flagging those would WARNING every scrollable screen (settings, feed,\n * list pages). Only horizontal overflow is unreachable by the user on\n * typical mobile layouts (the viewport is ~full-width, no horizontal\n * scroll), so that's the meaningful anomaly we surface.\n */\n\nimport type { NativeElementState } from '../core/types';\n\n// ============================================================================\n// Types (mirrors ui-bridge/src/server/page-health.ts)\n// ============================================================================\n\nexport type PageHealthSeverity = 'OK' | 'WARNING' | 'CRITICAL';\n\nexport interface PageHealthFinding {\n check: string;\n severity: PageHealthSeverity;\n detail: string;\n data: Record<string, unknown>;\n}\n\nexport interface PageHealthReport {\n summary: PageHealthSeverity;\n findings: PageHealthFinding[];\n heatmap: string[];\n element_count: number;\n visible_count: number;\n}\n\n/**\n * Mobile element shape consumed by the analyzer. A loosened subset of the\n * registry's full element record — only fields the analyzer actually reads.\n */\nexport interface PageHealthElement {\n type: string;\n state: NativeElementState;\n}\n\n// ============================================================================\n// Constants (lifted verbatim from the canonical analyzer)\n// ============================================================================\n\nconst GRID_SIZE = 20;\n\nconst NAV_TYPES = new Set(['button', 'heading', 'badge', 'status-message']);\n\nconst SKIP_TEXT_TYPES = new Set(['button', 'link', 'tab', 'menuitem']);\n\nconst INTERACTIVE_TYPES = new Set([\n 'button',\n 'input',\n 'switch',\n 'checkbox',\n 'radio',\n 'touchable',\n 'listItem',\n]);\n\nconst ERROR_PHRASES = [\n 'error occurred',\n 'failed to',\n 'exception',\n 'crash',\n 'unavailable',\n 'something went wrong',\n 'could not',\n];\n\nconst LOADING_PHRASES = [\n 'loading',\n 'starting',\n 'connecting',\n 'please wait',\n 'initializing',\n 'fetching',\n];\n\nconst EMPTY_PHRASES = [\n 'no data',\n 'no results',\n 'nothing here',\n 'empty',\n 'no items',\n 'get started',\n];\n\n// ============================================================================\n// Helpers\n// ============================================================================\n\nfunction severityRank(s: PageHealthSeverity): number {\n if (s === 'CRITICAL') return 3;\n if (s === 'WARNING') return 2;\n return 1;\n}\n\nfunction worstSeverity(findings: PageHealthFinding[]): PageHealthSeverity {\n let worst: PageHealthSeverity = 'OK';\n for (const f of findings) {\n if (severityRank(f.severity) > severityRank(worst)) {\n worst = f.severity;\n }\n }\n return worst;\n}\n\nfunction truncate(s: string, n: number): string {\n if (s.length <= n) return s;\n return [...s].slice(0, n).join('');\n}\n\ninterface NormRect {\n x: number;\n y: number;\n width: number;\n height: number;\n}\n\n/**\n * Project a mobile `state.layout` (pixels) into 0-1 viewport coords.\n *\n * Returns null when the element hasn't been measured yet (layout=null), the\n * viewport is degenerate (width/height ≤ 0), or pageX/pageY are absent —\n * the analyzer skips those rather than guessing.\n */\nfunction normalizeRect(\n state: NativeElementState,\n viewport: { width: number; height: number }\n): NormRect | null {\n const layout = state.layout;\n if (!layout) return null;\n if (viewport.width <= 0 || viewport.height <= 0) return null;\n // pageX/pageY are the absolute device-relative coords — what the analyzer\n // wants. Fall back to x/y (parent-relative) if the platform didn't fill\n // pageX/pageY; this loses absolute positioning but is better than dropping\n // the element entirely.\n const px = layout.pageX ?? layout.x;\n const py = layout.pageY ?? layout.y;\n return {\n x: px / viewport.width,\n y: py / viewport.height,\n width: layout.width / viewport.width,\n height: layout.height / viewport.height,\n };\n}\n\n// ============================================================================\n// Analyzer\n// ============================================================================\n\n/**\n * Run the page-health analyzer over a list of mobile registry elements.\n *\n * The pipeline mirrors the canonical analyzer step-for-step:\n *\n * 1. Visible filter (state.visible + measurable layout)\n * 2. Spatial coverage on a 20x20 grid + left/right halves\n * 3. Layout regions (sidebar/header/content) by center-point\n * 4. Element diversity (nav-only flag)\n * 5. Text signal scanning (errors / loading / empty)\n * 6. Interactive readiness (disabled ratio across interactive types)\n * 7. Visual anomalies (zero-size, outside-viewport)\n * 8. ASCII heatmap\n * 9. Worst severity rollup\n */\nexport function diagnosePageHealth(\n elements: PageHealthElement[],\n viewport: { width: number; height: number }\n): PageHealthReport {\n const findings: PageHealthFinding[] = [];\n\n // Project each element's layout once; the analyzer iterates the result\n // multiple times.\n const projected = elements.map((el) => ({\n el,\n rect: el.state.visible ? normalizeRect(el.state, viewport) : null,\n }));\n const visible = projected.filter((p) => p.rect !== null) as Array<{\n el: PageHealthElement;\n rect: NormRect;\n }>;\n\n // --- Step 2: Spatial coverage ---------------------------------------------\n const grid: boolean[][] = Array.from({ length: GRID_SIZE }, () =>\n Array.from({ length: GRID_SIZE }, () => false)\n );\n\n for (const { rect } of visible) {\n const colStart = Math.max(0, Math.floor(rect.x * GRID_SIZE));\n const colEnd = Math.min(GRID_SIZE, Math.ceil((rect.x + rect.width) * GRID_SIZE));\n const rowStart = Math.max(0, Math.floor(rect.y * GRID_SIZE));\n const rowEnd = Math.min(GRID_SIZE, Math.ceil((rect.y + rect.height) * GRID_SIZE));\n for (let r = rowStart; r < rowEnd; r++) {\n for (let c = colStart; c < colEnd; c++) {\n grid[r][c] = true;\n }\n }\n }\n\n const totalCells = GRID_SIZE * GRID_SIZE;\n const halfCells = totalCells / 2;\n let filled = 0;\n let leftFilled = 0;\n let rightFilled = 0;\n const half = GRID_SIZE / 2;\n for (let r = 0; r < GRID_SIZE; r++) {\n for (let c = 0; c < GRID_SIZE; c++) {\n if (grid[r][c]) {\n filled++;\n if (c < half) leftFilled++;\n else rightFilled++;\n }\n }\n }\n const coveragePct = Math.round((filled / totalCells) * 100);\n const leftHalfPct = Math.round((leftFilled / halfCells) * 100);\n const rightHalfPct = Math.round((rightFilled / halfCells) * 100);\n\n let spatialSeverity: PageHealthSeverity = 'OK';\n if (coveragePct < 15) spatialSeverity = 'CRITICAL';\n else if (coveragePct < 30) spatialSeverity = 'WARNING';\n if (rightHalfPct < 5 && leftHalfPct > 20) spatialSeverity = 'CRITICAL';\n\n findings.push({\n check: 'spatial_coverage',\n severity: spatialSeverity,\n detail: `Elements cover ${coveragePct}% of viewport. Left=${leftHalfPct}%, Right=${rightHalfPct}%`,\n data: {\n coverage_pct: coveragePct,\n left_half_pct: leftHalfPct,\n right_half_pct: rightHalfPct,\n },\n });\n\n // --- Step 3: Layout regions -----------------------------------------------\n let sidebar = 0;\n let header = 0;\n let content = 0;\n for (const { rect } of visible) {\n const cx = rect.x + rect.width / 2;\n const cy = rect.y + rect.height / 2;\n if (cx < 0.2) sidebar++;\n else if (cy < 0.08) header++;\n else content++;\n }\n\n let layoutSeverity: PageHealthSeverity = 'OK';\n if (content === 0) layoutSeverity = 'CRITICAL';\n else if (content < 3) layoutSeverity = 'WARNING';\n\n findings.push({\n check: 'layout_regions',\n severity: layoutSeverity,\n detail: `sidebar=${sidebar}, header=${header}, content=${content}`,\n data: { sidebar, header, content },\n });\n\n // --- Step 4: Element diversity --------------------------------------------\n const typeCounts: Record<string, number> = {};\n for (const el of elements) {\n const t = el.type || 'unknown';\n typeCounts[t] = (typeCounts[t] ?? 0) + 1;\n }\n const allNav =\n elements.length > 5 && Object.keys(typeCounts).every((k) => NAV_TYPES.has(k));\n const diversitySeverity: PageHealthSeverity = allNav ? 'WARNING' : 'OK';\n\n findings.push({\n check: 'element_diversity',\n severity: diversitySeverity,\n detail: `${Object.keys(typeCounts).length} type(s) across ${elements.length} elements${\n allNav ? ' (navigation-only)' : ''\n }`,\n data: { types: typeCounts },\n });\n\n // --- Step 5: Text signal scanning -----------------------------------------\n // No CSS-class scan on RN (no class names) — we still emit `css_signals:[]`\n // so callers branching on the field shape don't need a mobile special case.\n const detectedErrors: string[] = [];\n const detectedLoading: string[] = [];\n const detectedEmpty: string[] = [];\n const detectedCss: string[] = [];\n\n for (const el of elements) {\n const elType = el.type ?? '';\n if (SKIP_TEXT_TYPES.has(elType)) continue;\n\n const text = (el.state.textContent ?? '').toString();\n if (!text) continue;\n const textLower = text.toLowerCase();\n for (const p of ERROR_PHRASES) {\n if (textLower.includes(p)) {\n detectedErrors.push(truncate(text, 120));\n break;\n }\n }\n for (const p of LOADING_PHRASES) {\n if (textLower.includes(p)) {\n detectedLoading.push(truncate(text, 120));\n break;\n }\n }\n for (const p of EMPTY_PHRASES) {\n if (textLower.includes(p)) {\n detectedEmpty.push(truncate(text, 120));\n break;\n }\n }\n }\n\n let textSeverity: PageHealthSeverity = 'OK';\n if (detectedErrors.length > 0) textSeverity = 'CRITICAL';\n else if (detectedLoading.length > 0 || detectedEmpty.length > 0) textSeverity = 'WARNING';\n\n findings.push({\n check: 'text_signals',\n severity: textSeverity,\n detail: `errors=${detectedErrors.length}, loading=${detectedLoading.length}, empty=${detectedEmpty.length}, css_signals=${detectedCss.length}`,\n data: {\n errors: detectedErrors,\n loading: detectedLoading,\n empty: detectedEmpty,\n css_signals: detectedCss,\n },\n });\n\n // --- Step 6: Interactive readiness ----------------------------------------\n let interactiveTotal = 0;\n let interactiveDisabled = 0;\n for (const el of elements) {\n if (!INTERACTIVE_TYPES.has(el.type)) continue;\n interactiveTotal++;\n if (el.state.enabled === false) interactiveDisabled++;\n }\n const interactiveSeverity: PageHealthSeverity =\n interactiveTotal > 0 && interactiveDisabled / interactiveTotal > 0.5 ? 'WARNING' : 'OK';\n\n findings.push({\n check: 'interactive_readiness',\n severity: interactiveSeverity,\n detail: `${interactiveTotal} interactive elements, ${interactiveDisabled} disabled`,\n data: { total: interactiveTotal, disabled: interactiveDisabled },\n });\n\n // --- Step 7: Visual anomalies ---------------------------------------------\n // `outside_viewport` counts only *horizontal* overflow. Below-fold and\n // above-fold content is normal on scrollable mobile screens and must not\n // flag — see the fold-semantics note at the top of this file.\n let zeroSize = 0;\n let outsideViewport = 0;\n for (const { rect } of visible) {\n if (rect.width === 0 || rect.height === 0) zeroSize++;\n if (rect.x + rect.width < 0 || rect.x > 1) {\n outsideViewport++;\n }\n }\n const anomalySeverity: PageHealthSeverity =\n zeroSize > 0 || outsideViewport > 0 ? 'WARNING' : 'OK';\n\n findings.push({\n check: 'visual_anomalies',\n severity: anomalySeverity,\n detail: `zero_size=${zeroSize}, outside_viewport=${outsideViewport} (horizontal-overflow only; below/above-fold scrollable content is not an anomaly)`,\n data: { zero_size: zeroSize, outside_viewport: outsideViewport },\n });\n\n // --- Step 8: ASCII heatmap ------------------------------------------------\n const heatmap: string[] = grid.map((row) =>\n row.map((cell) => (cell ? '#' : '.')).join('')\n );\n\n return {\n summary: worstSeverity(findings),\n findings,\n heatmap,\n element_count: elements.length,\n visible_count: visible.length,\n };\n}\n","/**\n * UI Bridge Native Server Handlers\n *\n * Request handlers for the HTTP API endpoints.\n */\n\n/**\n * SDK version string, injected at build time by tsup's `define` and at\n * test time by vitest's `define` (both source from this package's\n * `package.json` `version` field). Surfaced on the `/health` endpoint's\n * `data.uiBridge.version` so external automation agents can fingerprint\n * which on-device SDK build a runner is consuming without parsing the\n * bundle. Mirrors the web SDK's `__SDK_VERSION__` convention in\n * `@qontinui/ui-bridge` (see UIBridgeProviderInit.ts / tsup.config.ts).\n */\ndeclare const __SDK_VERSION__: string;\n\nimport {\n type NativeUIBridgeRegistry,\n computeVisibility,\n extractHandlerNames,\n matchesCurrentRoute,\n projectBbox,\n} from '../core/registry';\nimport { projectVisionFields } from '../core/vision-fields';\nimport type { NativeElementType, NativeLayout, NativeModalInfo, WorkflowStep } from '../core/types';\nimport type { ControlActionRequest, NativeActionExecutor } from '../control/types';\nimport type {\n APIResponse,\n ConsoleErrorsResponse,\n DismissModalResponse,\n FillFormFieldInput,\n FillFormFieldResult,\n FillFormResponse,\n HandlerContext,\n NativeServerHandlers,\n NetworkRequestsResponse,\n PushModalRequest,\n PushModalResponse,\n TapAtResponse,\n} from './types';\nimport { createDesignHandlers } from './design-handlers';\nimport type { ConsoleErrorBuffer, NetworkRequestBuffer } from './observability';\nimport { diagnosePageHealth, type PageHealthElement } from './page-health';\nimport { serializeElementCustomActions } from '../core/element-actions';\n\n/**\n * Registry-based text/label match used by the app-agnostic interaction\n * handlers (clickByText / typeInto / findByText). Mirrors the priority order\n * the `find` handler applies to a `query`: label first, then identifier\n * fields (testId / accessibilityLabel / treePath / uiId), then registered\n * handler names. Returns matches sorted by best-priority, then registry\n * insertion order (stable). `visibleOnly` filters to currently-visible\n * elements before scoring.\n *\n * Native has no DOM, so there is no `query` field on `NativeFindRequest`\n * (the executor only filters by type/testId/accessibilityLabel pattern);\n * this helper provides the same free-text matching the `find` handler does\n * for its `query` param, shared so the interaction handlers stay aligned.\n */\nfunction matchElementsByText(\n registry: NativeUIBridgeRegistry,\n text: string,\n opts?: { visibleOnly?: boolean }\n): Array<{ id: string; type: NativeElementType; label?: string }> {\n const needle = text.toLowerCase();\n const contains = (v: unknown): boolean =>\n typeof v === 'string' && v.toLowerCase().includes(needle);\n\n let all = registry.getAllElements();\n if (opts?.visibleOnly) {\n all = all.filter((e) => e.getState().visible);\n }\n\n const scored: Array<{\n rank: number;\n element: { id: string; type: NativeElementType; label?: string };\n }> = [];\n\n for (const e of all) {\n let rank = Number.POSITIVE_INFINITY;\n if (contains(e.label)) rank = Math.min(rank, 0);\n const ident = e.getIdentifier();\n if (ident) {\n if (contains(ident.testId)) rank = Math.min(rank, 1);\n if (contains(ident.accessibilityLabel)) rank = Math.min(rank, 1);\n if (contains(ident.treePath)) rank = Math.min(rank, 1);\n if (contains(ident.uiId)) rank = Math.min(rank, 1);\n }\n if (rank === Number.POSITIVE_INFINITY) {\n const handlers = extractHandlerNames(e.props);\n if (handlers.some((h) => h.toLowerCase().includes(needle))) rank = 2;\n }\n if (rank !== Number.POSITIVE_INFINITY) {\n scored.push({ rank, element: { id: e.id, type: e.type, label: e.label } });\n }\n }\n\n scored.sort((a, b) => a.rank - b.rank);\n return scored.map((s) => s.element);\n}\n\n/**\n * Resolve the element's runtime state for the single-element read endpoints,\n * guaranteeing `state.value` is populated for controlled inputs.\n *\n * Why this exists: `setValue`/`type`/`clear` write the new value into\n * `state.value` via `registry.updateElementState`, and `/control/snapshot`\n * reads it straight back. But a controlled `<TextInput value={x} />` carries\n * its value on `props.value` too, and there are windows where `state.value`\n * has not yet been mirrored from the prop (registration before the first\n * `updateElementProps`, or a host that wires `onChangeText` without threading\n * `value` into `useUIElement`). In those windows `GET /control/element/:id`\n * returned `value: undefined` while the snapshot — which benefits from the\n * registry's prop→state mirror on the same element — showed the real value.\n *\n * The fallback keeps the single-element read path consistent with the\n * snapshot: when `state.value` is absent for an input that has a string\n * `props.value`, surface the prop value. Never overwrites an explicit\n * `state.value` (which an action or `onChangeText` set), and only applies to\n * `type: 'input'` so non-inputs that happen to carry a `value` prop are\n * untouched (mirrors the gating in `registry.updateElementProps`).\n */\nfunction resolveElementState(\n element: NonNullable<ReturnType<NativeUIBridgeRegistry['getElement']>>\n): ReturnType<NonNullable<ReturnType<NativeUIBridgeRegistry['getElement']>>['getState']> {\n const state = element.getState();\n if (\n element.type === 'input' &&\n state.value === undefined &&\n typeof element.props?.value === 'string'\n ) {\n return { ...state, value: element.props.value as string };\n }\n return state;\n}\n\n/**\n * Result of executing a single workflow step\n */\ninterface WorkflowStepResult {\n stepId: string;\n type: string;\n status: 'completed' | 'failed' | 'skipped';\n result?: unknown;\n error?: string;\n durationMs: number;\n}\n\n/**\n * Execute a single workflow step using the registry and executor\n */\nasync function executeWorkflowStep(\n step: WorkflowStep,\n registry: NativeUIBridgeRegistry,\n executor: NativeActionExecutor\n): Promise<WorkflowStepResult> {\n const startTime = Date.now();\n\n try {\n switch (step.type) {\n case 'element-action': {\n if (!step.target || !step.action) {\n return {\n stepId: step.id,\n type: step.type,\n status: 'failed',\n error: 'element-action step requires target and action',\n durationMs: Date.now() - startTime,\n };\n }\n\n const response = await executor.executeAction(step.target, {\n action: step.action,\n params: step.params,\n waitOptions: step.waitOptions,\n });\n\n return {\n stepId: step.id,\n type: step.type,\n status: response.success ? 'completed' : 'failed',\n result: response.result,\n error: response.error,\n durationMs: Date.now() - startTime,\n };\n }\n\n case 'component-action': {\n if (!step.target || !step.action) {\n return {\n stepId: step.id,\n type: step.type,\n status: 'failed',\n error: 'component-action step requires target and action',\n durationMs: Date.now() - startTime,\n };\n }\n\n const response = await executor.executeComponentAction(step.target, {\n action: step.action,\n params: step.params,\n });\n\n return {\n stepId: step.id,\n type: step.type,\n status: response.success ? 'completed' : 'failed',\n result: response.result,\n error: response.error,\n durationMs: Date.now() - startTime,\n };\n }\n\n case 'wait': {\n if (!step.target) {\n return {\n stepId: step.id,\n type: step.type,\n status: 'failed',\n error: 'wait step requires target element id',\n durationMs: Date.now() - startTime,\n };\n }\n\n const waitResult = await executor.waitForElement(\n step.target,\n step.waitOptions || { visible: true, timeout: 10000, interval: 100 }\n );\n\n return {\n stepId: step.id,\n type: step.type,\n status: waitResult.met ? 'completed' : 'failed',\n result: waitResult.state,\n error: waitResult.error,\n durationMs: Date.now() - startTime,\n };\n }\n\n case 'assert': {\n if (!step.target) {\n return {\n stepId: step.id,\n type: step.type,\n status: 'failed',\n error: 'assert step requires target element id',\n durationMs: Date.now() - startTime,\n };\n }\n\n const element = registry.getElement(step.target);\n if (!element) {\n return {\n stepId: step.id,\n type: step.type,\n status: 'failed',\n error: `Element not found: ${step.target}`,\n durationMs: Date.now() - startTime,\n };\n }\n\n const state = element.getState();\n const expected = step.params || {};\n const stateRecord = state as unknown as Record<string, unknown>;\n const mismatches: string[] = [];\n\n for (const [key, value] of Object.entries(expected)) {\n const actual = stateRecord[key];\n const isEqual =\n typeof value === 'object' && value !== null\n ? JSON.stringify(actual) === JSON.stringify(value)\n : actual === value;\n if (!isEqual) {\n mismatches.push(\n `${key}: expected ${JSON.stringify(value)}, got ${JSON.stringify(actual)}`\n );\n }\n }\n\n return {\n stepId: step.id,\n type: step.type,\n status: mismatches.length === 0 ? 'completed' : 'failed',\n result: { state, mismatches },\n error: mismatches.length > 0 ? `Assertion failed: ${mismatches.join('; ')}` : undefined,\n durationMs: Date.now() - startTime,\n };\n }\n\n case 'custom': {\n if (!step.handler) {\n return {\n stepId: step.id,\n type: step.type,\n status: 'failed',\n error: 'custom step requires a handler function',\n durationMs: Date.now() - startTime,\n };\n }\n\n const result = await step.handler();\n // Allow handlers to signal failure by returning { success: false, error: '...' }\n const failed =\n result &&\n typeof result === 'object' &&\n 'success' in result &&\n (result as Record<string, unknown>).success === false;\n\n return {\n stepId: step.id,\n type: step.type,\n status: failed ? 'failed' : 'completed',\n result,\n error: failed\n ? ((result as Record<string, unknown>).error as string) ||\n 'Custom handler returned failure'\n : undefined,\n durationMs: Date.now() - startTime,\n };\n }\n\n case 'log': {\n const message = step.params?.message ?? step.params?.text ?? `[workflow] step ${step.id}`;\n console.log(`[ui-bridge-native] workflow log: ${message}`);\n\n return {\n stepId: step.id,\n type: step.type,\n status: 'completed',\n result: { message },\n durationMs: Date.now() - startTime,\n };\n }\n\n case 'navigate':\n case 'branch':\n case 'loop':\n case 'extract':\n return {\n stepId: step.id,\n type: step.type,\n status: 'skipped',\n error: `Step type \"${step.type}\" is not yet supported in native workflow execution`,\n durationMs: Date.now() - startTime,\n };\n\n default:\n return {\n stepId: step.id,\n type: step.type,\n status: 'failed',\n error: `Unknown step type: ${step.type}`,\n durationMs: Date.now() - startTime,\n };\n }\n } catch (err) {\n return {\n stepId: step.id,\n type: step.type,\n status: 'failed',\n error: err instanceof Error ? err.message : String(err),\n durationMs: Date.now() - startTime,\n };\n }\n}\n\n/**\n * Create a success response\n */\nfunction success<T>(data: T): APIResponse<T> {\n return {\n success: true,\n data,\n timestamp: Date.now(),\n };\n}\n\n/**\n * Create an error response\n */\nfunction error<T = unknown>(message: string, code?: string): APIResponse<T> {\n return {\n success: false,\n error: message,\n code,\n timestamp: Date.now(),\n };\n}\n\n/**\n * Create server handlers\n */\nexport function createServerHandlers(\n registry: NativeUIBridgeRegistry,\n executor: NativeActionExecutor,\n config?: {\n appInfo?: { appId: string; appName: string; appType: string; framework?: string };\n /** Optional console-error ring buffer powering `GET /control/console-errors`. */\n consoleErrorBuffer?: ConsoleErrorBuffer;\n /** Optional network-request ring buffer powering `GET /sdk/network-requests`. */\n networkRequestBuffer?: NetworkRequestBuffer;\n /**\n * Optional viewport getter for `POST /control/page-health`. Injected by\n * `UIBridgeNativeProvider` from `Dimensions.get('window')`. Kept out of\n * `handlers.ts` so this file has no `react-native` dep at all — the\n * `require('react-native')` pattern crashed the host in 0.6.3/0.6.4\n * (Metro/Hermes can't statically resolve the require even with a\n * `try/catch`; the `unknownModuleError` escapes and tears down the JS\n * thread). When absent (e.g. tests, or a custom host that doesn't pass\n * one), `getPageHealth` falls back to `body.viewport` then `{0,0}`.\n */\n viewportProvider?: () => { width: number; height: number };\n }\n): NativeServerHandlers {\n // Pipe the injected viewportProvider through to the design handlers so\n // they share the same react-native-free dependency-injection pattern as\n // `getPageHealth`. Without this, `design-handlers.ts` falls back to\n // `require('react-native')` inside `getScreenDimensions()` — which is the\n // identical Metro/Hermes `unknownModuleError` latent crash that 0.6.3/0.6.4\n // shipped on the page-health endpoint. See the `viewportProvider` doc\n // comment on this config and `feedback_metro_require_gotcha.md`.\n const designHandlers = createDesignHandlers(registry, config?.viewportProvider);\n\n return {\n // Elements\n getElements: async (ctx: HandlerContext) => {\n // Measure-on-read: refresh every mounted-visible element's geometry\n // from its live ref before serving stored layouts. Without this, the\n // registry serves mount-time coordinates that go stale on scroll /\n // recycle / re-render (RN never re-fires onLayout on pure translation).\n // Bounded by refreshMeasurements' internal timeout; never throws.\n await registry.refreshMeasurements();\n\n const visibleOnly =\n ctx.query?.visibleOnly === 'true' ||\n (ctx.body as Record<string, unknown>)?.visibleOnly === true;\n const forRoute = (ctx.query?.route || (ctx.body as Record<string, unknown>)?.route) as\n | string\n | undefined;\n\n // visibleOnly uses the looser mounted-visible filter so callers don't\n // miss elements whose first `onLayout` hasn't fired yet. Each element\n // carries a `visibility` field (`\"visible\"` / `\"likely-visible\"`) so\n // agents can branch on measured vs unmeasured downstream.\n let allElements = visibleOnly\n ? registry.getMountedVisibleElements()\n : registry.getAllElements();\n\n // Filter by specific route. Uses the same loose `matchesCurrentRoute`\n // semantics as `createSnapshot` so app-root chrome (tabs, persistent\n // headers) registered with `registrationRoute: null` survives the\n // filter alongside elements explicitly tagged for `forRoute`. See\n // `matchesCurrentRoute` in core/registry.ts for the contract.\n if (forRoute) {\n allElements = allElements.filter((e) => matchesCurrentRoute(e.registrationRoute, forRoute));\n }\n\n // Read once for the whole response, for the same reason `createSnapshot`\n // does: per-element reads cost a `Dimensions.get` each and let a rotation\n // split one response across two clip regions.\n const viewport = registry.getViewportRect();\n\n const elements = allElements.map((e) => {\n const handlers = extractHandlerNames(e.props);\n const state = e.getState();\n // Same helper `createSnapshot` uses — this used to be a hand-copied\n // duplicate of the predicate, which is how the two surfaces could\n // disagree about what \"visible\" means.\n const { visibility, visibilityReason } = computeVisibility(\n state,\n registry.getClipRectFor(e, viewport)\n );\n const bbox = projectBbox(state, visibility, registry.getPixelRatio());\n const vision = projectVisionFields({\n type: e.type,\n label: e.label,\n // Real handler names (onPress/...), NOT inferred actions which\n // synthesize press/click onto every element. See projectVisionFields.\n handlerNames: handlers,\n state,\n flatStyle: e.flatStyle,\n });\n return {\n id: e.id,\n type: e.type,\n label: e.label,\n identifier: e.getIdentifier(),\n state,\n actions: e.actions,\n customActions: serializeElementCustomActions(e.customActions),\n registeredHandlers: handlers.length > 0 ? handlers : undefined,\n registrationRoute: e.registrationRoute,\n visibility,\n ...(visibilityReason ? { visibilityReason } : {}),\n ...(bbox ? { bbox } : {}),\n ...vision,\n };\n });\n\n return success({ elements });\n },\n\n getElement: async (ctx: HandlerContext) => {\n const { id } = ctx.params;\n const element = registry.getElement(id);\n\n if (!element) {\n return error(`Element not found: ${id}`, 'ELEMENT_NOT_FOUND');\n }\n\n const handlers = extractHandlerNames(element.props);\n\n return success({\n element: {\n id: element.id,\n type: element.type,\n label: element.label,\n identifier: element.getIdentifier(),\n state: resolveElementState(element),\n actions: element.actions,\n customActions: serializeElementCustomActions(element.customActions),\n registeredHandlers: handlers.length > 0 ? handlers : undefined,\n registrationRoute: element.registrationRoute,\n },\n });\n },\n\n getElementState: async (ctx: HandlerContext) => {\n const { id } = ctx.params;\n const element = registry.getElement(id);\n\n if (!element) {\n return error(`Element not found: ${id}`, 'ELEMENT_NOT_FOUND');\n }\n\n return success({ state: resolveElementState(element) });\n },\n\n executeAction: async (ctx: HandlerContext) => {\n // Accept BOTH action-envelope shapes so the mobile server matches the\n // runner/web SDK contract:\n // 1. Flat HTTP body — `POST /control/element/:id/action` with\n // `{ action, params, waitOptions }` (the documented HTTP shape).\n // 2. Relay/WS nested envelope — the runner SDK dispatches element\n // actions as `relayCommand('executeElementAction', { id, request })`\n // where `request = { action, params, waitOptions }` (see\n // `ui-bridge/src/react/commandHandlers.ts` `executeElementAction`).\n // Over the WS/JSON-RPC and cloud-relay transports the whole `params`\n // object becomes `ctx.body`, so the action lives at `body.request`,\n // NOT `body.action`. Without this unwrap a runner-driven\n // `{ action: 'press' }` was rejected with \"Action is required\".\n const rawBody = (ctx.body ?? {}) as Partial<ControlActionRequest> & {\n id?: string;\n request?: Partial<ControlActionRequest>;\n };\n\n // The nested `request` envelope wins when present (relay/WS path);\n // otherwise read the flat fields (direct HTTP path).\n const envelope =\n rawBody.request && typeof rawBody.request === 'object' ? rawBody.request : rawBody;\n\n // Element id comes from the path param (`/control/element/:id/action`),\n // falling back to `body.id` for the relay `{ id, request }` envelope.\n const id = ctx.params.id ?? rawBody.id ?? '';\n\n if (!envelope?.action) {\n return error('Action is required', 'INVALID_REQUEST');\n }\n\n // Forwarded WHOLE, not field-by-field. Re-listing the fields is how the\n // web seam silently dropped every request option added after the list\n // was written — the caller opted in, the executor never heard about it,\n // and the response still came back `success: true`.\n const response = await executor.executeAction(id, envelope as ControlActionRequest);\n\n if (!response.success) {\n // An action that failed with a code of its own (`NOT_SUPPORTED` from\n // `scrollIntoView`) keeps it — mapped to 501 by `http-server.ts` — so\n // \"this element cannot do that\" is not reported as a retryable 400.\n return error(response.error || 'Action failed', response.code ?? 'ACTION_FAILED');\n }\n\n return success(response);\n },\n\n // Components\n getComponents: async () => {\n const components = registry.getAllComponents().map((c) => ({\n id: c.id,\n name: c.name,\n description: c.description,\n // Phase 4 (plan 2026-08-20-ui-bridge-action-declaration-shape):\n // carry the safety annotation onto the native wire too — a walker\n // driving a React Native app needs the same `destructive` exclusion\n // the web channel gets.\n actions: c.actions.map((a) => ({ id: a.id, label: a.label, effect: a.effect })),\n elementIds: c.elementIds,\n }));\n\n return success({ components });\n },\n\n getComponent: async (ctx: HandlerContext) => {\n const { id } = ctx.params;\n const component = registry.getComponent(id);\n\n if (!component) {\n return error(`Component not found: ${id}`, 'COMPONENT_NOT_FOUND');\n }\n\n return success({\n component: {\n id: component.id,\n name: component.name,\n description: component.description,\n actions: component.actions.map((a) => ({\n id: a.id,\n label: a.label,\n description: a.description,\n // Phase 4 — see the listing twin above.\n effect: a.effect,\n })),\n elementIds: component.elementIds,\n },\n });\n },\n\n executeComponentAction: async (ctx: HandlerContext) => {\n const { id, actionId } = ctx.params;\n // `timeoutMs` is read from the body, not dropped: an HTTP caller cannot\n // hand over an `AbortSignal`, so this is its ONLY way to call off a hung\n // handler. The executor validates and clamps it\n // (`normalizeActionTimeoutMs`) before it can reach a timer.\n const body = ctx.body as { params?: Record<string, unknown>; timeoutMs?: number };\n\n const response = await executor.executeComponentAction(id, {\n action: actionId,\n params: body?.params,\n timeoutMs: body?.timeoutMs,\n });\n\n if (!response.success) {\n return error(response.error || 'Action failed', 'ACTION_FAILED');\n }\n\n return success(response);\n },\n\n // Discovery\n //\n // Native parity with the runner's `POST /ui-bridge/ai/find`. The runner\n // matches a free-text `query` against label > text > value > aria-label >\n // placeholder > name. We replicate that here against the native registry's\n // analogues:\n // 1. `label` (the registered display label)\n // 2. identifier fields: `testId`, `accessibilityLabel`, `treePath`, `uiId`\n // 3. registered handler names (e.g. `onPress`, `onChangeText`)\n //\n // Match is case-insensitive substring. Empty/missing query falls back to\n // the structured filters (types/visibleOnly/etc.) so callers that don't\n // pass `query` still get the legacy behaviour. Once we've narrowed by\n // query the response is shaped through the executor's NativeFindResponse\n // envelope so the wire format stays stable.\n find: async (ctx: HandlerContext) => {\n const body = ctx.body as {\n query?: string;\n types?: NativeElementType[];\n testIdPattern?: string;\n accessibilityLabelPattern?: string;\n visibleOnly?: boolean;\n limit?: number;\n };\n\n const response = await executor.find({\n types: body?.types,\n testIdPattern: body?.testIdPattern,\n accessibilityLabelPattern: body?.accessibilityLabelPattern,\n visibleOnly: body?.visibleOnly,\n // When `query` is supplied we apply our own limit *after* ranking so\n // the highest-priority matches survive the cap; defer slicing to us\n // by widening here.\n limit: body?.query && body.query.length > 0 ? undefined : body?.limit,\n });\n\n const rawQuery = typeof body?.query === 'string' ? body.query.trim() : '';\n if (rawQuery.length === 0) {\n return success(response);\n }\n\n const needle = rawQuery.toLowerCase();\n const containsNeedle = (value: unknown): boolean =>\n typeof value === 'string' && value.toLowerCase().includes(needle);\n\n // Score each discovered element by best-priority field match. Lower\n // priorityRank wins; ties keep registry insertion order (stable sort).\n const scored: Array<{ priorityRank: number; element: (typeof response.elements)[number] }> =\n [];\n\n for (const el of response.elements) {\n let priorityRank = Number.POSITIVE_INFINITY;\n\n // 1. label\n if (containsNeedle(el.label)) {\n priorityRank = Math.min(priorityRank, 0);\n }\n\n // 2. identifier fields\n const ident = el.identifier;\n if (ident) {\n if (containsNeedle(ident.testId)) priorityRank = Math.min(priorityRank, 1);\n if (containsNeedle(ident.accessibilityLabel)) priorityRank = Math.min(priorityRank, 1);\n if (containsNeedle(ident.treePath)) priorityRank = Math.min(priorityRank, 1);\n if (containsNeedle(ident.uiId)) priorityRank = Math.min(priorityRank, 1);\n }\n\n // 3. registered handler names — pull from the registry since the\n // discovered envelope doesn't include props.\n if (priorityRank === Number.POSITIVE_INFINITY) {\n const registered = registry.getElement(el.id);\n const handlers = extractHandlerNames(registered?.props);\n if (handlers.some((h) => h.toLowerCase().includes(needle))) {\n priorityRank = 2;\n }\n }\n\n if (priorityRank !== Number.POSITIVE_INFINITY) {\n scored.push({ priorityRank, element: el });\n }\n }\n\n scored.sort((a, b) => a.priorityRank - b.priorityRank);\n\n const limit = body?.limit && body.limit > 0 ? body.limit : undefined;\n const filtered = limit ? scored.slice(0, limit) : scored;\n\n return success({\n ...response,\n elements: filtered.map((s) => s.element),\n total: filtered.length,\n });\n },\n\n getSnapshot: async (ctx: HandlerContext) => {\n // Measure-on-snapshot: re-measure geometry at read time so snapshot\n // `bbox` values reflect where elements ARE, not where they mounted.\n // Critical for virtualized lists (FlashList) whose cells move without\n // re-firing onLayout. `createSnapshot` itself stays sync; the refresh\n // is bounded by an internal timeout and never throws.\n await registry.refreshMeasurements();\n\n const visibleOnly =\n ctx.query?.visibleOnly === 'true' ||\n (ctx.body as Record<string, unknown>)?.visibleOnly === true;\n const currentRouteOnly =\n ctx.query?.currentRouteOnly === 'true' ||\n (ctx.body as Record<string, unknown>)?.currentRouteOnly === true;\n // Pass `undefined` (not `null`) for routeInfo so `createSnapshot`\n // falls back to a registry-registered route provider if one exists —\n // without that fallback, the cloud-relay / bare-server path would\n // emit `currentRoute: null` even when a `RouteTracker` was wired.\n const snapshot = registry.createSnapshot(undefined, { visibleOnly, currentRouteOnly });\n return success(snapshot);\n },\n\n getPageHealth: async (ctx: HandlerContext) => {\n // Viewport resolution priority:\n // 1. Explicit body.viewport — for offline analysis, replaying a\n // snapshot from a different device, or any caller that wants to\n // override the device's reported viewport.\n // 2. `config.viewportProvider()` — injected by\n // `UIBridgeNativeProvider` from `Dimensions.get('window')`.\n // 3. `{0,0}` fallback (degenerates to a coverage_pct=0 report\n // rather than crashing).\n //\n // The injection indirection exists because importing react-native\n // from this file (or `require('react-native')` with try/catch) both\n // crash the host RN app — see the [[viewportProvider]] doc comment\n // in `NativeServerConfig` and the project memory entry\n // `feedback_metro_require_gotcha.md`.\n const bodyViewport = (ctx.body as { viewport?: { width: number; height: number } })?.viewport;\n const viewport = bodyViewport ?? config?.viewportProvider?.() ?? { width: 0, height: 0 };\n\n const elements: PageHealthElement[] = registry.getAllElements().map((e) => ({\n type: e.type,\n state: e.getState(),\n }));\n\n const report = diagnosePageHealth(elements, viewport);\n return success(report);\n },\n\n // Workflows\n getWorkflows: async () => {\n const workflows = registry.getAllWorkflows().map((w) => ({\n id: w.id,\n name: w.name,\n description: w.description,\n stepCount: w.steps.length,\n }));\n\n return success({ workflows });\n },\n\n runWorkflow: async (ctx: HandlerContext) => {\n const { id } = ctx.params;\n const workflow = registry.getWorkflow(id);\n\n if (!workflow) {\n return error(`Workflow not found: ${id}`, 'WORKFLOW_NOT_FOUND');\n }\n\n const runId = `run-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`;\n const startTime = Date.now();\n const stepResults: WorkflowStepResult[] = [];\n let status: 'completed' | 'failed' = 'completed';\n\n registry.emit('workflow:started', {\n runId,\n workflowId: id,\n workflowName: workflow.name,\n totalSteps: workflow.steps.length,\n });\n\n for (const step of workflow.steps) {\n const stepResult = await executeWorkflowStep(step, registry, executor);\n stepResults.push(stepResult);\n\n if (stepResult.status === 'completed' || stepResult.status === 'skipped') {\n registry.emit('workflow:stepCompleted', {\n runId,\n workflowId: id,\n step: stepResult,\n });\n }\n\n if (stepResult.status === 'failed') {\n status = 'failed';\n registry.emit('workflow:failed', {\n runId,\n workflowId: id,\n failedStep: stepResult,\n completedSteps: stepResults.length - 1,\n totalSteps: workflow.steps.length,\n });\n break;\n }\n }\n\n if (status === 'completed') {\n registry.emit('workflow:completed', {\n runId,\n workflowId: id,\n steps: stepResults,\n totalDurationMs: Date.now() - startTime,\n });\n }\n\n return success({\n runId,\n status,\n steps: stepResults,\n totalSteps: workflow.steps.length,\n completedSteps: stepResults.filter((s) => s.status === 'completed').length,\n failedSteps: stepResults.filter((s) => s.status === 'failed').length,\n skippedSteps: stepResults.filter((s) => s.status === 'skipped').length,\n durationMs: Date.now() - startTime,\n });\n },\n\n // Page Navigation (stubs — React Native apps should override with their navigation provider)\n pageRefresh: async () => {\n return error('Page refresh not supported on native platform', 'NOT_SUPPORTED');\n },\n\n pageNavigate: async () => {\n return error('Page navigation not supported on native platform', 'NOT_SUPPORTED');\n },\n\n pageReplace: async () => {\n return error('Page replace not supported on native platform', 'NOT_SUPPORTED');\n },\n\n pageGoBack: async () => {\n return error('Page go back not supported on native platform', 'NOT_SUPPORTED');\n },\n\n pageGoForward: async () => {\n return error('Page go forward not supported on native platform', 'NOT_SUPPORTED');\n },\n\n // Screenshot (stub — apps should override with their screen capture library)\n getScreenshot: async () => {\n return error(\n 'Screenshot not supported. Provide a screenshotProvider to UIBridgeNativeProvider.',\n 'NOT_SUPPORTED'\n );\n },\n\n // Keep-awake (stub — apps should override via setKeepAwakeProvider, which\n // the provider wires when a keepAwakeProvider prop is supplied)\n keepAwake: async () => {\n return error(\n 'keep-awake not configured. Provide a keepAwakeProvider to UIBridgeNativeProvider.',\n 'NOT_SUPPORTED'\n );\n },\n\n // AI helpers — runner-only endpoints that have no React Native analog.\n //\n // The mobile bridge mounts explicit NOT_SUPPORTED stubs at the runner's\n // cheatsheet paths so callers (and the /manual-test skill in particular)\n // get a structured envelope explaining the gap rather than a bare\n // \"no such route\". These answer **HTTP 501** — `httpStatusForResponse` in\n // server/http-server.ts maps NOT_SUPPORTED → 501, so the status line and\n // the envelope agree; an unmounted path answers 404 instead. Each error\n // message names an in-tree mobile replacement so operators aren't left\n // guessing what to use instead.\n aiForms: async () => {\n return error<never>(\n 'ai/forms (form discovery) is runner-only; mobile React Native has no DOM to walk. ' +\n 'Use GET /ui-bridge/control/snapshot and filter for type === \"input\" instead.',\n 'NOT_SUPPORTED'\n );\n },\n\n aiIdleStatus: async () => {\n return error<never>(\n 'ai/idle-status (page-idle signal) is runner-only; mobile React Native has no DOM-mutation / network-idle signals. ' +\n 'Use the registry event stream (WS subscribe to \"element:registered\"/\"element:stateChanged\") or poll /control/snapshot for stability.',\n 'NOT_SUPPORTED'\n );\n },\n\n aiChangeBufferEnable: async () => {\n return error<never>(\n 'ai/change-buffer (DOM mutation diff buffer) is runner-only; mobile React Native has no DOM. ' +\n 'Use the WS event bridge (subscribe to \"element:registered\"/\"element:unregistered\"/\"element:stateChanged\") for change notifications.',\n 'NOT_SUPPORTED'\n );\n },\n\n aiWaitForElement: async () => {\n return error<never>(\n 'POST /ai/wait-for-element is runner-only on mobile. ' +\n 'Use the WS \"waitForElement\" JSON-RPC method or \"waitForCondition\" instead — same semantics, no HTTP polling overhead.',\n 'NOT_SUPPORTED'\n );\n },\n\n // Meta / Introspection (stub — server constructor overrides with real route table)\n getMethods: async () => {\n return error('Methods introspection not configured', 'NOT_SUPPORTED');\n },\n\n // AI helpers\n //\n // Mobile-side parity with the runner's `POST /ui-bridge/ai/fill-form`.\n // Each entry in `fields` is dispatched through the existing executor as a\n // `type` action with `clear: true` so the input value is replaced\n // atomically (the closest native equivalent to the web bridge's\n // \"setValue\" semantics — there is no `setValue` action on native).\n //\n // Failures do not short-circuit: every field is attempted, and the\n // response carries per-field success/error plus aggregate counts.\n fillForm: async (ctx: HandlerContext): Promise<APIResponse<FillFormResponse>> => {\n const body = ctx.body as { fields?: unknown } | undefined;\n const rawFields = body?.fields;\n\n if (!Array.isArray(rawFields)) {\n return error('Request body must include \"fields\" array', 'INVALID_REQUEST');\n }\n\n const results: FillFormFieldResult[] = [];\n\n for (let i = 0; i < rawFields.length; i++) {\n const field = rawFields[i] as Partial<FillFormFieldInput> | null | undefined;\n\n // Validate per-field shape; record the failure but keep going so the\n // caller gets a complete picture of what worked and what didn't.\n if (!field || typeof field !== 'object') {\n results.push({\n elementId: '',\n success: false,\n error: `fields[${i}] must be an object with \"elementId\" and \"value\"`,\n });\n continue;\n }\n\n const { elementId, value } = field;\n\n if (typeof elementId !== 'string' || elementId.length === 0) {\n results.push({\n elementId: typeof elementId === 'string' ? elementId : '',\n success: false,\n error: `fields[${i}] is missing a non-empty \"elementId\"`,\n });\n continue;\n }\n\n if (typeof value !== 'string') {\n results.push({\n elementId,\n success: false,\n error: `fields[${i}] is missing a string \"value\"`,\n });\n continue;\n }\n\n try {\n const response = await executor.executeAction(elementId, {\n action: 'type',\n params: { text: value, clear: true },\n });\n\n if (response.success) {\n results.push({ elementId, success: true });\n } else {\n results.push({\n elementId,\n success: false,\n error: response.error ?? 'Action failed',\n });\n }\n } catch (err) {\n // executor.executeAction normally captures errors itself, but a\n // bespoke executor implementation may still throw — surface that.\n results.push({\n elementId,\n success: false,\n error: err instanceof Error ? err.message : String(err),\n });\n }\n }\n\n const succeededCount = results.filter((r) => r.success).length;\n const failedCount = results.length - succeededCount;\n\n return success({ results, succeededCount, failedCount });\n },\n\n // ========================================================================\n // App-agnostic interaction parity (cross-platform `/control/page/*`)\n //\n // Mirrors the web/runner convenience endpoints so the SAME contract drives\n // mobile. Text/label interactions compose `executor.find` (registry-based\n // discovery) + `executor.executeAction` (press/type). Selector-only\n // variants have no React-Native analog and return NOT_SUPPORTED — the\n // mobile bridge's snapshot + `/control/find` (testID / accessibilityLabel)\n // cover what a selector would on web.\n // ========================================================================\n\n clickByText: async (\n ctx: HandlerContext\n ): Promise<APIResponse<{ clicked: boolean; element?: unknown }>> => {\n const body = ctx.body as { text?: string; visibleOnly?: boolean } | undefined;\n const text = typeof body?.text === 'string' ? body.text.trim() : '';\n if (!text) {\n return error('text is required and must not be empty', 'INVALID_REQUEST');\n }\n const match = matchElementsByText(registry, text, { visibleOnly: body?.visibleOnly })[0];\n if (!match) {\n return error(`No element found with text \"${text}\"`, 'ELEMENT_NOT_FOUND');\n }\n const response = await executor.executeAction(match.id, { action: 'press' });\n if (!response.success) {\n return error(response.error || 'Press failed', 'ACTION_FAILED');\n }\n return success({\n clicked: true,\n element: { id: match.id, type: match.type, label: match.label },\n });\n },\n\n clickBySelector: async (): Promise<APIResponse<never>> => {\n return error(\n 'clickBySelector is not supported on native platform — React Native has no CSS-selector DOM. Use clickByText, or /control/find with testIdPattern/accessibilityLabelPattern then /control/element/:id/action.',\n 'NOT_SUPPORTED'\n );\n },\n\n typeInto: async (\n ctx: HandlerContext\n ): Promise<APIResponse<{ typed: boolean; element?: unknown }>> => {\n const body = ctx.body as\n | { label?: string; text?: string; clear?: boolean; visibleOnly?: boolean }\n | undefined;\n const label = typeof body?.label === 'string' ? body.label.trim() : '';\n if (!label) {\n return error(\n 'label is required on native (selector-based typeInto is web-only)',\n 'INVALID_REQUEST'\n );\n }\n const text = typeof body?.text === 'string' ? body.text : '';\n const match = matchElementsByText(registry, label, { visibleOnly: body?.visibleOnly })[0];\n if (!match) {\n return error(`No input found for label \"${label}\"`, 'ELEMENT_NOT_FOUND');\n }\n const response = await executor.executeAction(match.id, {\n action: 'type',\n params: { text, clear: body?.clear === true },\n });\n if (!response.success) {\n return error(response.error || 'Type failed', 'ACTION_FAILED');\n }\n return success({\n typed: true,\n element: { id: match.id, type: match.type, label: match.label },\n });\n },\n\n readValue: async (): Promise<APIResponse<never>> => {\n return error(\n 'readValue is not supported on native platform — React Native has no CSS-selector DOM. Use /control/element/:id/state to read an element value.',\n 'NOT_SUPPORTED'\n );\n },\n\n findByText: async (\n ctx: HandlerContext\n ): Promise<APIResponse<Array<{ index: number; id: string; type: string; label?: string }>>> => {\n const body = ctx.body as { text?: string; visibleOnly?: boolean } | undefined;\n const text = typeof body?.text === 'string' ? body.text.trim() : '';\n if (!text) {\n return error('text is required and must not be empty', 'INVALID_REQUEST');\n }\n const matches = matchElementsByText(registry, text, { visibleOnly: body?.visibleOnly });\n return success(\n matches.map((el, index) => ({\n index,\n id: el.id,\n type: el.type,\n label: el.label,\n }))\n );\n },\n\n // Coord-based tap\n //\n // Synthesizes a press at the given screen coordinates by scanning the\n // registered elements' layout rects for a containing match. We prefer the\n // *topmost* match (smallest area = innermost child) since native UIs\n // generally render parents before children, and the user's tap should\n // logically hit the leaf-most interactive element.\n //\n // Coords are interpreted in the absolute (screen) space published by\n // `measureInWindow`; we compare against `pageX/pageY` when available and\n // fall back to the layout's relative `x/y` so this works in test fixtures\n // that don't measure (the fallback only matches single-rooted screens but\n // is good enough for the unit suite).\n tapAt: async (ctx: HandlerContext): Promise<APIResponse<TapAtResponse>> => {\n // Measure-on-read: refresh stored geometry before hit-testing, so taps\n // land on elements' CURRENT rects (post-scroll/recycle), not their\n // mount-time positions. Bounded by an internal timeout; never throws.\n await registry.refreshMeasurements();\n\n const body = ctx.body as\n | Partial<{\n x: number;\n y: number;\n action: 'press' | 'longPress' | 'doubleTap';\n }>\n | undefined;\n\n const x = body?.x;\n const y = body?.y;\n\n if (typeof x !== 'number' || !Number.isFinite(x)) {\n return error<TapAtResponse>('\"x\" must be a finite number', 'INVALID_REQUEST');\n }\n if (typeof y !== 'number' || !Number.isFinite(y)) {\n return error<TapAtResponse>('\"y\" must be a finite number', 'INVALID_REQUEST');\n }\n\n const action = body?.action ?? 'press';\n const allowedActions: ReadonlyArray<TapAtResponse['action']> = [\n 'press',\n 'longPress',\n 'doubleTap',\n ];\n if (!allowedActions.includes(action)) {\n return error<TapAtResponse>(\n `\"action\" must be one of: ${allowedActions.join(', ')}`,\n 'INVALID_REQUEST'\n );\n }\n\n // Collect all candidates whose layout rect contains (x, y). Prefer\n // pageX/pageY (absolute coords) when both are populated; fall back to\n // the relative x/y otherwise.\n type Candidate = {\n elementId: string;\n layout: NativeLayout;\n area: number;\n };\n const candidates: Candidate[] = [];\n\n for (const el of registry.getAllElements()) {\n const state = el.getState();\n const layout = state?.layout;\n if (!layout) continue;\n if (\n typeof layout.width !== 'number' ||\n typeof layout.height !== 'number' ||\n layout.width <= 0 ||\n layout.height <= 0\n ) {\n continue;\n }\n\n const hasPage =\n typeof layout.pageX === 'number' &&\n typeof layout.pageY === 'number' &&\n Number.isFinite(layout.pageX) &&\n Number.isFinite(layout.pageY);\n\n const left = hasPage ? layout.pageX : layout.x;\n const top = hasPage ? layout.pageY : layout.y;\n\n if (x >= left && x <= left + layout.width && y >= top && y <= top + layout.height) {\n candidates.push({\n elementId: el.id,\n layout,\n area: layout.width * layout.height,\n });\n }\n }\n\n if (candidates.length === 0) {\n return error<TapAtResponse>(\n `No element registered at (${x}, ${y})`,\n 'no_element_at_coords'\n );\n }\n\n // Topmost = smallest area. Stable sort preserves registration order for\n // ties, so a parent and a same-size child won't flip non-deterministically.\n candidates.sort((a, b) => a.area - b.area);\n const target = candidates[0];\n\n const response = await executor.executeAction(target.elementId, { action });\n if (!response.success) {\n return error<TapAtResponse>(response.error || 'Action failed', 'ACTION_FAILED');\n }\n\n return success<TapAtResponse>({\n elementId: target.elementId,\n action,\n layout: {\n x: target.layout.x,\n y: target.layout.y,\n width: target.layout.width,\n height: target.layout.height,\n pageX: target.layout.pageX,\n pageY: target.layout.pageY,\n },\n });\n },\n\n // Observability — console error / network request ring buffers.\n //\n // The buffers are owned by NativeUIBridgeServer and patched onto the\n // globals on `start()` (gated behind `features.testHooks`). When no\n // buffer is provided (no testHooks, or a stripped-down server fixture),\n // these handlers gracefully return empty arrays so callers can probe\n // without 500ing.\n getConsoleErrors: async (ctx: HandlerContext): Promise<APIResponse<ConsoleErrorsResponse>> => {\n const buf = config?.consoleErrorBuffer;\n const since = ctx.query?.since !== undefined ? Number(ctx.query.since) : undefined;\n const limit = ctx.query?.limit !== undefined ? Number(ctx.query.limit) : undefined;\n\n if (!buf) {\n return success<ConsoleErrorsResponse>({\n entries: [],\n count: 0,\n bufferSize: 0,\n installed: false,\n });\n }\n\n const entries = buf.entries({\n since: typeof since === 'number' && Number.isFinite(since) ? since : undefined,\n limit: typeof limit === 'number' && Number.isFinite(limit) ? limit : undefined,\n });\n\n return success<ConsoleErrorsResponse>({\n entries,\n count: entries.length,\n bufferSize: buf.size(),\n installed: buf.isInstalled(),\n });\n },\n\n getNetworkRequests: async (\n ctx: HandlerContext\n ): Promise<APIResponse<NetworkRequestsResponse>> => {\n const buf = config?.networkRequestBuffer;\n const since = ctx.query?.since !== undefined ? Number(ctx.query.since) : undefined;\n const limit = ctx.query?.limit !== undefined ? Number(ctx.query.limit) : undefined;\n\n if (!buf) {\n return success<NetworkRequestsResponse>({\n entries: [],\n count: 0,\n bufferSize: 0,\n installed: false,\n });\n }\n\n const entries = buf.entries({\n since: typeof since === 'number' && Number.isFinite(since) ? since : undefined,\n limit: typeof limit === 'number' && Number.isFinite(limit) ? limit : undefined,\n });\n\n return success<NetworkRequestsResponse>({\n entries,\n count: entries.length,\n bufferSize: buf.size(),\n installed: buf.isInstalled(),\n });\n },\n\n // Test hooks — modal stack manipulation\n //\n // These two endpoints exist so external automation runners can drive\n // ModalDetector state via HTTP, mirroring the in-tree `pushModal` /\n // `dismissModal` calls that components normally make. They're gated by\n // `features.testHooks` at the route layer (see http-server.ts); the\n // handlers themselves still defend against a missing modalDetector\n // because the bare server path used by CloudRelayClient may run before\n // enrichers are wired.\n pushModal: async (ctx: HandlerContext): Promise<APIResponse<PushModalResponse>> => {\n const detector = registry.getEnrichers().modalDetector;\n if (!detector) {\n return error<PushModalResponse>('modal detector not registered', 'ENRICHER_UNAVAILABLE');\n }\n\n const body = ctx.body as Partial<PushModalRequest> | undefined;\n const id = body?.id;\n if (typeof id !== 'string' || id.length === 0) {\n return error<PushModalResponse>('pushModal requires a non-empty \"id\"', 'INVALID_REQUEST');\n }\n\n const allowedTypes = ['modal', 'sheet', 'drawer', 'popover', 'alertdialog', 'dialog'];\n const requestedType = body?.type;\n if (\n requestedType !== undefined &&\n (typeof requestedType !== 'string' || !allowedTypes.includes(requestedType))\n ) {\n return error<PushModalResponse>(\n `pushModal \"type\" must be one of: ${allowedTypes.join(', ')}`,\n 'INVALID_REQUEST'\n );\n }\n\n detector.pushModal({\n id,\n title: body?.title,\n // requestedType is narrowed by the allowedTypes guard above; the cast\n // converts the validated string to the NativeModalInfo['type'] union.\n type: requestedType as NativeModalInfo['type'] | undefined,\n blocking: body?.blocking,\n dismissible: body?.dismissible,\n });\n\n // Pull the canonicalised entry back out so the response reflects what's\n // actually in the stack (defaults applied, detectedAt populated).\n const stored = detector.getActive().find((m) => m.id === id);\n return success<PushModalResponse>({\n pushed: true,\n id,\n title: stored?.title,\n type: stored?.type,\n blocking: stored?.blocking,\n dismissible: stored?.dismissible,\n pushedAt: stored?.detectedAt ?? Date.now(),\n });\n },\n\n dismissModal: async (ctx: HandlerContext): Promise<APIResponse<DismissModalResponse>> => {\n const detector = registry.getEnrichers().modalDetector;\n if (!detector) {\n return error<DismissModalResponse>('modal detector not registered', 'ENRICHER_UNAVAILABLE');\n }\n\n const { id } = ctx.params;\n if (typeof id !== 'string' || id.length === 0) {\n return error<DismissModalResponse>(\n 'dismissModal requires a modal id in the path',\n 'INVALID_REQUEST'\n );\n }\n\n // The slot type allows `dismissModal` to return either `boolean` (the\n // canonical ModalDetector class) or `void` (legacy/duck-typed impls).\n // Probe via `getActive()` first so the result is consistent regardless\n // of the implementation's return signal.\n const wasPresent = detector.getActive().some((m) => m.id === id);\n if (!wasPresent) {\n return error<DismissModalResponse>(`modal not found: ${id}`, 'MODAL_NOT_FOUND');\n }\n\n detector.dismissModal(id);\n return success<DismissModalResponse>({ dismissed: id });\n },\n\n // Design Review\n ...designHandlers,\n\n // Health\n health: async () => {\n const stats = registry.getStats();\n const registration = registry.getRegistrationCoverage();\n const response: Record<string, unknown> = {\n status: 'healthy',\n timestamp: Date.now(),\n ...stats,\n registration,\n };\n\n if (config?.appInfo) {\n response.uiBridge = {\n version: __SDK_VERSION__,\n ...config.appInfo,\n capabilities: ['elements', 'components', 'actions', 'design'],\n elementCount: stats.elements,\n componentCount: stats.components,\n };\n }\n\n return success(response);\n },\n };\n}\n","/**\n * UI Bridge Native — observability ring buffers.\n *\n * Two small last-N buffers backing the `/control/console-errors` and\n * `/sdk/network-requests` endpoints. Each buffer monkey-patches the relevant\n * global on `install()` and restores the original on `uninstall()`, so they\n * can be installed/torn-down with the server's lifecycle.\n *\n * Both buffers are gated behind `features.observability` by the caller (see\n * NativeUIBridgeServer), which defaults to the `features.testHooks` value.\n * Builds with both flags off never run these patches; release builds can\n * opt in with `observability: true` without enabling testHooks.\n *\n * Implementation notes:\n * - Buffers default to capacity 100 entries and drop oldest on overflow.\n * - Patches are idempotent: `install()` is a no-op when already installed;\n * `uninstall()` is a no-op when not installed.\n * - Patches only restore the *original* function captured at install time;\n * if other code wraps `console.error` / `fetch` between install and\n * uninstall, those wrappers will be lost. Acceptable for test hooks.\n */\nimport type { ConsoleErrorEntry, NetworkRequestEntry } from './types';\n\n// ── Ring buffer ─────────────────────────────────────────────────────────────\n\n/** A simple ring buffer that drops oldest on overflow. */\nclass RingBuffer<T extends { timestamp: number }> {\n private items: T[] = [];\n\n constructor(private readonly capacity: number) {}\n\n push(entry: T): void {\n this.items.push(entry);\n if (this.items.length > this.capacity) {\n this.items.splice(0, this.items.length - this.capacity);\n }\n }\n\n /**\n * Return entries optionally filtered by `since` (timestamp ms) and capped\n * at `limit`. Newest-end is preserved when `limit` would otherwise truncate.\n */\n entries(opts: { since?: number; limit?: number } = {}): T[] {\n const { since, limit } = opts;\n let filtered = this.items;\n if (typeof since === 'number') {\n filtered = filtered.filter((e) => e.timestamp >= since);\n }\n if (typeof limit === 'number' && limit >= 0 && filtered.length > limit) {\n filtered = filtered.slice(filtered.length - limit);\n }\n return filtered.slice();\n }\n\n size(): number {\n return this.items.length;\n }\n\n clear(): void {\n this.items.length = 0;\n }\n}\n\n// ── Console error buffer ────────────────────────────────────────────────────\n\ninterface PatchedConsole {\n error: (...args: unknown[]) => void;\n warn: (...args: unknown[]) => void;\n}\n\n/**\n * Format console arguments the same way `console.log` would (joined by\n * spaces, with errors stringified to their `message`).\n */\nfunction formatConsoleArgs(args: unknown[]): string {\n return args\n .map((a) => {\n if (a instanceof Error) return a.message;\n if (typeof a === 'string') return a;\n try {\n return JSON.stringify(a);\n } catch {\n return String(a);\n }\n })\n .join(' ');\n}\n\n/** Pull the first `Error` from the args, if any, and return its `.stack`. */\nfunction extractStack(args: unknown[]): string | undefined {\n for (const a of args) {\n if (a instanceof Error && a.stack) return a.stack;\n }\n return undefined;\n}\n\nexport class ConsoleErrorBuffer {\n private buffer: RingBuffer<ConsoleErrorEntry>;\n private installed = false;\n private originalError?: PatchedConsole['error'];\n private originalWarn?: PatchedConsole['warn'];\n\n constructor(capacity = 100) {\n this.buffer = new RingBuffer<ConsoleErrorEntry>(capacity);\n }\n\n install(): void {\n if (this.installed) return;\n if (typeof console === 'undefined') return;\n\n // Capture the originals as-is (no .bind) so `uninstall()` restores the\n // exact reference callers had before we touched the global.\n this.originalError = console.error as PatchedConsole['error'];\n this.originalWarn = console.warn as PatchedConsole['warn'];\n\n const buffer = this.buffer;\n const origError = this.originalError;\n const origWarn = this.originalWarn;\n\n console.error = (...args: unknown[]): void => {\n try {\n buffer.push({\n timestamp: Date.now(),\n level: 'error',\n message: formatConsoleArgs(args),\n stack: extractStack(args),\n });\n } catch {\n // Never let the patch throw — fall through to the original.\n }\n origError.apply(console, args);\n };\n\n console.warn = (...args: unknown[]): void => {\n try {\n buffer.push({\n timestamp: Date.now(),\n level: 'warn',\n message: formatConsoleArgs(args),\n stack: extractStack(args),\n });\n } catch {\n // ignore\n }\n origWarn.apply(console, args);\n };\n\n this.installed = true;\n }\n\n uninstall(): void {\n if (!this.installed) return;\n if (typeof console === 'undefined') return;\n\n if (this.originalError) console.error = this.originalError;\n if (this.originalWarn) console.warn = this.originalWarn;\n\n this.originalError = undefined;\n this.originalWarn = undefined;\n this.installed = false;\n }\n\n entries(opts: { since?: number; limit?: number } = {}): ConsoleErrorEntry[] {\n return this.buffer.entries(opts);\n }\n\n size(): number {\n return this.buffer.size();\n }\n\n clear(): void {\n this.buffer.clear();\n }\n\n isInstalled(): boolean {\n return this.installed;\n }\n}\n\n// ── Network request buffer ──────────────────────────────────────────────────\n\ntype FetchFn = (input: RequestInfo | URL, init?: RequestInit) => Promise<Response>;\n\n/**\n * Best-effort URL extraction from a `fetch` first-arg. Mirrors what RN's\n * polyfill accepts (string | URL | Request).\n */\nfunction extractUrl(input: unknown): string {\n if (typeof input === 'string') return input;\n if (input && typeof input === 'object') {\n const obj = input as { url?: unknown; toString?: () => string };\n if (typeof obj.url === 'string') return obj.url;\n try {\n return String(input);\n } catch {\n return '';\n }\n }\n return '';\n}\n\n/**\n * Best-effort method extraction. `fetch(url, {method})` overrides the\n * Request's method, so we check `init` first and fall back to the Request.\n */\nfunction extractMethod(input: unknown, init?: RequestInit): string {\n if (init && typeof init.method === 'string') return init.method.toUpperCase();\n if (input && typeof input === 'object') {\n const obj = input as { method?: unknown };\n if (typeof obj.method === 'string') return obj.method.toUpperCase();\n }\n return 'GET';\n}\n\n/** Minimal shape of `globalThis` we patch. Avoids depending on DOM types. */\ninterface PatchableGlobal {\n fetch?: FetchFn;\n XMLHttpRequest?: typeof XMLHttpRequest;\n}\n\n/**\n * An XHR instance, plus the markers the patches hang on it.\n *\n * `__uiBridgeMethod` / `__uiBridgeUrl` carry method+url from `open` to `send`.\n * `__uiBridgeFromFetch` marks an XHR that the `fetch` polyfill created for\n * itself — see {@link NetworkRequestBuffer.install}.\n */\ntype MarkedXhr = XMLHttpRequest & {\n __uiBridgeMethod?: string;\n __uiBridgeUrl?: string;\n __uiBridgeFromFetch?: boolean;\n};\n\nexport class NetworkRequestBuffer {\n private buffer: RingBuffer<NetworkRequestEntry>;\n private installed = false;\n private originalFetch?: FetchFn;\n private originalXhrOpen?: typeof XMLHttpRequest.prototype.open;\n private originalXhrSend?: typeof XMLHttpRequest.prototype.send;\n /**\n * Synchronous re-entrancy depth: non-zero while the ORIGINAL `fetch` is\n * executing, which is exactly the window in which React Native's whatwg-fetch\n * polyfill constructs and opens its internal `XMLHttpRequest`.\n *\n * A counter rather than a boolean so a `fetch` called from inside a `fetch`\n * (an interceptor, a retry wrapper) still unwinds to zero. Safe as a plain\n * number: JS is single-threaded and the only writes are the paired\n * increment/decrement around one synchronous call.\n */\n private fetchDepth = { value: 0 };\n\n constructor(capacity = 100) {\n this.buffer = new RingBuffer<NetworkRequestEntry>(capacity);\n }\n\n /**\n * Patch `fetch` and `XMLHttpRequest` so `GET /sdk/network-requests` can\n * report what the app talked to.\n *\n * ONE REQUEST MUST PRODUCE ONE ENTRY. React Native implements `fetch` **on\n * top of** XHR (whatwg-fetch), so both patches observe the same request and\n * the buffer used to carry every call twice — same url, timestamps ~1ms\n * apart, and on failure one `\"Network request failed\"` beside one\n * `\"XMLHttpRequest error\"`. A tester reads that as a double-fetch bug in the\n * app and chases a defect that does not exist.\n *\n * The de-dup: `fetchDepth` is raised across the synchronous call into the\n * original `fetch`, which is when the polyfill builds its XHR; `open` stamps\n * any XHR created in that window with `__uiBridgeFromFetch`, and `send`\n * skips recording those. The `fetch` patch keeps the entry, because it is\n * the layer the app actually called and the only one that sees `Response.ok`.\n *\n * Uninstalling both patches together keeps this sound: an XHR can only be\n * marked while the fetch patch is live.\n *\n * KNOWN LIMIT — it is coupled to the polyfill building its XHR SYNCHRONOUSLY,\n * which whatwg-fetch does (its work happens in the Promise executor). If the\n * host's `fetch` is wrapped by an interceptor that defers the real call to a\n * microtask or `setTimeout`, the depth is back to 0 by the time `open` runs\n * and every request duplicates again — the original symptom, with no signal\n * that the mechanism disengaged. Duplicates in `/sdk/network-requests` are\n * the thing to look for; they mean this assumption stopped holding, not that\n * the app double-fetched.\n */\n install(): void {\n if (this.installed) return;\n const g = globalThis as PatchableGlobal;\n\n if (typeof g.fetch === 'function') {\n // Capture the original reference as-is so `uninstall()` restores the\n // exact function callers had before we patched.\n this.originalFetch = g.fetch;\n const buffer = this.buffer;\n const original = this.originalFetch;\n const fetchDepth = this.fetchDepth;\n\n const patched: FetchFn = async (input, init) => {\n const start = Date.now();\n const url = extractUrl(input);\n const method = extractMethod(input, init);\n\n try {\n // The polyfill's `new XMLHttpRequest()` / `open` / `send` all happen\n // synchronously inside this call (whatwg-fetch does its work in the\n // Promise executor), so raising the depth across just the invocation\n // — not the await — covers exactly that window and nothing else.\n let pending: Promise<Response>;\n fetchDepth.value += 1;\n try {\n pending = original.call(globalThis, input, init);\n } finally {\n fetchDepth.value -= 1;\n }\n const res = await pending;\n buffer.push({\n timestamp: start,\n method,\n url,\n status: res.status,\n durationMs: Date.now() - start,\n ok: res.ok,\n });\n return res;\n } catch (err) {\n buffer.push({\n timestamp: start,\n method,\n url,\n status: 0,\n durationMs: Date.now() - start,\n ok: false,\n error: err instanceof Error ? err.message : String(err),\n });\n throw err;\n }\n };\n\n g.fetch = patched;\n }\n\n // Patch XMLHttpRequest if present (RN ships it; node doesn't unless polyfilled).\n if (typeof g.XMLHttpRequest === 'function') {\n const Xhr = g.XMLHttpRequest;\n this.originalXhrOpen = Xhr.prototype.open;\n this.originalXhrSend = Xhr.prototype.send;\n\n const buffer = this.buffer;\n const fetchDepth = this.fetchDepth;\n\n // Stash method+url on the instance so `send` can record them.\n const origOpen = this.originalXhrOpen;\n Xhr.prototype.open = function (\n this: MarkedXhr,\n method: string,\n url: string | URL,\n ...rest: unknown[]\n ) {\n this.__uiBridgeMethod = method.toUpperCase();\n this.__uiBridgeUrl = typeof url === 'string' ? url : String(url);\n // Opened while the original `fetch` was running: this XHR belongs to\n // the fetch polyfill, and the fetch patch already records it.\n //\n // KNOWN LIMIT — the window, not the identity, is what's tested, so an\n // UNRELATED xhr opened synchronously inside another wrapper's `fetch`\n // (an analytics beacon, an error-reporter transport) is dropped too.\n // Narrowing this to the polyfill's own XHR means matching on url, and\n // whatwg-fetch normalises the url it opens with — a mismatch there\n // would silently restore the duplicate-every-request bug rather than\n // lose one beacon. Pinned by a test in network-buffer-dedup.test.ts.\n if (fetchDepth.value > 0) {\n this.__uiBridgeFromFetch = true;\n }\n // origOpen has overloaded signatures; we forward the original args.\n return (origOpen as (...args: unknown[]) => unknown).call(\n this,\n method,\n url,\n ...rest\n ) as void;\n } as typeof XMLHttpRequest.prototype.open;\n\n const origSend = this.originalXhrSend;\n Xhr.prototype.send = function (\n this: MarkedXhr,\n body?: Document | XMLHttpRequestBodyInit | null\n ) {\n // The fetch patch owns this request's entry. Recording it here too is\n // what made every RN request appear twice in the buffer.\n //\n // The MARKER is the whole test, deliberately. A `fetchDepth > 0` check\n // here as well would also drop any UNRELATED xhr sent synchronously\n // during a `fetch` — an analytics beacon from a library that wrapped\n // `fetch` first, say — and a silently absent request is a worse answer\n // than a visible duplicate.\n if (this.__uiBridgeFromFetch === true) {\n return (origSend as (...args: unknown[]) => unknown).call(this, body) as void;\n }\n\n const start = Date.now();\n const method = this.__uiBridgeMethod ?? 'GET';\n const url = this.__uiBridgeUrl ?? '';\n\n const finalize = (status: number, ok: boolean, error?: string) => {\n buffer.push({\n timestamp: start,\n method,\n url,\n status,\n durationMs: Date.now() - start,\n ok,\n error,\n });\n };\n\n const onLoadEnd = () => {\n this.removeEventListener('loadend', onLoadEnd);\n this.removeEventListener('error', onError);\n finalize(this.status, this.status >= 200 && this.status < 300);\n };\n const onError = () => {\n this.removeEventListener('loadend', onLoadEnd);\n this.removeEventListener('error', onError);\n finalize(0, false, 'XMLHttpRequest error');\n };\n\n this.addEventListener('loadend', onLoadEnd);\n this.addEventListener('error', onError);\n\n return (origSend as (...args: unknown[]) => unknown).call(\n this,\n body\n ) as void;\n } as typeof XMLHttpRequest.prototype.send;\n }\n\n this.installed = true;\n }\n\n uninstall(): void {\n if (!this.installed) return;\n const g = globalThis as PatchableGlobal;\n\n if (this.originalFetch) {\n g.fetch = this.originalFetch;\n this.originalFetch = undefined;\n }\n if (typeof g.XMLHttpRequest === 'function') {\n if (this.originalXhrOpen) {\n g.XMLHttpRequest.prototype.open = this.originalXhrOpen;\n }\n if (this.originalXhrSend) {\n g.XMLHttpRequest.prototype.send = this.originalXhrSend;\n }\n }\n this.originalXhrOpen = undefined;\n this.originalXhrSend = undefined;\n this.installed = false;\n }\n\n entries(opts: { since?: number; limit?: number } = {}): NetworkRequestEntry[] {\n return this.buffer.entries(opts);\n }\n\n size(): number {\n return this.buffer.size();\n }\n\n clear(): void {\n this.buffer.clear();\n }\n\n isInstalled(): boolean {\n return this.installed;\n }\n}\n","/**\n * WebSocket JSON-RPC message types for the UI Bridge protocol.\n */\n\n// ── Client → Server ─────────────────────────────────────────────────────────\n\n/** Standard JSON-RPC request */\nexport interface JsonRpcRequest {\n id: number | string;\n method: string;\n params?: Record<string, unknown>;\n}\n\n/** Batch request — execute multiple requests concurrently */\nexport interface JsonRpcBatchRequest {\n id: number | string;\n batch: JsonRpcRequest[];\n}\n\n/** Subscribe to registry events */\nexport interface JsonRpcSubscribe {\n id: number | string;\n method: 'subscribe';\n params: {\n events: string[];\n /** Optional throttle in ms — batch rapid events within this window */\n throttleMs?: number;\n };\n}\n\n/** Unsubscribe from registry events */\nexport interface JsonRpcUnsubscribe {\n id: number | string;\n method: 'unsubscribe';\n params: { events: string[] };\n}\n\n/** Any client message */\nexport type JsonRpcClientMessage =\n | JsonRpcRequest\n | JsonRpcBatchRequest\n | JsonRpcSubscribe\n | JsonRpcUnsubscribe;\n\n// ── Server → Client ─────────────────────────────────────────────────────────\n\n/** Standard JSON-RPC response */\nexport interface JsonRpcResponse {\n id: number | string;\n result?: {\n success: boolean;\n data?: unknown;\n error?: string;\n code?: string;\n timestamp?: number;\n };\n}\n\n/** Batch response */\nexport interface JsonRpcBatchResponse {\n id: number | string;\n results: JsonRpcResponse[];\n}\n\n/** Server-pushed event (no id — not a response to a request) */\nexport interface JsonRpcEvent {\n event: string;\n data: unknown;\n timestamp: number;\n}\n\n/** Any server message */\nexport type JsonRpcServerMessage = JsonRpcResponse | JsonRpcBatchResponse | JsonRpcEvent;\n\n// ── Helpers ─────────────────────────────────────────────────────────────────\n\n/** Check if a message is a batch request */\nexport function isBatchRequest(msg: unknown): msg is JsonRpcBatchRequest {\n return (\n typeof msg === 'object' &&\n msg !== null &&\n 'batch' in msg &&\n Array.isArray((msg as JsonRpcBatchRequest).batch)\n );\n}\n\n/** Check if a message is a subscribe request */\nexport function isSubscribe(msg: unknown): msg is JsonRpcSubscribe {\n return (\n typeof msg === 'object' && msg !== null && (msg as JsonRpcSubscribe).method === 'subscribe'\n );\n}\n\n/** Check if a message is an unsubscribe request */\nexport function isUnsubscribe(msg: unknown): msg is JsonRpcUnsubscribe {\n return (\n typeof msg === 'object' && msg !== null && (msg as JsonRpcUnsubscribe).method === 'unsubscribe'\n );\n}\n","/**\n * UI Bridge Native HTTP Server\n *\n * Abstract HTTP server implementation for React Native.\n * This provides a framework-agnostic server interface that can be\n * implemented using various React Native HTTP server libraries.\n *\n * Supported libraries:\n * - react-native-http-bridge (recommended)\n * - @aspect/react-native-http-server\n * - Custom implementations\n */\n\nimport type { NativeUIBridgeRegistry } from '../core/registry';\nimport type { NativeActionExecutor, PageNavigationResponse } from '../control/types';\nimport type {\n NativeServerConfig,\n NativeServerHandlers,\n NavigationProvider,\n RouteProvider,\n ScreenshotProvider,\n KeepAwakeProvider,\n APIResponse,\n HandlerContext,\n} from './types';\nimport type { BridgeEvent } from '../core/types';\nimport { createServerHandlers } from './handlers';\nimport { ConsoleErrorBuffer, NetworkRequestBuffer } from './observability';\nimport type { WebSocketEventBridge } from './ws-event-bridge';\nimport type { JsonRpcRequest, JsonRpcResponse } from './ws-types';\nimport { isBatchRequest, isSubscribe, isUnsubscribe } from './ws-types';\n\n// ── HTTP status mapping ─────────────────────────────────────────────────────\n\n/**\n * HTTP status for each `APIResponse.code` that has an honest status of its own.\n *\n * Handlers already distinguish \"this platform will never do that\"\n * (`NOT_SUPPORTED`), \"no such route\" (`NOT_FOUND`) and \"wrong verb\"\n * (`METHOD_NOT_ALLOWED`) in the response envelope. Anything not listed here is\n * a client-input problem and keeps 400, which is what 400 is for.\n *\n * `NOT_SUPPORTED` is also ELEMENT-scoped, not only platform-scoped: an element\n * action that fails with a `NativeActionError` keeps its code through\n * `handlers.ts` `executeAction` — today `scrollIntoView` on an element with no\n * usable declared `scrollAncestorId`. Either way it means \"retrying this\n * request will not help\", which is why it maps to 501 rather than 400.\n *\n * RESOURCE-level misses are deliberately NOT here. `ELEMENT_NOT_FOUND`,\n * `COMPONENT_NOT_FOUND`, `MODAL_NOT_FOUND` and `WORKFLOW_NOT_FOUND`\n * (`handlers.ts`) keep 400: the route resolved and served a request whose\n * *argument* named nothing — a client-input problem, not a routing one.\n * Widening 404 to cover them would make \"this endpoint does not exist\" and\n * \"this id does not exist\" the same status, which is the ambiguity this\n * mapping exists to remove.\n *\n * A `Map` rather than an object literal on purpose: a plain object resolves\n * inherited keys, so a `code` of `\"toString\"` or `\"constructor\"` would return\n * a FUNCTION where a status number is typed, and it would be relayed straight\n * into the cloud tunnel (`transport/CloudRelayClient.ts`). Unreachable today —\n * every `code` in the tree is a hardcoded literal — but a `Map` costs nothing\n * and closes it structurally rather than by audit.\n */\nconst ERROR_CODE_HTTP_STATUS = new Map<string, number>([\n ['NOT_SUPPORTED', 501],\n ['NOT_FOUND', 404],\n ['METHOD_NOT_ALLOWED', 405],\n]);\n\n/**\n * Derive the HTTP status for a completed `APIResponse`.\n *\n * Every unsuccessful response used to be flattened to HTTP 400, which made a\n * deliberately-unimplemented route (`/ai/forms` → `NOT_SUPPORTED`) and a route\n * that does not exist (`NOT_FOUND`) indistinguishable from a malformed request\n * — so callers retried request shapes against endpoints that were never going\n * to answer. The envelope's `code` already carries the distinction; this maps\n * it onto the status line so a caller reading only the status gets the truth.\n */\nexport function httpStatusForResponse(response: APIResponse): number {\n if (response.success) return 200;\n const mapped = response.code ? ERROR_CODE_HTTP_STATUS.get(response.code) : undefined;\n return mapped ?? 400;\n}\n\n// ── Path pattern matching ───────────────────────────────────────────────────\n\n/**\n * Match an actual path against a pattern with :name placeholders.\n * Returns extracted params, or null if the pattern does not match.\n *\n * Example: parsePath('control/element/:id/action', 'control/element/tab-runs/action')\n * → { id: 'tab-runs' }\n */\nfunction parsePath(pattern: string, actual: string): Record<string, string> | null {\n const patternParts = pattern.split('/');\n const actualParts = actual.split('/');\n\n if (patternParts.length !== actualParts.length) {\n return null;\n }\n\n const params: Record<string, string> = {};\n for (let i = 0; i < patternParts.length; i++) {\n if (patternParts[i].startsWith(':')) {\n params[patternParts[i].slice(1)] = actualParts[i];\n } else if (patternParts[i] !== actualParts[i]) {\n return null;\n }\n }\n return params;\n}\n\n// ── WebSocket route table ───────────────────────────────────────────────────\n\n/**\n * Route table for WebSocket JSON-RPC methods.\n *\n * Method strings use the same path structure as HTTP routes (with :id placeholders)\n * but without the /ui-bridge/ prefix. Path params are extracted automatically.\n *\n * Examples:\n * \"health\" → handlers.health\n * \"control/snapshot\" → handlers.getSnapshot\n * \"control/element/tab-runs/action\" → handlers.executeAction ({id: 'tab-runs'})\n * \"control/component/my-comp/action/submit\" → handlers.executeComponentAction\n */\ntype HandlerKey = keyof NativeServerHandlers;\ntype HttpVerb = 'GET' | 'POST' | 'DELETE';\n\ninterface WsRoute {\n pattern: string;\n handler: HandlerKey;\n /**\n * HTTP verbs this route accepts when invoked over HTTP. When absent the\n * route is WS-only (or matches any verb on HTTP). Multiple verbs allow\n * a single pattern to serve GET+POST etc.\n */\n httpMethods?: readonly HttpVerb[];\n /**\n * When true, the route is only mounted (HTTP + WS + manifest) when the\n * server config opts in via `testHooks`. Production builds default to\n * `testHooks: false` so these endpoints simply don't exist in the route\n * table — agents probing `/_routes` won't see them.\n */\n requiresTestHooks?: boolean;\n}\n\nconst WS_ROUTES: readonly WsRoute[] = [\n // Health\n { pattern: 'health', handler: 'health', httpMethods: ['GET'] },\n\n // Elements\n { pattern: 'control/elements', handler: 'getElements', httpMethods: ['GET'] },\n // Flat alias — matches the runner UI Bridge's `/ui-bridge/elements` path so\n // agents can use the same URL across runner + mobile without remembering\n // the `control/` prefix. Delegates to the same handler.\n { pattern: 'elements', handler: 'getElements', httpMethods: ['GET'] },\n { pattern: 'control/element/:id', handler: 'getElement', httpMethods: ['GET'] },\n { pattern: 'control/element/:id/state', handler: 'getElementState', httpMethods: ['GET'] },\n { pattern: 'control/element/:id/action', handler: 'executeAction', httpMethods: ['POST'] },\n\n // Components\n { pattern: 'control/components', handler: 'getComponents', httpMethods: ['GET'] },\n { pattern: 'control/component/:id', handler: 'getComponent', httpMethods: ['GET'] },\n {\n pattern: 'control/component/:id/action/:actionId',\n handler: 'executeComponentAction',\n httpMethods: ['POST'],\n },\n\n // Discovery\n { pattern: 'control/find', handler: 'find', httpMethods: ['POST'] },\n // Runner-parity alias for `control/find`; the runner exposes its\n // AI-powered element search at `/ui-bridge/ai/find`, so mobile mounts the\n // same handler at both paths to keep agents portable across platforms.\n { pattern: 'ai/find', handler: 'find', httpMethods: ['POST'] },\n { pattern: 'control/snapshot', handler: 'getSnapshot', httpMethods: ['GET'] },\n // Discovery alias — web/runner parity with `POST /control/discover` (a\n // legacy alias for snapshot/find). Mounted on HTTP (GET+POST) so mobile\n // doesn't 404 where web returns 200; delegates to the snapshot handler.\n { pattern: 'control/discover', handler: 'getSnapshot', httpMethods: ['GET', 'POST'] },\n // Page health — accepts both GET and POST so the canonical skill invocation\n // (`POST .../control/page-health` with an empty body) and ad-hoc curls both\n // work without a body-shape gotcha.\n { pattern: 'control/page-health', handler: 'getPageHealth', httpMethods: ['GET', 'POST'] },\n\n // Workflows\n { pattern: 'control/workflows', handler: 'getWorkflows', httpMethods: ['GET'] },\n { pattern: 'control/workflow/:id/run', handler: 'runWorkflow', httpMethods: ['POST'] },\n\n // Page Navigation\n { pattern: 'control/page/refresh', handler: 'pageRefresh', httpMethods: ['POST'] },\n { pattern: 'control/page/navigate', handler: 'pageNavigate', httpMethods: ['POST'] },\n { pattern: 'control/page/replace', handler: 'pageReplace', httpMethods: ['POST'] },\n { pattern: 'control/page/back', handler: 'pageGoBack', httpMethods: ['POST'] },\n { pattern: 'control/page/forward', handler: 'pageGoForward', httpMethods: ['POST'] },\n\n // Screenshot — accepts both GET and POST on HTTP\n { pattern: 'control/screenshot', handler: 'getScreenshot', httpMethods: ['GET', 'POST'] },\n\n // Design Review\n { pattern: 'design/element/:id/styles', handler: 'getElementStyles', httpMethods: ['GET'] },\n {\n pattern: 'design/element/:id/state-styles',\n handler: 'getElementStateStyles',\n httpMethods: ['POST'],\n },\n { pattern: 'design/snapshot', handler: 'getDesignSnapshot', httpMethods: ['POST'] },\n { pattern: 'design/responsive', handler: 'getResponsiveSnapshots', httpMethods: ['POST'] },\n { pattern: 'design/audit', handler: 'runDesignAudit', httpMethods: ['POST'] },\n { pattern: 'design/style-guide/load', handler: 'loadStyleGuide', httpMethods: ['POST'] },\n { pattern: 'design/style-guide', handler: 'getStyleGuide', httpMethods: ['GET'] },\n // style-guide/clear: WS uses this pattern; HTTP uses DELETE on /design/style-guide.\n // We keep a WS-only entry for the explicit \"clear\" subpath, and add a DELETE-on-style-guide entry.\n { pattern: 'design/style-guide/clear', handler: 'clearStyleGuide' },\n { pattern: 'design/style-guide', handler: 'clearStyleGuide', httpMethods: ['DELETE'] },\n\n // Quality Evaluation\n { pattern: 'design/evaluate', handler: 'evaluateQuality', httpMethods: ['POST'] },\n { pattern: 'design/evaluate/contexts', handler: 'getQualityContexts', httpMethods: ['GET'] },\n { pattern: 'design/evaluate/baseline', handler: 'saveBaseline', httpMethods: ['POST'] },\n { pattern: 'design/evaluate/diff', handler: 'diffBaseline', httpMethods: ['POST'] },\n\n // Meta / Introspection\n { pattern: 'meta/methods', handler: 'getMethods', httpMethods: ['GET'] },\n\n // AI helpers — mobile parity with the runner's `/ui-bridge/ai/*` family.\n { pattern: 'ai/fill-form', handler: 'fillForm', httpMethods: ['POST'] },\n\n // AI helpers — NOT_SUPPORTED stubs. These endpoints exist on the runner-side\n // UI Bridge surface (and the /manual-test skill's cheatsheet documents them\n // as if they're universally available). Mobile React Native has no DOM, so\n // the mobile bridge mounts explicit stubs so callers get a structured\n // NOT_SUPPORTED envelope (with a hint pointing at the mobile-native\n // replacement) instead of a confusing HTTP 404.\n { pattern: 'ai/forms', handler: 'aiForms', httpMethods: ['GET'] },\n { pattern: 'ai/idle-status', handler: 'aiIdleStatus', httpMethods: ['GET'] },\n {\n pattern: 'ai/change-buffer/enable',\n handler: 'aiChangeBufferEnable',\n httpMethods: ['POST'],\n },\n {\n pattern: 'ai/wait-for-element',\n handler: 'aiWaitForElement',\n httpMethods: ['POST'],\n },\n\n // Coord-based tap — synthesizes a press at the given screen coords by\n // matching against registered elements' layout rects.\n { pattern: 'control/tap', handler: 'tapAt', httpMethods: ['POST'] },\n\n // App-agnostic interaction parity — mirrors the web/runner convenience\n // endpoints (`/control/page/click-by-text` etc.) so the SAME cross-platform\n // contract drives mobile. Text/label-based interactions compose\n // `executor.find` + `executor.executeAction` over the registry; the\n // DOM-selector-only variants (`click-by-selector`, `read-value`) have no RN\n // analog and return a structured NOT_SUPPORTED envelope.\n { pattern: 'control/page/click-by-text', handler: 'clickByText', httpMethods: ['POST'] },\n { pattern: 'control/page/click-by-selector', handler: 'clickBySelector', httpMethods: ['POST'] },\n { pattern: 'control/page/type-into', handler: 'typeInto', httpMethods: ['POST'] },\n { pattern: 'control/page/read-value', handler: 'readValue', httpMethods: ['POST'] },\n { pattern: 'control/page/find-by-text', handler: 'findByText', httpMethods: ['POST'] },\n\n // Test hooks — gated behind `features.testHooks`. Let external runners\n // drive the ModalDetector over HTTP so tests can flip `snapshot.modalStack`\n // without mounting React components.\n {\n pattern: 'control/modal/push',\n handler: 'pushModal',\n httpMethods: ['POST'],\n requiresTestHooks: true,\n },\n {\n pattern: 'control/modal/dismiss/:id',\n handler: 'dismissModal',\n httpMethods: ['POST'],\n requiresTestHooks: true,\n },\n {\n pattern: 'control/keep-awake',\n handler: 'keepAwake',\n httpMethods: ['POST'],\n requiresTestHooks: true,\n },\n\n // Observability — last-N console errors + network requests.\n //\n // Always mounted (not testHooks-gated) so they return a schema-valid 200\n // on every build instead of a 404 that agents can't distinguish from a\n // missing route. The INVASIVE part — monkey-patching `console.error` /\n // `fetch` / `XMLHttpRequest` — stays gated behind `testHooks` (see\n // NativeUIBridgeServer.start → buffer.install()). When the patches aren't\n // installed the handlers report `installed: false` + empty entries, so\n // production builds expose the contract without observing real users'\n // console/network traffic. Set `features.testHooks` (typically on\n // `__DEV__`) to populate the buffers with live data.\n {\n pattern: 'control/console-errors',\n handler: 'getConsoleErrors',\n httpMethods: ['GET'],\n },\n {\n pattern: 'sdk/network-requests',\n handler: 'getNetworkRequests',\n httpMethods: ['GET'],\n },\n];\n\n/**\n * The two discovery endpoints, which `routeRequest` special-cases rather than\n * dispatching through `WS_ROUTES` — there is no handler to dispatch to. Both\n * are GET-only.\n *\n * ⚠️ This is the DISPATCH-adjacent copy, not the only one. The same two path\n * strings are also written out in `buildRoutesPayload` (which appends them to\n * the `_routes` manifest) and in the two serving branches of `routeRequest`,\n * and their `HELP` / `ROUTES` entries live in `types.ts`. Adding a third\n * discovery endpoint means touching all four. Only the `types.ts` ↔\n * `buildRoutesPayload` pair is ratcheted, by `route-table-parity.test.ts`;\n * forgetting THIS set silently downgrades the new endpoint's wrong-verb answer\n * to 404 and nothing fails. Collapsing the four into one declaration is a\n * worthwhile follow-up and is not attempted here.\n */\nconst DISCOVERY_PATHS = new Set(['_help', '_routes']);\n\n/**\n * The verbs this surface serves for a path, in table order.\n *\n * Fills the `Allow` header that RFC 9110 §15.5.6 makes mandatory on a 405, and\n * that the wrong-verb arm answered without: a caller told only \"method not\n * allowed\" has to guess which verb to retry, which is the guessing game the\n * status mapping exists to end. Read off `WS_ROUTES` — the array `routeRequest`\n * itself iterates — plus `DISCOVERY_PATHS`, which is the other thing\n * `routeRequest` dispatches on, so the header cannot come to disagree with the\n * status about what this surface accepts.\n *\n * `testHooks` is honoured for the same reason `routeRequest` honours it: a\n * production build must not advertise a gated verb it will not serve. `path` is\n * the full request path; the `/ui-bridge/` prefix is stripped here. Empty for a\n * path no route matches, in which case no header is set — that path answers\n * 404, where `Allow` would be meaningless.\n */\nfunction allowedMethodsForPath(path: string, testHooks: boolean): string[] {\n const PREFIX = '/ui-bridge/';\n if (!path.startsWith(PREFIX)) return [];\n const stripped = path.slice(PREFIX.length);\n\n const methods: string[] = [];\n if (DISCOVERY_PATHS.has(stripped)) methods.push('GET');\n for (const route of WS_ROUTES) {\n if (!route.httpMethods) continue;\n if (route.requiresTestHooks && !testHooks) continue;\n if (parsePath(route.pattern, stripped) === null) continue;\n for (const verb of route.httpMethods) {\n if (!methods.includes(verb)) methods.push(verb);\n }\n }\n return methods;\n}\n\n// ── _help payload ───────────────────────────────────────────────────────────\n\n/**\n * Short description keyed by handler name — rendered alongside the route\n * list so `_help` is self-documenting. Only needs to cover handlers that\n * appear in WS_ROUTES.\n */\nconst HANDLER_DESCRIPTIONS: Record<string, string> = {\n health: 'Liveness probe; returns app metadata + element count',\n getElements: 'Flat list of registered UI elements',\n getElement: 'Single element by id',\n getElementState: 'Dynamic state (value, focused, checked) for one element',\n executeAction: 'Run an action on an element (see \"actions\" below for names)',\n getComponents: 'Higher-level components with action schemas',\n getComponent: 'Component detail + per-action paramSchema',\n executeComponentAction: 'Invoke a component action directly (preferred over button clicks)',\n find: 'AI-powered element search by natural-language query',\n getSnapshot:\n 'Full snapshot: elements + route + state. Supports ?visibleOnly=true and ?currentRouteOnly=true',\n getPageHealth:\n 'Holistic page health diagnostic over current snapshot elements (spatial coverage, layout regions, text/anomaly signals, heatmap). Optional body: { viewport?: { width, height } } to override Dimensions.get(\"window\").',\n getWorkflows: 'List registered workflows',\n runWorkflow: 'Trigger a workflow by id',\n pageRefresh: 'Reload the current route',\n pageNavigate: 'Imperative router.push(url) — preferred over tapping tab buttons',\n pageReplace: 'router.replace(url)',\n pageGoBack: 'router.back()',\n pageGoForward: 'router.forward()',\n getScreenshot: 'PNG screenshot of the current screen',\n getElementStyles: 'Computed styles for an element (design review)',\n getElementStateStyles: 'Computed styles per interaction state (hover/focus/disabled)',\n getDesignSnapshot: 'Visual + style snapshot for design review',\n getResponsiveSnapshots: 'Screenshots at multiple viewport widths',\n runDesignAudit: 'Accessibility + visual audit',\n loadStyleGuide: 'Load a design system style guide',\n getStyleGuide: 'Fetch the currently loaded style guide',\n clearStyleGuide: 'Unload the style guide',\n evaluateQuality: 'Score the current UI against a quality context',\n getQualityContexts: 'List available quality evaluation contexts',\n saveBaseline: 'Save a quality baseline snapshot',\n diffBaseline: 'Diff current UI against a saved baseline',\n getMethods: 'List every handler name (legacy introspection)',\n fillForm:\n 'Fill multiple inputs in one call: body { fields: [{elementId, value}] } — each field dispatches `type` + `clear:true`',\n aiForms:\n 'STUB — runner-only; mobile returns NOT_SUPPORTED. Use /control/snapshot + filter type===\"input\" instead.',\n aiIdleStatus:\n 'STUB — runner-only; mobile returns NOT_SUPPORTED. Subscribe to registry events over WS for change signals.',\n aiChangeBufferEnable:\n 'STUB — runner-only; mobile returns NOT_SUPPORTED. Use WS event subscriptions for change notifications.',\n aiWaitForElement:\n 'STUB — runner-only; mobile returns NOT_SUPPORTED. Use the WS waitForElement / waitForCondition JSON-RPC methods.',\n tapAt:\n 'Synthesize a press at given screen coords by matching registered element layout rects: body { x, y, action? }',\n clickByText:\n 'App-agnostic: press the first element matching free-text (label/accessibilityLabel/testID): body { text, visibleOnly? }',\n clickBySelector:\n 'STUB — selector-based; NOT_SUPPORTED on native (no DOM). Use clickByText or /control/find + /control/element/:id/action.',\n typeInto:\n 'App-agnostic: type into the input matching a label: body { label, text, clear?, visibleOnly? }. (selector form is web-only)',\n readValue:\n 'STUB — selector-based; NOT_SUPPORTED on native (no DOM). Use /control/element/:id/state to read a value.',\n findByText:\n 'App-agnostic: list elements matching free-text (no press): body { text, visibleOnly? }',\n getConsoleErrors:\n 'Last-N console.error/console.warn entries; ?since=<ms>&limit=<n>. `installed:false` when capture is off (no testHooks) — entries empty but schema-valid.',\n getNetworkRequests:\n 'Last-N fetch/XHR entries with status + duration; ?since=<ms>&limit=<n>. `installed:false` when capture is off (no testHooks) — entries empty but schema-valid.',\n pushModal:\n 'TEST HOOK — push a modal onto the snapshot.modalStack via the registry ModalDetector',\n dismissModal:\n 'TEST HOOK — dismiss a modal by id from the snapshot.modalStack via the registry ModalDetector',\n keepAwake:\n 'TEST HOOK — keep the device screen awake via the injected keepAwakeProvider: body { enabled: boolean, durationMs?: number }',\n};\n\n/** Static reference for common action names + their params. */\nconst ACTION_REFERENCE = [\n { name: 'press', aliases: ['click'], params: 'PressActionParams (optional position)' },\n { name: 'longPress', params: 'PressActionParams (optional position)' },\n { name: 'doubleTap', params: 'none' },\n {\n name: 'type',\n params:\n 'TypeActionParams { text, delay?, clear? | clearFirst? } — `clear:true` replaces content atomically',\n },\n { name: 'clear', params: 'none — empties the input' },\n { name: 'focus', params: 'none' },\n { name: 'blur', params: 'none' },\n { name: 'scroll', params: 'ScrollActionParams { offset? {x,y}, to? }' },\n {\n name: 'scrollIntoView',\n params:\n \"ScrollIntoViewActionParams { padding? (dp, default 16) } — scrolls the element's DECLARED scrollAncestorId ScrollView; returns { alreadyVisible, scrolled }; NOT_SUPPORTED (501) without a usable declared ancestor\",\n },\n { name: 'swipe', params: 'SwipeActionParams { direction, distance }' },\n { name: 'toggle', params: 'none — flips boolean controls' },\n];\n\n/**\n * Minimal `{method, path}` list matching the runner's `/_routes` shape so\n * the same URL works across platforms. Expanded multi-verb routes into one\n * entry per verb. `testHooks` enables the gated `control/modal/*` endpoints.\n */\nfunction buildRoutesPayload(testHooks: boolean) {\n const entries: Array<{ method: string; path: string }> = [];\n for (const r of WS_ROUTES) {\n if (!r.httpMethods) continue;\n if (r.requiresTestHooks && !testHooks) continue;\n for (const m of r.httpMethods) {\n entries.push({ method: m, path: `/ui-bridge/${r.pattern}` });\n }\n }\n // Expose the two discovery endpoints themselves so self-reference is clean.\n entries.push({ method: 'GET', path: '/ui-bridge/_help' });\n entries.push({ method: 'GET', path: '/ui-bridge/_routes' });\n entries.sort((a, b) => a.path.localeCompare(b.path) || a.method.localeCompare(b.method));\n return { routes: entries, count: entries.length };\n}\n\n/**\n * Build the `/_help` payload: route index + action reference.\n * Cheap to compute; we don't cache since it's rarely called.\n * Routes that require `testHooks` are filtered out when the flag is off so\n * agents probing the manifest never see endpoints they can't call.\n */\nfunction buildHelpPayload(testHooks: boolean) {\n return {\n version: 1,\n description: 'UI Bridge Native HTTP surface. Prefix every path with /ui-bridge/.',\n routes: WS_ROUTES.filter((r) => !r.requiresTestHooks || testHooks).map((r) => ({\n pattern: r.pattern,\n httpMethods: r.httpMethods ?? [],\n wsOnly: !r.httpMethods,\n handler: r.handler,\n description: HANDLER_DESCRIPTIONS[r.handler] ?? '',\n })),\n actions: ACTION_REFERENCE,\n tips: [\n 'Start with `GET /ui-bridge/control/snapshot?visibleOnly=true` to see what the user actually sees.',\n 'Prefer `control/component/:id/action/:actionId` over button presses — typed paramSchema, no button-id guessing.',\n 'Use `pageNavigate` for tab switches instead of pressing tab buttons; gesture state often swallows clicks.',\n 'The `type` action supports `clear:true` to replace existing text atomically in one call.',\n ],\n };\n}\n\n/**\n * HTTP Request interface (library-agnostic)\n */\nexport interface HTTPRequest {\n method: string;\n path: string;\n headers: Record<string, string>;\n query: Record<string, string>;\n body?: unknown;\n}\n\n/**\n * HTTP Response interface (library-agnostic)\n */\nexport interface HTTPResponse {\n status: number;\n headers: Record<string, string>;\n body: string;\n}\n\n/**\n * Request handler type\n */\nexport type RequestHandler = (request: HTTPRequest) => Promise<HTTPResponse>;\n\n/**\n * Server adapter interface\n *\n * Implement this interface to integrate with your chosen HTTP server library.\n */\nexport interface ServerAdapter {\n /** Start the server */\n start(port: number, handler: RequestHandler): Promise<void>;\n /** Stop the server */\n stop(): Promise<void>;\n /** Check if server is running */\n isRunning(): boolean;\n}\n\n/**\n * WebSocket-aware server adapter interface.\n *\n * Extends ServerAdapter with callbacks for WebSocket connections.\n * The adapter manages the raw TCP/WS layer; these callbacks let the\n * UI Bridge server handle message routing and event broadcasting.\n */\nexport interface WebSocketServerAdapter extends ServerAdapter {\n /** Called when a JSON text frame is received from a WS client. Returns response string or null. */\n onWebSocketMessage?: (connId: string, message: string) => Promise<string | null>;\n /** Called when a new WS connection is established after the HTTP 101 upgrade. */\n onWebSocketConnect?: (connId: string) => void;\n /** Called when a WS connection is closed or drops. */\n onWebSocketDisconnect?: (connId: string) => void;\n /** Send a message to a specific WS connection by ID. */\n sendToConnection?: (connId: string, message: string) => void;\n /** Send a message to all connected WS clients. */\n broadcast?: (message: string) => void;\n}\n\n/**\n * Native UI Bridge HTTP Server\n */\nexport class NativeUIBridgeServer {\n private config: NativeServerConfig;\n private handlers: NativeServerHandlers;\n private adapter?: ServerAdapter;\n private running = false;\n private keepAwakeProvider?: KeepAwakeProvider;\n /**\n * Per-connection cleanup thunks for in-flight waiters (waitForElement,\n * waitForCondition, ...). Aborted when a client disconnects so the\n * underlying timers/listeners don't leak.\n */\n private pendingWaiters = new Map<string, Set<() => void>>();\n\n /**\n * Observability ring buffers backing `/control/console-errors` and\n * `/sdk/network-requests`. Allocated unconditionally so the handler can\n * always read them, but the global patches (`install()`) only fire on\n * `start()` when observability is enabled (the dedicated `observability`\n * flag, defaulting to `testHooks`) — builds with both off don't\n * monkey-patch.\n */\n private consoleErrorBuffer: ConsoleErrorBuffer;\n private networkRequestBuffer: NetworkRequestBuffer;\n\n /**\n * Whether the console/network capture should be installed. The dedicated\n * `observability` flag wins when set; otherwise falls back to `testHooks`\n * so consumers predating the flag keep their exact behavior.\n */\n private observabilityEnabled(): boolean {\n return this.config.observability ?? this.config.testHooks === true;\n }\n\n constructor(\n private registry: NativeUIBridgeRegistry,\n private executor: NativeActionExecutor,\n config: NativeServerConfig = {}\n ) {\n this.config = {\n serverPort: 8087,\n cors: true,\n ...config,\n };\n this.consoleErrorBuffer = new ConsoleErrorBuffer();\n this.networkRequestBuffer = new NetworkRequestBuffer();\n // Mirror appInfo into the registry so `createSnapshot` includes it\n // automatically — keeps the default `getSnapshot` handler and any other\n // call site (e.g. context.createSnapshot, cloud-relay tunnels) on the\n // same code path without each having to thread `appInfo` through.\n if (this.config.appInfo) {\n this.registry.setAppInfo(this.config.appInfo);\n }\n this.handlers = createServerHandlers(registry, executor, {\n appInfo: this.config.appInfo,\n consoleErrorBuffer: this.consoleErrorBuffer,\n networkRequestBuffer: this.networkRequestBuffer,\n viewportProvider: this.config.viewportProvider,\n });\n\n // Set up method introspection from the route table\n this.handlers.getMethods = async () => {\n const testHooks = this.config.testHooks === true;\n const methods = WS_ROUTES.filter((r) => !r.requiresTestHooks || testHooks).map((r) => ({\n method: r.pattern,\n httpMethods: r.httpMethods ? [...r.httpMethods] : undefined,\n }));\n // Add special WebSocket-only methods not in the route table\n const wsMethods = [\n { method: 'waitForElement', description: 'Wait for an element to be registered' },\n { method: 'waitForCondition', description: 'Wait for an element state predicate' },\n { method: 'sequence', description: 'Execute a sequence of steps in order' },\n { method: 'events/history', description: 'Replay recent registry events' },\n { method: 'subscriptions/list', description: 'List current event subscriptions' },\n ];\n return {\n success: true,\n data: { methods: [...methods, ...wsMethods] },\n timestamp: Date.now(),\n };\n };\n }\n\n /**\n * Set the server adapter\n */\n setAdapter(adapter: ServerAdapter): void {\n this.adapter = adapter;\n }\n\n /**\n * Set a navigation provider for programmatic route navigation.\n * This enables `control/page/navigate` and `control/page/back` on native.\n */\n setNavigationProvider(provider: NavigationProvider): void {\n this.handlers.pageNavigate = async (ctx): Promise<APIResponse<PageNavigationResponse>> => {\n const body = ctx.body as Record<string, unknown> | undefined;\n const url = body?.url;\n if (!url || typeof url !== 'string') {\n return { success: false, error: 'Missing required \"url\" parameter', timestamp: Date.now() };\n }\n try {\n provider.navigate(url);\n return {\n success: true,\n data: { success: true, url, timestamp: Date.now() },\n timestamp: Date.now(),\n };\n } catch (e: unknown) {\n return {\n success: false,\n error: `Navigation failed: ${e instanceof Error ? e.message : String(e)}`,\n timestamp: Date.now(),\n };\n }\n };\n\n this.handlers.pageReplace = async (ctx): Promise<APIResponse<PageNavigationResponse>> => {\n if (!provider.replace) {\n return {\n success: false,\n error: 'Replace navigation not supported by navigation provider',\n timestamp: Date.now(),\n };\n }\n const body = ctx.body as Record<string, unknown> | undefined;\n const url = body?.url;\n if (!url || typeof url !== 'string') {\n return { success: false, error: 'Missing required \"url\" parameter', timestamp: Date.now() };\n }\n try {\n provider.replace(url);\n return {\n success: true,\n data: { success: true, url, timestamp: Date.now() },\n timestamp: Date.now(),\n };\n } catch (e: unknown) {\n return {\n success: false,\n error: `Replace navigation failed: ${e instanceof Error ? e.message : String(e)}`,\n timestamp: Date.now(),\n };\n }\n };\n\n this.handlers.pageGoBack = async (): Promise<APIResponse<PageNavigationResponse>> => {\n if (!provider.back) {\n return { success: false, error: 'Back navigation not supported', timestamp: Date.now() };\n }\n try {\n provider.back();\n return {\n success: true,\n data: { success: true, timestamp: Date.now() },\n timestamp: Date.now(),\n };\n } catch (e: unknown) {\n return {\n success: false,\n error: `Back navigation failed: ${e instanceof Error ? e.message : String(e)}`,\n timestamp: Date.now(),\n };\n }\n };\n\n this.handlers.pageRefresh = async (): Promise<APIResponse<PageNavigationResponse>> => {\n if (!provider.refresh) {\n return {\n success: false,\n error: 'Page refresh not supported by navigation provider',\n timestamp: Date.now(),\n };\n }\n try {\n provider.refresh();\n return {\n success: true,\n data: { success: true, timestamp: Date.now() },\n timestamp: Date.now(),\n };\n } catch (e: unknown) {\n return {\n success: false,\n error: `Refresh failed: ${e instanceof Error ? e.message : String(e)}`,\n timestamp: Date.now(),\n };\n }\n };\n }\n\n /**\n * Set a route provider for reporting the current navigation route.\n * When set, `control/snapshot` responses include `currentRoute` and\n * `segments`, plus the canonical `route` / `activeTab` aliases the web SDK's\n * `BridgeSnapshot` spells the same way.\n *\n * Also forwards the provider into the registry so the *default*\n * `getSnapshot` handler (and any other call site of\n * `registry.createSnapshot`) reads the route too — without this the\n * cloud-relay/bare-server path returned `currentRoute: null` even when\n * a `RouteTracker` was wired, because that path never installed the\n * server-level handler override below.\n */\n setRouteProvider(provider: RouteProvider): void {\n this.registry.setRouteProvider(provider);\n // Override getElements to support currentRouteOnly filtering with real route data\n const baseGetElements = this.handlers.getElements;\n this.handlers.getElements = async (ctx: HandlerContext) => {\n const currentRouteOnly =\n ctx.query?.currentRouteOnly === 'true' ||\n (ctx.body as Record<string, unknown>)?.currentRouteOnly === true;\n\n // If currentRouteOnly requested and no explicit route param, inject the current route\n if (currentRouteOnly && !ctx.query?.route && !(ctx.body as Record<string, unknown>)?.route) {\n // Defensive for the same reason as `getSnapshot` below: a throwing\n // provider must degrade to \"no route filter\", not 500 the route.\n let currentRoute: string | null;\n try {\n currentRoute = provider.getCurrentRoute();\n } catch {\n currentRoute = null;\n }\n if (currentRoute) {\n // Inject route into query so the base handler can filter by it\n ctx.query = { ...ctx.query, route: currentRoute };\n }\n }\n return baseGetElements(ctx);\n };\n\n this.handlers.getSnapshot = async (ctx: HandlerContext) => {\n const visibleOnly =\n ctx?.query?.visibleOnly === 'true' ||\n (ctx?.body as Record<string, unknown>)?.visibleOnly === true;\n const currentRouteOnly =\n ctx?.query?.currentRouteOnly === 'true' ||\n (ctx?.body as Record<string, unknown>)?.currentRouteOnly === true;\n // Read the provider defensively. The registry's own fallback path wraps\n // these same calls in a try/catch and degrades to a null route; without\n // the same guard here a host whose provider throws mid-navigation turns\n // the whole `control/snapshot` response into a 500 instead of a snapshot\n // that simply does not know its route.\n //\n // THREE separate guards, not one, because the three facts fail\n // independently and `currentRoute` is load-bearing: `createSnapshot`\n // applies the `currentRouteOnly` filter only when `currentRoute` is\n // truthy, so letting an optional `getSegments()` throw discard a route we\n // successfully read would answer `?currentRouteOnly=true` with EVERY\n // registered element in the app, labelled as the current route's. That\n // turns a loud 500 into a silent wrong answer a runner would act on.\n let currentRoute: string | null;\n try {\n currentRoute = provider.getCurrentRoute() ?? null;\n } catch {\n currentRoute = null;\n }\n let segments: string[] | undefined;\n try {\n segments = provider.getSegments?.();\n } catch {\n segments = undefined;\n }\n // Passed explicitly rather than left to the registry to resolve. The\n // registry's `resolveActiveTab` reads whatever provider is registered on\n // IT, which is not necessarily this one — a host that detaches with\n // `registry.setRouteProvider(null)` (the documented HMR/teardown escape\n // hatch) would leave this closure still reporting the right `route` while\n // `activeTab` silently reverted to the segment derivation. Reading our own\n // provider keeps the emitted snapshot internally consistent.\n let activeTab: string | null | undefined;\n try {\n activeTab = provider.getActiveTab?.();\n } catch {\n activeTab = undefined;\n }\n const snapshot = this.registry.createSnapshot(\n { currentRoute, segments, activeTab },\n { visibleOnly, currentRouteOnly }\n );\n return { success: true, data: snapshot, timestamp: Date.now() };\n };\n }\n\n /**\n * Set a screenshot provider for native screen capture.\n * This enables `control/screenshot` on native.\n */\n setScreenshotProvider(provider: ScreenshotProvider): void {\n const SCREENSHOT_TIMEOUT_MS = 10_000;\n this.handlers.getScreenshot = async () => {\n try {\n const result = await Promise.race([\n provider.capture(),\n new Promise<never>((_, reject) =>\n setTimeout(\n () =>\n reject(new Error(`Screenshot capture timed out after ${SCREENSHOT_TIMEOUT_MS}ms`)),\n SCREENSHOT_TIMEOUT_MS\n )\n ),\n ]);\n return {\n success: true,\n data: { screenshot: result.base64, width: result.width, height: result.height },\n timestamp: Date.now(),\n };\n } catch (e: unknown) {\n return {\n success: false,\n error: `Screenshot capture failed: ${e instanceof Error ? e.message : String(e)}`,\n timestamp: Date.now(),\n };\n }\n };\n }\n\n /**\n * Set a keep-awake provider for native screen-wake control.\n * This enables `control/keep-awake` and arms the auto-arm hook in\n * handleRequest (every request keeps the screen alive for 60s).\n */\n setKeepAwakeProvider(provider: KeepAwakeProvider): void {\n this.keepAwakeProvider = provider;\n this.handlers.keepAwake = async (ctx) => {\n const { enabled, durationMs } = (ctx.body ?? {}) as {\n enabled?: unknown;\n durationMs?: unknown;\n };\n if (typeof enabled !== 'boolean') {\n return {\n success: false,\n error: 'enabled must be boolean',\n code: 'INVALID_REQUEST',\n timestamp: Date.now(),\n };\n }\n if (enabled) {\n provider.request('ui-bridge', typeof durationMs === 'number' ? durationMs : undefined);\n } else {\n provider.release('ui-bridge');\n }\n return {\n success: true,\n data: { enabled, durationMs: typeof durationMs === 'number' ? durationMs : null },\n timestamp: Date.now(),\n };\n };\n }\n\n /**\n * Start the HTTP server\n */\n async start(): Promise<void> {\n if (this.running) {\n console.warn('[ui-bridge-native] Server already running');\n return;\n }\n\n if (!this.adapter) {\n console.warn('[ui-bridge-native] No server adapter configured. Call setAdapter() first.');\n console.warn('[ui-bridge-native] See documentation for supported adapters.');\n return;\n }\n\n // Install observability patches before binding the port — gated behind\n // the dedicated `observability` flag, which defaults to `testHooks` so\n // existing consumers are unchanged. Decoupling the two lets release\n // builds capture console/network evidence without also exposing the\n // testHooks-gated control surface (`control/modal/*` etc.).\n if (this.observabilityEnabled()) {\n this.consoleErrorBuffer.install();\n this.networkRequestBuffer.install();\n }\n\n await this.adapter.start(this.config.serverPort!, this.handleRequest.bind(this));\n this.running = true;\n\n console.log(`[ui-bridge-native] HTTP server started on port ${this.config.serverPort}`);\n }\n\n /**\n * Stop the HTTP server\n */\n async stop(): Promise<void> {\n if (!this.running || !this.adapter) {\n return;\n }\n\n await this.adapter.stop();\n this.running = false;\n\n // Restore the original globals; idempotent if never installed.\n this.consoleErrorBuffer.uninstall();\n this.networkRequestBuffer.uninstall();\n\n console.log('[ui-bridge-native] HTTP server stopped');\n }\n\n /**\n * Check if server is running\n */\n isRunning(): boolean {\n return this.running;\n }\n\n // ── WebSocket Support ───────────────────────────────────────────────────\n\n private eventBridge?: WebSocketEventBridge;\n\n /**\n * Set the event bridge for WebSocket event broadcasting and subscriptions.\n */\n setEventBridge(bridge: WebSocketEventBridge): void {\n this.eventBridge = bridge;\n }\n\n /**\n * Handle a JSON-RPC message from a WebSocket client.\n * Parses the message, routes to the appropriate handler, and returns\n * a JSON string response (or null for events that need no response).\n */\n async handleWebSocketMessage(connId: string, rawMessage: string): Promise<string | null> {\n let msg: unknown;\n try {\n msg = JSON.parse(rawMessage);\n } catch {\n return JSON.stringify({\n error: 'Invalid JSON',\n timestamp: Date.now(),\n });\n }\n\n if (typeof msg !== 'object' || msg === null) {\n return JSON.stringify({\n error: 'Message must be a JSON object',\n timestamp: Date.now(),\n });\n }\n\n const message = msg as Record<string, unknown>;\n const id = (message.id as string | number | undefined) ?? 0;\n\n // Handle batch requests\n if (isBatchRequest(message)) {\n const results = await this.handleBatchRequest(message.batch);\n return JSON.stringify({ id, results });\n }\n\n // Handle subscribe\n if (isSubscribe(message)) {\n const events = message.params?.events || [];\n const throttleMs = message.params?.throttleMs;\n const ok = this.eventBridge?.handleSubscribe(connId, events, throttleMs) ?? false;\n return JSON.stringify({\n id,\n result: {\n success: ok,\n data: { subscribed: events },\n timestamp: Date.now(),\n },\n } satisfies JsonRpcResponse);\n }\n\n // Handle unsubscribe\n if (isUnsubscribe(message)) {\n const events = message.params?.events || [];\n const ok = this.eventBridge?.handleUnsubscribe(connId, events) ?? false;\n return JSON.stringify({\n id,\n result: {\n success: ok,\n data: { unsubscribed: events },\n timestamp: Date.now(),\n },\n } satisfies JsonRpcResponse);\n }\n\n const method = message.method as string;\n const params = (message.params || {}) as Record<string, unknown>;\n\n // ── Connection-aware special methods ──────────────────────────────────\n\n // subscriptions/list — return current subscriptions + throttle for this connection\n if (method === 'subscriptions/list') {\n const events = this.eventBridge?.getSubscriptions(connId) ?? [];\n const throttleMs = this.eventBridge?.getThrottleMs(connId);\n return JSON.stringify({\n id,\n result: {\n success: true,\n data: { events, throttleMs: throttleMs ?? null },\n timestamp: Date.now(),\n },\n } satisfies JsonRpcResponse);\n }\n\n // waitForElement — resolve when element is registered, or timeout\n if (method === 'waitForElement') {\n return this.handleWaitForElement(connId, id, params);\n }\n\n // waitForCondition — resolve when an element state predicate becomes true\n if (method === 'waitForCondition') {\n return this.handleWaitForCondition(connId, id, params);\n }\n\n // sequence — execute steps in order, stop on first failure\n if (method === 'sequence') {\n return this.handleSequence(id, params);\n }\n\n // events/history — replay recent events matching optional filter\n if (method === 'events/history') {\n const eventsFilter = Array.isArray(params.events) ? (params.events as string[]) : undefined;\n const since = typeof params.since === 'number' ? params.since : undefined;\n const limit = typeof params.limit === 'number' ? params.limit : undefined;\n const history = this.eventBridge?.getHistory({ events: eventsFilter, since }) ?? [];\n const sliced =\n limit !== undefined && limit > 0 && history.length > limit\n ? history.slice(history.length - limit)\n : history;\n return JSON.stringify({\n id,\n result: {\n success: true,\n data: { events: sliced },\n timestamp: Date.now(),\n },\n } satisfies JsonRpcResponse);\n }\n\n // Standard JSON-RPC request\n\n if (!method) {\n return JSON.stringify({\n id,\n result: {\n success: false,\n error: 'Missing \"method\" field',\n code: 'INVALID_REQUEST',\n timestamp: Date.now(),\n },\n } satisfies JsonRpcResponse);\n }\n\n try {\n const apiResponse = await this.routeMethodToHandler(method, params);\n return JSON.stringify({ id, result: apiResponse } satisfies JsonRpcResponse);\n } catch (error) {\n return JSON.stringify({\n id,\n result: {\n success: false,\n error: error instanceof Error ? error.message : 'Internal error',\n code: 'INTERNAL_ERROR',\n timestamp: Date.now(),\n },\n } satisfies JsonRpcResponse);\n }\n }\n\n /**\n * Execute a batch of JSON-RPC requests concurrently.\n */\n async handleBatchRequest(batch: JsonRpcRequest[]): Promise<JsonRpcResponse[]> {\n return Promise.all(\n batch.map(async (req) => {\n try {\n const result = await this.routeMethodToHandler(\n req.method,\n (req.params || {}) as Record<string, unknown>\n );\n return { id: req.id, result } as JsonRpcResponse;\n } catch (error) {\n return {\n id: req.id,\n result: {\n success: false,\n error: error instanceof Error ? error.message : 'Internal error',\n code: 'INTERNAL_ERROR',\n timestamp: Date.now(),\n },\n } satisfies JsonRpcResponse;\n }\n })\n );\n }\n\n /**\n * Register an in-flight waiter's cleanup thunk under the given connection.\n * Returns an `unregister` thunk that the natural-resolution path should\n * call so the cleanup isn't re-invoked on disconnect.\n */\n private registerWaiter(connId: string, cleanup: () => void): () => void {\n let set = this.pendingWaiters.get(connId);\n if (!set) {\n set = new Set();\n this.pendingWaiters.set(connId, set);\n }\n set.add(cleanup);\n return () => {\n const s = this.pendingWaiters.get(connId);\n if (!s) return;\n s.delete(cleanup);\n if (s.size === 0) this.pendingWaiters.delete(connId);\n };\n }\n\n /**\n * Abort all pending waiters associated with a connection. Called by the\n * provider's WS disconnect handler so timers/listeners don't leak after\n * the client goes away.\n */\n abortWaitersForConnection(connId: string): void {\n const set = this.pendingWaiters.get(connId);\n if (!set) return;\n for (const cleanup of set) {\n try {\n cleanup();\n } catch (err) {\n console.warn('[ui-bridge-native] waiter cleanup threw:', err);\n }\n }\n this.pendingWaiters.delete(connId);\n }\n\n /**\n * Wait for an element to be registered, or resolve immediately if it already exists.\n * Returns a JsonRpcResponse JSON string.\n */\n private async handleWaitForElement(\n connId: string,\n id: string | number,\n params: Record<string, unknown>\n ): Promise<string> {\n const targetId = params.id;\n const timeout = typeof params.timeout === 'number' ? params.timeout : 10000;\n\n if (!targetId || typeof targetId !== 'string') {\n return JSON.stringify({\n id,\n result: {\n success: false,\n error: 'Missing or invalid \"id\" parameter',\n code: 'INVALID_REQUEST',\n timestamp: Date.now(),\n },\n } satisfies JsonRpcResponse);\n }\n\n // Already registered — return immediately\n const existing = this.registry.getElement(targetId);\n if (existing) {\n return JSON.stringify({\n id,\n result: {\n success: true,\n data: {\n id: targetId,\n state: existing.getState(),\n identifier: existing.getIdentifier(),\n waited: false,\n },\n timestamp: Date.now(),\n },\n } satisfies JsonRpcResponse);\n }\n\n // Wait for element:registered event with matching id, or timeout\n return new Promise<string>((resolve) => {\n let settled = false;\n let unsub: (() => void) | null = null;\n let timer: ReturnType<typeof setTimeout> | null = null;\n let unregister: (() => void) | null = null;\n\n const cleanup = () => {\n if (settled) return;\n settled = true;\n if (unsub) {\n unsub();\n unsub = null;\n }\n if (timer) {\n clearTimeout(timer);\n timer = null;\n }\n if (unregister) {\n unregister();\n unregister = null;\n }\n };\n\n // Track this waiter so it can be aborted if the connection closes.\n unregister = this.registerWaiter(connId, () => {\n cleanup();\n resolve(\n JSON.stringify({\n id,\n result: {\n success: false,\n error: 'Connection closed before element was registered',\n code: 'CONNECTION_CLOSED',\n timestamp: Date.now(),\n },\n } satisfies JsonRpcResponse)\n );\n });\n\n unsub = this.registry.on('element:registered', (event: BridgeEvent) => {\n if (settled) return;\n const data = event.data as { id?: string } | undefined;\n if (data?.id !== targetId) return;\n\n cleanup();\n const el = this.registry.getElement(targetId);\n resolve(\n JSON.stringify({\n id,\n result: {\n success: true,\n data: {\n id: targetId,\n state: el?.getState() ?? null,\n identifier: el?.getIdentifier() ?? null,\n waited: true,\n },\n timestamp: Date.now(),\n },\n } satisfies JsonRpcResponse)\n );\n });\n\n timer = setTimeout(() => {\n if (settled) return;\n cleanup();\n resolve(\n JSON.stringify({\n id,\n result: {\n success: false,\n error: `Timeout waiting for element: ${targetId}`,\n code: 'TIMEOUT',\n timestamp: Date.now(),\n },\n } satisfies JsonRpcResponse)\n );\n }, timeout);\n });\n }\n\n /**\n * Wait for an arbitrary element-state predicate to become true.\n *\n * Supported `condition` shapes:\n * {field: \"mounted\"|\"visible\"|\"enabled\"|\"focused\", equals: boolean}\n * {field: \"layout\", exists: true}\n * {field: string, equals: unknown} // generic: state[field] === equals\n *\n * Resolves immediately with `waited:false` if the predicate already\n * holds. Otherwise subscribes to `element:registered` and\n * `element:stateChanged` until the predicate matches or timeout fires.\n */\n private async handleWaitForCondition(\n connId: string,\n id: string | number,\n params: Record<string, unknown>\n ): Promise<string> {\n const targetId = params.elementId;\n const condition = params.condition as\n | { field?: string; equals?: unknown; exists?: boolean }\n | undefined;\n const timeout = typeof params.timeout === 'number' ? params.timeout : 10000;\n\n if (!targetId || typeof targetId !== 'string') {\n return JSON.stringify({\n id,\n result: {\n success: false,\n error: 'Missing or invalid \"elementId\" parameter',\n code: 'INVALID_REQUEST',\n timestamp: Date.now(),\n },\n } satisfies JsonRpcResponse);\n }\n if (!condition || typeof condition.field !== 'string') {\n return JSON.stringify({\n id,\n result: {\n success: false,\n error: 'Missing or invalid \"condition.field\"',\n code: 'INVALID_REQUEST',\n timestamp: Date.now(),\n },\n } satisfies JsonRpcResponse);\n }\n\n const evaluate = (state: Record<string, unknown> | null | undefined): boolean => {\n if (!state) return false;\n const value = state[condition.field as string];\n if (condition.exists === true) return value !== null && value !== undefined;\n if ('equals' in condition) return value === condition.equals;\n return false;\n };\n\n const makeResult = (state: Record<string, unknown> | null, waited: boolean) =>\n JSON.stringify({\n id,\n result: {\n success: true,\n data: { id: targetId, state, waited },\n timestamp: Date.now(),\n },\n } satisfies JsonRpcResponse);\n\n // Fast path: already holds.\n const existing = this.registry.getElement(targetId);\n if (existing) {\n const state = existing.getState() as unknown as Record<string, unknown> | null;\n if (evaluate(state)) {\n return makeResult(state, false);\n }\n }\n\n return new Promise<string>((resolve) => {\n let settled = false;\n let unsubRegistered: (() => void) | null = null;\n let unsubStateChanged: (() => void) | null = null;\n let timer: ReturnType<typeof setTimeout> | null = null;\n let unregister: (() => void) | null = null;\n\n const cleanup = () => {\n if (settled) return;\n settled = true;\n if (unsubRegistered) {\n unsubRegistered();\n unsubRegistered = null;\n }\n if (unsubStateChanged) {\n unsubStateChanged();\n unsubStateChanged = null;\n }\n if (timer) {\n clearTimeout(timer);\n timer = null;\n }\n if (unregister) {\n unregister();\n unregister = null;\n }\n };\n\n unregister = this.registerWaiter(connId, () => {\n cleanup();\n resolve(\n JSON.stringify({\n id,\n result: {\n success: false,\n error: 'Connection closed before condition was met',\n code: 'CONNECTION_CLOSED',\n timestamp: Date.now(),\n },\n } satisfies JsonRpcResponse)\n );\n });\n\n const checkAndResolve = () => {\n if (settled) return;\n const el = this.registry.getElement(targetId);\n if (!el) return;\n const state = el.getState() as unknown as Record<string, unknown> | null;\n if (evaluate(state)) {\n cleanup();\n resolve(makeResult(state, true));\n }\n };\n\n unsubRegistered = this.registry.on('element:registered', (event: BridgeEvent) => {\n if (settled) return;\n const data = event.data as { id?: string } | undefined;\n if (data?.id !== targetId) return;\n checkAndResolve();\n });\n\n unsubStateChanged = this.registry.on('element:stateChanged', (event: BridgeEvent) => {\n if (settled) return;\n const data = event.data as { id?: string } | undefined;\n if (data?.id !== targetId) return;\n checkAndResolve();\n });\n\n timer = setTimeout(() => {\n if (settled) return;\n cleanup();\n resolve(\n JSON.stringify({\n id,\n result: {\n success: false,\n error: `Timeout waiting for condition on element: ${targetId}`,\n code: 'TIMEOUT',\n timestamp: Date.now(),\n },\n } satisfies JsonRpcResponse)\n );\n }, timeout);\n });\n }\n\n /**\n * Execute a sequence of JSON-RPC steps in order, stopping on first failure.\n * Returns a JsonRpcResponse JSON string with per-step results.\n */\n private async handleSequence(\n id: string | number,\n params: Record<string, unknown>\n ): Promise<string> {\n const rawSteps = params.steps;\n\n if (!Array.isArray(rawSteps) || rawSteps.length === 0) {\n return JSON.stringify({\n id,\n result: {\n success: false,\n error: 'Missing or empty \"steps\" array',\n code: 'INVALID_REQUEST',\n timestamp: Date.now(),\n },\n } satisfies JsonRpcResponse);\n }\n\n const steps = rawSteps as Array<{ method: string; params?: Record<string, unknown> }>;\n const results: Array<{ step: number; method: string; result: APIResponse }> = [];\n let allSuccess = true;\n\n for (let i = 0; i < steps.length; i++) {\n const step = steps[i];\n\n if (!step || typeof step.method !== 'string') {\n results.push({\n step: i,\n method: String(step?.method ?? ''),\n result: {\n success: false,\n error: 'Step is missing \"method\" field',\n code: 'INVALID_REQUEST',\n timestamp: Date.now(),\n },\n });\n allSuccess = false;\n break;\n }\n\n try {\n const stepResult = await this.routeMethodToHandler(step.method, step.params ?? {});\n results.push({ step: i, method: step.method, result: stepResult });\n if (!stepResult.success) {\n allSuccess = false;\n break;\n }\n } catch (err) {\n results.push({\n step: i,\n method: step.method,\n result: {\n success: false,\n error: err instanceof Error ? err.message : 'Step execution failed',\n code: 'STEP_FAILED',\n timestamp: Date.now(),\n },\n });\n allSuccess = false;\n break;\n }\n }\n\n return JSON.stringify({\n id,\n result: {\n success: allSuccess,\n data: {\n completedSteps: results.length,\n totalSteps: steps.length,\n results,\n },\n timestamp: Date.now(),\n },\n } satisfies JsonRpcResponse);\n }\n\n /**\n * Route a JSON-RPC method string to the appropriate handler using path-style matching.\n *\n * Method strings mirror HTTP routes but without the /ui-bridge/ prefix.\n * Path params are extracted from :name placeholders in the route pattern.\n *\n * Examples:\n * \"health\" → handlers.health\n * \"control/snapshot\" → handlers.getSnapshot\n * \"control/element/tab-runs/action\" → handlers.executeAction ({id:'tab-runs'})\n * \"control/component/my-comp/action/submit\" → handlers.executeComponentAction\n */\n private async routeMethodToHandler(\n method: string,\n params: Record<string, unknown>\n ): Promise<APIResponse> {\n const testHooks = this.config.testHooks === true;\n for (const route of WS_ROUTES) {\n const pathParams = parsePath(route.pattern, method);\n if (!pathParams) continue;\n\n // Test-hook routes are invisible over WS too when the flag is off.\n if (route.requiresTestHooks && !testHooks) continue;\n\n const ctx: HandlerContext = {\n params: pathParams,\n query:\n params.query && typeof params.query === 'object'\n ? (params.query as Record<string, string>)\n : {},\n body: params,\n };\n\n return this.handlers[route.handler](ctx);\n }\n\n return {\n success: false,\n error: `Unknown method: ${method}`,\n code: 'NOT_FOUND',\n timestamp: Date.now(),\n };\n }\n\n /**\n * Handle incoming HTTP request\n *\n * Exposed as public so that CloudRelayClient can call it directly (without\n * loopback TCP overhead) when processing tunneled requests.\n */\n async handleRequest(request: HTTPRequest): Promise<HTTPResponse> {\n // Add CORS headers if enabled\n const headers: Record<string, string> = {\n 'Content-Type': 'application/json',\n };\n\n if (this.config.cors) {\n headers['Access-Control-Allow-Origin'] = this.config.allowedOrigins\n ? this.config.allowedOrigins.join(',')\n : '*';\n headers['Access-Control-Allow-Methods'] = 'GET, POST, PUT, DELETE, OPTIONS';\n headers['Access-Control-Allow-Headers'] = 'Content-Type, Authorization';\n }\n\n // Handle CORS preflight\n if (request.method === 'OPTIONS') {\n return { status: 204, headers, body: '' };\n }\n\n // Auto-arm: when test hooks are enabled and a keep-awake provider is\n // wired, every incoming request keeps the screen alive for 60s so an\n // external runner driving the device never loses it to a screen lock.\n // Best-effort — must never throw and break the request. This is the\n // single chokepoint for HTTP, WS-tunnelled, and cloud-relay paths\n // (CloudRelayClient calls handleRequest directly).\n if (this.config.testHooks === true && this.keepAwakeProvider) {\n try {\n this.keepAwakeProvider.request('auto-arm', 60_000);\n } catch {\n /* keep-awake is best-effort; never break a request */\n }\n }\n\n try {\n const response = await this.routeRequest(request);\n // A 405 must name the verbs that ARE accepted, or the caller is left\n // guessing exactly as it was under the blanket 400. `Allow` is not a\n // CORS-safelisted response header, so without `Access-Control-Expose-\n // Headers` a cross-origin browser caller — a web page or a browser-based\n // agent — reads `null` from it and gets nothing from this at all.\n if (response.code === 'METHOD_NOT_ALLOWED') {\n const allow = allowedMethodsForPath(request.path, this.config.testHooks === true);\n if (allow.length > 0) {\n headers['Allow'] = allow.join(', ');\n if (this.config.cors) headers['Access-Control-Expose-Headers'] = 'Allow';\n }\n }\n return {\n status: httpStatusForResponse(response),\n headers,\n body: JSON.stringify(response),\n };\n } catch (error) {\n const errorResponse: APIResponse = {\n success: false,\n error: error instanceof Error ? error.message : 'Internal server error',\n code: 'INTERNAL_ERROR',\n timestamp: Date.now(),\n };\n return {\n status: 500,\n headers,\n body: JSON.stringify(errorResponse),\n };\n }\n }\n\n /**\n * Route an HTTP request to the appropriate handler using WS_ROUTES.\n *\n * Strips the `/ui-bridge/` prefix from the path, then iterates the shared\n * WS_ROUTES table. Each route's `pattern` is matched against the stripped\n * path via the module-level `parsePath` helper; path params are merged\n * with the request body into a HandlerContext.\n *\n * `httpMethods` disambiguates routes that share a pattern but differ\n * by verb (e.g. GET vs DELETE on `design/style-guide`). A route without\n * `httpMethods` is WS-only and will not be matched on HTTP.\n */\n private async routeRequest(request: HTTPRequest): Promise<APIResponse> {\n const { method, path, query, body } = request;\n\n const PREFIX = '/ui-bridge/';\n if (!path.startsWith(PREFIX)) {\n return {\n success: false,\n error: `Route not found: ${method} ${path}`,\n code: 'NOT_FOUND',\n timestamp: Date.now(),\n };\n }\n\n const stripped = path.slice(PREFIX.length);\n\n // Discoverability:\n // - `_help` (rich) — routes + action reference + tips\n // - `_routes` (minimal) — runner-compatible shape for parity\n // Lets agents fetch a single URL on either runner or mobile to see what\n // they can do without reading docs.\n const testHooks = this.config.testHooks === true;\n\n if (method === 'GET' && stripped === '_help') {\n return {\n success: true,\n data: buildHelpPayload(testHooks),\n timestamp: Date.now(),\n };\n }\n if (method === 'GET' && stripped === '_routes') {\n return {\n success: true,\n data: buildRoutesPayload(testHooks),\n timestamp: Date.now(),\n };\n }\n\n // Reaching here with a discovery path means the PATH was right and the VERB\n // was not — the two branches above are the only ones that serve them, and\n // both are GET-only. They live outside `WS_ROUTES` (there is no handler to\n // dispatch to), so the loop below cannot notice them, and `POST\n // /ui-bridge/_routes` used to answer \"no such route\" about a route\n // `buildRoutesPayload` publishes one line up. Seeding the flag here keeps\n // \"wrong verb on a path we publish → 405\" true for every entry in\n // `UI_BRIDGE_NATIVE_ROUTES`, including these two.\n let patternMatchedButWrongVerb = DISCOVERY_PATHS.has(stripped);\n\n for (const route of WS_ROUTES) {\n const pathParams = parsePath(route.pattern, stripped);\n if (!pathParams) continue;\n\n // Pattern matches — now filter on HTTP verb.\n if (!route.httpMethods) {\n // WS-only route; don't serve on HTTP.\n continue;\n }\n // Route gated by `testHooks`: behave as if it isn't registered when\n // the flag is off so production builds get a vanilla NOT_FOUND.\n if (route.requiresTestHooks && !testHooks) {\n continue;\n }\n if (!route.httpMethods.includes(method as HttpVerb)) {\n patternMatchedButWrongVerb = true;\n continue;\n }\n\n const ctx: HandlerContext = { params: pathParams, query, body };\n return this.handlers[route.handler](ctx);\n }\n\n // The verbs go in the ENVELOPE as well as the `Allow` header, because\n // almost nothing in this tree reads headers: `CloudRelayClient` relays the\n // whole response, but the skills, the cheatsheets and every documented\n // probe read the JSON body (`curl … | jq .error`). A caller doing that saw\n // \"Method not allowed: POST /ui-bridge/health\" and still had to guess.\n const allowed = patternMatchedButWrongVerb\n ? allowedMethodsForPath(path, testHooks)\n : ([] as string[]);\n\n return {\n success: false,\n error: patternMatchedButWrongVerb\n ? `Method not allowed: ${method} ${path}${\n allowed.length > 0 ? ` (allowed: ${allowed.join(', ')})` : ''\n }`\n : `Route not found: ${method} ${path}`,\n code: patternMatchedButWrongVerb ? 'METHOD_NOT_ALLOWED' : 'NOT_FOUND',\n timestamp: Date.now(),\n };\n }\n}\n\n/**\n * Create a UI Bridge Native server\n */\nexport function createNativeServer(\n registry: NativeUIBridgeRegistry,\n executor: NativeActionExecutor,\n config?: NativeServerConfig\n): NativeUIBridgeServer {\n return new NativeUIBridgeServer(registry, executor, config);\n}\n\n/**\n * Example adapter using react-native-http-bridge\n *\n * To use this adapter:\n * 1. Install: npm install react-native-http-bridge\n * 2. Link native modules\n * 3. Create adapter and pass to server\n *\n * ```tsx\n * import httpBridge from 'react-native-http-bridge';\n *\n * const adapter: ServerAdapter = {\n * start: async (port, handler) => {\n * httpBridge.start(port, 'ui-bridge', async (request) => {\n * const response = await handler({\n * method: request.type,\n * path: request.url,\n * headers: request.headers || {},\n * query: parseQuery(request.url),\n * body: request.postData ? JSON.parse(request.postData) : undefined,\n * });\n * httpBridge.respond(\n * request.requestId,\n * response.status,\n * response.headers['Content-Type'],\n * response.body\n * );\n * });\n * },\n * stop: async () => {\n * httpBridge.stop();\n * },\n * isRunning: () => true,\n * };\n *\n * server.setAdapter(adapter);\n * await server.start();\n * ```\n */\n","/**\n * Bridges NativeUIBridgeRegistry events to WebSocket clients.\n *\n * Subscribes to all registry event types and broadcasts them as\n * JsonRpcEvent messages to connected WebSocket clients based on\n * their per-connection subscription sets.\n */\n\nimport type { NativeUIBridgeRegistry } from '../core/registry';\nimport type { BridgeEventType, BridgeEvent } from '../core/types';\nimport type { WebSocketConnection } from './ws-connection';\nimport type { JsonRpcEvent } from './ws-types';\n\n/** All event types the bridge can subscribe to */\nconst BRIDGE_EVENT_TYPES: BridgeEventType[] = [\n 'element:registered',\n 'element:unregistered',\n 'element:stateChanged',\n 'component:registered',\n 'component:unregistered',\n 'action:started',\n 'action:completed',\n 'action:failed',\n 'workflow:started',\n 'workflow:stepCompleted',\n 'workflow:completed',\n 'workflow:failed',\n 'render:snapshot',\n 'error',\n];\n\n/** Per-connection throttle state for batching rapid events */\ninterface ThrottleState {\n ms: number;\n pending: JsonRpcEvent[];\n timer: ReturnType<typeof setTimeout> | null;\n}\n\n// ── Glob pattern matching ───────────────────────────────────────────────────\n\n/** Cache of compiled glob→RegExp to avoid recompiling hot patterns. */\nconst GLOB_CACHE = new Map<string, RegExp>();\n\n/**\n * Convert a glob-style pattern (supports `*` / `**` wildcards) to a RegExp.\n * All other regex metacharacters are escaped, so colons and other\n * event-name characters pass through literally.\n *\n * globToRegex(\"*\") → /^.*$/\n * globToRegex(\"element:*\") → /^element:.*$/\n * globToRegex(\"*:stateChanged\") → /^.*:stateChanged$/\n */\nexport function globToRegex(pattern: string): RegExp {\n const cached = GLOB_CACHE.get(pattern);\n if (cached) return cached;\n\n // Normalize ** → * (same semantics for flat event names)\n const normalized = pattern.replace(/\\*\\*/g, '*');\n // Escape regex metacharacters except '*'\n const escaped = normalized.replace(/[.+?^${}()|[\\]\\\\]/g, '\\\\$&');\n // Replace '*' with '.*'\n const body = escaped.replace(/\\*/g, '.*');\n const regex = new RegExp(`^${body}$`);\n GLOB_CACHE.set(pattern, regex);\n return regex;\n}\n\n/** Options for the WebSocketEventBridge constructor. */\nexport interface WebSocketEventBridgeOptions {\n /** Heartbeat ping interval in ms (default 30000) */\n heartbeatIntervalMs?: number;\n /** Max number of events to retain in the replay history buffer (default 100, 0 disables) */\n maxHistory?: number;\n}\n\nexport class WebSocketEventBridge {\n private connections = new Map<string, WebSocketConnection>();\n private throttles = new Map<string, ThrottleState>();\n private unsubscribers: Array<() => void> = [];\n private heartbeatTimer: ReturnType<typeof setInterval> | null = null;\n private registry: NativeUIBridgeRegistry;\n private heartbeatIntervalMs: number;\n /**\n * True ring buffer for event replay history.\n *\n * `historyBuf` is a fixed-capacity slot array; `historyHead` points at the\n * NEXT write position; `historyCount` is the number of valid slots\n * (clamped to capacity). Append is O(1) — no array shifting.\n */\n private historyBuf: (JsonRpcEvent | undefined)[] = [];\n private historyHead = 0;\n private historyCount = 0;\n\n constructor(\n registry: NativeUIBridgeRegistry,\n optionsOrHeartbeatMs: WebSocketEventBridgeOptions | number = {}\n ) {\n this.registry = registry;\n // Accept legacy positional number form\n const opts: WebSocketEventBridgeOptions =\n typeof optionsOrHeartbeatMs === 'number'\n ? { heartbeatIntervalMs: optionsOrHeartbeatMs }\n : optionsOrHeartbeatMs;\n this.heartbeatIntervalMs = opts.heartbeatIntervalMs ?? 30000;\n const cap = Math.max(0, (opts.maxHistory ?? 100) | 0);\n this.historyBuf = cap > 0 ? new Array(cap) : [];\n }\n\n /** Effective ring buffer capacity. 0 means history is disabled. */\n private get historyCapacity(): number {\n return this.historyBuf.length;\n }\n\n /**\n * Start listening to registry events and broadcasting to WS clients.\n * Also starts the heartbeat timer.\n */\n start(): void {\n for (const eventType of BRIDGE_EVENT_TYPES) {\n const unsub = this.registry.on(eventType, (event: BridgeEvent) => {\n this.broadcastEvent(eventType, event.data);\n });\n this.unsubscribers.push(unsub);\n }\n\n this.startHeartbeat();\n }\n\n /** Stop listening to registry events and clear connections. */\n stop(): void {\n for (const unsub of this.unsubscribers) {\n unsub();\n }\n this.unsubscribers = [];\n\n if (this.heartbeatTimer) {\n clearInterval(this.heartbeatTimer);\n this.heartbeatTimer = null;\n }\n\n // Clean up throttle timers\n for (const throttle of this.throttles.values()) {\n if (throttle.timer) clearTimeout(throttle.timer);\n }\n this.throttles.clear();\n\n // Close all connections\n for (const conn of this.connections.values()) {\n conn.close(1001, 'Server shutting down');\n }\n this.connections.clear();\n this.historyBuf.fill(undefined);\n this.historyHead = 0;\n this.historyCount = 0;\n }\n\n /** Register a new WebSocket connection. */\n addConnection(conn: WebSocketConnection): void {\n this.connections.set(conn.id, conn);\n }\n\n /** Remove a WebSocket connection (called on disconnect). */\n removeConnection(connId: string): void {\n this.connections.delete(connId);\n const throttle = this.throttles.get(connId);\n if (throttle?.timer) clearTimeout(throttle.timer);\n this.throttles.delete(connId);\n }\n\n /** Get the number of active connections. */\n get connectionCount(): number {\n return this.connections.size;\n }\n\n /**\n * Add event subscriptions for a connection.\n *\n * Event names are stored as glob patterns. Supported forms:\n * - Exact: \"element:registered\"\n * - Prefix: \"element:*\"\n * - Suffix: \"*:stateChanged\"\n * - All: \"*\"\n *\n * @param throttleMs — if >0, batch rapid events within this window before sending\n */\n handleSubscribe(connId: string, events: string[], throttleMs?: number): boolean {\n const conn = this.connections.get(connId);\n if (!conn) return false;\n for (const event of events) {\n conn.subscriptions.add(event);\n }\n if (throttleMs && throttleMs > 0) {\n this.throttles.set(connId, { ms: throttleMs, pending: [], timer: null });\n }\n return true;\n }\n\n /**\n * Remove event subscriptions for a connection.\n * If all subscriptions are cleared, also drops the throttle entry\n * (and any pending flush timer) so a subsequent resubscribe starts clean.\n */\n handleUnsubscribe(connId: string, events: string[]): boolean {\n const conn = this.connections.get(connId);\n if (!conn) return false;\n for (const event of events) {\n conn.subscriptions.delete(event);\n }\n if (conn.subscriptions.size === 0) {\n const throttle = this.throttles.get(connId);\n if (throttle?.timer) clearTimeout(throttle.timer);\n this.throttles.delete(connId);\n }\n return true;\n }\n\n /**\n * Get the subscription set for a connection.\n * Returns the original pattern strings (not compiled regexes).\n */\n getSubscriptions(connId: string): string[] {\n const conn = this.connections.get(connId);\n return conn ? Array.from(conn.subscriptions) : [];\n }\n\n /**\n * Check if a connection is subscribed to a specific event.\n * Matches exact names first (fast path), then tests each stored\n * pattern as a glob against the event type.\n */\n isSubscribed(connId: string, eventType: string): boolean {\n const conn = this.connections.get(connId);\n if (!conn) return false;\n // Fast path: exact match\n if (conn.subscriptions.has(eventType)) return true;\n // Glob path: test each pattern\n for (const pattern of conn.subscriptions) {\n // Skip exact names with no wildcard — already tested above\n if (!pattern.includes('*')) continue;\n if (globToRegex(pattern).test(eventType)) return true;\n }\n return false;\n }\n\n /** Get the throttle window (in ms) configured for a connection, or undefined if none. */\n getThrottleMs(connId: string): number | undefined {\n return this.throttles.get(connId)?.ms;\n }\n\n /**\n * Get recent events from the replay history buffer.\n *\n * @param filter.events — optional list of glob patterns to match event types against\n * @param filter.since — optional timestamp (ms); only events at or after this time\n */\n getHistory(filter?: { events?: string[]; since?: number }): JsonRpcEvent[] {\n const cap = this.historyCapacity;\n if (cap === 0 || this.historyCount === 0) return [];\n\n const since = filter?.since;\n const regexes = filter?.events?.map((p) => globToRegex(p));\n\n // Walk the ring buffer in chronological (oldest → newest) order.\n const start = (this.historyHead - this.historyCount + cap) % cap;\n const out: JsonRpcEvent[] = [];\n for (let i = 0; i < this.historyCount; i++) {\n const e = this.historyBuf[(start + i) % cap];\n if (!e) continue;\n if (since !== undefined && e.timestamp < since) continue;\n if (regexes && regexes.length > 0 && !regexes.some((r) => r.test(e.event))) continue;\n out.push(e);\n }\n return out;\n }\n\n /**\n * Configure the max history buffer size at runtime. 0 disables history.\n * Reallocates the ring buffer, preserving the most recent\n * min(historyCount, newCapacity) events in chronological order.\n */\n setMaxHistory(maxHistory: number): void {\n const newCap = Math.max(0, maxHistory | 0);\n if (newCap === this.historyCapacity) return;\n\n if (newCap === 0) {\n this.historyBuf = [];\n this.historyHead = 0;\n this.historyCount = 0;\n return;\n }\n\n // Preserve the latest min(count, newCap) events.\n const oldCap = this.historyCapacity;\n const keep = Math.min(this.historyCount, newCap);\n const newBuf: (JsonRpcEvent | undefined)[] = new Array(newCap);\n if (keep > 0 && oldCap > 0) {\n // Source range: the last `keep` events ending just before historyHead.\n const start = (this.historyHead - keep + oldCap) % oldCap;\n for (let i = 0; i < keep; i++) {\n newBuf[i] = this.historyBuf[(start + i) % oldCap];\n }\n }\n this.historyBuf = newBuf;\n this.historyCount = keep;\n this.historyHead = keep % newCap;\n }\n\n // ── Internal ────────────────────────────────────────────────────────────\n\n private broadcastEvent(eventType: string, data: unknown): void {\n const event: JsonRpcEvent = {\n event: eventType,\n data,\n timestamp: Date.now(),\n };\n\n // Append to ring buffer — O(1), no shifting.\n const cap = this.historyCapacity;\n if (cap > 0) {\n this.historyBuf[this.historyHead] = event;\n this.historyHead = (this.historyHead + 1) % cap;\n if (this.historyCount < cap) this.historyCount++;\n }\n\n for (const [connId, conn] of this.connections) {\n const throttle = this.throttles.get(connId);\n if (throttle) {\n this.enqueueThrottled(connId, conn, throttle, event);\n } else {\n conn.sendEvent(event);\n }\n }\n }\n\n /** Queue an event for throttled delivery, flushing after the throttle window. */\n private enqueueThrottled(\n connId: string,\n conn: WebSocketConnection,\n throttle: ThrottleState,\n event: JsonRpcEvent\n ): void {\n throttle.pending.push(event);\n if (throttle.timer) return; // Flush already scheduled\n\n throttle.timer = setTimeout(() => {\n const events = throttle.pending.splice(0);\n throttle.timer = null;\n // Verify connection still exists\n if (!this.connections.has(connId)) return;\n for (const e of events) {\n conn.sendEvent(e);\n }\n }, throttle.ms);\n }\n\n private startHeartbeat(): void {\n this.heartbeatTimer = setInterval(() => {\n for (const [id, conn] of this.connections) {\n if (!conn.isOpen) {\n this.connections.delete(id);\n continue;\n }\n\n if (!conn.alive) {\n // Missed previous ping — connection is dead\n console.warn(`[ws-event-bridge] Connection ${id} missed heartbeat, closing`);\n conn.close(1001, 'Heartbeat timeout');\n this.connections.delete(id);\n continue;\n }\n\n // Mark as not-alive, send ping. If pong arrives, alive is set back to true.\n conn.alive = false;\n conn.ping();\n }\n }, this.heartbeatIntervalMs);\n }\n}\n","/**\n * Minimal logger for the UI Bridge Native transport layer.\n *\n * Wraps console so callers go through a single controlled point. Log output\n * can be suppressed globally by setting:\n *\n * import { transportLogger } from './logger';\n * transportLogger.silent = true;\n *\n * In production builds you can also tree-shake the verbose log() calls by\n * checking `__DEV__` in your Metro bundler config, but the silent flag is\n * simpler and works without build-time configuration.\n */\n\nexport interface TransportLogger {\n log(message: string, ...args: unknown[]): void;\n warn(message: string, ...args: unknown[]): void;\n error(message: string, ...args: unknown[]): void;\n /** Set to true to suppress all log output (warn/error are always emitted). */\n silent: boolean;\n}\n\nfunction createTransportLogger(): TransportLogger {\n return {\n silent: false,\n log(message: string, ...args: unknown[]): void {\n if (!this.silent) {\n console.log(message, ...args);\n }\n },\n warn(message: string, ...args: unknown[]): void {\n console.warn(message, ...args);\n },\n error(message: string, ...args: unknown[]): void {\n console.error(message, ...args);\n },\n };\n}\n\n/** Shared logger instance for the transport layer. */\nexport const transportLogger = createTransportLogger();\n","/**\n * Shared log hygiene for the two WebSocket clients that dial the cloud relay.\n *\n * `CloudRelayClient` and `DeviceAnnouncer` build the SAME URL from the SAME\n * credential — `<relayUrl>?token=<authToken>` — and both hand their diagnostics\n * to `transportLogger`, whose sink (the observability ring buffer behind\n * `GET /control/console-errors`) is readable by anything that can reach the\n * bridge. When these helpers lived as file-private functions inside\n * `CloudRelayClient`, fixing that client's token leak left the announcer's\n * identical `transportLogger.log('… connecting to', url)` untouched: one secret,\n * two sinks, one of them redacted.\n *\n * They live here so a third dialler cannot repeat that, and so the redaction\n * rule has exactly one definition to test.\n */\n\n/**\n * Query-parameter names whose VALUE is a credential and must never be logged.\n *\n * Both diallers build `<relayUrl>?token=<authToken>` today, so `token` is the\n * only name that matters right now. The rest are here because this function's\n * whole purpose is to be the one place the rule lives: a relay URL that later\n * spells the credential `access_token` or signs with `sig` would otherwise sail\n * through a redactor that everything else trusts. Over-redacting a log line\n * costs nothing; under-redacting one costs a device credential.\n */\nconst CREDENTIAL_PARAMS = ['token', 'access_token', 'auth', 'authorization', 'key', 'sig'];\n\nconst CREDENTIAL_PARAM_RE = new RegExp(`([?&](?:${CREDENTIAL_PARAMS.join('|')})=)[^&#]*`, 'gi');\n\n/** `wss://user:secret@host/…` — credentials in the URL's userinfo component. */\nconst USERINFO_RE = /^([a-z][a-z0-9+.-]*:\\/\\/)[^/?#@]*@/i;\n\n/**\n * Replace credential values in a relay URL with a marker.\n *\n * The relay URL is built as `<relayUrl>?token=<authToken>`; every log line that\n * names the target URL goes through here first so the device auth token never\n * lands in a log file, a console-error ring buffer, or a bug report.\n *\n * Redacts every {@link CREDENTIAL_PARAMS} query value plus any `user:pass@`\n * userinfo. It does NOT attempt to find secrets in a path segment or a fragment\n * — a URL that puts one there needs a different fix, not a cleverer regex.\n */\nexport function redactRelayUrl(url: string): string {\n return url.replace(USERINFO_RE, '$1<redacted>@').replace(CREDENTIAL_PARAM_RE, '$1<redacted>');\n}\n\n/**\n * Render a WebSocket close event as `code=… reason=… wasClean=…`.\n *\n * Read defensively: React Native's WebSocket delivers a plain object rather\n * than a DOM `CloseEvent`, and a missing field must read `unknown` rather than\n * silently print `undefined` as if the relay had told us something.\n *\n * The close CODE is the whole diagnosis — 1006 is \"no close frame\"\n * (network/TLS died), 1008/4001-class codes are the relay rejecting our token,\n * 1001 is the backend going away. Logging the raw event instead says nothing: a\n * DOM `CloseEvent` has no own enumerable properties, so the observability\n * capture's `JSON.stringify` renders it as `{}`.\n */\nexport function describeCloseEvent(event: unknown): string {\n const e = (event ?? {}) as { code?: unknown; reason?: unknown; wasClean?: unknown };\n const code = typeof e.code === 'number' ? String(e.code) : 'unknown';\n const reason = typeof e.reason === 'string' && e.reason.length > 0 ? e.reason : '(none)';\n const wasClean = typeof e.wasClean === 'boolean' ? String(e.wasClean) : 'unknown';\n return `code=${code} reason=${reason} wasClean=${wasClean}`;\n}\n\n/**\n * Render a WebSocket error event. React Native puts the useful text on\n * `message`; some transports also carry an `Error` on `error`, and a few\n * surface a close `code` on the error event itself.\n *\n * Same `{}`-stringification trap as {@link describeCloseEvent}.\n */\nexport function describeErrorEvent(event: unknown): string {\n const e = (event ?? {}) as { message?: unknown; error?: unknown; code?: unknown };\n const parts: string[] = [];\n if (typeof e.message === 'string' && e.message.length > 0) parts.push(`message=${e.message}`);\n if (e.error instanceof Error) parts.push(`error=${e.error.message}`);\n else if (typeof e.error === 'string' && e.error.length > 0) parts.push(`error=${e.error}`);\n if (typeof e.code === 'number') parts.push(`code=${e.code}`);\n if (parts.length === 0) parts.push('message=(none reported by the transport)');\n return parts.join(' ');\n}\n","/**\n * Device Announcer — mDNS + Cloud registration for physical device discovery\n *\n * Announces the UI Bridge service on the local network via mDNS (when\n * react-native-zeroconf is available) and optionally registers with the\n * cloud relay backend.\n */\n\nimport { Platform } from 'react-native';\nimport { transportLogger } from './logger';\nimport { describeCloseEvent, describeErrorEvent, redactRelayUrl } from './relay-logging';\n\nexport interface AnnouncerConfig {\n /** Stable device identifier */\n deviceId: string;\n /** App bundle/package ID */\n appId: string;\n /** UI Bridge server port (default 8087) */\n port?: number;\n /** Cloud relay WebSocket URL for registration */\n cloudRelayUrl?: string;\n /** Auth token for cloud relay */\n cloudToken?: string;\n /** UI Bridge SDK version */\n version?: string;\n}\n\nexport interface DeviceAnnouncerState {\n mdnsActive: boolean;\n cloudConnected: boolean;\n}\n\n/**\n * Minimal interface for the react-native-zeroconf Zeroconf instance.\n *\n * The positional `publishService` form is the one every published version\n * accepts (0.17.x keeps it as a deprecated overload beside the options object).\n * Both methods are typed `void | Promise<unknown>` because 0.17.x returns a\n * Promise that REJECTS on failure (e.g. local-network permission denied); the\n * announcer awaits it so a failure lands in its catch instead of becoming an\n * unhandled rejection with `mdnsActive` already reporting true.\n */\nexport interface ZeroconfService {\n /** `type` / `protocol` are bare (`'uibridge'`, `'tcp'`): the library adds the underscores. */\n publishService(\n type: string,\n protocol: string,\n domain: string,\n name: string,\n port: number,\n txtRecord: Record<string, string>\n ): void | Promise<unknown>;\n unpublishService(name: string): void | Promise<unknown>;\n /**\n * 0.17.x's constructor subscribes native event listeners\n * (`addDeviceListeners()`); without this call every discarded instance keeps\n * them. Optional because older versions and test fakes may not have it.\n */\n removeDeviceListeners?(): void;\n}\n\n/**\n * The name the library actually registered. 0.17.x resolves `publishService`\n * with the published service, whose name can differ from the requested one when\n * that name is taken (Android registers `\"<name> (2)\"`); unpublishing the\n * REQUESTED name would then remove someone else's advertisement and leak ours.\n * A library that resolves nothing (older versions) registered the requested name.\n */\nfunction registeredServiceName(result: unknown, requested: string): string {\n if (result !== null && typeof result === 'object') {\n const name = (result as { name?: unknown }).name;\n if (typeof name === 'string' && name.length > 0) return name;\n }\n return requested;\n}\n\n/**\n * The `Zeroconf` constructor `startMdnsAdvertise` accepts — the default export\n * of `react-native-zeroconf` satisfies it. The one definition of the type: the\n * provider's `zeroconf` prop is declared as this, not a parallel copy.\n */\nexport type ZeroconfConstructor = new () => ZeroconfService;\n\n/** Possible messages received over the cloud relay WebSocket */\ninterface RelayMessage {\n type: string;\n [key: string]: unknown;\n}\n\nconst DEFAULT_PORT = 8087;\n\n/**\n * Withdraw `name` (when one was registered) and drop the instance's native\n * listeners. Best-effort: cleanup never throws.\n */\nasync function releaseZeroconf(zeroconf: ZeroconfService, name: string | null): Promise<void> {\n if (name !== null) {\n try {\n await zeroconf.unpublishService(name);\n } catch {\n // ignore\n }\n }\n try {\n zeroconf.removeDeviceListeners?.();\n } catch {\n // ignore\n }\n}\nconst RECONNECT_INITIAL_DELAY_MS = 2_000;\nconst RECONNECT_MAX_DELAY_MS = 60_000;\n\n/**\n * Announces the UI Bridge server on the local network (mDNS) and optionally\n * registers with the qontinui.io cloud relay for remote discovery.\n */\nexport class DeviceAnnouncer {\n private config: Required<Pick<AnnouncerConfig, 'deviceId' | 'appId'>> & AnnouncerConfig;\n private state: DeviceAnnouncerState = {\n mdnsActive: false,\n cloudConnected: false,\n };\n private cloudWs: WebSocket | null = null;\n private reconnectTimer: ReturnType<typeof setTimeout> | null = null;\n private reconnectDelay = RECONNECT_INITIAL_DELAY_MS;\n private stopped = false;\n /** Zeroconf instance, set when mDNS is started (cleared by `stop()`) */\n private zeroconf: ZeroconfService | null = null;\n /** The name the library registered — the only name this announcer may unpublish */\n private publishedName: string | null = null;\n /**\n * True while a publish is awaiting the library. A `stop()` that lands in that\n * window leaves the cleanup to the publish path, which is the only side that\n * will learn the registered name.\n */\n private publishInFlight = false;\n /** Rotated pairing token for mDNS TXT records */\n private pairingToken: string;\n\n constructor(config: AnnouncerConfig) {\n this.config = config;\n this.pairingToken = generateHex(16);\n }\n\n // ── mDNS ──────────────────────────────────────────────────────────────────\n\n /**\n * Start mDNS advertisement.\n *\n * The consumer must pass the `Zeroconf` constructor (from `react-native-zeroconf`)\n * explicitly; otherwise this is a no-op.\n *\n * Rationale: Metro's `require()` throws an uncatchable module-load error if the\n * bundle doesn't include the named package. That error escapes async try/catch\n * boundaries and crashes the app. We avoid it by never calling `require()`\n * ourselves — the consumer imports the package when they know it's installed.\n *\n * @param ZeroconfCtor - constructor from `import Zeroconf from 'react-native-zeroconf'`\n */\n async startMdnsAdvertise(ZeroconfCtor?: ZeroconfConstructor): Promise<void> {\n if (!ZeroconfCtor) {\n transportLogger.log(\n '[DeviceAnnouncer] mDNS advertisement skipped (no Zeroconf constructor provided). ' +\n 'Pass one to enable mDNS.'\n );\n return;\n }\n if (this.stopped) return;\n let zeroconf: ZeroconfService | null = null;\n try {\n zeroconf = new ZeroconfCtor();\n this.zeroconf = zeroconf;\n\n const port = this.config.port ?? DEFAULT_PORT;\n const serviceName = `UIBridge-${this.config.deviceId.slice(0, 8)}`;\n\n this.publishInFlight = true;\n let result: unknown;\n try {\n // react-native-zeroconf takes the type and protocol WITHOUT their\n // leading underscores and formats `_%s._%s` natively (iOS\n // RNZeroconf.m, Android NsdServiceImpl/DnssdImpl), so passing\n // '_uibridge' / '_tcp.' registered `__uibridge.__tcp.`, which no\n // `_uibridge._tcp` browser (the runner's mdns_scanner) ever matches.\n result = await zeroconf.publishService('uibridge', 'tcp', 'local.', serviceName, port, {\n device_id: this.config.deviceId,\n app_id: this.config.appId,\n version: this.config.version ?? 'unknown',\n pairing_token: this.pairingToken,\n });\n } finally {\n this.publishInFlight = false;\n }\n const registered = registeredServiceName(result, serviceName);\n\n // `stop()` ran while the publish was in flight and deferred to us: withdraw\n // the name that was actually registered, and never report active.\n if (this.stopped) {\n await releaseZeroconf(zeroconf, registered);\n return;\n }\n\n this.publishedName = registered;\n this.state = { ...this.state, mdnsActive: true };\n transportLogger.log(`[DeviceAnnouncer] mDNS: advertising \"${registered}\" on port ${port}`);\n } catch (err) {\n if (this.stopped) {\n // A publish that fails after we were told to stop is not a start\n // failure anyone needs to act on; just drop the instance.\n if (zeroconf) await releaseZeroconf(zeroconf, null);\n return;\n }\n transportLogger.warn('[DeviceAnnouncer] mDNS start failed:', err);\n }\n }\n\n // ── Cloud relay ───────────────────────────────────────────────────────────\n\n /**\n * Connect to the cloud relay WebSocket and send a device_register message.\n *\n * Reconnects automatically with exponential backoff (2 s → 60 s) if the\n * connection drops.\n */\n async connectCloudRelay(): Promise<void> {\n if (!this.config.cloudRelayUrl || !this.config.cloudToken) {\n return;\n }\n if (this.stopped) return;\n\n const url = `${this.config.cloudRelayUrl}?token=${encodeURIComponent(this.config.cloudToken)}`;\n // Same credential, same sink, same rule as `CloudRelayClient`: the relay URL\n // carries the device auth token in its query string and `transportLogger`\n // feeds the ring buffer behind `/control/console-errors`, so nothing that\n // reaches a log sink may name the raw URL.\n const safeUrl = redactRelayUrl(url);\n\n transportLogger.log('[DeviceAnnouncer] Cloud relay: connecting to', safeUrl);\n\n const ws = new WebSocket(url);\n this.cloudWs = ws;\n\n ws.onopen = () => {\n if (this.stopped) {\n ws.close();\n return;\n }\n this.reconnectDelay = RECONNECT_INITIAL_DELAY_MS;\n this.state = { ...this.state, cloudConnected: true };\n transportLogger.log('[DeviceAnnouncer] Cloud relay: connected');\n\n // Register this device with the backend\n ws.send(\n JSON.stringify({\n type: 'device_register',\n device_id: this.config.deviceId,\n app_id: this.config.appId,\n platform: getPlatform(),\n display_name: this.config.deviceId,\n ui_bridge_version: this.config.version ?? 'unknown',\n })\n );\n };\n\n ws.onmessage = (event: MessageEvent) => {\n try {\n const msg = JSON.parse(event.data as string) as RelayMessage;\n transportLogger.log('[DeviceAnnouncer] Cloud relay message:', msg.type);\n // Tunneled HTTP requests are handled by CloudRelayClient when wired up\n } catch {\n // ignore malformed messages\n }\n };\n\n ws.onclose = (event: CloseEvent) => {\n this.state = { ...this.state, cloudConnected: false };\n const detail = describeCloseEvent(event);\n if (this.stopped) {\n // Expected: `stop()` asked for this close. Defensive rather than\n // reachable in the normal lifecycle — `stop()` nulls this handler\n // before calling `close()`, and `connectCloudRelay()` early-returns\n // once stopped — so this arm only fires if a transport delivers a\n // close to a handler captured before `stop()` ran. Kept because\n // \"logged nothing\" is what made the pre-fix behaviour undiagnosable.\n transportLogger.log(`[DeviceAnnouncer] Cloud relay closed ${detail} url=${safeUrl}`);\n } else {\n // Unexpected: the registration socket died and we are about to\n // reconnect. Logging the bare event said nothing — a DOM `CloseEvent`\n // has no own enumerable properties, so the observability capture's\n // `JSON.stringify` rendered it as `{}`. The close code is the whole\n // diagnosis: 1008/4001-class means the relay rejected this device's\n // token, which is otherwise indistinguishable from a flaky network.\n transportLogger.warn(\n `[DeviceAnnouncer] Cloud relay closed unexpectedly ${detail} url=${safeUrl}`\n );\n this.scheduleReconnect();\n }\n };\n\n ws.onerror = (err: Event) => {\n transportLogger.warn(\n `[DeviceAnnouncer] Cloud relay error: ${describeErrorEvent(err)} url=${safeUrl}`\n );\n // onclose will fire after this and trigger reconnect\n };\n }\n\n // ── Lifecycle ─────────────────────────────────────────────────────────────\n\n /** Stop all advertising and registration. */\n async stop(): Promise<void> {\n this.stopped = true;\n\n // Cancel any pending reconnect\n if (this.reconnectTimer !== null) {\n clearTimeout(this.reconnectTimer);\n this.reconnectTimer = null;\n }\n\n // Unpublish mDNS service. Only the REGISTERED name is ours to withdraw;\n // with a publish still in flight the publish path does the cleanup once it\n // learns that name (see `startMdnsAdvertise`).\n const zeroconf = this.zeroconf;\n const publishedName = this.publishedName;\n const inFlight = this.publishInFlight;\n this.zeroconf = null;\n this.publishedName = null;\n this.state = { ...this.state, mdnsActive: false };\n if (zeroconf && !inFlight) {\n await releaseZeroconf(zeroconf, publishedName);\n }\n\n // Close cloud WebSocket\n if (this.cloudWs) {\n this.cloudWs.onclose = null; // prevent reconnect loop\n this.cloudWs.close();\n this.cloudWs = null;\n }\n this.state = { ...this.state, cloudConnected: false };\n }\n\n /** Return a copy of the current announcer state. */\n getState(): DeviceAnnouncerState {\n return { ...this.state };\n }\n\n // ── Private ───────────────────────────────────────────────────────────────\n\n private scheduleReconnect(): void {\n if (this.stopped) return;\n const delay = this.reconnectDelay;\n transportLogger.log(`[DeviceAnnouncer] Cloud relay: reconnecting in ${delay}ms`);\n this.reconnectTimer = setTimeout(() => {\n this.reconnectTimer = null;\n if (!this.stopped) {\n void this.connectCloudRelay();\n }\n }, delay);\n // Exponential backoff\n this.reconnectDelay = Math.min(this.reconnectDelay * 2, RECONNECT_MAX_DELAY_MS);\n }\n}\n\n// ── Utilities ─────────────────────────────────────────────────────────────────\n\nfunction generateHex(bytes: number): string {\n const arr = new Uint8Array(bytes);\n // In React Native, Math.random() is fine for a non-security pairing token\n for (let i = 0; i < bytes; i++) {\n arr[i] = Math.floor(Math.random() * 256);\n }\n return Array.from(arr)\n .map((b) => b.toString(16).padStart(2, '0'))\n .join('');\n}\n\nfunction getPlatform(): string {\n return Platform?.OS ?? 'unknown';\n}\n","/**\n * Cloud Relay Client — WebSocket tunnel from mobile device to backend\n *\n * Maintains a persistent WebSocket connection to the qontinui.io backend.\n * Receives tunneled HTTP requests from runners, calls the local NativeUIBridgeServer,\n * and sends responses back through the tunnel.\n */\n\nimport type { NativeUIBridgeServer } from '../server/http-server';\nimport { transportLogger } from './logger';\nimport { describeCloseEvent, describeErrorEvent, redactRelayUrl } from './relay-logging';\n\nexport interface CloudRelayConfig {\n /** WebSocket URL for the device bridge endpoint */\n relayUrl: string;\n /** Stable device identifier */\n deviceId: string;\n /** Authentication token */\n authToken: string;\n /** Reference to the local UI Bridge server for processing requests */\n uiBridgeServer: NativeUIBridgeServer;\n}\n\ninterface TunnelRequest {\n id: string;\n method: string;\n path: string;\n headers: Record<string, string>;\n body?: unknown;\n}\n\ninterface TunnelResponse {\n id: string;\n status: number;\n headers: Record<string, string>;\n body?: unknown;\n}\n\nconst INITIAL_RECONNECT_DELAY_MS = 2_000;\nconst MAX_RECONNECT_DELAY_MS = 60_000;\n\n/**\n * Manages a WebSocket tunnel from the mobile device to the qontinui.io backend.\n *\n * When a runner sends an HTTP request to a cloud device it is serialised as a\n * `TunnelRequest` JSON frame by the backend and forwarded here. This client\n * deserializes it, calls `NativeUIBridgeServer.handleRequest()` directly\n * (avoiding loopback TCP overhead), and sends the `TunnelResponse` back.\n */\nexport class CloudRelayClient {\n private ws: WebSocket | null = null;\n private config: CloudRelayConfig;\n private reconnectDelay = INITIAL_RECONNECT_DELAY_MS;\n private maxReconnectDelay = MAX_RECONNECT_DELAY_MS;\n private stopped = false;\n private _isConnected = false;\n private reconnectTimer: ReturnType<typeof setTimeout> | null = null;\n\n constructor(config: CloudRelayConfig) {\n this.config = config;\n }\n\n /** Whether the relay WebSocket is currently connected */\n get isConnected(): boolean {\n return this._isConnected;\n }\n\n // ── Lifecycle ─────────────────────────────────────────────────────────────\n\n /** Connect to the relay and start processing tunneled requests. */\n start(): void {\n this.stopped = false;\n this.connect();\n }\n\n /** Disconnect and stop reconnecting. */\n stop(): void {\n this.stopped = true;\n this._isConnected = false;\n\n if (this.reconnectTimer !== null) {\n clearTimeout(this.reconnectTimer);\n this.reconnectTimer = null;\n }\n\n if (this.ws) {\n this.ws.onclose = null; // prevent reconnect loop\n this.ws.close();\n this.ws = null;\n }\n }\n\n // ── Private ───────────────────────────────────────────────────────────────\n\n private connect(): void {\n if (this.stopped) return;\n\n const url = `${this.config.relayUrl}?token=${encodeURIComponent(this.config.authToken)}`;\n // Everything that reaches a log sink uses the redacted spelling — the\n // relay URL carries the device auth token in its query string, and\n // `/control/console-errors` is readable by anything that can reach the\n // bridge.\n const safeUrl = redactRelayUrl(url);\n\n transportLogger.log('[CloudRelayClient] Connecting to', safeUrl);\n\n const ws = new WebSocket(url);\n this.ws = ws;\n\n ws.onopen = () => {\n if (this.stopped) {\n ws.close();\n return;\n }\n this._isConnected = true;\n this.reconnectDelay = INITIAL_RECONNECT_DELAY_MS;\n\n transportLogger.log('[CloudRelayClient] Connected to relay');\n\n // Register as a device\n ws.send(\n JSON.stringify({\n type: 'device_register',\n device_id: this.config.deviceId,\n })\n );\n };\n\n ws.onmessage = (event: MessageEvent) => {\n void this.onMessage(event.data as string);\n };\n\n ws.onclose = (event: CloseEvent) => {\n this._isConnected = false;\n const detail = describeCloseEvent(event);\n if (this.stopped) {\n // Expected: we asked for this close (or `stop()` raced the handshake).\n transportLogger.log(`[CloudRelayClient] WebSocket closed ${detail} url=${safeUrl}`);\n } else {\n // Unexpected: the tunnel died under us and we are about to reconnect.\n // The close CODE is the whole diagnosis here — 1006 is \"no close frame\"\n // (network/TLS died), 1008/4001-class codes are the relay rejecting our\n // token, 1001 is the backend going away. Logging the raw event instead\n // said nothing: a DOM CloseEvent has no own enumerable properties, so\n // the observability capture's `JSON.stringify` rendered it as `{}`.\n transportLogger.warn(\n `[CloudRelayClient] WebSocket closed unexpectedly ${detail} url=${safeUrl}`\n );\n this.scheduleReconnect();\n }\n };\n\n ws.onerror = (err: Event) => {\n // Same trap as onclose: the bare event stringifies to `{}`. Pull the\n // fields that exist across React Native's event shape and the DOM one.\n transportLogger.warn(\n `[CloudRelayClient] WebSocket error: ${describeErrorEvent(err)} url=${safeUrl}`\n );\n // onclose will fire next and handle reconnect\n };\n }\n\n private async onMessage(raw: string): Promise<void> {\n let msg: Record<string, unknown>;\n try {\n msg = JSON.parse(raw) as Record<string, unknown>;\n } catch {\n transportLogger.warn('[CloudRelayClient] Received non-JSON message');\n return;\n }\n\n // Only handle tunnel_request frames\n if (msg['type'] !== 'tunnel_request') return;\n\n // Validate required fields\n if (\n typeof msg['id'] !== 'string' ||\n typeof msg['method'] !== 'string' ||\n typeof msg['path'] !== 'string'\n ) {\n transportLogger.warn('[CloudRelayClient] Malformed tunnel_request — missing required fields');\n return;\n }\n\n const req: TunnelRequest = {\n id: msg['id'],\n method: msg['method'],\n path: msg['path'],\n headers: (msg['headers'] as Record<string, string>) ?? {},\n body: msg['body'],\n };\n\n const resp = await this.handleTunneledRequest(req);\n\n // Send response back through the WebSocket\n if (this.ws && this.ws.readyState === WebSocket.OPEN) {\n this.ws.send(JSON.stringify({ type: 'tunnel_response', ...resp }));\n }\n }\n\n /**\n * Process a tunneled HTTP request by calling the local NativeUIBridgeServer\n * directly (no loopback TCP involved).\n */\n private async handleTunneledRequest(req: TunnelRequest): Promise<TunnelResponse> {\n try {\n const httpResp = await this.config.uiBridgeServer.handleRequest({\n method: req.method,\n path: req.path,\n headers: req.headers,\n query: parseQueryParams(req.path),\n body: req.body,\n });\n\n // Parse the JSON body back to an object so it can be re-serialised as a\n // proper JSON value in the tunnel response (avoids double-encoding).\n let bodyValue: unknown;\n try {\n bodyValue = httpResp.body ? (JSON.parse(httpResp.body) as unknown) : undefined;\n } catch {\n bodyValue = httpResp.body || undefined;\n }\n\n return {\n id: req.id,\n status: httpResp.status,\n headers: httpResp.headers,\n body: bodyValue,\n };\n } catch (err) {\n transportLogger.error('[CloudRelayClient] Error handling tunneled request:', err);\n return {\n id: req.id,\n status: 500,\n headers: { 'content-type': 'application/json' },\n body: {\n success: false,\n error: err instanceof Error ? err.message : 'Internal server error',\n },\n };\n }\n }\n\n private scheduleReconnect(): void {\n if (this.stopped) return;\n const delay = this.reconnectDelay;\n transportLogger.log(`[CloudRelayClient] Reconnecting in ${delay}ms`);\n this.reconnectTimer = setTimeout(() => {\n this.reconnectTimer = null;\n if (!this.stopped) {\n this.connect();\n }\n }, delay);\n this.reconnectDelay = Math.min(this.reconnectDelay * 2, this.maxReconnectDelay);\n }\n}\n\n// ── Utilities ─────────────────────────────────────────────────────────────────\n\n/**\n * Extract query-string parameters from a URL path.\n * e.g. `/ui-bridge/control/elements?visibleOnly=true` → `{ visibleOnly: 'true' }`\n */\nfunction parseQueryParams(path: string): Record<string, string> {\n const qIdx = path.indexOf('?');\n if (qIdx === -1) return {};\n const qs = path.slice(qIdx + 1);\n const result: Record<string, string> = {};\n for (const pair of qs.split('&')) {\n const [k, v] = pair.split('=');\n if (k) {\n result[decodeURIComponent(k)] = decodeURIComponent(v ?? '');\n }\n }\n return result;\n}\n","import type { NativeModalInfo, NativeSnapshotModalContext } from '../core/types';\n\nexport interface ModalPushInput {\n id: string;\n title?: string;\n type?: NativeModalInfo['type'];\n blocking?: boolean;\n dismissible?: boolean;\n}\n\n/**\n * Declarative modal store. Components/hooks call pushModal/dismissModal directly\n * — there is no DOM/tree scanner. The detector is the single source of truth for\n * the snapshot's modalStack context.\n */\nexport class ModalDetector {\n /** Map preserves O(1) idempotent replace by id; ordering comes from detectedAt. */\n private modals = new Map<string, NativeModalInfo>();\n\n pushModal(modal: ModalPushInput): void {\n const existing = this.modals.get(modal.id);\n const detectedAt = existing ? existing.detectedAt : Date.now();\n const next: NativeModalInfo = {\n id: modal.id,\n title: modal.title,\n type: modal.type ?? 'modal',\n blocking: modal.blocking ?? true,\n dismissible: modal.dismissible ?? true,\n detectedAt,\n };\n this.modals.set(modal.id, next);\n }\n\n /**\n * Remove a modal from the stack. Returns `true` if a modal with that id\n * was actually deleted, `false` if nothing matched (idempotent so repeated\n * calls don't throw, but callers — e.g. the HTTP test-hook endpoint — can\n * surface the miss to clients).\n */\n dismissModal(id: string): boolean {\n return this.modals.delete(id);\n }\n\n getSnapshotModalContext(): NativeSnapshotModalContext {\n const active = this.getActive();\n const ctx: NativeSnapshotModalContext = {\n modals: active,\n hasBlockingModal: active.some((m) => m.blocking),\n count: active.length,\n };\n if (active.length > 0) {\n ctx.topModal = active[active.length - 1];\n }\n return ctx;\n }\n\n getActive(): NativeModalInfo[] {\n return Array.from(this.modals.values()).sort((a, b) => a.detectedAt - b.detectedAt);\n }\n\n clear(): void {\n this.modals.clear();\n }\n}\n","import type { NativeCapturedToast, NativeSnapshotToastContext } from '../core/types';\n\nexport interface ToastRecordInput {\n id: string;\n message: string;\n level?: NativeCapturedToast['level'];\n appearedAt?: number;\n}\n\nexport interface ToastCaptureConfig {\n maxRecent?: number;\n}\n\nconst DEFAULT_MAX_RECENT = 50;\n\n/**\n * Declarative toast/snackbar tracker. Components call recordToast/dismissToast\n * directly — there is no DOM/tree scanner. The active map plus a fixed-size\n * recent ring buffer feed the snapshot's toasts context.\n */\nexport class ToastCapture {\n private active = new Map<string, NativeCapturedToast>();\n private recent: NativeCapturedToast[] = [];\n private totalCaptured = 0;\n private maxRecent: number;\n\n constructor(config: ToastCaptureConfig = {}) {\n this.maxRecent = config.maxRecent ?? DEFAULT_MAX_RECENT;\n }\n\n recordToast(toast: ToastRecordInput): void {\n if (this.active.has(toast.id)) {\n return;\n }\n const appearedAt = toast.appearedAt ?? Date.now();\n const entry: NativeCapturedToast = {\n id: toast.id,\n message: toast.message,\n level: toast.level ?? 'info',\n appearedAt,\n visible: true,\n durationMs: 0,\n };\n this.active.set(toast.id, entry);\n this.totalCaptured += 1;\n }\n\n dismissToast(id: string): void {\n const entry = this.active.get(id);\n if (!entry) {\n return;\n }\n this.active.delete(id);\n const dismissedAt = Date.now();\n const dismissed: NativeCapturedToast = {\n ...entry,\n dismissedAt,\n visible: false,\n durationMs: dismissedAt - entry.appearedAt,\n };\n this.recent.push(dismissed);\n if (this.recent.length > this.maxRecent) {\n this.recent.shift();\n }\n }\n\n getSnapshotToastContext(): NativeSnapshotToastContext {\n const now = Date.now();\n const active = Array.from(this.active.values()).map((entry) => ({\n ...entry,\n durationMs: now - entry.appearedAt,\n }));\n return {\n active,\n recent: [...this.recent],\n totalCaptured: this.totalCaptured,\n };\n }\n\n clear(): void {\n this.active.clear();\n this.recent = [];\n this.totalCaptured = 0;\n }\n}\n","import type { NativeSnapshotUndoContext } from '../core/types';\n\n/**\n * A single bridge action recorded for undo correlation. Action-correlation\n * only — RN has no DOM/execCommand probe, so we rely on developer\n * declaration plus this rolling history of recent actions.\n */\nexport interface ActionRecord {\n id: string;\n type: string;\n targetId?: string;\n description?: string;\n timestamp: number;\n /** Default true — set false for actions that aren't reversible (e.g. navigation, network calls) */\n reversible?: boolean;\n}\n\n/**\n * Developer-declared undo/redo state. When set, this is authoritative and\n * overrides any heuristic inference from action history.\n */\nexport interface DeclaredUndoState {\n canUndo: boolean;\n canRedo: boolean;\n undoDescription?: string;\n redoDescription?: string;\n undoDepth?: number;\n redoDepth?: number;\n}\n\nexport interface UndoTrackerConfig {\n maxHistory?: number;\n}\n\nconst DEFAULT_MAX_HISTORY = 50;\n\nfunction buildSummary(ctx: {\n canUndo: boolean;\n canRedo: boolean;\n undoDescription?: string;\n redoDescription?: string;\n}): string {\n if (!ctx.canUndo && !ctx.canRedo) {\n return 'no undo available';\n }\n const parts: string[] = [];\n if (ctx.canUndo) {\n parts.push(`undo: '${ctx.undoDescription ?? 'available'}'`);\n }\n if (ctx.canRedo) {\n parts.push(`redo: '${ctx.redoDescription ?? 'available'}'`);\n }\n return parts.join(' / ');\n}\n\n/**\n * Action-correlation undo tracker for React Native.\n *\n * Maintains a rolling buffer of recent actions and a developer-declared\n * undo state slot. The declared state is authoritative when set; otherwise\n * we infer `canUndo` from whether any reversible action has been recorded.\n * `executeUndo`/`executeRedo` are placeholders pending an IPC path through\n * ui-bridge-native to the runner's `/control/undo`.\n */\nexport class UndoTracker {\n private readonly maxHistory: number;\n private actions: ActionRecord[] = [];\n private declaredState: DeclaredUndoState | null = null;\n\n constructor(config: UndoTrackerConfig = {}) {\n this.maxHistory = config.maxHistory ?? DEFAULT_MAX_HISTORY;\n }\n\n recordAction(record: ActionRecord): void {\n this.actions.push(record);\n if (this.actions.length > this.maxHistory) {\n this.actions = this.actions.slice(-this.maxHistory);\n }\n }\n\n setDeclaredState(state: DeclaredUndoState): void {\n this.declaredState = state;\n }\n\n getActionHistory(): ActionRecord[] {\n return this.actions.slice();\n }\n\n getSnapshotUndoContext(): NativeSnapshotUndoContext {\n const declared = this.declaredState;\n if (declared) {\n const summary = buildSummary({\n canUndo: declared.canUndo,\n canRedo: declared.canRedo,\n undoDescription: declared.undoDescription,\n redoDescription: declared.redoDescription,\n });\n return {\n canUndo: declared.canUndo,\n canRedo: declared.canRedo,\n undoDescription: declared.undoDescription,\n redoDescription: declared.redoDescription,\n undoDepth: declared.undoDepth,\n redoDepth: declared.redoDepth,\n summary,\n };\n }\n\n const canUndo = this.actions.some((a) => a.reversible !== false);\n const canRedo = false;\n // Surface the most recent reversible action's description as the inferred undo target\n const lastReversible = [...this.actions].reverse().find((a) => a.reversible !== false);\n const undoDescription = lastReversible?.description;\n const summary = buildSummary({ canUndo, canRedo, undoDescription });\n return {\n canUndo,\n canRedo,\n undoDescription,\n summary,\n };\n }\n\n executeUndo(): { ok: boolean; reason?: string } {\n return { ok: false, reason: 'Not implemented in native' };\n }\n\n executeRedo(): { ok: boolean; reason?: string } {\n return { ok: false, reason: 'Not implemented in native' };\n }\n\n clear(): void {\n this.actions = [];\n this.declaredState = null;\n }\n}\n","/**\n * UI Bridge Native Provider\n *\n * React context provider for UI Bridge Native functionality.\n */\n\nimport React, {\n createContext,\n use,\n useMemo,\n useEffect,\n useCallback,\n useRef,\n useState,\n} from 'react';\nimport { Dimensions, PixelRatio } from 'react-native';\nimport type {\n NativeUIBridgeFeatures,\n NativeUIBridgeConfig,\n RegisteredNativeElement,\n RegisteredNativeComponent,\n NativeBridgeSnapshot,\n BridgeEventType,\n BridgeEventListener,\n} from '../core/types';\nimport { NativeUIBridgeRegistry, setGlobalRegistry, resetGlobalRegistry } from '../core/registry';\nimport { createNativeActionExecutor } from '../control/action-executor';\nimport type { NativeActionExecutor } from '../control/types';\nimport {\n createNativeServer,\n type NativeUIBridgeServer,\n type ServerAdapter,\n type WebSocketServerAdapter,\n} from '../server/http-server';\nimport type { RouteProvider, KeepAwakeProvider } from '../server/types';\nimport { WebSocketEventBridge } from '../server/ws-event-bridge';\nimport { DeviceAnnouncer, type ZeroconfConstructor } from '../transport/DeviceAnnouncer';\nimport { CloudRelayClient, type CloudRelayConfig } from '../transport/CloudRelayClient';\nimport { ModalDetector } from '../modal/modal-detector';\nimport { ToastCapture } from '../toast/toast-capture';\nimport { UndoTracker } from '../undo/undo-tracker';\n\n/**\n * UI Bridge Native context value\n */\nexport interface UIBridgeNativeContextValue {\n /** Feature flags */\n features: NativeUIBridgeFeatures;\n /** Configuration */\n config: NativeUIBridgeConfig;\n /** Element registry */\n registry: NativeUIBridgeRegistry;\n /** Action executor */\n executor: NativeActionExecutor;\n /** Modal stack tracker (declarative pushModal/dismissModal) */\n modalDetector: ModalDetector;\n /** Toast/snackbar tracker (declarative recordToast/dismissToast) */\n toastCapture: ToastCapture;\n /** Undo/redo action-correlation tracker */\n undoTracker: UndoTracker;\n /** Get all registered elements */\n getElements: () => RegisteredNativeElement[];\n /** Get all registered components */\n getComponents: () => RegisteredNativeComponent[];\n /** Create a snapshot */\n createSnapshot: () => NativeBridgeSnapshot;\n /** Subscribe to events */\n on: <T = unknown>(type: BridgeEventType, listener: BridgeEventListener<T>) => () => void;\n /** Unsubscribe from events */\n off: <T = unknown>(type: BridgeEventType, listener: BridgeEventListener<T>) => void;\n /** Whether the provider is initialized */\n initialized: boolean;\n /** Server running status */\n serverRunning: boolean;\n /** Start the HTTP server */\n startServer: () => Promise<void>;\n /** Stop the HTTP server */\n stopServer: () => void;\n /** Get the current navigation route (if a RouteProvider is configured) */\n getCurrentRoute: () => string | null;\n}\n\n/**\n * UI Bridge Native context\n */\nconst UIBridgeNativeContext = createContext<UIBridgeNativeContextValue | null>(null);\n\n/**\n * Stable defaults for the two optional object props.\n *\n * Written as `features = {}` these were fresh literals on every render, so\n * `Object.is` failed for both entries of the `contextValue` `useMemo` deps below\n * and the context value was NEW on every provider render. `useUIElement`'s\n * auto-register effect has deps `[autoRegister, bridge, id]` where `bridge` IS\n * that context value, and its cleanup runs a real `registry.unregisterElement`\n * followed by a full `registerElement` — not an in-place mutate. So a host that\n * re-renders its provider (any `useState` in the root layout) churned the entire\n * element registry every time. `useUIComponent` (deps `[autoRegister, bridge]`)\n * had the identical exposure.\n *\n * The two sibling providers in this repo — `packages/ui-bridge/src/react/\n * UIBridgeProvider.tsx` and `packages/ui-bridge/src/native/react/\n * UIBridgeNativeProvider.tsx` — already carry exactly this idiom. Plain\n * literals, not `Object.freeze`d, to match them verbatim.\n */\nconst EMPTY_FEATURES: NativeUIBridgeFeatures = {};\nconst EMPTY_CONFIG: NativeUIBridgeConfig = {};\n\n/**\n * Hold an options object's identity steady for as long as its VALUE is\n * unchanged.\n *\n * Stable defaults alone only fix the host that OMITS the prop. This component's\n * own usage example passes inline literals —\n * `features={{ server: __DEV__, debug: __DEV__ }} config={{ serverPort: 8087 }}`\n * — which are freshly allocated on every render of the host's layout, so\n * `Object.is` fails and the context value churns exactly as before. That is the\n * documented pattern, so it is the one that has to work.\n *\n * Keyed on a JSON signature rather than an enumerated field list: both\n * `NativeUIBridgeFeatures` and `NativeUIBridgeConfig` are small, plain,\n * JSON-serialisable bags (booleans, a number, strings, and one nested `appInfo`\n * of strings — no functions, no cycles), and a field list would silently stop\n * covering a field the day one is added, with nothing to catch it. Cost is one\n * `JSON.stringify` of a handful of scalars per render.\n *\n * Two honest limits: a host that reorders its object's keys between renders\n * produces a different signature, and a host that MUTATES the object in place\n * without changing the reference will now be noticed rather than ignored. Both\n * degrade to the previous behaviour (a new context value), never to a stale one.\n */\nfunction useValueStable<T>(value: T): T {\n const signature = JSON.stringify(value);\n // Keyed on the VALUE signature on purpose: `value`'s identity is precisely\n // what this hook exists to discard, so listing it as a dep would defeat it.\n // eslint-disable-next-line react-hooks/exhaustive-deps\n return useMemo(() => value, [signature]);\n}\n\n/**\n * UI Bridge Native provider props\n */\nexport interface UIBridgeNativeProviderProps {\n /** Child components */\n children: React.ReactNode;\n /** Feature flags */\n features?: NativeUIBridgeFeatures;\n /** Configuration */\n config?: NativeUIBridgeConfig;\n /** Event handler */\n onEvent?: BridgeEventListener;\n /**\n * A ServerAdapter instance for the HTTP server.\n * The app is responsible for creating this using its preferred native TCP/HTTP library.\n * @see ServerAdapter interface in server/http-server.ts\n */\n serverAdapter?: ServerAdapter;\n /**\n * Navigation provider for programmatic route navigation via UI Bridge.\n * Pass Expo Router's push/back functions to enable `control/page/navigate`.\n */\n navigationProvider?: { navigate: (url: string) => void; back?: () => void };\n /**\n * Screenshot provider for native screen capture via UI Bridge.\n * Pass a function that captures the current screen as base64 PNG.\n */\n screenshotProvider?: {\n capture: () => Promise<{ base64: string; width: number; height: number }>;\n };\n /**\n * Keep-awake provider for native screen-wake control via UI Bridge.\n * Pass expo-keep-awake's activateKeepAwakeAsync/deactivateKeepAwake (wrapped\n * to the request/release shape) so an external runner never loses the device\n * to a screen lock. The SDK never imports expo-keep-awake directly.\n */\n keepAwakeProvider?: KeepAwakeProvider;\n /**\n * Route provider for exposing the current navigation route in snapshots.\n * Wire this to Expo Router's `usePathname()` / `useSegments()` via a module-level ref.\n */\n routeProvider?: RouteProvider;\n /**\n * Configuration for the cloud relay tunnel (enables remote device verification\n * when USB/LAN are not available). Omit `uiBridgeServer` — the provider wires\n * that automatically after the server starts.\n */\n cloudRelayConfig?: Omit<CloudRelayConfig, 'uiBridgeServer'>;\n /**\n * Enable mDNS advertisement so that runners on the same LAN can discover this\n * device automatically. Advertises `_uibridge._tcp` only when `zeroconf` is\n * also passed; without it the announcer logs that advertisement was skipped.\n */\n enableMdnsAnnounce?: boolean;\n /**\n * The `Zeroconf` constructor from `react-native-zeroconf`\n * (`import Zeroconf from 'react-native-zeroconf'` → `zeroconf={Zeroconf}`),\n * forwarded to `DeviceAnnouncer.startMdnsAdvertise`. The SDK never\n * `require()`s that package itself — Metro raises an uncatchable module-load\n * error when it is absent — so the host app, which knows it is installed,\n * hands the constructor in. Omitted, mDNS advertisement is skipped.\n *\n * Must be a STABLE reference — the module-level import, never an inline\n * wrapper — because it is a dependency of the transport effect: a new\n * identity per render tears down and re-publishes the advertisement (and the\n * cloud relay) on every render.\n */\n zeroconf?: ZeroconfConstructor;\n /**\n * Stable device identifier used for mDNS TXT records and cloud relay\n * registration. Typically sourced from expo-device or a UUID stored in\n * AsyncStorage.\n */\n deviceId?: string;\n}\n\n/**\n * UI Bridge Native Provider\n *\n * Provides UI Bridge Native context to child components.\n *\n * @example\n * ```tsx\n * // app/_layout.tsx\n * import { UIBridgeNativeProvider } from '@qontinui/ui-bridge-native';\n *\n * export default function RootLayout() {\n * return (\n * <UIBridgeNativeProvider\n * features={{ server: __DEV__, debug: __DEV__ }}\n * config={{ serverPort: 8087 }}\n * >\n * <Stack>{children}</Stack>\n * </UIBridgeNativeProvider>\n * );\n * }\n * ```\n */\n/**\n * The device window size in logical dp — the single definition, shared by every\n * consumer that needs it.\n *\n * Read through `react-native` HERE rather than inside the core registry or the\n * server: the require/import pattern there crashed the host RN app in\n * 0.6.3/0.6.4 (Metro/Hermes raised `unknownModuleError` past every try/catch).\n * This file already has a live react-native import, so it is the safe\n * injection point. See feedback_metro_require_gotcha for the full incident.\n *\n * Injected as a FUNCTION, not a value, so a rotation or split-screen resize is\n * picked up on the next read with nothing to keep in sync. Its three sinks —\n * `getPageHealth`, the design handlers, and the registry's visibility clipping\n * — must not each carry their own copy of this fact and drift apart.\n */\nfunction readWindowViewport(): { width: number; height: number } {\n const win = Dimensions.get('window');\n return { width: win.width, height: win.height };\n}\n\nexport function UIBridgeNativeProvider({\n children,\n features: featuresProp = EMPTY_FEATURES,\n config: configProp = EMPTY_CONFIG,\n onEvent,\n serverAdapter,\n navigationProvider,\n screenshotProvider,\n keepAwakeProvider,\n routeProvider,\n cloudRelayConfig,\n enableMdnsAnnounce,\n zeroconf,\n deviceId,\n}: UIBridgeNativeProviderProps) {\n // Identity held steady by VALUE — see `useValueStable`. Everything below,\n // including the `contextValue` memo, reads these rather than the raw props.\n const features = useValueStable(featuresProp);\n const config = useValueStable(configProp);\n\n const registryRef = useRef<NativeUIBridgeRegistry | null>(null);\n const executorRef = useRef<NativeActionExecutor | null>(null);\n const modalDetectorRef = useRef<ModalDetector | null>(null);\n const toastCaptureRef = useRef<ToastCapture | null>(null);\n const undoTrackerRef = useRef<UndoTracker | null>(null);\n const [serverRunning, setServerRunning] = useState(false);\n\n // Initialize on first render\n if (!registryRef.current) {\n registryRef.current = new NativeUIBridgeRegistry({\n verbose: config.verbose,\n onEvent,\n });\n // Inject the device pixel ratio so `createSnapshot` can project each\n // element's `state.layout` (logical dp) into a physical-pixel `bbox` the\n // runner's vision pipeline accepts. Done here (a React file that already\n // imports react-native) rather than inside the core registry, which must\n // stay free of react-native imports — see the `projectBbox` doc comment.\n registryRef.current.setPixelRatio(PixelRatio.get());\n // Inject the window bounds so reported `visibility` is clipped against the\n // viewport instead of meaning \"mounted and measured somewhere\". Same\n // injection rationale as `setPixelRatio` above — the core registry must\n // stay free of react-native imports. A PROVIDER rather than a value so a\n // rotation or a split-screen resize is picked up on the next read.\n registryRef.current.setViewportProvider(readWindowViewport);\n setGlobalRegistry(registryRef.current);\n }\n\n const registry = registryRef.current;\n\n // Create executor (memoized)\n if (!executorRef.current) {\n executorRef.current = createNativeActionExecutor(registry);\n }\n\n const executor = executorRef.current;\n\n // Trackers — lazy-init the same way as registry/executor so each provider\n // lifecycle has exactly one stable instance.\n if (!modalDetectorRef.current) modalDetectorRef.current = new ModalDetector();\n if (!toastCaptureRef.current) toastCaptureRef.current = new ToastCapture();\n if (!undoTrackerRef.current) undoTrackerRef.current = new UndoTracker();\n\n const modalDetector = modalDetectorRef.current;\n const toastCapture = toastCaptureRef.current;\n const undoTracker = undoTrackerRef.current;\n\n // Server instance (persisted across renders)\n const serverRef = useRef<NativeUIBridgeServer | null>(null);\n const eventBridgeRef = useRef<WebSocketEventBridge | null>(null);\n\n // Cloud / mDNS transport references\n const announcerRef = useRef<DeviceAnnouncer | null>(null);\n const cloudRelayRef = useRef<CloudRelayClient | null>(null);\n\n // Server management — uses injected serverAdapter if provided\n const startServer = useCallback(async () => {\n if (!features.server) return;\n\n if (!serverAdapter) {\n console.warn(\n `[ui-bridge-native] HTTP server not available: no serverAdapter prop provided. ` +\n `Pass a serverAdapter to UIBridgeNativeProvider to enable the HTTP server.`\n );\n return;\n }\n\n const server = createNativeServer(registry, executor, {\n serverPort: config.serverPort || 8087,\n cors: true,\n appInfo: config.appInfo,\n testHooks: features.testHooks === true,\n // Dedicated console/network-capture flag; the server defaults it to\n // the `testHooks` value when undefined, so passing it through verbatim\n // keeps existing consumers unchanged.\n observability: features.observability,\n // Injected device-viewport getter for POST /control/page-health and the\n // design handlers. Same source as the registry's clipping bounds — see\n // `readWindowViewport`.\n viewportProvider: readWindowViewport,\n });\n\n server.setAdapter(serverAdapter);\n\n // Wire navigation provider if supplied\n if (navigationProvider) {\n server.setNavigationProvider(navigationProvider);\n }\n\n // Wire screenshot provider if supplied\n if (screenshotProvider) {\n server.setScreenshotProvider(screenshotProvider);\n }\n\n // Wire keep-awake provider if supplied\n if (keepAwakeProvider) {\n server.setKeepAwakeProvider(keepAwakeProvider);\n }\n\n // Wire route provider if supplied (must be set AFTER navigationProvider\n // since both may override getSnapshot / pageNavigate handlers)\n if (routeProvider) {\n server.setRouteProvider(routeProvider);\n }\n\n // Wire up WebSocket event bridge if adapter supports it\n const wsAdapter = serverAdapter as WebSocketServerAdapter;\n if (typeof wsAdapter.broadcast === 'function') {\n const eventBridge = new WebSocketEventBridge(registry);\n server.setEventBridge(eventBridge);\n\n wsAdapter.onWebSocketConnect = (connId: string) => {\n // Create a lightweight connection proxy for the event bridge\n // The actual WebSocketConnection lives in the adapter\n eventBridge.addConnection({\n id: connId,\n subscriptions: new Set(),\n alive: true,\n isOpen: true,\n send: (msg: string) => wsAdapter.sendToConnection?.(connId, msg),\n sendEvent: (event: { event: string }) => {\n if (!eventBridge.isSubscribed(connId, event.event)) return;\n wsAdapter.sendToConnection?.(connId, JSON.stringify(event));\n },\n ping: () => {\n /* adapter handles heartbeat */\n },\n close: () => {\n /* adapter handles close */\n },\n destroy: () => {\n /* adapter handles destroy */\n },\n } as any); // eslint-disable-line @typescript-eslint/no-explicit-any\n };\n\n wsAdapter.onWebSocketDisconnect = (connId: string) => {\n // Abort any pending waiters (waitForElement / waitForCondition)\n // for this connection BEFORE removing it — stops leaked timers\n // and registry listeners.\n server.abortWaitersForConnection(connId);\n eventBridge.removeConnection(connId);\n };\n\n wsAdapter.onWebSocketMessage = async (connId: string, message: string) => {\n return server.handleWebSocketMessage(connId, message);\n };\n\n eventBridge.start();\n eventBridgeRef.current = eventBridge;\n }\n\n try {\n await server.start();\n serverRef.current = server;\n setServerRunning(true);\n } catch (err) {\n console.warn('[ui-bridge-native] Failed to start HTTP server:', err);\n }\n }, [\n features.server,\n features.testHooks,\n features.observability,\n config.serverPort,\n config.appInfo,\n registry,\n executor,\n serverAdapter,\n navigationProvider,\n screenshotProvider,\n keepAwakeProvider,\n routeProvider,\n ]);\n\n const stopServer = useCallback(() => {\n if (eventBridgeRef.current) {\n eventBridgeRef.current.stop();\n eventBridgeRef.current = null;\n }\n if (serverRef.current) {\n serverRef.current.stop().catch(() => {});\n serverRef.current = null;\n }\n setServerRunning(false);\n }, []);\n\n // Auto-start server if enabled\n useEffect(() => {\n if (features.server) {\n startServer();\n return () => stopServer();\n }\n }, [features.server, startServer, stopServer]);\n\n // Start mDNS announcement and cloud relay.\n //\n // The cloud relay path does NOT require the HTTP server to be running —\n // it calls `server.handleRequest()` directly, bypassing HTTP. This matters\n // for preview/production builds where `features.server` is typically\n // false (no native TCP server adapter available). We still need a\n // NativeUIBridgeServer instance to handle tunneled requests, so we create\n // a bare instance here if startServer() didn't already make one.\n //\n // mDNS also doesn't need the HTTP server — it just advertises on the\n // network so remote devices can discover this phone's address.\n useEffect(() => {\n // Everything here is best-effort — any exception must not crash the app.\n try {\n const needsBareServer = !serverRef.current && !!cloudRelayConfig;\n if (needsBareServer) {\n try {\n // Create a server instance for handleRequest() use only; no adapter,\n // no HTTP listener. This is safe without features.server.\n const bareServer = createNativeServer(registry, executor, {\n serverPort: config.serverPort || 8087,\n cors: true,\n appInfo: config.appInfo,\n testHooks: features.testHooks === true,\n observability: features.observability,\n viewportProvider: readWindowViewport,\n });\n if (navigationProvider) bareServer.setNavigationProvider(navigationProvider);\n if (screenshotProvider) bareServer.setScreenshotProvider(screenshotProvider);\n if (keepAwakeProvider) bareServer.setKeepAwakeProvider(keepAwakeProvider);\n if (routeProvider) bareServer.setRouteProvider(routeProvider);\n serverRef.current = bareServer;\n } catch (err) {\n console.warn('[ui-bridge-native] Failed to create bare server:', err);\n }\n }\n\n // mDNS advertisement\n if (enableMdnsAnnounce && deviceId) {\n try {\n const announcer = new DeviceAnnouncer({\n deviceId,\n appId: config.appInfo?.appId ?? 'unknown',\n port: config.serverPort ?? 8087,\n cloudRelayUrl: cloudRelayConfig?.relayUrl,\n cloudToken: cloudRelayConfig?.authToken,\n });\n announcerRef.current = announcer;\n void announcer.startMdnsAdvertise(zeroconf).catch((err) => {\n console.warn('[ui-bridge-native] mDNS advertise failed:', err);\n });\n } catch (err) {\n console.warn('[ui-bridge-native] Failed to start DeviceAnnouncer:', err);\n }\n }\n\n // Cloud relay tunnel (works without HTTP server)\n if (cloudRelayConfig && serverRef.current) {\n try {\n const relayClient = new CloudRelayClient({\n ...cloudRelayConfig,\n uiBridgeServer: serverRef.current,\n });\n cloudRelayRef.current = relayClient;\n relayClient.start();\n } catch (err) {\n console.warn('[ui-bridge-native] Failed to start CloudRelayClient:', err);\n }\n }\n } catch (err) {\n console.warn('[ui-bridge-native] Transport effect failed:', err);\n }\n\n return () => {\n try {\n if (announcerRef.current) {\n void announcerRef.current.stop().catch(() => {});\n announcerRef.current = null;\n }\n if (cloudRelayRef.current) {\n cloudRelayRef.current.stop();\n cloudRelayRef.current = null;\n }\n } catch {\n // cleanup must never throw\n }\n };\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [\n serverRunning,\n cloudRelayConfig?.relayUrl,\n cloudRelayConfig?.authToken,\n enableMdnsAnnounce,\n zeroconf,\n deviceId,\n ]);\n\n // Cleanup on unmount\n useEffect(() => {\n return () => {\n stopServer();\n resetGlobalRegistry();\n };\n }, [stopServer]);\n\n // Context methods\n const getElements = useCallback(() => registry.getAllElements(), [registry]);\n\n const getComponents = useCallback(() => registry.getAllComponents(), [registry]);\n\n const createSnapshot = useCallback(() => registry.createSnapshot(), [registry]);\n\n const getCurrentRoute = useCallback(() => {\n return routeProvider?.getCurrentRoute() ?? null;\n }, [routeProvider]);\n\n // Mark the previous route's elements offscreen when the active route changes.\n // Without this, React Navigation's persistent-mount behavior leaves stale\n // layouts in the registry for tabs the user has left. Elements on the new\n // route re-fire `onLayout` and repopulate their layout.\n useEffect(() => {\n if (!routeProvider) return;\n\n let lastRoute: string | null = routeProvider.getCurrentRoute();\n\n return routeProvider.subscribe((current: string | null) => {\n if (current !== lastRoute && lastRoute != null) {\n registry.markRouteOffscreen(lastRoute);\n }\n lastRoute = current;\n });\n }, [routeProvider, registry]);\n\n // Wire trackers into the registry's snapshot enricher slots. Trackers are\n // stable refs, so this effect runs exactly once per provider lifecycle.\n useEffect(() => {\n registry.setEnrichers({ modalDetector, toastCapture, undoTracker });\n }, [registry, modalDetector, toastCapture, undoTracker]);\n\n // Mirror successful bridge actions into UndoTracker's rolling history so\n // snapshots can surface action-correlation undo context without each\n // action site needing to call recordAction manually.\n useEffect(() => {\n const unsubscribe = executor.onActionExecuted((event) => {\n if (!event.success) return;\n undoTracker.recordAction({\n id: event.requestId ?? `action-${event.timestamp}`,\n type: event.action,\n targetId: event.elementId,\n timestamp: event.timestamp,\n reversible: true,\n });\n });\n return unsubscribe;\n }, [executor, undoTracker]);\n\n const on = useCallback(\n <T = unknown,>(type: BridgeEventType, listener: BridgeEventListener<T>) =>\n registry.on(type, listener),\n [registry]\n );\n\n const off = useCallback(\n <T = unknown,>(type: BridgeEventType, listener: BridgeEventListener<T>) =>\n registry.off(type, listener),\n [registry]\n );\n\n const contextValue = useMemo<UIBridgeNativeContextValue>(\n () => ({\n features,\n config,\n registry,\n executor,\n modalDetector,\n toastCapture,\n undoTracker,\n getElements,\n getComponents,\n createSnapshot,\n on,\n off,\n initialized: true,\n serverRunning,\n startServer,\n stopServer,\n getCurrentRoute,\n }),\n [\n features,\n config,\n registry,\n executor,\n modalDetector,\n toastCapture,\n undoTracker,\n getElements,\n getComponents,\n createSnapshot,\n on,\n off,\n serverRunning,\n startServer,\n stopServer,\n getCurrentRoute,\n ]\n );\n\n return <UIBridgeNativeContext value={contextValue}>{children}</UIBridgeNativeContext>;\n}\n\n/**\n * useUIBridgeNative hook\n *\n * Access the UI Bridge Native context. Throws if used outside provider.\n */\nexport function useUIBridgeNative(): UIBridgeNativeContextValue {\n const context = use(UIBridgeNativeContext);\n if (!context) {\n throw new Error('useUIBridgeNative must be used within a UIBridgeNativeProvider');\n }\n return context;\n}\n\n/**\n * useUIBridgeNativeOptional hook\n *\n * Access the UI Bridge Native context, returning null if outside provider.\n */\nexport function useUIBridgeNativeOptional(): UIBridgeNativeContextValue | null {\n return use(UIBridgeNativeContext);\n}\n\n/**\n * useUIBridgeNativeRequired hook\n *\n * Alias for useUIBridgeNative (throws if outside provider).\n */\nexport const useUIBridgeNativeRequired = useUIBridgeNative;\n","/**\n * useUIElement Hook for React Native\n *\n * Register a native element with UI Bridge for control and observation.\n */\n\nimport { useRef, useEffect, useCallback, useMemo, useState } from 'react';\nimport { StyleSheet } from 'react-native';\nimport type {\n NativeElementType,\n NativeStandardAction,\n NativeCustomAction,\n NativeElementState,\n NativeElementIdentifier,\n RegisteredNativeElement,\n NativeElementRef,\n NativeLayout,\n} from '../core/types';\nimport { useUIBridgeNativeOptional } from './UIBridgeNativeProvider';\n\n/**\n * Flatten an RN style prop into a plain object.\n * Uses StyleSheet.flatten which handles arrays, IDs, and nested objects.\n */\nfunction flattenStyle(style: unknown): Record<string, unknown> | undefined {\n if (style == null) return undefined;\n try {\n const flat = StyleSheet.flatten(style as Parameters<typeof StyleSheet.flatten>[0]);\n return flat ? (flat as Record<string, unknown>) : undefined;\n } catch {\n return undefined;\n }\n}\n\n/**\n * Flatten state style overrides into plain objects.\n */\nfunction flattenStateStyles(stateStyles?: {\n pressed?: unknown;\n focused?: unknown;\n disabled?: unknown;\n}):\n | {\n pressed?: Record<string, unknown>;\n focused?: Record<string, unknown>;\n disabled?: Record<string, unknown>;\n }\n | undefined {\n if (!stateStyles) return undefined;\n const result: {\n pressed?: Record<string, unknown>;\n focused?: Record<string, unknown>;\n disabled?: Record<string, unknown>;\n } = {};\n if (stateStyles.pressed != null) result.pressed = flattenStyle(stateStyles.pressed);\n if (stateStyles.focused != null) result.focused = flattenStyle(stateStyles.focused);\n if (stateStyles.disabled != null) result.disabled = flattenStyle(stateStyles.disabled);\n return Object.keys(result).length > 0 ? result : undefined;\n}\n\n/**\n * Local type definition for the layout data we extract from LayoutChangeEvent.\n * We use this internally to avoid type conflicts between different react-native versions\n * (e.g., when ui-bridge-native is used as a file: dependency with a different RN version).\n */\ninterface LayoutEventData {\n nativeEvent: {\n layout: {\n x: number;\n y: number;\n width: number;\n height: number;\n };\n };\n}\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\ntype AnyHandler = (...args: any[]) => any;\n\n/**\n * A press handler for `button`/`pressable` types. Matches the loose RN\n * `Pressable` `onPress` shape (no required argument), so consumers can pass\n * either a no-arg callback or one that consumes the gesture event.\n */\nexport type PressHandler = (event?: unknown) => void;\n\n/**\n * Element types that require a press handler at registration. The TS\n * signature on `useUIElement` rejects these types unless `handlers.onPress`\n * is provided in options.\n *\n * Picked from the action-executor in `control/action-executor.ts` — the\n * `press` action looks up `props.onPress` (or `onPressIn` /\n * `onResponderRelease`); registering a button without one is a guaranteed\n * dead-button per the 2026-05-20 manual-test session.\n */\nexport type PressNeedingNativeElementType = 'button' | 'pressable';\n\n/**\n * Base options for `useUIElement`. The discriminated union below layers\n * `handlers` requirements on top of this — see {@link UseUIElementOptions}.\n */\nexport interface UseUIElementOptionsBase<T extends NativeElementType = NativeElementType> {\n /** Unique identifier for the element */\n id: string;\n /** Element type (defaults to 'custom') */\n type?: T;\n /** Human-readable label */\n label?: string;\n /** Override available actions */\n actions?: NativeStandardAction[];\n /** Custom actions */\n customActions?: Record<string, NativeCustomAction>;\n /**\n * Current controlled value for text inputs. When provided, it is threaded\n * into the registered element's `state.value` so a `GET /control/element/:id`\n * (or `/state`) reflects what the user sees — without this, the input\n * registers with `value: undefined` and a bridge read returns null even\n * though the field is populated. Pass the same value you bind to the RN\n * `<TextInput value={...} />` prop; the hook keeps the registry in sync as\n * it changes.\n */\n value?: string;\n /** Whether to automatically register on mount */\n autoRegister?: boolean;\n /** Callback when state changes */\n onStateChange?: (state: NativeElementState) => void;\n /** Parent component path for tree path generation */\n parentPath?: string;\n /**\n * Id of the registered scrollable container (`type: 'scroll' | 'list'`) this\n * element is rendered inside.\n *\n * Supplying it makes the bridge clip this element's reported `visibility`\n * against that container's measured frame, so a row scrolled past the fold\n * reports `visibility: 'hidden'` with `visibilityReason: 'off-screen'`\n * instead of claiming to be on screen. Without it, the device window is the\n * only clip region.\n *\n * It has to be declared: `useUIElement` is a hook, so it never wraps its\n * element's children and cannot publish itself to them as an ancestor. See\n * `RegisterElementOptions.scrollAncestorId` for why guessing geometrically\n * would be worse than not clipping.\n *\n * It is also what the `scrollIntoView` action scrolls, and declaring it is\n * what advertises that action — but only when `actions` is left to be\n * inferred. An explicit `actions` list is taken as written; include\n * `'scrollIntoView'` in it yourself if you want the action advertised.\n */\n scrollAncestorId?: string;\n /** RN style prop — will be flattened for design review */\n style?: unknown;\n /** State-specific style overrides for design review (pressed, focused, disabled) */\n stateStyles?: {\n pressed?: unknown;\n focused?: unknown;\n disabled?: unknown;\n };\n}\n\n/**\n * Options shape for press-needing types — `handlers.onPress` is REQUIRED.\n * Registering a `button`/`pressable` without an `onPress` produces a\n * \"No press handler found on element\" error when the bridge fires\n * `POST /control/element/:id/action {\"action\":\"press\"}`. Phase 1 of plan\n * `2026-05-20-manual-test-remediation` makes that a compile-time error.\n *\n * Consumers that wire `onPress` lazily (e.g. computed from props during\n * render) should use {@link useUIElementWithProps} + `captureProps({ onPress })`\n * instead. The runtime guard in this hook also warns once per id when\n * `onPress` never reaches the registry.\n */\nexport interface UseUIElementOptionsHandlersRequired<\n T extends PressNeedingNativeElementType = PressNeedingNativeElementType,\n> extends UseUIElementOptionsBase<T> {\n /**\n * Handler props to auto-register with the bridge for action execution.\n * For `button`/`pressable`, `onPress` is required — UI Bridge invokes it\n * when a `press` action is dispatched.\n *\n * @example\n * ```tsx\n * const { ref, onLayout, bridgeProps } = useUIElement({\n * id: 'my-button',\n * type: 'pressable',\n * handlers: { onPress: handlePress },\n * });\n * ```\n */\n handlers: {\n /** Required — UI Bridge invokes this on `press`/`click` actions. */\n onPress: PressHandler;\n /** Additional handlers (`onLongPress`, `onPressIn`, etc.) */\n [key: string]: AnyHandler | undefined;\n };\n}\n\n/**\n * Options shape for non-press-needing types — `handlers` is optional.\n * Applies to `input`, `text`, `view`, `list`, etc. — anything where a\n * missing `onPress` doesn't indicate a dead button.\n */\nexport interface UseUIElementOptionsHandlersOptional<\n T extends NativeElementType = NativeElementType,\n> extends UseUIElementOptionsBase<T> {\n /**\n * Handler props to auto-register with the bridge for action execution.\n * Optional for non-press-needing types.\n */\n handlers?: Record<string, AnyHandler | undefined>;\n}\n\n/**\n * useUIElement options — discriminated union over element type.\n *\n * For `type: 'button' | 'pressable'`, `handlers.onPress` is required.\n * For all other types, `handlers` is optional.\n */\nexport type UseUIElementOptions<T extends NativeElementType = NativeElementType> =\n T extends PressNeedingNativeElementType\n ? UseUIElementOptionsHandlersRequired<T>\n : UseUIElementOptionsHandlersOptional<T>;\n\n/**\n * Bridge props to spread onto the component\n */\nexport interface UIBridgeProps {\n /** Test ID for automation */\n testID: string;\n /** Accessibility label */\n accessibilityLabel?: string;\n}\n\n/**\n * useUIElement return value\n */\nexport interface UseUIElementReturn {\n /** Ref to attach to the element */\n ref: React.RefObject<NativeElementRef>;\n /** onLayout handler to spread onto the element - uses generic type for RN version compatibility */\n onLayout: (event: {\n nativeEvent: { layout: { x: number; y: number; width: number; height: number } };\n }) => void;\n /** Props to spread onto the element for identification */\n bridgeProps: UIBridgeProps;\n /** Whether the element is registered */\n registered: boolean;\n /** Get current state */\n getState: () => NativeElementState | null;\n /** Get element identifier */\n getIdentifier: () => NativeElementIdentifier | null;\n /** Trigger an action on this element */\n trigger: (\n action: NativeStandardAction | string,\n params?: Record<string, unknown>\n ) => Promise<void>;\n /** Manually register the element */\n register: () => void;\n /** Manually unregister the element */\n unregister: () => void;\n /** The registered element info */\n registeredElement: RegisteredNativeElement | null;\n /** Update style for design review (flattens and stores in registry) */\n updateStyle: (\n style: unknown,\n stateStyles?: { pressed?: unknown; focused?: unknown; disabled?: unknown }\n ) => void;\n /**\n * Re-publish the element's label (and the mirrored `accessibilityLabel` /\n * `testId` so spec-check and a11y stay in sync). Idempotent — no-op when\n * the new label equals the current registered value.\n *\n * NOT required for the common case any more. The `label` OPTION passed to\n * `useUIElement({ id, label })` is now auto-re-published whenever its value\n * changes, so a state-derived label (a tab's active suffix, a card's\n * `${title}: ${loading ? 'loading' : value}`, a list's \"N events\" count)\n * stays in sync with zero call-site ceremony. Existing consumers that still\n * drive `updateLabel(label)` from their own `useEffect` keep working — the\n * second publish is inert, not a flicker.\n *\n * Reach for this only when the string you want in the registry is NOT the\n * `label` option — e.g. a label owned by an imperative handler, or one\n * computed outside the render path.\n *\n * @example\n * ```tsx\n * // No `updateLabel` needed — the option is republished automatically.\n * const { ref } = useUIElement({ id: 'events-list', label: `${events.length} events`, type: 'list' });\n * ```\n */\n updateLabel: (newLabel: string) => void;\n}\n\n/**\n * useUIElement hook for React Native\n *\n * Registers a native element with UI Bridge for programmatic control.\n *\n * @example\n * ```tsx\n * function SubmitButton() {\n * const { ref, onLayout, bridgeProps, trigger } = useUIElement({\n * id: 'submit-btn',\n * type: 'button',\n * label: 'Submit Form',\n * });\n *\n * return (\n * <Pressable\n * ref={ref}\n * onLayout={onLayout}\n * {...bridgeProps}\n * onPress={() => handleSubmit()}\n * >\n * <Text>Submit</Text>\n * </Pressable>\n * );\n * }\n * ```\n */\n/**\n * Module-scoped set of ids we've already warned about so the dead-button\n * `console.warn` only fires once per id even if the component re-mounts.\n */\nconst warnedDeadButtonIds = new Set<string>();\n\n/**\n * Module-scoped set of ids that have already received a no-op-updateLabel\n * warning. Mirrors {@link warnedDeadButtonIds} — one warn per id per process\n * lifetime, so a hot loop calling `updateLabel(sameString)` doesn't spam\n * the console while still surfacing the case during development.\n */\nconst warnedRedundantUpdateLabelIds = new Set<string>();\n\n/**\n * Schedule a deferred check: after one microtask + one macrotask, look up\n * the registered element. If it's a press-needing type AND no `onPress`\n * (or fallback press handler) is on the registry's `props`, emit a\n * `console.warn` pointing at the fix. Deferred so consumers using\n * {@link useUIElementWithProps} + synchronous `captureProps({ onPress })`\n * still pass the check.\n */\nfunction scheduleDeadButtonWarning(\n bridge: ReturnType<typeof useUIBridgeNativeOptional>,\n id: string,\n type: NativeElementType\n): void {\n if (type !== 'button' && type !== 'pressable') return;\n if (warnedDeadButtonIds.has(id)) return;\n if (!bridge) return;\n\n // Defer via macrotask so `useUIElementWithProps` consumers that call\n // `captureProps({ onPress })` from their render body land their props\n // into the registry first. queueMicrotask alone runs before the next\n // render commit on some React schedulers; setTimeout(0) is a safer\n // \"after next paint\" boundary without bringing in `requestAnimationFrame`.\n setTimeout(() => {\n if (warnedDeadButtonIds.has(id)) return;\n const element = bridge.registry.getElement(id);\n if (!element) return;\n const props = (element.props ?? {}) as Record<string, unknown>;\n const hasPress =\n typeof props.onPress === 'function' ||\n typeof props.onPressIn === 'function' ||\n typeof props.onResponderRelease === 'function';\n if (hasPress) return;\n warnedDeadButtonIds.add(id);\n console.warn(\n `[UI Bridge] Registered \\`${type}\\` element \"${id}\" without an \\`onPress\\` handler — UI Bridge \\`press\\` actions on this element will fail with \"No press handler found on element\". Use \\`useUIElementWithProps\\` and \\`captureProps({onPress})\\` instead.`\n );\n }, 0);\n}\n\n// Public overload — narrow signature. External callers see ONLY this; the\n// discriminated union forces `handlers.onPress` for press-needing types.\nexport function useUIElement<T extends NativeElementType = NativeElementType>(\n options: UseUIElementOptions<T>\n): UseUIElementReturn;\n// Implementation signature — wide. Not visible to external callers (TS\n// hides the impl sig); used internally by `useUIElementWithProps` via the\n// narrow public sig with a structural cast.\nexport function useUIElement(options: UseUIElementOptionsHandlersOptional): UseUIElementReturn {\n const bridge = useUIBridgeNativeOptional();\n const [registered, setRegistered] = useState(false);\n const [_layout, setLayout] = useState<NativeLayout | null>(null);\n const propsRef = useRef<Record<string, unknown>>({});\n // Authoritative registration tracking. See the web `useUIElement` for\n // rationale: consumers commonly pass inline `style`/`stateStyles` objects,\n // and threading the `registered` state into the register useCallback's deps\n // creates a cleanup/run feedback loop past React's 50-update ceiling.\n const registeredRef = useRef(false);\n const registeredIdRef = useRef<string | null>(null);\n // Last label value the SDK's OWN auto-publisher wrote to the registry\n // (seeded by `register()`). Only the auto-publish paths write it — a manual\n // `updateLabel(...)` deliberately does not, so the redundant-call warning\n // below can still tell \"the SDK already published this\" apart from \"this\n // call site republishes the same string on its own\".\n const autoPublishedLabelRef = useRef<string | undefined>(undefined);\n\n // Latest bridge for the ref interceptor below. React attaches/detaches\n // refs during the commit phase — outside any effect closure — so the\n // interceptor reads the live bridge through this ref.\n const bridgeRef = useRef(bridge);\n bridgeRef.current = bridge;\n\n // Element ref with attach/detach interception.\n //\n // The registry seeds `visible: true` at registration (see\n // `registerElement`) so unmeasured-but-mounted elements still appear in\n // `visibleOnly` snapshots. That seed is wrong for refs that DETACH after\n // render: conditional branches (e.g. a status element rendered only in an\n // error branch) leave stale `visible: true` + layout in the registry when\n // the branch unmounts, because RN fires no event on detach. React's only\n // detach signal for object refs is the `ref.current = null` write it\n // performs on unmount — so instead of a plain `useRef`, we hand consumers\n // a stable RefObject whose `current` setter mirrors attach/detach into the\n // registry's `visible` flag:\n // - detach (node → null) while registered ⇒ `visible: false`\n // - (re)attach (null → node) while registered ⇒ `visible: true`\n // (restores the registration seed; onLayout / measureInWindow refine\n // it with real dimensions as usual)\n // Reads (`ref.current`) behave exactly like a normal ref.\n const nodeRef = useRef<NativeElementRef>(null);\n const refInterceptorRef = useRef<React.RefObject<NativeElementRef> | null>(null);\n if (refInterceptorRef.current === null) {\n refInterceptorRef.current = {\n get current(): NativeElementRef {\n return nodeRef.current;\n },\n set current(node: NativeElementRef) {\n const prev = nodeRef.current;\n nodeRef.current = node;\n const liveBridge = bridgeRef.current;\n const registeredId = registeredIdRef.current;\n if (!liveBridge || !registeredRef.current || registeredId === null) return;\n if (node == null && prev != null) {\n // Detached after render — the element left the tree while the hook\n // (and its registration) stayed mounted. Without this write the\n // registry keeps reporting the registration-seeded `visible: true`.\n const state = liveBridge.registry.getElement(registeredId)?.getState();\n if (state && state.visible !== false) {\n liveBridge.registry.updateElementState(registeredId, { visible: false });\n }\n } else if (node != null && prev == null) {\n // (Re)attached — restore the seed's \"mounted, should be visible\"\n // optimism; layout measurement refines it from here.\n const state = liveBridge.registry.getElement(registeredId)?.getState();\n if (state && state.visible !== true) {\n liveBridge.registry.updateElementState(registeredId, { visible: true });\n }\n }\n },\n } as React.RefObject<NativeElementRef>;\n }\n const ref = refInterceptorRef.current;\n\n const {\n id,\n type = 'custom',\n label,\n actions,\n customActions,\n autoRegister = true,\n onStateChange,\n parentPath,\n scrollAncestorId,\n style,\n stateStyles: stateStylesProp,\n handlers: handlersProp,\n value: valueProp,\n } = options;\n\n // Build tree path\n const treePath = parentPath ? `${parentPath}/${id}` : id;\n\n // Bridge props to spread onto the element\n const bridgeProps: UIBridgeProps = useMemo(\n () => ({\n testID: id,\n accessibilityLabel: label,\n }),\n [id, label]\n );\n\n // Register the element\n const register = useCallback(() => {\n if (!bridge || registeredRef.current) return;\n\n bridge.registry.registerElement(id, ref, {\n type,\n label,\n actions,\n customActions,\n treePath,\n testId: id,\n accessibilityLabel: label,\n registrationRoute: bridge.getCurrentRoute(),\n scrollAncestorId,\n flatStyle: flattenStyle(style),\n stateStyles: flattenStateStyles(stateStylesProp),\n });\n registeredRef.current = true;\n registeredIdRef.current = id;\n autoPublishedLabelRef.current = typeof label === 'string' ? label : undefined;\n\n // Seed the controlled value into the element state so a bridge read\n // reflects what the user sees immediately on mount — before any `type`/\n // `setValue` action runs. Only write when a value was actually supplied\n // so non-input elements aren't given a spurious empty `value`.\n if (typeof valueProp === 'string') {\n bridge.registry.updateElementState(id, { value: valueProp });\n }\n\n setRegistered(true);\n\n // Runtime backstop for the type-tightening: warns once per id when a\n // press-needing type is registered without an `onPress` reaching the\n // registry. Catches JS consumers and `as any` escape hatches that\n // bypass the discriminated-union signature above. Deferred so consumers\n // using `useUIElementWithProps` + `captureProps({ onPress })` from the\n // render body still pass.\n scheduleDeadButtonWarning(bridge, id, type);\n // `ref` (the interceptor object) is created exactly once per hook\n // instance, so listing it is identity-stable — included to satisfy\n // exhaustive-deps now that it isn't a direct useRef result.\n }, [\n bridge,\n id,\n type,\n label,\n actions,\n customActions,\n treePath,\n scrollAncestorId,\n style,\n stateStylesProp,\n valueProp,\n ref,\n ]);\n\n // Unregister the element\n const unregister = useCallback(() => {\n if (!bridge || !registeredRef.current) return;\n\n bridge.registry.unregisterElement(registeredIdRef.current ?? id);\n registeredRef.current = false;\n registeredIdRef.current = null;\n autoPublishedLabelRef.current = undefined;\n setRegistered(false);\n }, [bridge, id]);\n\n // Keep `onStateChange` in a ref so the layout callback doesn't get\n // re-created (and thereby miss the first layout event) when the consumer\n // passes an inline arrow function.\n const onStateChangeRef = useRef(onStateChange);\n useEffect(() => {\n onStateChangeRef.current = onStateChange;\n }, [onStateChange]);\n\n // Handle layout changes.\n //\n // Registry write gating uses `registeredRef.current` (not the React\n // `registered` state) so the very first `onLayout` event — which can fire\n // before `setRegistered(true)` has been committed by React — still pushes\n // layout into the registry. Without this, snapshots show layout `(?, ?)`\n // until the element is interacted with, because the initial onLayout's\n // closure captured `registered === false` and silently dropped the write.\n // updateElementState itself is also no-op when the id isn't registered,\n // so this is safe even when `onLayout` fires before mount.\n const onLayout = useCallback(\n (event: LayoutEventData) => {\n const { x, y, width, height } = event.nativeEvent.layout;\n\n const writeLayout = (newLayout: NativeLayout) => {\n setLayout(newLayout);\n if (!bridge) return;\n const newState: NativeElementState = {\n mounted: true,\n visible: width > 0 && height > 0,\n enabled: true,\n focused: false,\n layout: newLayout,\n };\n bridge.registry.updateElementState(id, newState);\n onStateChangeRef.current?.(newState);\n };\n\n // Get absolute position using measureInWindow when available.\n if (ref.current && 'measureInWindow' in ref.current) {\n (\n ref.current as {\n measureInWindow: (\n callback: (pageX: number, pageY: number, w: number, h: number) => void\n ) => void;\n }\n ).measureInWindow((pageX: number, pageY: number) => {\n writeLayout({ x, y, width, height, pageX, pageY });\n });\n } else {\n // Fallback when measureInWindow isn't on the ref (test fixtures, web).\n // `pageX`/`pageY` are PARENT-RELATIVE here, not window coordinates —\n // flagged so visibility clipping declines to compare them against the\n // window rather than mixing coordinate spaces. See `NativeLayout`.\n writeLayout({ x, y, width, height, pageX: x, pageY: y, pageOriginUnmeasured: true });\n }\n },\n // `ref` is the once-per-hook interceptor object — identity-stable.\n [bridge, id, ref]\n );\n\n // Keep latest register/unregister in refs so the auto-register effect does\n // not re-run when consumers pass inline `style`/`stateStyles` options.\n const registerRef = useRef(register);\n const unregisterRef = useRef(unregister);\n useEffect(() => {\n registerRef.current = register;\n unregisterRef.current = unregister;\n }, [register, unregister]);\n\n // Auto-register on mount, and RE-register when `id` changes.\n //\n // `id` is a real dependency even though the effect body never reads it:\n // recycled virtualized-list cells (FlashList) re-render the same hook\n // instance with a NEW id. Without `id` in the deps, the effect never\n // re-ran, so the OLD id stayed registered forever (a stale entry no\n // re-measure can fix) and the NEW id was never registered at all.\n //\n // Ordering on an id-change render: the cleanup runs first and closes over\n // the PREVIOUS `unregisterRef.current`, whose `unregister` removes\n // `registeredIdRef.current` — i.e. the OLD id — and resets the guard\n // flags. The ref-sync effect above is declared before this one, so by the\n // time this effect's body re-runs, `registerRef.current` is the fresh\n // closure that registers the NEW id. Invariant: after a rerender that\n // changes `id` from A to B, the registry has no entry for A and a live\n // entry for B.\n useEffect(() => {\n if (autoRegister) {\n registerRef.current();\n }\n\n return () => {\n if (registeredRef.current) {\n unregisterRef.current();\n }\n };\n }, [autoRegister, bridge, id]);\n\n // Layout-on-mount fallback with backoff retry.\n //\n // Bug being addressed: the registry's `layout` field shows `(?, ?)` until\n // the element is actioned. Three compounding causes:\n // 1. The first `onLayout` event used to drop its write because the\n // callback's closure captured `registered === false` (fixed above by\n // switching to a registry-only write path).\n // 2. Some consumers don't actually thread `onLayout={onLayout}` onto\n // their RN component, so the layout never measures.\n // 3. Elements registered while their subtree is mounted-but-not-laid-out\n // (Expo Router lazy tabs; routes hidden behind an overlay like a\n // Connect/login screen) return zero dims from the first\n // `measureInWindow` call. RN doesn't re-fire `onLayout` on visibility\n // changes when intrinsic dimensions don't change, so a single-shot\n // measure leaves the registry entry at `visible:false, layout:null`\n // permanently — even after the user navigates to the screen.\n //\n // Schedule a `measureInWindow` immediately after registration, and retry\n // with backoff (50/200/500/1000/2500 ms) whenever the call returns zeros.\n // Stops on first non-zero result or after the last retry. All pending\n // timers are cleared on unmount / re-register.\n useEffect(() => {\n if (!bridge || !registered) return;\n const node = ref.current as\n | (NativeElementRef & {\n measureInWindow?: (\n callback: (pageX: number, pageY: number, w: number, h: number) => void\n ) => void;\n })\n | null;\n if (!node) {\n // Never attached: the hook registered the element but no rendered node\n // ever received the ref (refs attach during commit, BEFORE effects run\n // — so a null ref here means the element isn't in the tree, e.g. a\n // status element only rendered in an error branch). The registration\n // seed optimistically reports `visible: true`; correct it so snapshots\n // don't claim never-rendered elements are on screen. Mounted nodes\n // that merely haven't measured yet keep the seeded `true` (the\n // lazy-tab rationale above), and the ref interceptor flips this back\n // to `true` if the element attaches later.\n const seeded = bridge.registry.getElement(id)?.getState();\n if (seeded && seeded.visible !== false) {\n bridge.registry.updateElementState(id, { visible: false });\n }\n return;\n }\n if (typeof node.measureInWindow !== 'function') return;\n\n let cancelled = false;\n let pendingTimer: ReturnType<typeof setTimeout> | null = null;\n const backoffMs = [50, 200, 500, 1000, 2500];\n let attempt = 0;\n\n const tryMeasure = () => {\n if (cancelled || !node.measureInWindow) return;\n node.measureInWindow((pageX: number, pageY: number, w: number, h: number) => {\n if (cancelled) return;\n if (w > 0 && h > 0) {\n const newLayout: NativeLayout = {\n x: pageX,\n y: pageY,\n width: w,\n height: h,\n pageX,\n pageY,\n };\n setLayout(newLayout);\n const newState: NativeElementState = {\n mounted: true,\n visible: true,\n enabled: true,\n focused: false,\n layout: newLayout,\n };\n bridge.registry.updateElementState(id, newState);\n onStateChangeRef.current?.(newState);\n return;\n }\n if (attempt >= backoffMs.length) return;\n pendingTimer = setTimeout(tryMeasure, backoffMs[attempt++]);\n });\n };\n\n tryMeasure();\n\n return () => {\n cancelled = true;\n if (pendingTimer != null) clearTimeout(pendingTimer);\n };\n // `ref` is the once-per-hook interceptor object — identity-stable.\n }, [bridge, registered, id, ref]);\n\n // Auto-register handler props (onPress, onChangeText, etc.) when provided.\n // We use a ref to track which keys were last registered so we can clear\n // stale handlers on cleanup or when the handlers object changes.\n const registeredHandlerKeysRef = useRef<string[]>([]);\n\n useEffect(() => {\n if (!bridge || !registered || !handlersProp) return;\n\n // Filter to only function values\n const fnProps: Record<string, unknown> = {};\n for (const [key, value] of Object.entries(handlersProp)) {\n if (typeof value === 'function') {\n fnProps[key] = value;\n }\n }\n\n const newKeys = Object.keys(fnProps);\n\n // Clear any previously registered keys that are no longer present\n const removedKeys = registeredHandlerKeysRef.current.filter((k) => !newKeys.includes(k));\n if (removedKeys.length > 0) {\n const cleared: Record<string, unknown> = {};\n for (const key of removedKeys) {\n cleared[key] = undefined;\n }\n bridge.registry.updateElementProps(id, cleared);\n }\n\n if (newKeys.length > 0) {\n bridge.registry.updateElementProps(id, fnProps);\n }\n registeredHandlerKeysRef.current = newKeys;\n\n return () => {\n // On unmount or re-run, clear all registered handlers\n if (registeredHandlerKeysRef.current.length > 0) {\n const cleared: Record<string, unknown> = {};\n for (const key of registeredHandlerKeysRef.current) {\n cleared[key] = undefined;\n }\n bridge.registry.updateElementProps(id, cleared);\n registeredHandlerKeysRef.current = [];\n }\n };\n }, [bridge, registered, id, handlersProp]);\n\n // Keep the registry's `state.value` in sync with the controlled `value`\n // prop. RN controlled inputs re-render with a new `value` on every\n // keystroke; mirroring it here means a bridge read (`/control/element/:id`)\n // always reflects the live field contents, not just the value at mount or\n // the last bridge-driven `type`/`setValue`. Guarded on `registered` so the\n // write lands after registration; `updateElementState` is a no-op for\n // unknown ids anyway.\n useEffect(() => {\n if (!bridge || !registered) return;\n if (typeof valueProp !== 'string') return;\n const current = bridge.registry.getElement(id)?.getState().value;\n if (current === valueProp) return;\n bridge.registry.updateElementState(id, { value: valueProp });\n }, [bridge, registered, id, valueProp]);\n\n // Keep the registry's label in sync with the `label` OPTION — automatically.\n //\n // ROOT CAUSE this closes: `register()` publishes `label` exactly once and is\n // guarded by `registeredRef.current`, while the auto-register effect only\n // re-runs on `[autoRegister, bridge, id]`. A consumer whose label is derived\n // from state — `${title}: ${error ? 'error' : loading ? 'loading' : value}` —\n // therefore left the registry holding the MOUNT-TIME string forever unless it\n // also remembered to call `updateLabel(...)` by hand. Measured consequence:\n // five `operations-card-*` elements reporting `Fleet: loading` /\n // `Questions: loading` indefinitely while the screen beside them rendered the\n // real numbers. That is both an a11y defect (TalkBack reads \"loading\"\n // forever) and a test-surface defect (any bridge assertion on those labels\n // reads a fossil). `updateLabel` stays as the escape hatch for labels that\n // are NOT the `label` option; it is no longer something a call site has to\n // remember.\n //\n // Identity trap, handled twice over:\n // 1. `label` is a STRING, so React's `Object.is` dependency compare IS a\n // value compare. An inline template literal rebuilt on every render but\n // producing the same text does NOT re-run this effect — no publish per\n // render, per element.\n // 2. `updateElementMeta` compares each field by value before mutating and\n // returns `false` without emitting when nothing changed. So even when\n // the effect DOES re-run for another reason (`registered` flipping,\n // `bridge`/`id` changing), a same-value publish is inert.\n //\n // Publishes the LABEL ONLY. `registerElement` is never called a second time,\n // so the registry entry is mutated in place: no churn, no duplicate entry, and\n // no reset of state / props / layout / handler registration. Double-publishing\n // alongside a consumer that still calls `updateLabel(label)` itself is\n // therefore idempotent rather than a flicker.\n useEffect(() => {\n if (!bridge || !registered) return;\n if (typeof label !== 'string') return;\n autoPublishedLabelRef.current = label;\n bridge.registry.updateElementMeta(id, {\n label,\n accessibilityLabel: label,\n testId: id,\n });\n }, [bridge, registered, id, label]);\n\n // Update props for action execution (allows accessing onPress, onChangeText, etc.)\n const _updateProps = useCallback(\n (props: Record<string, unknown>) => {\n propsRef.current = { ...propsRef.current, ...props };\n if (bridge && registered) {\n bridge.registry.updateElementProps(id, props);\n }\n },\n [bridge, registered, id]\n );\n\n // Get state\n const getState = useCallback((): NativeElementState | null => {\n if (!bridge) return null;\n const element = bridge.registry.getElement(id);\n return element?.getState() || null;\n }, [bridge, id]);\n\n // Get identifier\n const getIdentifier = useCallback((): NativeElementIdentifier | null => {\n if (!bridge) return null;\n const element = bridge.registry.getElement(id);\n return element?.getIdentifier() || null;\n }, [bridge, id]);\n\n // Trigger action\n const trigger = useCallback(\n async (action: NativeStandardAction | string, params?: Record<string, unknown>) => {\n if (!bridge) {\n throw new Error('UI Bridge Native not available');\n }\n\n const response = await bridge.executor.executeAction(id, {\n action,\n params,\n });\n\n if (!response.success) {\n throw new Error(response.error || 'Action failed');\n }\n },\n [bridge, id]\n );\n\n // Re-publish label / a11y label / testId for state-driven labels.\n //\n // The bug being addressed: `useUIElement({id, label})` registers the label\n // exactly once on mount. Consumers that compute a label from state\n // (e.g. `Tab: Actions${active ? ' (active)' : ''}`, `${events.length} events`)\n // see the registry permanently stuck at the mount-time string.\n //\n // Idempotent — the registry's `updateElementMeta` returns false when no\n // field actually changed, so a hot render loop calling `updateLabel(sameString)`\n // costs one Map lookup + three equality checks. To surface obviously-redundant\n // call sites during development, we emit a one-time `console.warn` per id on\n // the first observed no-op.\n const updateLabel = useCallback(\n (newLabel: string) => {\n if (!bridge || !registered) return;\n const changed = bridge.registry.updateElementMeta(id, {\n label: newLabel,\n accessibilityLabel: newLabel,\n testId: id,\n });\n // The hook now auto-publishes the `label` option (see the effect above),\n // so a consumer that ALSO drives `updateLabel(label)` from its own\n // `useEffect` will legitimately observe a no-op every time. Warning there\n // would fire on every correct pre-existing call site, so the warning is\n // scoped to the case it was written for: a redundant publish of a string\n // the SDK did NOT just publish itself.\n const alreadyPublishedBySdk = newLabel === autoPublishedLabelRef.current;\n if (!changed && !alreadyPublishedBySdk && !warnedRedundantUpdateLabelIds.has(id)) {\n warnedRedundantUpdateLabelIds.add(id);\n console.warn(\n `[UI Bridge] updateLabel(\"${newLabel}\") on element \"${id}\" was a no-op (label unchanged). Gate the call behind a useEffect with [label] deps to avoid redundant publishes.`\n );\n }\n },\n [bridge, registered, id]\n );\n\n // Update style for design review\n const updateStyle = useCallback(\n (\n newStyle: unknown,\n newStateStyles?: { pressed?: unknown; focused?: unknown; disabled?: unknown }\n ) => {\n if (!bridge || !registered) return;\n const flat = flattenStyle(newStyle);\n if (flat) {\n bridge.registry.updateElementStyle(id, flat, flattenStateStyles(newStateStyles));\n }\n },\n [bridge, registered, id]\n );\n\n // Get registered element\n const registeredElement = useMemo(() => {\n if (!bridge) return null;\n return bridge.registry.getElement(id) || null;\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [bridge, id, registered]);\n\n return {\n ref,\n onLayout,\n bridgeProps,\n registered,\n getState,\n getIdentifier,\n trigger,\n register,\n unregister,\n registeredElement,\n updateStyle,\n updateLabel,\n };\n}\n\n/**\n * useUIElementWithProps hook\n *\n * Extended version that also captures component props for action execution.\n * Useful when you need the bridge to be able to call onPress, onChangeText, etc.\n *\n * @example\n * ```tsx\n * function TextInputField({ onChangeText, value }) {\n * const { ref, onLayout, bridgeProps, captureProps } = useUIElementWithProps({\n * id: 'email-input',\n * type: 'input',\n * });\n *\n * // Capture props so bridge can call onChangeText\n * captureProps({ onChangeText, value });\n *\n * return (\n * <TextInput\n * ref={ref}\n * onLayout={onLayout}\n * {...bridgeProps}\n * value={value}\n * onChangeText={onChangeText}\n * />\n * );\n * }\n * ```\n */\nexport interface UseUIElementWithPropsReturn extends UseUIElementReturn {\n /** Capture props for action execution */\n captureProps: (props: Record<string, unknown>) => void;\n}\n\n/**\n * Loose options for `useUIElementWithProps` — `handlers` is optional for ALL\n * element types because the consumer will later call `captureProps({ onPress,\n * ... })` from the render body. The runtime warning in {@link useUIElement}\n * still backstops the \"captured but never called with onPress\" case.\n */\nexport type UseUIElementWithPropsOptions<T extends NativeElementType = NativeElementType> =\n UseUIElementOptionsHandlersOptional<T>;\n\nexport function useUIElementWithProps<T extends NativeElementType = NativeElementType>(\n options: UseUIElementWithPropsOptions<T>\n): UseUIElementWithPropsReturn {\n // `useUIElement`'s narrow public signature demands `handlers.onPress` for\n // press-needing types, but the whole point of this hook is to capture\n // props after the fact (via `captureProps` returned below) — so we widen\n // through `unknown`. The runtime warning in `useUIElement` still fires if\n // no onPress ever lands in the registry, regardless of the cast.\n const elementReturn = useUIElement(options as unknown as UseUIElementOptions<'view'>);\n const bridge = useUIBridgeNativeOptional();\n\n const captureProps = useCallback(\n (props: Record<string, unknown>) => {\n if (bridge && elementReturn.registered) {\n bridge.registry.updateElementProps(options.id, props);\n }\n },\n [bridge, elementReturn.registered, options.id]\n );\n\n return {\n ...elementReturn,\n captureProps,\n };\n}\n","/**\n * useUIComponent Hook for React Native\n *\n * Register a component with UI Bridge for component-level actions.\n */\n\nimport { useEffect, useCallback, useRef, useState } from 'react';\nimport type { IREffect, RegisteredNativeComponent } from '../core/types';\nimport { useUIBridgeNativeOptional } from './UIBridgeNativeProvider';\n\n/**\n * Action definition for useUIComponent\n */\nexport interface ComponentActionDef<TParams = unknown, TResult = unknown> {\n /** Action identifier */\n id: string;\n /** Human-readable label */\n label?: string;\n /** Description */\n description?: string;\n /**\n * Parameter schema — **serialized, published to agents, and VALIDATED.**\n *\n * It is spread onto `/control/components` and `/control/component/:id`, and\n * four `qontinui-runner` consumers read it from there — including the LLM\n * router that generates a slash command's args from it. Since Phase 2 of\n * plan `2026-08-20-ui-bridge-action-declaration-shape` the invocation seam\n * checks `params` against it BEFORE your handler runs, so a schema declared\n * here is a promise the runtime keeps.\n *\n * (The doc this replaces promised both halves of a contradiction: the schema\n * is \"surfaced verbatim on `/control/component/:id`\" AND \"No runtime\n * validation is performed.\" The first half was always true; the second is no\n * longer.)\n *\n * Two accepted shapes:\n *\n * - **Object-schema form** — `{ type: 'object', properties: { ... },\n * required: ['...'], additionalProperties: false }`. The only form that can\n * express *requiredness*. `paramSchemaOf()` from\n * `@qontinui/ui-bridge-wrapper` emits it for you.\n * - **Map form** — `{ paramName: 'string', other: { type: 'number' } }`. A\n * TYPE hint only: it cannot mark anything required, and a string that is\n * not one of the seven JSON Schema primitive names (`string`, `number`,\n * `integer`, `boolean`, `object`, `array`, `null`) is read as prose and\n * constrains nothing — which is what keeps the fleet's many\n * `{ count: 'number (>= 1, defaults to 1)' }` hint maps working.\n *\n * Recognised keywords: `type`, `enum`, `const`, `properties`, `required`,\n * `additionalProperties: false`, `items`, `minimum`/`maximum`,\n * `minLength`/`maxLength`, `pattern`. **Anything else is ignored, never\n * rejected** — a schema richer than the subset is still valid JSON Schema,\n * it just expresses fewer enforced constraints. No type coercion: `\"5\"` does\n * not satisfy `{ type: 'number' }`.\n *\n * Enforcement is a deployment setting and defaults to `'warn'` — violations\n * are logged and the handler still runs until someone calls\n * `setDefaultParamValidationMode('enforce')`. The full grammar, and why warn\n * is the default, are documented at `core/param-schema.ts`.\n */\n paramSchema?: Record<string, unknown>;\n /**\n * Safety annotation — `'read' | 'write' | 'destructive'` (Phase 4 of plan\n * `2026-08-20-ui-bridge-action-declaration-shape`).\n *\n * **Declare `'destructive'` on anything irreversible** — a delete, a send, a\n * charge, a deploy. It is the one value nothing can infer for you: the\n * static verb map behind this field never produces `'destructive'`, because\n * destructiveness depends on what your control does, not on what it is\n * called. An autonomous walk excludes destructive actions and walks\n * everything else, so an unmarked delete control gets pressed.\n *\n * **Precedence:** what you write here wins, and it is the **only** thing\n * that reaches the wire. `NATIVE_STANDARD_ACTION_EFFECTS` supplies a default\n * when the action `id` happens to be one of the native standard verbs\n * (`press`, `longPress`, `swipe`, …), but that default is applied **by the\n * consumer**, via the exported `resolveActionEffect()` — the SDK does *not*\n * stamp it onto the response. Leave this undefined and the field is simply\n * **absent** from every projection, which is the honest encoding of \"nobody\n * classified this action\" (see `core/action-effect.ts` for why a\n * server-applied default would fail open).\n */\n effect?: IREffect;\n /**\n * Handler function.\n *\n * The second argument is the `ActionHandlerOptions` bag whose `signal` is\n * aborted when the caller cancels or the request's `timeoutMs` elapses\n * (Phase 3 of plan `2026-08-20-ui-bridge-action-declaration-shape`).\n * Observing it is optional: the executor races this promise against the\n * abort, so an unobservant handler is abandoned anyway — observing it is how\n * a handler releases its own in-flight work instead of leaving it detached.\n */\n handler: (params?: TParams, options?: { signal?: AbortSignal }) => TResult | Promise<TResult>;\n}\n\n/**\n * useUIComponent options\n */\nexport interface UseUIComponentOptions {\n /** Unique identifier for the component */\n id: string;\n /** Human-readable name */\n name: string;\n /** Description */\n description?: string;\n /** Actions available on this component */\n actions?: ComponentActionDef[];\n /** Child element IDs owned by this component */\n elementIds?: string[];\n /** Whether to automatically register on mount */\n autoRegister?: boolean;\n}\n\n/**\n * useUIComponent return value\n */\nexport interface UseUIComponentReturn {\n /** Whether the component is registered */\n registered: boolean;\n /** Execute an action on this component */\n executeAction: <TParams = unknown, TResult = unknown>(\n actionId: string,\n params?: TParams\n ) => Promise<TResult>;\n /** Manually register the component */\n register: () => void;\n /** Manually unregister the component */\n unregister: () => void;\n /**\n * Publish an action list that is NOT the `actions` option.\n *\n * **Not required for the common case any more.** The `actions` OPTION passed\n * to `useUIComponent({ id, actions })` is now auto-re-published whenever its\n * published shape changes, so a state-derived action list — a label carrying\n * a count, an action that only exists while a row is selected, a\n * `paramSchema` that widens once options load — reaches\n * `/control/components` without a call site doing anything. This is the\n * escape hatch for actions the hook does not own, the same role `updateLabel`\n * plays for `useUIElement`.\n *\n * If you pass BOTH the `actions` option and call this, the option wins on the\n * next render that changes its signature: the declarative lane is the one the\n * republish effect re-asserts.\n */\n updateActions: (actions: ComponentActionDef[]) => void;\n /**\n * Add an element ID to this component. Published to the registry\n * immediately — this used to write to a private ref and stop there, so the\n * ownership list an agent read never moved.\n *\n * Survives re-renders. It is replaced only when the DECLARED `elementIds`\n * option itself changes value, which is the point at which the call site has\n * said something newer than the imperative edit.\n */\n addElement: (elementId: string) => void;\n /** Remove an element ID from this component. Same publishing rules as {@link addElement}. */\n removeElement: (elementId: string) => void;\n /**\n * The registered component as the registry currently holds it — `null` until\n * registration commits, then refreshed on every republish that changes the\n * published shape.\n */\n registeredComponent: RegisteredNativeComponent | null;\n}\n\n/**\n * useUIComponent hook for React Native\n *\n * Registers a component with UI Bridge for component-level control.\n * Components can expose high-level actions that may orchestrate multiple element interactions.\n *\n * @example\n * ```tsx\n * function LoginForm() {\n * const [email, setEmail] = useState('');\n * const [password, setPassword] = useState('');\n *\n * useUIComponent({\n * id: 'login-form',\n * name: 'Login Form',\n * actions: [\n * {\n * id: 'login',\n * label: 'Submit Login',\n * handler: async ({ email, password }) => {\n * setEmail(email);\n * setPassword(password);\n * await submitLogin();\n * },\n * },\n * {\n * id: 'clear',\n * label: 'Clear Form',\n * handler: () => {\n * setEmail('');\n * setPassword('');\n * },\n * },\n * ],\n * });\n *\n * return (\n * <View>\n * <TextInput value={email} onChangeText={setEmail} />\n * <TextInput value={password} onChangeText={setPassword} secureTextEntry />\n * <Button title=\"Login\" onPress={handleSubmit} />\n * </View>\n * );\n * }\n * ```\n */\nexport function useUIComponent(options: UseUIComponentOptions): UseUIComponentReturn {\n const bridge = useUIBridgeNativeOptional();\n // `registeredRef` is authoritative for the register/unregister guard (same\n // rationale as `useUIElement`: threading the state into the register\n // callback's deps builds a cleanup/run feedback loop). `registered` is the\n // rendered mirror — the value this hook RETURNS, which used to be\n // `registeredRef.current` and so was read during render before any effect had\n // set it: it was `false` on the first render and only ever changed if\n // something unrelated re-rendered the consumer.\n const [registered, setRegistered] = useState(false);\n // Bumped whenever the registry's copy of this component demonstrably changed,\n // to force the render-phase read of `registeredComponent` below to re-run.\n //\n // A version counter rather than holding the entry itself in state, and that is\n // load-bearing. `registerComponent` returns a FRESH object every call, so\n // storing it would re-render on every registration — and a provider whose\n // context value churns per render re-registers every element on every render,\n // which would then be an unbounded loop instead of the bounded registry churn\n // it is today. PR #179 fixed that churn at the provider, but this hook should\n // not be the thing that turns a provider bug into a hang. Hence\n // `publishedIdRef`: a re-registration under an UNCHANGED id bumps nothing.\n const [publishVersion, setPublishVersion] = useState(0);\n const publishedIdRef = useRef<string | null>(null);\n const registeredRef = useRef(false);\n const registeredIdRef = useRef<string | null>(null);\n const actionsRef = useRef(options.actions || []);\n const elementIdsRef = useRef(options.elementIds || []);\n\n const { id, name, description, autoRegister = true } = options;\n\n // Value signatures of the DECLARED lists. The arrays themselves are freshly\n // allocated on essentially every render at every call site, so their identity\n // says nothing; these say whether anything a bridge consumer can SEE moved.\n // `handler` is excluded for the same reason the registry excludes it (see\n // `publishedActionSignature`) — it is never published, and it changes every\n // render.\n const actionsSignature = JSON.stringify(\n (options.actions ?? []).map((a) => [a.id, a.label, a.description, a.paramSchema, a.effect])\n );\n const elementIdsSignature = JSON.stringify(options.elementIds ?? []);\n\n // Track the declared `actions` on every render, so the trampoline below always\n // resolves to the CURRENT closure. Only when the option is actually SUPPLIED:\n // overwriting unconditionally — which is what `options.actions || []` did —\n // wipes an action list installed through the imperative `updateActions` lane\n // on the very next render of a call site that declares no `actions` option.\n useEffect(() => {\n if (options.actions !== undefined) actionsRef.current = options.actions;\n }, [options.actions]);\n\n // `elementIds` carries no closures, so it is re-asserted only when the\n // DECLARED value actually changes. Doing it every render instead would undo\n // `addElement` / `removeElement` on the next render of any call site that\n // declares an `elementIds` option AND adds to it — the two lanes would fight,\n // and the imperative one would appear to work and then silently revert.\n useEffect(() => {\n if (options.elementIds !== undefined) elementIdsRef.current = options.elementIds;\n // Keyed on the value signature, not the array identity, which is freshly\n // allocated on every render at every call site.\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [elementIdsSignature]);\n\n // Map the declared actions into the registry's shape.\n //\n // The handler is a trampoline that resolves through `actionsRef.current` at\n // INVOKE time. Without it the registry holds the closure from the render that\n // registered the component, for the life of the mount — so an action handler\n // reading component state read that state as it was at mount, and\n // `updateActions` was the only escape from a staleness nothing announced.\n //\n // Everything else is spread rather than re-listed field by field. The\n // hand-rolled list this replaces is the exact silent-drop trap this file's own\n // comments recorded twice (`paramSchema` in Phase 2, `effect` in Phase 4): a\n // field added to `ComponentActionDef` stayed assignable here and simply never\n // arrived. The registry closes the field list once, on the way in; a second\n // closed list here is only a second place to forget.\n const toRegistryActions = useCallback(\n () =>\n actionsRef.current.map(({ handler: declaredHandler, ...rest }) => ({\n ...rest,\n handler: (params?: unknown, handlerOptions?: { signal?: AbortSignal }) => {\n const latest = actionsRef.current.find((a) => a.id === rest.id);\n return (latest?.handler ?? declaredHandler)(params, handlerOptions);\n },\n })),\n []\n );\n\n // Register the component\n const register = useCallback(() => {\n if (!bridge || registeredRef.current) return;\n\n bridge.registry.registerComponent(id, {\n name,\n description,\n actions: toRegistryActions(),\n elementIds: elementIdsRef.current,\n });\n registeredRef.current = true;\n registeredIdRef.current = id;\n setRegistered(true);\n // Only when the id this hook has PUBLISHED actually moved. A re-registration\n // under the same id produces an entry a consumer cannot tell apart from the\n // one it already has, so it is not worth a render — and skipping it is what\n // keeps a churning provider from spinning this hook forever.\n if (publishedIdRef.current !== id) {\n publishedIdRef.current = id;\n setPublishVersion((v) => v + 1);\n }\n }, [bridge, id, name, description, toRegistryActions]);\n\n // Unregister the component\n const unregister = useCallback(() => {\n if (!bridge || !registeredRef.current) return;\n\n bridge.registry.unregisterComponent(registeredIdRef.current ?? id);\n registeredRef.current = false;\n registeredIdRef.current = null;\n setRegistered(false);\n // `publishedIdRef` is deliberately NOT cleared here. It records the id whose\n // registration the render-phase read has already been told about, and\n // clearing it would re-arm the bump in `register()` � which is exactly the\n // unbounded loop this guard exists to prevent, since a provider with a\n // churning context value runs unregister+register on every render. Going\n // un-registered is already visible through `registered` flipping to false.\n }, [bridge, id]);\n\n // Execute an action\n const executeAction = useCallback(\n async <TParams = unknown, TResult = unknown>(\n actionId: string,\n params?: TParams\n ): Promise<TResult> => {\n if (!bridge) {\n throw new Error('UI Bridge Native not available');\n }\n\n const response = await bridge.executor.executeComponentAction(id, {\n action: actionId,\n params: params as Record<string, unknown>,\n });\n\n if (!response.success) {\n throw new Error(response.error || 'Action failed');\n }\n\n return response.result as TResult;\n },\n [bridge, id]\n );\n\n // Publish whatever `elementIdsRef` now holds. Shared by `addElement` and\n // `removeElement`, which BOTH used to mutate the ref and stop there — the\n // registry kept its mount-time `elementIds` and the component's ownership\n // list, as read from `/control/components`, was a fossil. The hook returned\n // two functions that did nothing observable.\n const publishElementIds = useCallback(() => {\n if (!registeredRef.current || !bridge) return;\n const changed = bridge.registry.updateComponentMeta(registeredIdRef.current ?? id, {\n elementIds: elementIdsRef.current,\n });\n if (changed) {\n setPublishVersion((v) => v + 1);\n }\n }, [bridge, id]);\n\n // Update actions dynamically\n const updateActions = useCallback(\n (actions: ComponentActionDef[]) => {\n actionsRef.current = actions;\n\n // Publish in place. This used to unregister and re-register, which emitted\n // a spurious `component:unregistered`/`component:registered` pair and left\n // the component ABSENT from the registry for the width of the call — a\n // snapshot taken in that window reported a component the app had not\n // stopped rendering.\n if (registeredRef.current && bridge) {\n const targetId = registeredIdRef.current ?? id;\n const changed = bridge.registry.updateComponentMeta(targetId, {\n actions: toRegistryActions(),\n });\n if (changed) {\n setPublishVersion((v) => v + 1);\n }\n }\n },\n [bridge, id, toRegistryActions]\n );\n\n // Add element ID\n const addElement = useCallback(\n (elementId: string) => {\n if (!elementIdsRef.current.includes(elementId)) {\n elementIdsRef.current = [...elementIdsRef.current, elementId];\n publishElementIds();\n }\n },\n [publishElementIds]\n );\n\n // Remove element ID\n const removeElement = useCallback(\n (elementId: string) => {\n if (!elementIdsRef.current.includes(elementId)) return;\n elementIdsRef.current = elementIdsRef.current.filter((eid) => eid !== elementId);\n publishElementIds();\n },\n [publishElementIds]\n );\n\n // Keep latest register/unregister in refs so the auto-register effect does\n // not re-run when consumers pass inline options.\n const registerRef = useRef(register);\n const unregisterRef = useRef(unregister);\n useEffect(() => {\n registerRef.current = register;\n unregisterRef.current = unregister;\n }, [register, unregister]);\n\n // Auto-register on mount, and RE-register when `id` changes.\n //\n // `id` is a real dependency even though the effect body never reads it, for\n // the same reason `useUIElement`'s effect lists it: without it the effect\n // never re-ran on an id change, so the OLD id stayed registered forever and\n // the NEW id was never registered at all. `registeredIdRef` existed to name\n // the old id during teardown and could never actually differ from `id`,\n // because nothing re-ran the effect — the field was dead for want of this dep.\n //\n // Ordering on an id-change render: the cleanup runs first, closing over the\n // PREVIOUS `unregisterRef.current`, which removes `registeredIdRef.current` —\n // the OLD id — and resets the guard. The ref-sync effect above is declared\n // first, so by the time this body re-runs, `registerRef.current` registers the\n // NEW id.\n useEffect(() => {\n if (autoRegister) {\n registerRef.current();\n }\n\n return () => {\n if (registeredRef.current) {\n unregisterRef.current();\n }\n };\n }, [autoRegister, bridge, id]);\n\n // Keep the registry's copy of the declaration in step with the OPTIONS —\n // automatically.\n //\n // ROOT CAUSE this closes, and it is PR #176's defect one level up:\n // `register()` publishes name / description / actions / elementIds exactly\n // once and is guarded by `registeredRef`, while the auto-register effect\n // re-runs only on `[autoRegister, bridge, id]`. So a component whose\n // declaration is derived from state — an action label carrying a count, an\n // action that exists only while a row is selected, a `paramSchema` that widens\n // once options load — published its mount-time shape to `/control/components`\n // for the life of the mount. `updateActions` was the manual escape hatch, the\n // same shape `updateLabel` was for elements before #176 auto-published the\n // `label` option.\n //\n // Only the fields the call site actually DECLARES are re-asserted: a hook used\n // purely imperatively (no `actions` / `elementIds` option) must not have its\n // `updateActions` / `addElement` work overwritten by an empty declarative\n // lane.\n //\n // Gated on `registered` rather than `registeredRef` so it runs on the commit\n // that FOLLOWS registration, and keyed on the value signatures rather than the\n // arrays, whose identity churns every render.\n useEffect(() => {\n if (!bridge || !registered) return;\n const targetId = registeredIdRef.current ?? id;\n const changed = bridge.registry.updateComponentMeta(targetId, {\n name,\n description,\n ...(options.actions !== undefined ? { actions: toRegistryActions() } : {}),\n ...(options.elementIds !== undefined ? { elementIds: elementIdsRef.current } : {}),\n });\n if (changed) {\n setPublishVersion((v) => v + 1);\n }\n // `actionsSignature` / `elementIdsSignature` stand in for the arrays they\n // summarise; the arrays themselves are deliberately NOT deps, since their\n // identity changes on every render at every call site.\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [\n bridge,\n registered,\n id,\n name,\n description,\n actionsSignature,\n elementIdsSignature,\n toRegistryActions,\n ]);\n\n // Read straight out of the registry during render, rather than mirroring the\n // entry into state.\n //\n // The registry is the owner; a copy held in state is a second one that can\n // disagree. `publishVersion` is what makes this read re-run � it is bumped\n // exactly when the registry's copy demonstrably changed, so this value is as\n // fresh as the last publish and costs one `Map.get` per render.\n //\n // Pre-fix this was a `useMemo` on `[bridge, id]`, which ran BEFORE the\n // register effect on the first render and never recomputed: permanently\n // `null` for every consumer that read it.\n void publishVersion;\n const registeredComponent =\n registered && bridge ? (bridge.registry.getComponent(id) ?? null) : null;\n\n return {\n registered,\n executeAction,\n register,\n unregister,\n updateActions,\n addElement,\n removeElement,\n registeredComponent,\n };\n}\n\n/**\n * useUIComponentAction hook\n *\n * Create a stable action handler that can be used with useUIComponent.\n * Useful for memoizing action handlers.\n */\nexport function useUIComponentAction<TParams = unknown, TResult = unknown>(\n handler: (params?: TParams, options?: { signal?: AbortSignal }) => TResult | Promise<TResult>,\n deps: React.DependencyList\n): (params?: TParams, options?: { signal?: AbortSignal }) => TResult | Promise<TResult> {\n // eslint-disable-next-line react-hooks/exhaustive-deps\n return useCallback(handler, deps);\n}\n","/**\n * useUIBridge Hook for React Native\n *\n * Provides a simplified interface for common UI Bridge operations.\n */\n\nimport { useCallback, useMemo } from 'react';\nimport type {\n NativeActionRequest,\n NativeActionResponse,\n NativeFindRequest,\n NativeFindResponse,\n NativeBridgeSnapshot,\n RegisteredNativeElement,\n RegisteredNativeComponent,\n Workflow,\n} from '../core/types';\nimport type { ComponentActionRequest, ComponentActionResponse } from '../control/types';\nimport { useUIBridgeNativeOptional } from './UIBridgeNativeProvider';\n\n/**\n * Component action request / response.\n *\n * Re-exported from `../control/types` rather than re-declared. These were a\n * fifth and sixth copy of a shape that already existed there, and the copy had\n * already drifted: it carried neither `requestId` nor `timeoutMs`, so a React\n * Native caller reaching an action through this hook could not set a timeout\n * even though `DefaultNativeActionExecutor` has honoured one since Phase 3 of\n * plan `2026-08-20-ui-bridge-action-declaration-shape`. The executor accepted\n * it; the hook's own type refused to express it.\n *\n * `timeoutMs` is the only cancellation this seam can carry — an `AbortSignal`\n * is not JSON-serializable, and the hook does not forward the executor's\n * in-process `{ signal }` option bag.\n *\n * Collapsing rather than adding the two fields is the plan's stated direction:\n * \"collapse before you extend\", because eight copies drift and two already\n * had.\n */\nexport type {\n ComponentActionRequest,\n ComponentActionResponse,\n} from '../control/types';\n\n/**\n * useUIBridge return type\n */\nexport interface UseUIBridgeReturn {\n /** Whether UI Bridge is available */\n available: boolean;\n /** Whether UI Bridge is initialized */\n initialized: boolean;\n /** All registered elements */\n elements: RegisteredNativeElement[];\n /** All registered components */\n components: RegisteredNativeComponent[];\n /** All registered workflows */\n workflows: Workflow[];\n /** Create a snapshot of the current state */\n createSnapshot: () => NativeBridgeSnapshot;\n /** Execute an action on an element */\n executeAction: (elementId: string, request: NativeActionRequest) => Promise<NativeActionResponse>;\n /** Execute a component action */\n executeComponentAction: (\n componentId: string,\n request: ComponentActionRequest\n ) => Promise<ComponentActionResponse>;\n /** Find elements */\n find: (request?: NativeFindRequest) => Promise<NativeFindResponse>;\n /** Get an element by ID */\n getElement: (id: string) => RegisteredNativeElement | undefined;\n /** Get a component by ID */\n getComponent: (id: string) => RegisteredNativeComponent | undefined;\n /** Get element state by ID */\n getElementState: (id: string) => ReturnType<RegisteredNativeElement['getState']> | null;\n /** Register a workflow */\n registerWorkflow: (workflow: Workflow) => void;\n /** Unregister a workflow */\n unregisterWorkflow: (id: string) => void;\n}\n\n/**\n * useUIBridge hook\n *\n * Provides a simplified interface for accessing UI Bridge functionality.\n *\n * @example\n * ```tsx\n * function MyComponent() {\n * const { available, elements, executeAction, find } = useUIBridge();\n *\n * if (!available) {\n * return <Text>UI Bridge not available</Text>;\n * }\n *\n * const handlePress = async () => {\n * // Find all buttons\n * const result = await find({ types: ['button'] });\n * console.log('Found buttons:', result.elements);\n *\n * // Execute action on specific element\n * await executeAction('submit-btn', { action: 'press' });\n * };\n *\n * return (\n * <View>\n * <Text>Elements: {elements.length}</Text>\n * <Button title=\"Press\" onPress={handlePress} />\n * </View>\n * );\n * }\n * ```\n */\nexport function useUIBridge(): UseUIBridgeReturn {\n const bridge = useUIBridgeNativeOptional();\n\n const available = bridge !== null;\n const initialized = bridge?.initialized ?? false;\n\n // Get elements\n const elements = useMemo(() => (bridge ? bridge.getElements() : []), [bridge]);\n\n // Get components\n const components = useMemo(() => (bridge ? bridge.getComponents() : []), [bridge]);\n\n // Get workflows\n const workflows = useMemo(() => (bridge ? bridge.registry.getAllWorkflows() : []), [bridge]);\n\n // Create snapshot\n const createSnapshot = useCallback((): NativeBridgeSnapshot => {\n if (!bridge) {\n return {\n timestamp: Date.now(),\n elements: [],\n components: [],\n workflows: [],\n };\n }\n return bridge.createSnapshot();\n }, [bridge]);\n\n // Execute action\n const executeAction = useCallback(\n async (elementId: string, request: NativeActionRequest): Promise<NativeActionResponse> => {\n if (!bridge) {\n return {\n success: false,\n error: 'UI Bridge not available',\n durationMs: 0,\n timestamp: Date.now(),\n };\n }\n return bridge.executor.executeAction(elementId, request);\n },\n [bridge]\n );\n\n // Execute component action\n const executeComponentAction = useCallback(\n async (\n componentId: string,\n request: ComponentActionRequest\n ): Promise<ComponentActionResponse> => {\n if (!bridge) {\n return {\n success: false,\n error: 'UI Bridge not available',\n durationMs: 0,\n timestamp: Date.now(),\n };\n }\n return bridge.executor.executeComponentAction(componentId, request);\n },\n [bridge]\n );\n\n // Find elements\n const find = useCallback(\n async (request?: NativeFindRequest): Promise<NativeFindResponse> => {\n if (!bridge) {\n return {\n elements: [],\n total: 0,\n durationMs: 0,\n timestamp: Date.now(),\n };\n }\n return bridge.executor.find(request || {});\n },\n [bridge]\n );\n\n // Get element\n const getElement = useCallback((id: string) => bridge?.registry.getElement(id), [bridge]);\n\n // Get component\n const getComponent = useCallback((id: string) => bridge?.registry.getComponent(id), [bridge]);\n\n // Get element state\n const getElementState = useCallback(\n (id: string) => {\n const element = bridge?.registry.getElement(id);\n return element?.getState() ?? null;\n },\n [bridge]\n );\n\n // Register workflow\n const registerWorkflow = useCallback(\n (workflow: Workflow) => {\n bridge?.registry.registerWorkflow(workflow);\n },\n [bridge]\n );\n\n // Unregister workflow\n const unregisterWorkflow = useCallback(\n (id: string) => {\n bridge?.registry.unregisterWorkflow(id);\n },\n [bridge]\n );\n\n return {\n available,\n initialized,\n elements,\n components,\n workflows,\n createSnapshot,\n executeAction,\n executeComponentAction,\n find,\n getElement,\n getComponent,\n getElementState,\n registerWorkflow,\n unregisterWorkflow,\n };\n}\n\n/**\n * useUIBridgeRequired hook\n *\n * Same as useUIBridge but throws if not available.\n */\nexport function useUIBridgeRequired(): UseUIBridgeReturn {\n const result = useUIBridge();\n if (!result.available) {\n throw new Error('useUIBridgeRequired must be used within a UIBridgeNativeProvider');\n }\n return result;\n}\n","import { useEffect } from 'react';\nimport { useUIBridgeNative } from './UIBridgeNativeProvider';\nimport type { NativeModalInfo } from '../core/types';\n\nexport interface UseUIBridgeModalOptions {\n id: string;\n title?: string;\n type?: NativeModalInfo['type'];\n blocking?: boolean;\n dismissible?: boolean;\n}\n\n/**\n * Declarative hook: while mounted, registers a modal entry on the active\n * stack so UI Bridge snapshots reflect that a modal is open.\n */\nexport function useUIBridgeModal(opts: UseUIBridgeModalOptions): void {\n const { modalDetector } = useUIBridgeNative();\n const { id, title, type, blocking, dismissible } = opts;\n\n useEffect(() => {\n modalDetector.pushModal({ id, title, type, blocking, dismissible });\n return () => {\n modalDetector.dismissModal(id);\n };\n }, [modalDetector, id, title, type, blocking, dismissible]);\n}\n","import { useCallback, useEffect } from 'react';\nimport { useUIBridgeNative } from './UIBridgeNativeProvider';\nimport type { NativeCapturedToast } from '../core/types';\n\nexport interface UseUIBridgeToastOptions {\n id: string;\n message: string;\n level?: NativeCapturedToast['level'];\n}\n\n/**\n * Declarative hook: while mounted, surfaces a toast via the snapshot enricher.\n * Best for explicit-lifecycle toast components.\n */\nexport function useUIBridgeToast(opts: UseUIBridgeToastOptions): void {\n const { toastCapture } = useUIBridgeNative();\n const { id, message, level } = opts;\n\n useEffect(() => {\n toastCapture.recordToast({ id, message, level });\n return () => {\n toastCapture.dismissToast(id);\n };\n }, [toastCapture, id, message, level]);\n}\n\nexport interface ToastRecorderInput {\n id: string;\n message: string;\n level?: NativeCapturedToast['level'];\n}\n\n/**\n * Imperative hook: returns a `recordToast` callback for code that fires\n * toasts outside React (catch blocks, library callbacks, etc.).\n */\nexport function useToastRecorder(): {\n recordToast: (toast: ToastRecorderInput) => void;\n dismissToast: (id: string) => void;\n} {\n const { toastCapture } = useUIBridgeNative();\n const recordToast = useCallback(\n (toast: ToastRecorderInput) => {\n toastCapture.recordToast(toast);\n },\n [toastCapture]\n );\n const dismissToast = useCallback((id: string) => toastCapture.dismissToast(id), [toastCapture]);\n return { recordToast, dismissToast };\n}\n","import type { ReactElement, ReactNode } from 'react';\n\nexport interface StateAnnotationRequiredElement {\n role?: string;\n text?: string;\n testID?: string;\n [key: string]: unknown;\n}\n\nexport interface StateProps {\n id: string;\n name?: string;\n description?: string;\n requiredElements?: StateAnnotationRequiredElement[];\n blocking?: boolean;\n children?: ReactNode;\n [key: string]: unknown;\n}\n\nexport function State(props: StateProps): ReactElement {\n return <>{props.children}</>;\n}\n\nexport interface TransitionToProps {\n id: string;\n name?: string;\n fromStates?: string[];\n activateStates?: string[];\n exitStates?: string[];\n effect?: string;\n description?: string;\n children?: ReactNode;\n [key: string]: unknown;\n}\n\nexport function TransitionTo(props: TransitionToProps): ReactElement {\n return <>{props.children}</>;\n}\n","/**\n * UI Bridge Native Server Types\n *\n * Types for the embedded HTTP server.\n */\n\nimport type {\n NativeUIBridgeConfig,\n NativeActionResponse,\n NativeFindResponse,\n NativeBridgeSnapshot,\n} from '../core/types';\nimport type { ComponentActionResponse, PageNavigationResponse } from '../control/types';\nimport type { ElementDesignData, StateStyles, ResponsiveSnapshot } from '../design/design-types';\n\n/**\n * Navigation provider for React Native apps.\n *\n * Apps supply this to enable programmatic navigation via the UI Bridge\n * (e.g., `control/page/navigate` and `control/page/back`).\n * For Expo Router: pass `router.push` and `router.back`.\n */\nexport interface NavigationProvider {\n navigate: (url: string) => void;\n back?: () => void;\n /** Replace current route (no back-stack entry). For Expo Router: router.replace */\n replace?: (url: string) => void;\n /** Refresh the current route. For Expo Router: router.replace(currentPath) */\n refresh?: () => void;\n}\n\n/**\n * Screenshot provider for React Native apps.\n *\n * Apps supply this to enable screen capture via the UI Bridge\n * (`control/screenshot`). For react-native-view-shot: pass a function\n * that calls `captureRef` on the root view and returns base64 PNG data.\n */\nexport interface ScreenshotProvider {\n /** Capture the current screen and return base64-encoded PNG data (no data: prefix). */\n capture: () => Promise<{ base64: string; width: number; height: number }>;\n}\n\n/** Device keep-awake capability, injected by the host app (expo-keep-awake is mobile-only). */\nexport interface KeepAwakeProvider {\n request(source: string, durationMs?: number): void;\n release(source: string): void;\n}\n\n/**\n * Route provider for React Native apps.\n *\n * Apps supply this to expose the current navigation route in UI Bridge snapshots.\n * For Expo Router: render a RouteTracker component inside the router context that\n * calls `usePathname()` / `useSegments()` and writes the result to a module-level ref.\n */\nexport interface RouteProvider {\n /** Return the current route path (e.g. \"/(tabs)/runs\"), or null if unknown. */\n getCurrentRoute: () => string | null;\n /** Return the current route segments (e.g. [\"(tabs)\", \"runs\"]), if available. */\n getSegments?: () => string[];\n /**\n * Optionally return the currently-active tab id for the snapshot's\n * `activeTab` field. Only needed when the visible pane is decoupled from the\n * router; Expo Router apps can omit it and let the registry derive the value\n * from `getSegments()`.\n */\n getActiveTab?: () => string | null | undefined;\n /**\n * Subscribe to route changes. Required so the UI Bridge can clear stale\n * layouts on route changes with zero lag.\n *\n * Implementers must invoke `listener` synchronously whenever the route\n * changes, passing the new route (or null if unknown). The returned function\n * must unsubscribe the listener.\n *\n * For Expo Router: wrap your RouteTracker component in a module-level\n * listener set and call each listener from within the tracker's effect.\n */\n subscribe: (listener: (route: string | null) => void) => () => void;\n}\n\n/**\n * Server configuration\n */\nexport interface NativeServerConfig extends NativeUIBridgeConfig {\n /** Enable CORS */\n cors?: boolean;\n /** Allowed origins for CORS */\n allowedOrigins?: string[];\n /**\n * Enable test-only HTTP endpoints (currently `control/modal/push` and\n * `control/modal/dismiss/:id`) so external runners can drive registry\n * state. Default `false`; the React provider mirrors\n * `features.testHooks` into this slot.\n */\n testHooks?: boolean;\n /**\n * Enable the read-only observability capture (console.error/warn +\n * fetch/XHR ring buffers backing `GET /control/console-errors` and\n * `GET /sdk/network-requests`). When omitted, falls back to the\n * `testHooks` value so existing consumers are unchanged; set explicitly\n * to decouple release-build capture from the testHooks-gated control\n * surface. The React provider mirrors `features.observability` into\n * this slot.\n */\n observability?: boolean;\n /**\n * Viewport getter for `POST /control/page-health`.\n *\n * Injected by `UIBridgeNativeProvider` from `Dimensions.get('window')`.\n * Lives at config-injection level because importing react-native from\n * `handlers.ts` (or even `require('react-native')` with try/catch) crashed\n * the host RN app in 0.6.3/0.6.4: Metro/Hermes raised\n * `unknownModuleError` past every local try/catch and tore down the JS\n * thread (blank screen, React tree destroyed). The provider already has\n * a live import of `react-native`, so it's the safe injection point.\n *\n * When absent: `page-health` falls back to `body.viewport`, then `{0,0}`\n * (degenerate coverage report — no crash).\n */\n viewportProvider?: () => { width: number; height: number };\n}\n\n/**\n * Route definition\n */\nexport interface RouteDefinition {\n method: 'GET' | 'POST' | 'PUT' | 'DELETE';\n path: string;\n description: string;\n /**\n * True when the route is mounted only if the server config sets\n * `testHooks`. A production build (the default, `testHooks: false`) does not\n * serve it at all — `routeRequest` and `buildRoutesPayload` both drop it, so\n * the honest answer there is a bare 404 with no `Allow`.\n *\n * This field exists because the table is a static constant with no config to\n * consult, so it published the gated routes unconditionally and the only\n * signal was the free-text `(testHooks)` in `description` — which a consumer\n * code-generating a client from this table cannot read. It would call\n * `POST /ui-bridge/control/keep-awake` against a release build, get a bare\n * 404, and have no way to tell it from a typo. `route-table-parity.test.ts`\n * asserts this flag against the flag-off route set, so a fourth gated route —\n * or one of these three accidentally un-gated — cannot change the production\n * surface with the tests still green.\n */\n requiresTestHooks?: boolean;\n}\n\n/**\n * Every HTTP route this package serves.\n *\n * This is the contract an external consumer reads off the package root\n * (`src/index.ts` exports it) to learn what `@qontinui/ui-bridge-native`\n * answers. It is a SECOND declaration of a surface whose single source of\n * truth is `WS_ROUTES` in `./http-server.ts`, which is what `routeRequest`\n * iterates and what `/ui-bridge/_routes` publishes at runtime. Nothing in this\n * package reads the constant below, so nothing made the two agree.\n *\n * They had stopped agreeing. Measured 2026-08-31 against `_routes` with\n * `testHooks: true`: the router served **56** method+path pairs and this table\n * published **36** — every entry here was reachable, but twenty routes the\n * package serves were absent, among them `control/tap`, `control/screenshot`,\n * `ai/find`, the five `control/page/*` interaction endpoints (`click-by-text`,\n * `click-by-selector`, `type-into`, `read-value`, `find-by-text`), the four\n * `design/evaluate*` endpoints and the two discovery endpoints (`_help`,\n * `_routes`) a consumer would use to find the rest. The twenty were added and\n * `route-table-parity.test.ts` now asserts SET EQUALITY with `_routes` in both\n * directions, so neither declaration can move without the other.\n *\n * KEEP IN SYNC with `WS_ROUTES`. That comment used to be the whole mechanism;\n * it is now a pointer to the test that enforces it.\n *\n * The sibling surface (`@qontinui/ui-bridge/native`) exports a constant of the\n * same name over a smaller route set, and there `routeRequest` READS it — the\n * wrong-verb arm derives its 405 from it (qontinui/ui-bridge#189). Do not\n * assume an entry present in one is present in the other; the two packages\n * publish different surfaces and only the status mapping is pinned equal\n * (`packages/ui-bridge/src/native/server/http-status-parity.test.ts`).\n *\n * Multi-verb routes appear once PER VERB, because `RouteDefinition.method` is\n * singular — `control/discover`, `control/page-health` and `control/screenshot`\n * each take GET and POST, and `design/style-guide` takes GET and DELETE.\n */\nexport const UI_BRIDGE_NATIVE_ROUTES: Record<string, RouteDefinition> = {\n // Discovery / introspection — the two endpoints an agent hits first to learn\n // the rest of this table without reading docs. Special-cased in\n // `routeRequest` rather than living in `WS_ROUTES`, and appended by\n // `buildRoutesPayload` so `_routes` describes itself.\n HELP: {\n method: 'GET',\n path: '/ui-bridge/_help',\n description: 'Route index + action reference + tips (rich discovery payload)',\n },\n ROUTES: {\n method: 'GET',\n path: '/ui-bridge/_routes',\n description: 'Minimal {method, path} route list, matching the runner /_routes shape',\n },\n\n // Control - Elements\n GET_ELEMENTS: {\n method: 'GET',\n path: '/ui-bridge/control/elements',\n description: 'List all registered elements',\n },\n GET_ELEMENTS_FLAT: {\n method: 'GET',\n path: '/ui-bridge/elements',\n description: 'List all registered elements (flat alias matching the runner path)',\n },\n GET_ELEMENT: {\n method: 'GET',\n path: '/ui-bridge/control/element/:id',\n description: 'Get element details',\n },\n GET_ELEMENT_STATE: {\n method: 'GET',\n path: '/ui-bridge/control/element/:id/state',\n description: 'Get element state',\n },\n EXECUTE_ACTION: {\n method: 'POST',\n path: '/ui-bridge/control/element/:id/action',\n description: 'Execute action on element',\n },\n\n // Control - Components\n GET_COMPONENTS: {\n method: 'GET',\n path: '/ui-bridge/control/components',\n description: 'List all registered components',\n },\n GET_COMPONENT: {\n method: 'GET',\n path: '/ui-bridge/control/component/:id',\n description: 'Get component details',\n },\n EXECUTE_COMPONENT_ACTION: {\n method: 'POST',\n path: '/ui-bridge/control/component/:id/action/:actionId',\n description: 'Execute component action',\n },\n\n // Discovery\n FIND: {\n method: 'POST',\n path: '/ui-bridge/control/find',\n description: 'Find elements matching criteria',\n },\n AI_FIND: {\n method: 'POST',\n path: '/ui-bridge/ai/find',\n description: 'Find elements matching criteria (runner-parity alias for /control/find)',\n },\n GET_SNAPSHOT: {\n method: 'GET',\n path: '/ui-bridge/control/snapshot',\n description: 'Get full bridge snapshot',\n },\n DISCOVER: {\n method: 'GET',\n path: '/ui-bridge/control/discover',\n description: 'Discover elements (alias for snapshot; web/runner parity)',\n },\n DISCOVER_POST: {\n method: 'POST',\n path: '/ui-bridge/control/discover',\n description: 'Discover elements over POST (same handler as the GET form; web/runner parity)',\n },\n PAGE_HEALTH: {\n method: 'POST',\n path: '/ui-bridge/control/page-health',\n description:\n 'Holistic page health diagnostic: spatial coverage, layout regions, text signals, interactive readiness, anomalies + ASCII heatmap',\n },\n PAGE_HEALTH_GET: {\n method: 'GET',\n path: '/ui-bridge/control/page-health',\n description: 'Page health diagnostic over GET, for ad-hoc curls with no body',\n },\n\n // Screenshots — GET and POST both accepted so a curl works either way.\n //\n // Both keys carry an explicit verb suffix. The pre-existing multi-verb pairs\n // do not agree on what an UNSUFFIXED key means — `DISCOVER` is the GET and\n // `PAGE_HEALTH` is the POST — so a consumer reading `ROUTES.<NAME>.method`\n // off a bare name gets opposite verbs from equally unmarked keys. Those two\n // names are load-bearing for existing consumers and are left alone; new\n // multi-verb entries name their verb rather than entrenching the ambiguity.\n SCREENSHOT_GET: {\n method: 'GET',\n path: '/ui-bridge/control/screenshot',\n description: 'PNG screenshot of the current screen',\n },\n SCREENSHOT_POST: {\n method: 'POST',\n path: '/ui-bridge/control/screenshot',\n description: 'PNG screenshot of the current screen (POST form)',\n },\n\n // Coordinate-based interaction\n CONTROL_TAP: {\n method: 'POST',\n path: '/ui-bridge/control/tap',\n description:\n 'Synthesize a press at screen coords by matching registered element layout rects: body { x, y, action? }',\n },\n\n // App-agnostic interaction parity with the web/runner surface. The\n // selector-based pair has no RN analog and answers NOT_SUPPORTED (501).\n PAGE_CLICK_BY_TEXT: {\n method: 'POST',\n path: '/ui-bridge/control/page/click-by-text',\n description: 'Press the first element matching free text: body { text, visibleOnly? }',\n },\n PAGE_CLICK_BY_SELECTOR: {\n method: 'POST',\n path: '/ui-bridge/control/page/click-by-selector',\n description: 'Selector-based press (web-only; mobile returns NOT_SUPPORTED)',\n },\n PAGE_TYPE_INTO: {\n method: 'POST',\n path: '/ui-bridge/control/page/type-into',\n description: 'Type into the input matching a label: body { label, text, clear?, visibleOnly? }',\n },\n PAGE_READ_VALUE: {\n method: 'POST',\n path: '/ui-bridge/control/page/read-value',\n description: 'Selector-based value read (web-only; mobile returns NOT_SUPPORTED)',\n },\n PAGE_FIND_BY_TEXT: {\n method: 'POST',\n path: '/ui-bridge/control/page/find-by-text',\n description: 'List elements matching free text without pressing: body { text, visibleOnly? }',\n },\n\n // Meta\n META_METHODS: {\n method: 'GET',\n path: '/ui-bridge/meta/methods',\n description: 'List every handler name (legacy introspection; prefer /_routes)',\n },\n\n // Workflows\n GET_WORKFLOWS: {\n method: 'GET',\n path: '/ui-bridge/control/workflows',\n description: 'List all workflows',\n },\n RUN_WORKFLOW: {\n method: 'POST',\n path: '/ui-bridge/control/workflow/:id/run',\n description: 'Run a workflow',\n },\n\n // Page Navigation\n PAGE_REFRESH: {\n method: 'POST',\n path: '/ui-bridge/control/page/refresh',\n description: 'Refresh the current page',\n },\n PAGE_NAVIGATE: {\n method: 'POST',\n path: '/ui-bridge/control/page/navigate',\n description: 'Navigate to a URL',\n },\n PAGE_REPLACE: {\n method: 'POST',\n path: '/ui-bridge/control/page/replace',\n description: 'Replace current route without adding to back stack',\n },\n PAGE_GO_BACK: {\n method: 'POST',\n path: '/ui-bridge/control/page/back',\n description: 'Go back in navigation history',\n },\n PAGE_GO_FORWARD: {\n method: 'POST',\n path: '/ui-bridge/control/page/forward',\n description: 'Go forward in navigation history',\n },\n\n // Design Review\n DESIGN_ELEMENT_STYLES: {\n method: 'GET',\n path: '/ui-bridge/design/element/:id/styles',\n description: 'Get computed styles for an element',\n },\n DESIGN_ELEMENT_STATE_STYLES: {\n method: 'POST',\n path: '/ui-bridge/design/element/:id/state-styles',\n description: 'Get state-specific styles for an element',\n },\n DESIGN_SNAPSHOT: {\n method: 'POST',\n path: '/ui-bridge/design/snapshot',\n description: 'Get design data for all or selected elements',\n },\n DESIGN_RESPONSIVE: {\n method: 'POST',\n path: '/ui-bridge/design/responsive',\n description: 'Get responsive snapshots (current device only on native)',\n },\n DESIGN_AUDIT: {\n method: 'POST',\n path: '/ui-bridge/design/audit',\n description: 'Run style guide audit on elements',\n },\n DESIGN_STYLE_GUIDE_LOAD: {\n method: 'POST',\n path: '/ui-bridge/design/style-guide/load',\n description: 'Load a style guide for audit',\n },\n DESIGN_STYLE_GUIDE_GET: {\n method: 'GET',\n path: '/ui-bridge/design/style-guide',\n description: 'Get currently loaded style guide',\n },\n DESIGN_STYLE_GUIDE_CLEAR: {\n method: 'DELETE',\n path: '/ui-bridge/design/style-guide',\n description: 'Clear loaded style guide',\n },\n\n // Quality Evaluation\n DESIGN_EVALUATE: {\n method: 'POST',\n path: '/ui-bridge/design/evaluate',\n description: 'Score the current UI against a quality context',\n },\n DESIGN_EVALUATE_CONTEXTS: {\n method: 'GET',\n path: '/ui-bridge/design/evaluate/contexts',\n description: 'List available quality evaluation contexts',\n },\n DESIGN_EVALUATE_BASELINE: {\n method: 'POST',\n path: '/ui-bridge/design/evaluate/baseline',\n description: 'Save a quality baseline snapshot',\n },\n DESIGN_EVALUATE_DIFF: {\n method: 'POST',\n path: '/ui-bridge/design/evaluate/diff',\n description: 'Diff the current UI against a saved baseline',\n },\n\n // AI helpers\n AI_FILL_FORM: {\n method: 'POST',\n path: '/ui-bridge/ai/fill-form',\n description: 'Fill multiple input elements in a single call',\n },\n\n // AI helpers (NOT_SUPPORTED stubs) — these endpoints exist on the runner-side\n // UI Bridge surface but have no analog on mobile React Native. The mobile\n // bridge registers explicit stubs so callers get a structured NOT_SUPPORTED\n // envelope instead of a confusing HTTP 404. The mobile bridge's snapshot +\n // `/control/find` already cover what an operator would reach for these for.\n AI_FORMS: {\n method: 'GET',\n path: '/ui-bridge/ai/forms',\n description: 'Discover forms (runner-only; mobile returns NOT_SUPPORTED)',\n },\n AI_IDLE_STATUS: {\n method: 'GET',\n path: '/ui-bridge/ai/idle-status',\n description: 'Get page-idle signal (runner-only; mobile returns NOT_SUPPORTED)',\n },\n AI_CHANGE_BUFFER_ENABLE: {\n method: 'POST',\n path: '/ui-bridge/ai/change-buffer/enable',\n description: 'Enable DOM change buffer (runner-only; mobile returns NOT_SUPPORTED)',\n },\n AI_WAIT_FOR_ELEMENT: {\n method: 'POST',\n path: '/ui-bridge/ai/wait-for-element',\n description: 'Wait for element predicate via HTTP (runner-only; mobile returns NOT_SUPPORTED — use WS waitForElement instead)',\n },\n\n // Test hooks — drive ModalDetector state and the screen lock from outside\n // the React tree (gated by `features.testHooks`). Mirrors `pushModal` /\n // `dismissModal` calls that components normally make in-process.\n //\n // These are LISTED unconditionally — this table is a static constant with no\n // config to consult — but each carries `requiresTestHooks: true`, which is\n // the machine-readable form of the `(testHooks)` in its description. With the\n // flag off `routeRequest` and `buildRoutesPayload` both drop them and the\n // route answers a bare 404. `route-table-parity.test.ts` compares the whole\n // table against `_routes` at `testHooks: true`, and the flagged subset\n // against `_routes` at `testHooks: false`, so both surfaces are pinned.\n PUSH_MODAL: {\n method: 'POST',\n path: '/ui-bridge/control/modal/push',\n description: 'Push a modal onto the modal stack (testHooks)',\n requiresTestHooks: true,\n },\n DISMISS_MODAL: {\n method: 'POST',\n path: '/ui-bridge/control/modal/dismiss/:id',\n description: 'Dismiss a modal by id (testHooks)',\n requiresTestHooks: true,\n },\n KEEP_AWAKE: {\n method: 'POST',\n path: '/ui-bridge/control/keep-awake',\n description:\n 'Keep the device screen awake via the injected keepAwakeProvider: body { enabled, durationMs? } (testHooks)',\n requiresTestHooks: true,\n },\n\n // Observability — last-N ring buffers (always mounted; `installed:false`\n // when the console/network patches are off, i.e. no testHooks).\n CONSOLE_ERRORS: {\n method: 'GET',\n path: '/ui-bridge/control/console-errors',\n description: 'Last-N captured console.error/console.warn entries',\n },\n NETWORK_REQUESTS: {\n method: 'GET',\n path: '/ui-bridge/sdk/network-requests',\n description: 'Last-N captured fetch/XHR requests with status + duration',\n },\n\n // Health\n HEALTH: {\n method: 'GET',\n path: '/ui-bridge/health',\n description: 'Health check',\n },\n};\n\n/**\n * Request body for `POST /ai/fill-form`.\n *\n * The mobile native bridge has no `setValue` action — text inputs are driven\n * via the `type` action (which calls `onChangeText`). The fillForm handler\n * dispatches each field as `executor.executeAction(elementId, { action: 'type',\n * params: { text: value, clear: true } })` so existing values are atomically\n * replaced (matching the web bridge's \"setValue\" semantics).\n *\n * Shape mirrors the runner's `POST /ui-bridge/ai/fill-form` documented in\n * docs-site/api/runner-features.md (array-of-pairs form), so callers can use\n * the same JSON across mobile and web/runner without special-casing.\n */\nexport interface FillFormFieldInput {\n /** Target element id (registered id, testID, accessibilityLabel, etc.) */\n elementId: string;\n /** Text value to write into the input. */\n value: string;\n}\n\nexport interface FillFormRequest {\n fields: FillFormFieldInput[];\n}\n\n/**\n * Per-field outcome returned by `POST /ai/fill-form`.\n */\nexport interface FillFormFieldResult {\n /** Element id from the request, echoed back. */\n elementId: string;\n /** Whether `executor.executeAction` reported success for this field. */\n success: boolean;\n /** Error message when `success === false`. Omitted on success. */\n error?: string;\n}\n\n/**\n * Response payload returned in `APIResponse.data` for `POST /ai/fill-form`.\n */\nexport interface FillFormResponse {\n results: FillFormFieldResult[];\n succeededCount: number;\n failedCount: number;\n}\n\n/**\n * Request body for `POST /control/tap` — synthesize a press at given screen\n * coordinates by searching registered elements whose layout rect contains the\n * point.\n *\n * The handler picks the topmost (smallest-area) match — usually the innermost\n * child — then dispatches the requested action via the standard executor.\n * `action` defaults to `'press'`.\n */\nexport interface TapAtRequest {\n x: number;\n y: number;\n action?: 'press' | 'longPress' | 'doubleTap';\n}\n\n/**\n * Response payload returned in `APIResponse.data` for `POST /control/tap`.\n */\nexport interface TapAtResponse {\n /** Element id whose rect contained the tap coords. */\n elementId: string;\n /** Action that was dispatched. */\n action: 'press' | 'longPress' | 'doubleTap';\n /** The element's layout rect at dispatch time (best-effort). */\n layout: {\n x: number;\n y: number;\n width: number;\n height: number;\n pageX?: number;\n pageY?: number;\n } | null;\n}\n\n/**\n * Single console error/warn entry captured by the observability ring buffer.\n * Returned by `GET /control/console-errors`.\n */\nexport interface ConsoleErrorEntry {\n /** ms since epoch when the entry was captured. */\n timestamp: number;\n /** `'error'` or `'warn'`. */\n level: 'error' | 'warn';\n /** Joined message string (matches what console would have printed). */\n message: string;\n /** Captured stack trace if any of the args was an Error. */\n stack?: string;\n}\n\n/**\n * Response payload for `GET /control/console-errors`.\n */\nexport interface ConsoleErrorsResponse {\n entries: ConsoleErrorEntry[];\n /** Number of entries returned (post `since`/`limit` filtering). */\n count: number;\n /** Total entries currently held in the ring buffer (pre-filter). */\n bufferSize: number;\n /**\n * Whether the console capture patch is actively installed. `false` means\n * the endpoint is mounted and schema-valid but not observing — typically\n * because `features.testHooks` is off (production builds don't patch\n * `console.error`/`console.warn`). When `false`, `entries` is always empty.\n */\n installed: boolean;\n}\n\n/**\n * Single network request entry captured by the observability ring buffer.\n * Returned by `GET /sdk/network-requests`.\n */\nexport interface NetworkRequestEntry {\n /** ms since epoch at request start. */\n timestamp: number;\n /** HTTP method (uppercased). */\n method: string;\n /** Resolved request URL. */\n url: string;\n /** HTTP status code, or 0 if the request errored before a response. */\n status: number;\n /** Wall-clock duration in ms from start to settlement. */\n durationMs: number;\n /** Whether the request settled with a 2xx response. */\n ok: boolean;\n /** Error message when the request rejected before a response. */\n error?: string;\n}\n\n/**\n * Response payload for `GET /sdk/network-requests`.\n */\nexport interface NetworkRequestsResponse {\n entries: NetworkRequestEntry[];\n count: number;\n bufferSize: number;\n /**\n * Whether the network capture patch is actively installed. `false` means\n * the endpoint is mounted and schema-valid but not observing — typically\n * because `features.testHooks` is off (production builds don't patch\n * `fetch`/`XMLHttpRequest`). When `false`, `entries` is always empty.\n */\n installed: boolean;\n}\n\n/**\n * Request body for `POST /control/modal/push`.\n *\n * Mirrors `ModalDetector.pushModal`'s `ModalPushInput` shape; `metadata` is\n * a free-form object the test runner can stash for later assertions but is\n * not currently surfaced in the snapshot.\n */\nexport interface PushModalRequest {\n id: string;\n title?: string;\n type?: string;\n blocking?: boolean;\n dismissible?: boolean;\n metadata?: Record<string, unknown>;\n}\n\n/**\n * Response payload for `POST /control/modal/push`.\n */\nexport interface PushModalResponse {\n pushed: boolean;\n id: string;\n title?: string;\n type?: string;\n blocking?: boolean;\n dismissible?: boolean;\n pushedAt: number;\n}\n\n/**\n * Response payload for `POST /control/modal/dismiss/:id`.\n */\nexport interface DismissModalResponse {\n dismissed: string;\n}\n\n/**\n * API response wrapper\n */\nexport interface APIResponse<T = unknown> {\n success: boolean;\n data?: T;\n error?: string;\n code?: string;\n timestamp: number;\n}\n\n/**\n * Handler context\n */\nexport interface HandlerContext {\n params: Record<string, string>;\n query: Record<string, string>;\n body: unknown;\n}\n\n/**\n * Handler function type\n */\nexport type HandlerFunction<T = unknown> = (context: HandlerContext) => Promise<APIResponse<T>>;\n\n/**\n * Server handlers interface\n */\nexport interface NativeServerHandlers {\n // Elements\n getElements: HandlerFunction<{ elements: unknown[] }>;\n getElement: HandlerFunction<{ element: unknown }>;\n getElementState: HandlerFunction<{ state: unknown }>;\n executeAction: HandlerFunction<NativeActionResponse>;\n\n // Components\n getComponents: HandlerFunction<{ components: unknown[] }>;\n getComponent: HandlerFunction<{ component: unknown }>;\n executeComponentAction: HandlerFunction<ComponentActionResponse>;\n\n // Discovery\n find: HandlerFunction<NativeFindResponse>;\n getSnapshot: HandlerFunction<NativeBridgeSnapshot>;\n // Page health — structured diagnostic over the snapshot's elements +\n // device viewport. Output shape mirrors the runner/web analyzer so the\n // `page-health` skill is platform-neutral.\n getPageHealth: HandlerFunction<unknown>;\n\n // Workflows\n getWorkflows: HandlerFunction<{ workflows: unknown[] }>;\n runWorkflow: HandlerFunction<{\n runId: string;\n status: string;\n steps: Array<{\n stepId: string;\n type: string;\n status: string;\n result?: unknown;\n error?: string;\n durationMs: number;\n }>;\n totalSteps: number;\n completedSteps: number;\n failedSteps: number;\n skippedSteps: number;\n durationMs: number;\n }>;\n\n // Page Navigation\n pageRefresh: HandlerFunction<PageNavigationResponse>;\n pageNavigate: HandlerFunction<PageNavigationResponse>;\n pageReplace: HandlerFunction<PageNavigationResponse>;\n pageGoBack: HandlerFunction<PageNavigationResponse>;\n pageGoForward: HandlerFunction<PageNavigationResponse>;\n\n // Screenshot\n getScreenshot: HandlerFunction<{ screenshot: string; width: number; height: number }>;\n\n // Design Review\n getElementStyles: HandlerFunction<ElementDesignData>;\n getElementStateStyles: HandlerFunction<{ elementId: string; stateStyles: StateStyles[] }>;\n getDesignSnapshot: HandlerFunction<{ elements: ElementDesignData[]; timestamp: number }>;\n getResponsiveSnapshots: HandlerFunction<ResponsiveSnapshot[]>;\n runDesignAudit: HandlerFunction<unknown>;\n loadStyleGuide: HandlerFunction<{ loaded: boolean }>;\n getStyleGuide: HandlerFunction<unknown>;\n clearStyleGuide: HandlerFunction<{ cleared: boolean }>;\n\n // Quality Evaluation\n evaluateQuality: HandlerFunction<unknown>;\n getQualityContexts: HandlerFunction<Array<{ name: string; description: string }>>;\n saveBaseline: HandlerFunction<{ saved: boolean; elementCount: number }>;\n diffBaseline: HandlerFunction<unknown>;\n\n // Meta / Introspection\n getMethods: HandlerFunction<{\n methods: Array<{ method: string; httpMethods?: string[]; description?: string }>;\n }>;\n\n // AI helpers\n fillForm: HandlerFunction<FillFormResponse>;\n\n // App-agnostic interaction parity — cross-platform contract shared with the\n // web/runner bridge (`/control/page/*`). Text/label-based interactions\n // compose find + executeAction over the registry; selector-only variants\n // return NOT_SUPPORTED on native (no DOM).\n clickByText: HandlerFunction<{ clicked: boolean; element?: unknown }>;\n clickBySelector: HandlerFunction<never>;\n typeInto: HandlerFunction<{ typed: boolean; element?: unknown }>;\n readValue: HandlerFunction<never>;\n findByText: HandlerFunction<\n Array<{ index: number; id: string; type: string; label?: string }>\n >;\n\n // AI helpers — NOT_SUPPORTED stubs (runner-only endpoints; see route table).\n // These return `error(..., 'NOT_SUPPORTED')` and exist so the mobile bridge\n // never 404s on cheatsheet endpoints that work on the runner.\n aiForms: HandlerFunction<never>;\n aiIdleStatus: HandlerFunction<never>;\n aiChangeBufferEnable: HandlerFunction<never>;\n aiWaitForElement: HandlerFunction<never>;\n\n // Coord-based tap — synthesizes a press at the given screen coords by\n // searching registered elements whose layout rect contains the point.\n tapAt: HandlerFunction<TapAtResponse>;\n\n // Observability — last-N ring buffers for console + network. Both are\n // gated behind `features.testHooks` at the route layer; the handlers\n // themselves return empty buffers when the buffers aren't installed.\n getConsoleErrors: HandlerFunction<ConsoleErrorsResponse>;\n getNetworkRequests: HandlerFunction<NetworkRequestsResponse>;\n\n // Test hooks — modal stack manipulation\n pushModal: HandlerFunction<PushModalResponse>;\n dismissModal: HandlerFunction<DismissModalResponse>;\n\n // Test hooks — device keep-awake (screen stays on for the duration)\n keepAwake: HandlerFunction<{ enabled: boolean; durationMs: number | null }>;\n\n // Health\n health: HandlerFunction<Record<string, unknown>>;\n}\n","/**\n * Pure-JS RFC 6455 WebSocket protocol implementation.\n *\n * Provides frame encoding/decoding and handshake utilities for running\n * a WebSocket server on react-native-tcp-socket without native crypto deps.\n */\n\n// ── Constants ───────────────────────────────────────────────────────────────\n\nconst WS_GUID = '258EAFA5-E914-47DA-95CA-C5AB0DC85B11';\n\nexport const OPCODE_CONTINUATION = 0x00;\nexport const OPCODE_TEXT = 0x01;\nexport const OPCODE_BINARY = 0x02;\nexport const OPCODE_CLOSE = 0x08;\nexport const OPCODE_PING = 0x09;\nexport const OPCODE_PONG = 0x0a;\n\n// ── Types ───────────────────────────────────────────────────────────────────\n\nexport interface DecodedFrame {\n opcode: number;\n fin: boolean;\n payload: Uint8Array;\n masked: boolean;\n}\n\nexport interface DecodeResult {\n frames: DecodedFrame[];\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n remainder: Uint8Array<any>;\n}\n\n// ── SHA-1 (Pure JS) ─────────────────────────────────────────────────────────\n// Minimal inline SHA-1 per FIPS 180-4. Used only for the WS handshake.\n\nfunction sha1Bytes(input: Uint8Array): Uint8Array {\n const ml = input.length * 8;\n\n // Pre-processing: pad to 512-bit blocks\n const padLen = 64 - ((input.length + 9) % 64);\n const total = input.length + 1 + (padLen === 64 ? 0 : padLen) + 8;\n const msg = new Uint8Array(total);\n msg.set(input);\n msg[input.length] = 0x80;\n // Length in bits as 64-bit big-endian (we only use 32-bit since messages are small)\n const dv = new DataView(msg.buffer);\n dv.setUint32(total - 4, ml, false);\n\n // Initialize hash values\n let h0 = 0x67452301;\n let h1 = 0xefcdab89;\n let h2 = 0x98badcfe;\n let h3 = 0x10325476;\n let h4 = 0xc3d2e1f0;\n\n const w = new Uint32Array(80);\n\n for (let offset = 0; offset < total; offset += 64) {\n const block = new DataView(msg.buffer, offset, 64);\n\n for (let i = 0; i < 16; i++) {\n w[i] = block.getUint32(i * 4, false);\n }\n for (let i = 16; i < 80; i++) {\n const x = w[i - 3] ^ w[i - 8] ^ w[i - 14] ^ w[i - 16];\n w[i] = (x << 1) | (x >>> 31);\n }\n\n let a = h0,\n b = h1,\n c = h2,\n d = h3,\n e = h4;\n\n for (let i = 0; i < 80; i++) {\n let f: number, k: number;\n if (i < 20) {\n f = (b & c) | (~b & d);\n k = 0x5a827999;\n } else if (i < 40) {\n f = b ^ c ^ d;\n k = 0x6ed9eba1;\n } else if (i < 60) {\n f = (b & c) | (b & d) | (c & d);\n k = 0x8f1bbcdc;\n } else {\n f = b ^ c ^ d;\n k = 0xca62c1d6;\n }\n\n const temp = (((a << 5) | (a >>> 27)) + f + e + k + w[i]) | 0;\n e = d;\n d = c;\n c = (b << 30) | (b >>> 2);\n b = a;\n a = temp;\n }\n\n h0 = (h0 + a) | 0;\n h1 = (h1 + b) | 0;\n h2 = (h2 + c) | 0;\n h3 = (h3 + d) | 0;\n h4 = (h4 + e) | 0;\n }\n\n const result = new Uint8Array(20);\n const rdv = new DataView(result.buffer);\n rdv.setUint32(0, h0, false);\n rdv.setUint32(4, h1, false);\n rdv.setUint32(8, h2, false);\n rdv.setUint32(12, h3, false);\n rdv.setUint32(16, h4, false);\n return result;\n}\n\nconst B64_CHARS = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';\n\n/**\n * Manual base64 encoder — avoids Hermes btoa() which can silently corrupt\n * binary strings containing bytes > 127 (common in SHA-1 output).\n */\nfunction bytesToBase64(bytes: Uint8Array): string {\n let result = '';\n const len = bytes.length;\n for (let i = 0; i < len; i += 3) {\n const b0 = bytes[i];\n const b1 = i + 1 < len ? bytes[i + 1] : 0;\n const b2 = i + 2 < len ? bytes[i + 2] : 0;\n const triplet = (b0 << 16) | (b1 << 8) | b2;\n\n result += B64_CHARS[(triplet >> 18) & 0x3f];\n result += B64_CHARS[(triplet >> 12) & 0x3f];\n result += i + 1 < len ? B64_CHARS[(triplet >> 6) & 0x3f] : '=';\n result += i + 2 < len ? B64_CHARS[triplet & 0x3f] : '=';\n }\n return result;\n}\n\n// ── Handshake ───────────────────────────────────────────────────────────────\n\n/**\n * Compute the Sec-WebSocket-Accept value from the client's Sec-WebSocket-Key.\n */\nexport function computeAcceptKey(clientKey: string): string {\n const input = clientKey + WS_GUID;\n const encoder = new TextEncoder();\n const hash = sha1Bytes(encoder.encode(input));\n return bytesToBase64(hash);\n}\n\n/**\n * Build the HTTP 101 Switching Protocols response for a WebSocket upgrade.\n */\nexport function buildUpgradeResponse(clientKey: string): string {\n const accept = computeAcceptKey(clientKey);\n return (\n 'HTTP/1.1 101 Switching Protocols\\r\\n' +\n 'Upgrade: websocket\\r\\n' +\n 'Connection: Upgrade\\r\\n' +\n `Sec-WebSocket-Accept: ${accept}\\r\\n` +\n '\\r\\n'\n );\n}\n\n// ── Frame Encoding (Server → Client, unmasked) ─────────────────────────────\n\nfunction encodeFrame(opcode: number, payload: Uint8Array): Uint8Array {\n const len = payload.length;\n let headerLen: number;\n\n if (len < 126) {\n headerLen = 2;\n } else if (len < 65536) {\n headerLen = 4;\n } else {\n headerLen = 10;\n }\n\n const frame = new Uint8Array(headerLen + len);\n frame[0] = 0x80 | opcode; // FIN + opcode\n\n if (len < 126) {\n frame[1] = len; // No mask bit (server → client)\n } else if (len < 65536) {\n frame[1] = 126;\n frame[2] = (len >> 8) & 0xff;\n frame[3] = len & 0xff;\n } else {\n frame[1] = 127;\n // For payloads > 65535, use 8-byte length (upper 4 bytes zero for practical sizes)\n const dv = new DataView(frame.buffer, 2, 8);\n dv.setUint32(0, 0, false);\n dv.setUint32(4, len, false);\n }\n\n frame.set(payload, headerLen);\n return frame;\n}\n\n/** Encode a text message as a WebSocket frame. */\nexport function encodeTextFrame(text: string): Uint8Array {\n const payload = new TextEncoder().encode(text);\n return encodeFrame(OPCODE_TEXT, payload);\n}\n\n/** Encode a PING frame with optional payload. */\nexport function encodePingFrame(payload?: Uint8Array): Uint8Array {\n return encodeFrame(OPCODE_PING, payload ?? new Uint8Array(0));\n}\n\n/** Encode a PONG frame with the payload from the PING. */\nexport function encodePongFrame(payload: Uint8Array): Uint8Array {\n return encodeFrame(OPCODE_PONG, payload);\n}\n\n/** Encode a CLOSE frame with optional status code and reason. */\nexport function encodeCloseFrame(code?: number, reason?: string): Uint8Array {\n if (code === undefined) {\n return encodeFrame(OPCODE_CLOSE, new Uint8Array(0));\n }\n const reasonBytes = reason ? new TextEncoder().encode(reason) : new Uint8Array(0);\n const payload = new Uint8Array(2 + reasonBytes.length);\n payload[0] = (code >> 8) & 0xff;\n payload[1] = code & 0xff;\n payload.set(reasonBytes, 2);\n return encodeFrame(OPCODE_CLOSE, payload);\n}\n\n// ── Frame Decoding (Client → Server, masked) ───────────────────────────────\n\n/**\n * Decode one or more WebSocket frames from a byte buffer.\n * Returns decoded frames and any unconsumed bytes (for partial frames).\n */\nexport function decodeFrames(buffer: Uint8Array): DecodeResult {\n const frames: DecodedFrame[] = [];\n let offset = 0;\n\n while (offset < buffer.length) {\n // Need at least 2 bytes for the header\n if (buffer.length - offset < 2) break;\n\n const byte0 = buffer[offset];\n const byte1 = buffer[offset + 1];\n\n const fin = (byte0 & 0x80) !== 0;\n const opcode = byte0 & 0x0f;\n const masked = (byte1 & 0x80) !== 0;\n let payloadLen = byte1 & 0x7f;\n\n let headerLen = 2;\n\n if (payloadLen === 126) {\n if (buffer.length - offset < 4) break;\n payloadLen = (buffer[offset + 2] << 8) | buffer[offset + 3];\n headerLen = 4;\n } else if (payloadLen === 127) {\n if (buffer.length - offset < 10) break;\n const dv = new DataView(buffer.buffer, buffer.byteOffset + offset + 2, 8);\n payloadLen = dv.getUint32(4, false); // Use lower 32 bits only\n headerLen = 10;\n }\n\n if (masked) {\n headerLen += 4; // 4-byte masking key\n }\n\n const totalLen = headerLen + payloadLen;\n if (buffer.length - offset < totalLen) break; // Partial frame\n\n // Extract and unmask payload\n const payload = new Uint8Array(payloadLen);\n const dataStart = offset + headerLen;\n\n if (masked) {\n const maskOffset = offset + headerLen - 4;\n const mask = buffer.slice(maskOffset, maskOffset + 4);\n for (let i = 0; i < payloadLen; i++) {\n payload[i] = buffer[dataStart + i] ^ mask[i % 4];\n }\n } else {\n payload.set(buffer.slice(dataStart, dataStart + payloadLen));\n }\n\n frames.push({ opcode, fin, payload, masked });\n offset += totalLen;\n }\n\n return {\n frames,\n remainder: new Uint8Array(buffer.slice(offset)),\n };\n}\n\n/**\n * Decode a text payload from a Uint8Array.\n */\nexport function decodeTextPayload(payload: Uint8Array): string {\n return new TextDecoder().decode(payload);\n}\n","/**\n * Resilient TCP-bind helper for native UI Bridge server adapters.\n *\n * Background: the on-device bridge binds a TCP server on a fixed port (8087).\n * On hot-reload, app foreground/background cycles, or a crash-restart, the OS\n * can leave the previous socket in a lingering state, so the fresh bind fails\n * with `EADDRINUSE`. The original adapter gave up after 3 fixed retries\n * (~5s total), after which the bridge was permanently dead until the app was\n * fully restarted — a single transient stale socket bricked automation.\n *\n * This helper centralises a robust bind loop so every adapter (and a unit\n * test) shares one implementation:\n * - SO_REUSEADDR is requested on bind where the platform/library supports it\n * (passed through to the caller's `attempt` via `reuseAddress: true`), so\n * a lingering TIME_WAIT socket doesn't block rebind.\n * - On `EADDRINUSE` it retries with exponential backoff (capped) for at\n * least `minTotalMs` (default 30s) instead of bailing after a fixed count.\n * - Every retry is logged so operators can see the bridge recovering.\n * - Non-`EADDRINUSE` errors fail fast (a wrong-permission / bad-host error\n * won't fix itself by waiting).\n *\n * The helper is transport-agnostic: the caller supplies an `attempt` thunk\n * that performs ONE bind attempt and resolves on `listening` / rejects on\n * error. This keeps the package free of any concrete TCP library dependency\n * (the same reason `ServerAdapter` is an interface).\n */\n\n/** True when an error looks like an address-already-in-use bind failure. */\nexport function isAddrInUseError(err: unknown): boolean {\n const message =\n err instanceof Error ? err.message : typeof err === 'string' ? err : String(err);\n // Some RN TCP libraries surface a `.code` instead of (or alongside) the\n // message — check both.\n const code = (err as { code?: unknown })?.code;\n return (\n message.includes('EADDRINUSE') ||\n message.toLowerCase().includes('address already in use') ||\n code === 'EADDRINUSE'\n );\n}\n\nexport interface BindWithRetryOptions {\n /**\n * Minimum total wall-clock time to keep retrying `EADDRINUSE` before giving\n * up, in milliseconds. The loop always makes at least one attempt and keeps\n * retrying until this budget is exhausted. Default 30_000 (30s).\n *\n * Pass `Infinity` to retry indefinitely (with capped backoff) — appropriate\n * for an always-on device bridge that should self-heal whenever the stale\n * socket finally clears.\n */\n minTotalMs?: number;\n /** Initial backoff delay between retries, in ms. Default 500. */\n initialDelayMs?: number;\n /** Maximum backoff delay (cap for exponential growth), in ms. Default 5_000. */\n maxDelayMs?: number;\n /** Multiplier applied to the delay after each retry. Default 2. */\n backoffFactor?: number;\n /** Logger for retry diagnostics. Defaults to `console`. */\n logger?: Pick<Console, 'warn' | 'error'>;\n /** Injectable sleep — overridable in tests to avoid real timers. */\n sleep?: (ms: number) => Promise<void>;\n /** Injectable clock — overridable in tests. Defaults to `Date.now`. */\n now?: () => number;\n}\n\nconst defaultSleep = (ms: number): Promise<void> =>\n new Promise((resolve) => setTimeout(resolve, ms));\n\n/**\n * Run `attempt()` repeatedly until it resolves, retrying on `EADDRINUSE` with\n * exponential backoff for at least `minTotalMs`. Non-address-in-use errors\n * reject immediately. Resolves once a bind attempt succeeds.\n *\n * @param attempt One bind attempt. Receives the attempt index (0-based) and\n * MUST resolve on a successful `listening` event or reject on error. The\n * caller is responsible for tearing down any half-bound server before the\n * next attempt (see the adapter's `recreate` thunk).\n */\nexport async function bindWithRetry(\n attempt: (attemptIndex: number) => Promise<void>,\n options: BindWithRetryOptions = {}\n): Promise<void> {\n const {\n minTotalMs = 30_000,\n initialDelayMs = 500,\n maxDelayMs = 5_000,\n backoffFactor = 2,\n logger = console,\n sleep = defaultSleep,\n now = Date.now,\n } = options;\n\n const startedAt = now();\n let delay = initialDelayMs;\n let attemptIndex = 0;\n\n for (;;) {\n try {\n await attempt(attemptIndex);\n return; // bound successfully\n } catch (err) {\n const elapsed = now() - startedAt;\n const budgetExhausted = elapsed + delay >= minTotalMs;\n\n if (!isAddrInUseError(err) || budgetExhausted) {\n // Either a non-recoverable error, or we've spent our retry budget.\n throw err;\n }\n\n logger.warn(\n `[ui-bridge-native] bind failed with EADDRINUSE (attempt ${attemptIndex + 1}); ` +\n `retrying in ${delay}ms (elapsed ${elapsed}ms / budget ${\n minTotalMs === Infinity ? '∞' : minTotalMs\n }ms)`\n );\n\n await sleep(delay);\n delay = Math.min(delay * backoffFactor, maxDelayMs);\n attemptIndex += 1;\n }\n }\n}\n","/**\n * WebSocket connection wrapper for the UI Bridge server.\n *\n * Manages a single WebSocket connection after the HTTP upgrade handshake,\n * handling frame-level I/O, heartbeat, and event subscriptions.\n */\n\nimport {\n decodeFrames,\n decodeTextPayload,\n encodeTextFrame,\n encodePingFrame,\n encodePongFrame,\n encodeCloseFrame,\n OPCODE_TEXT,\n OPCODE_CLOSE,\n OPCODE_PING,\n OPCODE_PONG,\n OPCODE_CONTINUATION,\n type DecodedFrame,\n} from './ws-protocol';\nimport type { JsonRpcEvent } from './ws-types';\nimport { globToRegex } from './ws-event-bridge';\n\n/**\n * Callback for text messages received from the client.\n * Returns a response string to send back, or null for no response.\n */\nexport type WebSocketMessageHandler = (connId: string, message: string) => Promise<string | null>;\n\nexport class WebSocketConnection {\n readonly id: string;\n readonly subscriptions = new Set<string>();\n\n /** Heartbeat liveness flag — set false before ping, set true on pong */\n alive = true;\n\n private socket: {\n write: (data: Uint8Array | string, encoding?: string, cb?: () => void) => void;\n destroy: () => void;\n on: (event: string, handler: (...args: unknown[]) => void) => void;\n removeAllListeners: (event?: string) => void;\n setNoDelay?: (noDelay: boolean) => void;\n };\n\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n private buffer: Uint8Array<any> = new Uint8Array(0);\n private fragmentBuffer: Uint8Array[] = [];\n private fragmentOpcode = 0;\n private closed = false;\n private onMessage: WebSocketMessageHandler;\n private onClose: (connId: string) => void;\n\n constructor(\n id: string,\n socket: WebSocketConnection['socket'],\n onMessage: WebSocketMessageHandler,\n onClose: (connId: string) => void\n ) {\n this.id = id;\n this.socket = socket;\n this.onMessage = onMessage;\n this.onClose = onClose;\n\n // Disable Nagle's algorithm for low latency\n if (socket.setNoDelay) {\n socket.setNoDelay(true);\n }\n\n // Wire up data handler\n socket.on('data', (data: unknown) => {\n if (this.closed) return;\n const chunk =\n data instanceof Uint8Array\n ? data\n : typeof data === 'string'\n ? new TextEncoder().encode(data)\n : new Uint8Array(data as ArrayBuffer);\n this.handleData(chunk);\n });\n\n socket.on('error', () => {\n this.destroy();\n });\n\n socket.on('close', () => {\n this.destroy();\n });\n }\n\n /** Send a text message to the client. */\n send(message: string): void {\n if (this.closed) return;\n try {\n const frame = encodeTextFrame(message);\n this.writeRaw(frame);\n } catch {\n // Socket may be closed\n }\n }\n\n /**\n * Send an event if the client is subscribed to it. Subscription patterns\n * may be exact event names, `*` (all), or glob patterns containing `*`\n * (e.g. `element:*`, `*:stateChanged`). Exact matches and `*` are checked\n * via fast Set lookups; glob patterns fall through to a regex test.\n */\n sendEvent(event: JsonRpcEvent): void {\n if (this.closed) return;\n if (!this.matchesSubscription(event.event)) return;\n this.send(JSON.stringify(event));\n }\n\n private matchesSubscription(eventType: string): boolean {\n // Fast paths\n if (this.subscriptions.has(eventType)) return true;\n if (this.subscriptions.has('*')) return true;\n // Glob fallback — only patterns containing `*` (other than the bare `*`\n // already handled above) need the regex test.\n for (const pattern of this.subscriptions) {\n if (!pattern.includes('*')) continue;\n if (globToRegex(pattern).test(eventType)) return true;\n }\n return false;\n }\n\n /** Send a ping frame for heartbeat. */\n ping(): void {\n if (this.closed) return;\n try {\n this.writeRaw(encodePingFrame());\n } catch {\n // Socket may be closed\n }\n }\n\n /** Close the connection gracefully. */\n close(code = 1000, reason = ''): void {\n if (this.closed) return;\n this.closed = true;\n try {\n this.writeRaw(encodeCloseFrame(code, reason));\n // Give the frame time to flush before destroying\n setTimeout(() => this.socket.destroy(), 100);\n } catch {\n this.socket.destroy();\n }\n this.onClose(this.id);\n }\n\n /** Forcefully destroy the connection without a close frame. */\n destroy(): void {\n if (this.closed) return;\n this.closed = true;\n try {\n this.socket.destroy();\n } catch {\n // Already destroyed\n }\n this.onClose(this.id);\n }\n\n /** Whether the connection is still open. */\n get isOpen(): boolean {\n return !this.closed;\n }\n\n // ── Internal ────────────────────────────────────────────────────────────\n\n private writeRaw(data: Uint8Array): void {\n // react-native-tcp-socket write() accepts Buffer/Uint8Array/string.\n // Convert to binary string for compatibility with all socket implementations.\n // Use chunked String.fromCharCode to avoid call-stack limits on large payloads\n // while staying O(n) instead of O(n^2) from single-char concatenation.\n const CHUNK = 8192;\n const parts: string[] = [];\n for (let i = 0; i < data.length; i += CHUNK) {\n const end = Math.min(i + CHUNK, data.length);\n parts.push(String.fromCharCode.apply(null, data.subarray(i, end) as unknown as number[]));\n }\n this.socket.write(parts.join(''), 'binary');\n }\n\n private handleData(chunk: Uint8Array): void {\n // Append to buffer\n const newBuffer = new Uint8Array(this.buffer.length + chunk.length);\n newBuffer.set(this.buffer);\n newBuffer.set(chunk, this.buffer.length);\n this.buffer = newBuffer;\n\n // Decode frames\n const { frames, remainder } = decodeFrames(this.buffer);\n this.buffer = remainder;\n\n for (const frame of frames) {\n this.handleFrame(frame);\n }\n }\n\n private handleFrame(frame: DecodedFrame): void {\n // Handle fragmented messages\n if (!frame.fin && frame.opcode !== OPCODE_CONTINUATION) {\n // Start of fragmented message\n this.fragmentBuffer = [frame.payload];\n this.fragmentOpcode = frame.opcode;\n return;\n }\n\n if (frame.opcode === OPCODE_CONTINUATION) {\n this.fragmentBuffer.push(frame.payload);\n if (!frame.fin) return; // More fragments coming\n\n // Reassemble\n const totalLen = this.fragmentBuffer.reduce((sum, buf) => sum + buf.length, 0);\n const reassembled = new Uint8Array(totalLen);\n let offset = 0;\n for (const buf of this.fragmentBuffer) {\n reassembled.set(buf, offset);\n offset += buf.length;\n }\n this.fragmentBuffer = [];\n\n // Process as the original opcode\n this.handleFrame({\n opcode: this.fragmentOpcode,\n fin: true,\n payload: reassembled,\n masked: true,\n });\n return;\n }\n\n switch (frame.opcode) {\n case OPCODE_TEXT: {\n const text = decodeTextPayload(frame.payload);\n this.onMessage(this.id, text)\n .then((response) => {\n if (response !== null) {\n this.send(response);\n }\n })\n .catch((err) => {\n console.warn(`[ws-connection] message handler error:`, err);\n this.send(\n JSON.stringify({\n error: 'Internal error',\n timestamp: Date.now(),\n })\n );\n });\n break;\n }\n\n case OPCODE_PING:\n // Respond with PONG carrying the same payload\n try {\n this.writeRaw(encodePongFrame(frame.payload));\n } catch {\n // Socket may be closed\n }\n break;\n\n case OPCODE_PONG:\n this.alive = true;\n break;\n\n case OPCODE_CLOSE:\n this.close();\n break;\n }\n }\n}\n","/**\n * UI Bridge Native Debug Inspector\n *\n * An overlay component that shows registered elements and allows\n * inspection of the UI Bridge state.\n */\n\nimport { useState, useCallback, useMemo } from 'react';\nimport {\n View,\n Text,\n StyleSheet,\n TouchableOpacity,\n ScrollView,\n Modal,\n Dimensions,\n} from 'react-native';\nimport { useUIBridgeNativeOptional } from '../react/UIBridgeNativeProvider';\nimport type { RegisteredNativeElement } from '../core/types';\n\n/**\n * Inspector props\n */\nexport interface UIBridgeInspectorProps {\n /** Whether to show the inspector */\n visible?: boolean;\n /** Callback when inspector is closed */\n onClose?: () => void;\n /** Position of the inspector toggle button */\n togglePosition?: 'top-left' | 'top-right' | 'bottom-left' | 'bottom-right';\n}\n\n/**\n * Element info card\n */\nfunction ElementCard({\n element,\n onPress,\n}: {\n element: RegisteredNativeElement;\n onPress: (element: RegisteredNativeElement) => void;\n}) {\n const state = element.getState();\n const identifier = element.getIdentifier();\n\n return (\n <TouchableOpacity style={styles.elementCard} onPress={() => onPress(element)}>\n <View style={styles.elementHeader}>\n <Text style={styles.elementId}>{element.id}</Text>\n <Text style={styles.elementType}>{element.type}</Text>\n </View>\n {element.label && <Text style={styles.elementLabel}>{element.label}</Text>}\n <View style={styles.stateRow}>\n <StateIndicator label=\"Mounted\" value={state.mounted} />\n <StateIndicator label=\"Visible\" value={state.visible} />\n <StateIndicator label=\"Enabled\" value={state.enabled} />\n </View>\n {identifier.testId && <Text style={styles.testId}>testID: {identifier.testId}</Text>}\n </TouchableOpacity>\n );\n}\n\n/**\n * State indicator\n */\nfunction StateIndicator({ label, value }: { label: string; value: boolean }) {\n return (\n <View style={styles.stateIndicator}>\n <View style={[styles.stateDot, { backgroundColor: value ? '#4CAF50' : '#F44336' }]} />\n <Text style={styles.stateLabel}>{label}</Text>\n </View>\n );\n}\n\n/**\n * Element detail view\n */\nfunction ElementDetail({\n element,\n onClose,\n}: {\n element: RegisteredNativeElement;\n onClose: () => void;\n}) {\n const state = element.getState();\n const identifier = element.getIdentifier();\n\n return (\n <View style={styles.detailContainer}>\n <View style={styles.detailHeader}>\n <Text style={styles.detailTitle}>{element.id}</Text>\n <TouchableOpacity onPress={onClose}>\n <Text style={styles.closeButton}>Close</Text>\n </TouchableOpacity>\n </View>\n\n <ScrollView style={styles.detailContent}>\n <Text style={styles.sectionTitle}>Type</Text>\n <Text style={styles.sectionValue}>{element.type}</Text>\n\n {element.label && (\n <>\n <Text style={styles.sectionTitle}>Label</Text>\n <Text style={styles.sectionValue}>{element.label}</Text>\n </>\n )}\n\n <Text style={styles.sectionTitle}>State</Text>\n <View style={styles.stateSection}>\n <Text style={styles.stateText}>Mounted: {String(state.mounted)}</Text>\n <Text style={styles.stateText}>Visible: {String(state.visible)}</Text>\n <Text style={styles.stateText}>Enabled: {String(state.enabled)}</Text>\n <Text style={styles.stateText}>Focused: {String(state.focused)}</Text>\n {state.value !== undefined && <Text style={styles.stateText}>Value: {state.value}</Text>}\n </View>\n\n {state.layout && (\n <>\n <Text style={styles.sectionTitle}>Layout</Text>\n <View style={styles.stateSection}>\n <Text style={styles.stateText}>\n Position: ({state.layout.x}, {state.layout.y})\n </Text>\n <Text style={styles.stateText}>\n Size: {state.layout.width} x {state.layout.height}\n </Text>\n <Text style={styles.stateText}>\n Page: ({state.layout.pageX}, {state.layout.pageY})\n </Text>\n </View>\n </>\n )}\n\n <Text style={styles.sectionTitle}>Identifier</Text>\n <View style={styles.stateSection}>\n {identifier.uiId && <Text style={styles.stateText}>uiId: {identifier.uiId}</Text>}\n {identifier.testId && <Text style={styles.stateText}>testId: {identifier.testId}</Text>}\n {identifier.accessibilityLabel && (\n <Text style={styles.stateText}>a11yLabel: {identifier.accessibilityLabel}</Text>\n )}\n <Text style={styles.stateText}>treePath: {identifier.treePath}</Text>\n </View>\n\n <Text style={styles.sectionTitle}>Actions</Text>\n <View style={styles.actionsSection}>\n {element.actions.map((action) => (\n <View key={action} style={styles.actionBadge}>\n <Text style={styles.actionText}>{action}</Text>\n </View>\n ))}\n </View>\n\n {element.customActions && Object.keys(element.customActions).length > 0 && (\n <>\n <Text style={styles.sectionTitle}>Custom Actions</Text>\n <View style={styles.actionsSection}>\n {Object.keys(element.customActions).map((action) => (\n <View key={action} style={[styles.actionBadge, styles.customActionBadge]}>\n <Text style={styles.actionText}>{action}</Text>\n </View>\n ))}\n </View>\n </>\n )}\n </ScrollView>\n </View>\n );\n}\n\n/**\n * UI Bridge Inspector component\n *\n * Shows an overlay with information about registered elements.\n * Useful for debugging and development.\n *\n * @example\n * ```tsx\n * function App() {\n * const [showInspector, setShowInspector] = useState(false);\n *\n * return (\n * <UIBridgeNativeProvider features={{ debug: __DEV__ }}>\n * <MainContent />\n * {__DEV__ && (\n * <UIBridgeInspector\n * visible={showInspector}\n * onClose={() => setShowInspector(false)}\n * />\n * )}\n * </UIBridgeNativeProvider>\n * );\n * }\n * ```\n */\nexport function UIBridgeInspector({\n visible = false,\n onClose,\n togglePosition = 'bottom-right',\n}: UIBridgeInspectorProps) {\n const bridge = useUIBridgeNativeOptional();\n const [showInspector, setShowInspector] = useState(visible);\n const [selectedElement, setSelectedElement] = useState<RegisteredNativeElement | null>(null);\n\n const elements = useMemo(() => (bridge ? bridge.getElements() : []), [bridge]);\n\n const components = useMemo(() => (bridge ? bridge.getComponents() : []), [bridge]);\n\n const handleToggle = useCallback(() => {\n setShowInspector((prev) => !prev);\n }, []);\n\n const handleClose = useCallback(() => {\n setShowInspector(false);\n onClose?.();\n }, [onClose]);\n\n const handleSelectElement = useCallback((element: RegisteredNativeElement) => {\n setSelectedElement(element);\n }, []);\n\n const handleCloseDetail = useCallback(() => {\n setSelectedElement(null);\n }, []);\n\n // Position style for toggle button\n const toggleStyle = useMemo(() => {\n switch (togglePosition) {\n case 'top-left':\n return { top: 50, left: 10 };\n case 'top-right':\n return { top: 50, right: 10 };\n case 'bottom-left':\n return { bottom: 50, left: 10 };\n case 'bottom-right':\n default:\n return { bottom: 50, right: 10 };\n }\n }, [togglePosition]);\n\n if (!bridge) {\n return null;\n }\n\n return (\n <>\n {/* Toggle button */}\n <TouchableOpacity style={[styles.toggleButton, toggleStyle]} onPress={handleToggle}>\n <Text style={styles.toggleText}>UI</Text>\n </TouchableOpacity>\n\n {/* Inspector modal */}\n <Modal\n visible={showInspector}\n animationType=\"slide\"\n transparent={true}\n onRequestClose={handleClose}\n >\n <View style={styles.modalContainer}>\n <View style={styles.inspectorContainer}>\n {/* Header */}\n <View style={styles.header}>\n <Text style={styles.headerTitle}>UI Bridge Inspector</Text>\n <TouchableOpacity onPress={handleClose}>\n <Text style={styles.closeButton}>X</Text>\n </TouchableOpacity>\n </View>\n\n {/* Stats */}\n <View style={styles.statsRow}>\n <View style={styles.stat}>\n <Text style={styles.statValue}>{elements.length}</Text>\n <Text style={styles.statLabel}>Elements</Text>\n </View>\n <View style={styles.stat}>\n <Text style={styles.statValue}>{components.length}</Text>\n <Text style={styles.statLabel}>Components</Text>\n </View>\n <View style={styles.stat}>\n <Text style={styles.statValue}>{bridge.serverRunning ? 'ON' : 'OFF'}</Text>\n <Text style={styles.statLabel}>Server</Text>\n </View>\n </View>\n\n {/* Element list or detail */}\n {selectedElement ? (\n <ElementDetail element={selectedElement} onClose={handleCloseDetail} />\n ) : (\n <ScrollView style={styles.elementList}>\n {elements.map((element) => (\n <ElementCard key={element.id} element={element} onPress={handleSelectElement} />\n ))}\n {elements.length === 0 && (\n <Text style={styles.emptyText}>No elements registered yet</Text>\n )}\n </ScrollView>\n )}\n </View>\n </View>\n </Modal>\n </>\n );\n}\n\nconst { height: screenHeight } = Dimensions.get('window');\n\nconst styles = StyleSheet.create({\n toggleButton: {\n position: 'absolute',\n width: 44,\n height: 44,\n borderRadius: 22,\n backgroundColor: '#2196F3',\n justifyContent: 'center',\n alignItems: 'center',\n shadowColor: '#000',\n shadowOffset: { width: 0, height: 2 },\n shadowOpacity: 0.25,\n shadowRadius: 4,\n elevation: 5,\n zIndex: 1000,\n },\n toggleText: {\n color: '#fff',\n fontWeight: 'bold',\n fontSize: 14,\n },\n modalContainer: {\n flex: 1,\n backgroundColor: 'rgba(0, 0, 0, 0.5)',\n justifyContent: 'flex-end',\n },\n inspectorContainer: {\n backgroundColor: '#1e1e1e',\n borderTopLeftRadius: 16,\n borderTopRightRadius: 16,\n maxHeight: screenHeight * 0.8,\n },\n header: {\n flexDirection: 'row',\n justifyContent: 'space-between',\n alignItems: 'center',\n padding: 16,\n borderBottomWidth: 1,\n borderBottomColor: '#333',\n },\n headerTitle: {\n color: '#fff',\n fontSize: 18,\n fontWeight: 'bold',\n },\n closeButton: {\n color: '#2196F3',\n fontSize: 16,\n fontWeight: 'bold',\n },\n statsRow: {\n flexDirection: 'row',\n padding: 12,\n borderBottomWidth: 1,\n borderBottomColor: '#333',\n },\n stat: {\n flex: 1,\n alignItems: 'center',\n },\n statValue: {\n color: '#fff',\n fontSize: 20,\n fontWeight: 'bold',\n },\n statLabel: {\n color: '#888',\n fontSize: 12,\n marginTop: 2,\n },\n elementList: {\n padding: 12,\n },\n elementCard: {\n backgroundColor: '#2d2d2d',\n borderRadius: 8,\n padding: 12,\n marginBottom: 8,\n },\n elementHeader: {\n flexDirection: 'row',\n justifyContent: 'space-between',\n alignItems: 'center',\n },\n elementId: {\n color: '#fff',\n fontSize: 14,\n fontWeight: 'bold',\n },\n elementType: {\n color: '#888',\n fontSize: 12,\n backgroundColor: '#444',\n paddingHorizontal: 8,\n paddingVertical: 2,\n borderRadius: 4,\n },\n elementLabel: {\n color: '#aaa',\n fontSize: 12,\n marginTop: 4,\n },\n stateRow: {\n flexDirection: 'row',\n marginTop: 8,\n },\n stateIndicator: {\n flexDirection: 'row',\n alignItems: 'center',\n marginRight: 12,\n },\n stateDot: {\n width: 8,\n height: 8,\n borderRadius: 4,\n marginRight: 4,\n },\n stateLabel: {\n color: '#888',\n fontSize: 10,\n },\n testId: {\n color: '#666',\n fontSize: 10,\n marginTop: 4,\n fontFamily: 'monospace',\n },\n emptyText: {\n color: '#888',\n textAlign: 'center',\n marginTop: 20,\n },\n detailContainer: {\n flex: 1,\n },\n detailHeader: {\n flexDirection: 'row',\n justifyContent: 'space-between',\n alignItems: 'center',\n padding: 12,\n borderBottomWidth: 1,\n borderBottomColor: '#333',\n },\n detailTitle: {\n color: '#fff',\n fontSize: 16,\n fontWeight: 'bold',\n },\n detailContent: {\n padding: 12,\n },\n sectionTitle: {\n color: '#888',\n fontSize: 12,\n marginTop: 12,\n marginBottom: 4,\n textTransform: 'uppercase',\n },\n sectionValue: {\n color: '#fff',\n fontSize: 14,\n },\n stateSection: {\n backgroundColor: '#2d2d2d',\n borderRadius: 8,\n padding: 8,\n },\n stateText: {\n color: '#ddd',\n fontSize: 12,\n fontFamily: 'monospace',\n marginBottom: 2,\n },\n actionsSection: {\n flexDirection: 'row',\n flexWrap: 'wrap',\n },\n actionBadge: {\n backgroundColor: '#2196F3',\n paddingHorizontal: 8,\n paddingVertical: 4,\n borderRadius: 4,\n marginRight: 6,\n marginBottom: 6,\n },\n customActionBadge: {\n backgroundColor: '#9C27B0',\n },\n actionText: {\n color: '#fff',\n fontSize: 12,\n },\n});\n"]}