## Browser SDK

Serve your integration over HTTPS. Ask for camera access from a user action. Configure the output video for inline, muted autoplay.

### JavaScript integration example



```
import { createMirrorClient, prepareMirrorRuntime } from 'https://api.ikawn.com/sdk/mirror.js';

// Prepare on page load. This does not create or bill a session.
const runtimeReady = prepareMirrorRuntime();

// Call from your Start button after the user selects a garment image.
async function startTryOn(garmentFile, outputVideo, showError) {
  await runtimeReady;
  const requestKey = crypto.randomUUID();
  const mirror = createMirrorClient({
    sessionProvider: async ({ capability, queue }) => {
      const response = await fetch('/your-backend/session', {
        method: 'POST',
        credentials: 'same-origin',
        headers: {
          'Content-Type': 'application/json',
          'Idempotency-Key': requestKey
          // Include your app's CSRF protection where applicable.
        },
        body: JSON.stringify({ capability, queue }),
        cache: 'no-store'
      });
      if (!response.ok) throw new Error('Could not create session');
      return response.json();
    },
    onError: (error) => showError(error.message)
  });

  outputVideo.autoplay = true;
  outputVideo.playsInline = true;
  outputVideo.muted = true;
  const camera = await navigator.mediaDevices.getUserMedia({
    video: { width: 640, height: 480 }, audio: false
  });
  try {
    const live = await mirror.connect(camera, {
      capability: 'tryon',
      referenceImage: garmentFile,
      // No prompt: replace clothing only.
      onRemoteStream: (stream) => {
        outputVideo.srcObject = stream;
        outputVideo.play().catch(() => showError('Tap Play to start the video.'));
      }
    });
    return {
      set: (update) => live.set(update),
      async stop() {
        try { return await live.disconnect(); }
        finally {
          camera.getTracks().forEach((track) => track.stop());
          outputVideo.srcObject = null;
        }
      }
    };
  } catch (error) {
    camera.getTracks().forEach((track) => track.stop());
    throw error;
  }
}
```



`/your-backend/session` is a route you implement. Authenticate your own user, check their permission and rate limit, forward the capability, queue option and idempotency key to `POST /sessions` with your server-side API key, and return the JSON with `Cache-Control: no-store`.

The SDK starts a heartbeat every 10 seconds and renews credentials on the open session. It does not need your account API key in the browser.

### SDK options and callbacks

`appId` (optional) — A stable application identifier such as `com.example.shop`, using up to 120 letters, digits, dots, underscores or hyphens. Never supply a user identifier. Integration tracking in the updated SDK reports the browser hostname, SDK version and optional app ID using the scoped session credential; reporting failures do not interrupt streaming. No page paths, query strings or cookies are collected.

`sessionProvider({ capability, queue })` — Required. Returns the complete session-creation response from your backend, including HTTP 202 queued responses.

`queue` — Defaults to true. The current SDK waits and polls automatically. Set false and forward it to your backend only when you want immediate rejection instead of waiting.

`onQueue({ position, expires_at, billable, status })` — Reports the account waiting position with billable false. On admission, position is 0 and status is admitted. Show a waiting indicator and Cancel action.

`connect(stream, options)` — Requires a MediaStream containing a video track. Options: capability, prompt, referenceImage, onRemoteStream and an AbortSignal in signal. Abort to cancel a pending connection or disconnect an admitted session.

`onUsage(usage)` — Reports provisional session usage; do not mistake session usage_seconds for the account balance.

`onStage({ stage, elapsed_ms })` — Reports control milestones, such as session creation, reference acceptance and waiting for frames.

`onStats({ rtt_ms, frames_per_second, packet_loss_ratio })` — Reports transport observations. RTT is not total generation latency.

`onError(error)` — Show a useful recovery action. Retain API request IDs for support, without logging credentials.
