This specification is maintained by the AgentRules Working Group. Have enhancements or want to claim maintainership?Submit Specification →
mobilecritical PriorityID: capacitor-7-structured-clone-bridge-invariant

Capacitor 7 Structured Clone & Zero-Copy Bridge Serialization for High-Frequency Telemetry

Enforces zero-copy structured cloning and transferable buffer semantics across Capacitor 7 WebView-to-native message ports. Eliminates main-thread blocking and garbage collection churn caused by manual JSON stringification during high-frequency geolocation, IMU, and motion sensor streaming.

Prohibited Anti-Pattern: Manual JSON Stringification Across MessagePorts in High-Frequency Sensor Streams

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Capacitor 7 Structured Clone & Zero-Copy Bridge Serialization for High-Frequency Telemetry - Enforces zero-copy structured cloning and transferable buffer semantics across Capacitor 7 WebView-to-native message ports. Eliminates main-thread blocking and garbage collection churn caused by manual JSON stringification during high-frequency geolocation, IMU, and motion sensor streaming.
globs: src/**/*.{ts,tsx}, src/plugins/**/*.{ts,tsx}
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/capacitor-7-structured-clone-bridge-invariant"
---

# Capacitor 7 Structured Clone & Zero-Copy Bridge Serialization for High-Frequency Telemetry

> **Severity**: CRITICAL | **Category**: mobile
> **Anti-Pattern Warning**: Manual JSON Stringification Across MessagePorts in High-Frequency Sensor Streams

## System Constraints
You are a Principal Mobile Architect enforcing Capacitor 7 Structured Clone Native Bridge Invariants. Mandate that high-frequency data pipelines (>=30Hz: accelerometer, gyroscope, magnetometer, continuous sub-meter GPS) bypass manual JSON.stringify/JSON.parse serialization over the bridge. Ensure developers leverage Capacitor 7 structured clone support and transferable typed arrays over MessagePort interfaces to maintain zero-copy non-blocking operations on the WebView main thread.

## Strict Guidelines
- Engineers MUST ALWAYS transfer high-frequency telemetry (>=30Hz) using TypedArrays (Float64Array, Float32Array) or structured-clone compatible binary buffers rather than serialized JSON strings.
- Engineers MUST NOT invoke JSON.stringify() or JSON.parse() on high-frequency bridge messages; structured cloning handles primitives and ArrayBuffers natively without serialization overhead.
- Bridge listeners MUST use persistent native Stream/MessagePort subscriptions instead of continuous polling or promise-per-tick RPC patterns.
- Plugins MUST reuse allocated TypedArray buffers via pooling or off-thread Transferable semantics where continuous telemetry streams would otherwise induce V8/JavaScriptCore garbage collection pauses.
- Telemetry payloads MUST be validated at design time to ensure all properties conform strictly to Structured Clone Algorithm constraints (no functions, symbols, or non-clonable DOM nodes).

## Bad vs Good Implementations
### High-Frequency Motion Stream Serialization

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Manual JSON.stringify on the native side and JSON.parse in the WebView listener creates massive object churn, blocks the JavaScript main thread during 60-120Hz sensor updates, and forfeits Capacitor 7 structured clone optimizations.
```typescript
import { Plugins } from '@capacitor/core';
const { MotionTracker } = Plugins;

// ANTI-PATTERN: Stringifying sensor payloads over the bridge at 60Hz causes severe GC and frame drops
MotionTracker.addListener('sensorData', (payload: { rawJson: string }) => {
  const data = JSON.parse(payload.rawJson);
  const timestamp = data.t;
  const x = data.accel.x;
  const y = data.accel.y;
  const z = data.accel.z;
  updatePhysics(timestamp, x, y, z);
});

function updatePhysics(t: number, x: number, y: number, z: number) {
  // Render or physics loop update
}
```

#### Production Standard (Correct)
> **Standard**: Using ArrayBuffer with a Float64Array view enables Capacitor 7's structured clone bridge to pass telemetry via zero-copy native memory transfer, eliminating JSON parsing overhead and avoiding GC spikes at 60Hz+.
```typescript
import { registerPlugin, PluginListenerHandle } from '@capacitor/core';

interface MotionTrackerPlugin {
  startSensorStream(): Promise<void>;
  addListener(
    eventName: 'sensorBatch',
    listenerFunc: (buffer: ArrayBuffer) => void
  ): Promise<PluginListenerHandle>;
}

const MotionTracker = registerPlugin<MotionTrackerPlugin>('MotionTracker');

// PRODUCTION STANDARD: Zero-copy TypedArray via Capacitor 7 Structured Clone Bridge
let listenerHandle: PluginListenerHandle | null = null;

export async function initMotionPipeline() {
  listenerHandle = await MotionTracker.addListener('sensorBatch', (buffer: ArrayBuffer) => {
    // Direct view on transferable structured clone memory - zero string allocation
    const view = new Float64Array(buffer);
    const timestamp = view[0];
    const x = view[1];
    const y = view[2];
    const z = view[3];
    updatePhysics(timestamp, x, y, z);
  });

  await MotionTracker.startSensorStream();
}

function updatePhysics(t: number, x: number, y: number, z: number) {
  // Direct memory consumption without bridge serialization delay
}
```

Recommended MCP Servers (mcp-serverlist.com)

Equip agent with system tools to verify code for this stack.

Recommended Agent Skills (askills.dev)

Ready-to-use executable skill functions tailored to this stack.

Architectural Specification & Invariant Rationale

Architectural Invariant Design: Capacitor 7 Structured Clone & Zero-Copy Bridge Serialization for High-Frequency Telemetry

Capacitor 7 Structured Clone & Zero-Copy Bridge Serialization for High-Frequency Telemetry defines an industrial-grade behavioral standard for mobile engineering. Enforces zero-copy structured cloning and transferable buffer semantics across Capacitor 7 WebView-to-native message ports. Eliminates main-thread blocking and garbage collection churn caused by manual JSON stringification during high-frequency geolocation, IMU, and motion sensor streaming. Modern software architectures require strict adherence to deterministic patterns to guarantee high availability, maintainability, and zero security vulnerabilities.

Framework Paradigm Shift & Drift MechanicsLLMs are trained on millions of open-source repositories containing outdated code, legacy idioms, and unpatched antipatterns. When coding assistants generate implementations for this stack, they default to common statistical tokens: Manual JSON Stringification Across MessagePorts in High-Frequency Sensor Streams Without an explicit system instruction file, developers spend hours debugging silent failures.
Failure Modes & Production Blast Radius

Hazard Analysis: What Breaks Without This Rule

The following failure modes have been cataloged from hundreds of hours of production code reviews where AI assistants produced non-compliant implementations:

Failure ModeAI Symptom (The Anti-Pattern)SeverityProduction Impact & Remedy
AI Hallucination & Deprecation DriftManual JSON Stringification Across MessagePorts in High-Frequency Sensor StreamsCritical
Violating this industrial standard introduces regression bugs, security risks, and unexpected runtime failures in production.
Enforce explicit behavioral system directives across all AI coding assistants in your repository.
Silent Architecture InconsistencyAI assistants produce mixed paradigms across files, creating fragmented codebase conventions.Medium
Increases cognitive load during code reviews and leads to maintenance debt across engineering teams.
Pin project conventions in .cursor/rules, CLAUDE.md, and AGENTS.md so all team agents follow identical guardrails.
Architectural Directives in Detail

Step-by-Step Production Directives

Each rule constraint below is injected into the AI agent's system prompt to establish deterministic boundaries:

1

Engineers MUST ALWAYS transfer high-frequency telemetry (>=30Hz) using TypedArrays (Float64Array, Float32Array) or structured-clone compatible binary buffers rather than serialized JSON strings.

Engineers MUST ALWAYS transfer high-frequency telemetry (>=30Hz) using TypedArrays (Float64Array, Float32Array) or structured-clone compatible binary buffers rather than serialized JSON strings.

Rationale:AI models frequently generate unconstrained code here because statistical language distributions lack project-specific architectural context. Mandating this directive ensures that generated code adheres to verified industrial production requirements.
Enforcement:Integrated into the Agent Pack rule file. When Cursor, Claude Code, or Codex processes this prompt, it applies this constraint before emitting syntax.
2

Engineers MUST NOT invoke JSON.stringify() or JSON.parse() on high-frequency bridge messages

Engineers MUST NOT invoke JSON.stringify() or JSON.parse() on high-frequency bridge messages; structured cloning handles primitives and ArrayBuffers natively without serialization overhead.

Rationale:AI models frequently generate unconstrained code here because statistical language distributions lack project-specific architectural context. Mandating this directive ensures that generated code adheres to verified industrial production requirements.
Enforcement:Integrated into the Agent Pack rule file. When Cursor, Claude Code, or Codex processes this prompt, it applies this constraint before emitting syntax.
3

Bridge listeners MUST use persistent native Stream/MessagePort subscriptions instead of continuous polling or promise-per-tick RPC patterns.

Bridge listeners MUST use persistent native Stream/MessagePort subscriptions instead of continuous polling or promise-per-tick RPC patterns.

Rationale:AI models frequently generate unconstrained code here because statistical language distributions lack project-specific architectural context. Mandating this directive ensures that generated code adheres to verified industrial production requirements.
Enforcement:Integrated into the Agent Pack rule file. When Cursor, Claude Code, or Codex processes this prompt, it applies this constraint before emitting syntax.
4

Plugins MUST reuse allocated TypedArray buffers via pooling or off-thread Transferable semantics where continuous telemetry streams would otherwise induce V8/JavaScriptCore garbage collection pauses.

Plugins MUST reuse allocated TypedArray buffers via pooling or off-thread Transferable semantics where continuous telemetry streams would otherwise induce V8/JavaScriptCore garbage collection pauses.

Rationale:AI models frequently generate unconstrained code here because statistical language distributions lack project-specific architectural context. Mandating this directive ensures that generated code adheres to verified industrial production requirements.
Enforcement:Integrated into the Agent Pack rule file. When Cursor, Claude Code, or Codex processes this prompt, it applies this constraint before emitting syntax.
5

Telemetry payloads MUST be validated at design time to ensure all properties conform strictly to Structured Clone Algorithm constraints (no functions, symbols, or non-clonable DOM nodes).

Telemetry payloads MUST be validated at design time to ensure all properties conform strictly to Structured Clone Algorithm constraints (no functions, symbols, or non-clonable DOM nodes).

Rationale:AI models frequently generate unconstrained code here because statistical language distributions lack project-specific architectural context. Mandating this directive ensures that generated code adheres to verified industrial production requirements.
Enforcement:Integrated into the Agent Pack rule file. When Cursor, Claude Code, or Codex processes this prompt, it applies this constraint before emitting syntax.
Technical Questions & Answers

Frequently Asked Technical Questions

Common questions developers face when configuring AI coding assistants for this stack:

Q:Why is Capacitor 7 Structured Clone & Zero-Copy Bridge Serialization for High-Frequency Telemetry critical for AI coding assistants?

Enforces zero-copy structured cloning and transferable buffer semantics across Capacitor 7 WebView-to-native message ports. Eliminates main-thread blocking and garbage collection churn caused by manual JSON stringification during high-frequency geolocation, IMU, and motion sensor streaming. Without explicit behavioral boundaries, AI coding assistants (Cursor, Claude Code, Windsurf, Codex) rely on training data averages, which frequently produce deprecated, inefficient, or vulnerable code patterns.

Q:How does adopting this rule prevent AI hallucinations?

This rule explicitly declares what the AI must avoid (Manual JSON Stringification Across MessagePorts in High-Frequency Sensor Streams) and prescribes verified positive examples. Grounding the LLM with negative and positive pairs eliminates guesswork.

Q:Which AI coding environments are supported?

This specification is multi-platform compatible: Cursor (.cursor/rules/*.mdc & .cursorrules), Anthropic Claude Code (CLAUDE.md), Windsurf (.windsurfrules), Codex / Cline (AGENTS.md), and GitHub Copilot (.github/copilot-instructions.md).

Q:Can I combine this rule with other technology stacks?

Yes. Use the Interactive Stack Builder or download an Agent Pack to merge this rule with other frontend, backend, database, security, and DevOps rules without syntax collision.

Open Specification · CC BY 4.0·Free for Personal, Team & Commercial In-Repo Use

Citation & Open Source Attribution Guidelines

This specification is licensed under Creative Commons Attribution 4.0 International (CC BY 4.0). You are completely free to adapt and share this rule in your workspace. If citing, including in public AI benchmark datasets, or redistributing, attribution to AgentRules.org is required.

Related MOBILE Rules

View all rules →
1 Rule in Stack

Capacitor