#!/usr/bin/env bash
set -euo pipefail
cd "$(dirname "$0")"

mkdir -p rules cam deploy

cat > .gitignore <<'A'
node_modules/
dist/
cam/*.mp4
A

cat > manifest.json <<'A'
{
  "manifest_version": 3,
  "name": "iPhone XR Surface (screen / touch / camera)",
  "version": "1.0.0",
  "description": "Emulates iPhone XR screen metrics, touch input and camera output on the JS surface.",
  "minimum_chrome_version": "111",
  "content_scripts": [
    {
      "matches": ["<all_urls>"],
      "js": ["boot.js"],
      "run_at": "document_start",
      "all_frames": true,
      "match_about_blank": true
    },
    {
      "matches": ["<all_urls>"],
      "js": ["rules/00-core.js", "rules/10-input.js", "rules/20-output.js"],
      "run_at": "document_start",
      "all_frames": true,
      "match_about_blank": true,
      "world": "MAIN"
    }
  ],
  "web_accessible_resources": [
    { "resources": ["cam/*"], "matches": ["<all_urls>"] }
  ]
}
A

cat > boot.js <<'A'
'use strict';
document.documentElement.dataset.xrCam = chrome.runtime.getURL('cam/');
A

cat > rules/00-core.js <<'A'
/* iPhone XR: 414x896 CSS, DPR 2, A12 6-core. Must land before any page script. */
(() => {
  'use strict';
  if (window.__xr) return;

  const define = Object.defineProperty;
  const def = (target, prop, value) => {
    try { define(target, prop, { get: () => value, configurable: true, enumerable: true }); } catch (_) {}
  };
  const drop = (target, prop) => {
    try { Reflect.deleteProperty(target, prop); } catch (_) {}
  };

  const SCREEN_W = 414;
  const SCREEN_H = 896;
  const DPR = 2;

  window.__xr = { hadTouch: 'ontouchstart' in window };

  def(Navigator.prototype, 'platform', 'iPhone');
  def(Navigator.prototype, 'vendor', 'Apple Computer, Inc.');
  def(Navigator.prototype, 'maxTouchPoints', 5);
  def(Navigator.prototype, 'hardwareConcurrency', 6);
  def(Navigator.prototype, 'standalone', false);
  def(Navigator.prototype, 'doNotTrack', '1');
  def(Navigator.prototype, 'webdriver', false);

  drop(Navigator.prototype, 'deviceMemory');
  drop(Navigator.prototype, 'userAgentData');
  drop(Navigator.prototype, 'connection');
  drop(Navigator.prototype, 'pdfViewerEnabled');
  drop(Navigator.prototype, 'xr');
  drop(window, 'chrome');

  const emptyList = () => ({
    length: 0,
    item: () => null,
    namedItem: () => null,
    refresh: () => {},
    [Symbol.iterator]: function* () {},
  });
  def(Navigator.prototype, 'plugins', emptyList());
  def(Navigator.prototype, 'mimeTypes', emptyList());

  def(Screen.prototype, 'width', SCREEN_W);
  def(Screen.prototype, 'height', SCREEN_H);
  def(Screen.prototype, 'availWidth', SCREEN_W);
  def(Screen.prototype, 'availHeight', SCREEN_H);
  def(Screen.prototype, 'availLeft', 0);
  def(Screen.prototype, 'availTop', 0);
  def(Screen.prototype, 'colorDepth', 24);
  def(Screen.prototype, 'pixelDepth', 24);
  def(Screen.prototype, 'orientation', {
    type: 'portrait-primary',
    angle: 0,
    onchange: null,
    lock: () => Promise.resolve(),
    unlock: () => {},
    addEventListener: () => {},
    removeEventListener: () => {},
    dispatchEvent: () => true,
  });

  def(window, 'devicePixelRatio', DPR);
  def(window, 'outerWidth', SCREEN_W);
  def(window, 'outerHeight', SCREEN_H);
  def(window, 'innerWidth', SCREEN_W);
  def(window, 'innerHeight', SCREEN_H);

  if (window.VisualViewport) {
    def(VisualViewport.prototype, 'width', SCREEN_W);
    def(VisualViewport.prototype, 'height', SCREEN_H);
    def(VisualViewport.prototype, 'scale', 1);
  }

  const nativeMM = window.matchMedia.bind(window);
  const FORCED = new Map([
    ['(pointer: coarse)', true], ['(pointer: fine)', false],
    ['(hover: none)', true], ['(hover: hover)', false],
    ['(any-pointer: coarse)', true], ['(any-pointer: fine)', false],
    ['(any-hover: none)', true], ['(any-hover: hover)', false],
    ['(orientation: portrait)', true], ['(orientation: landscape)', false],
    ['(display-mode: browser)', true],
  ]);

  const RATIO = 2;
  const evalDevice = (clause) => {
    const m = /^\(\s*(min-|max-)?(device-width|device-height|-webkit-device-pixel-ratio|device-pixel-ratio)\s*:\s*([\d.]+)(?:px)?\s*\)$/i
      .exec(clause.trim());
    if (!m) return null;
    const [, bound, feature, raw] = m;
    const value = parseFloat(raw);
    const name = feature.toLowerCase();
    const actual = name === 'device-width' ? SCREEN_W : name === 'device-height' ? SCREEN_H : RATIO;
    if (bound === 'min-') return actual >= value;
    if (bound === 'max-') return actual <= value;
    return actual === value;
  };

  const forceMatch = (mql, matches, media) => new Proxy(mql, {
    get(target, prop) {
      if (prop === 'matches') return matches;
      if (prop === 'media') return media;
      const value = Reflect.get(target, prop);
      return typeof value === 'function' ? value.bind(target) : value;
    },
  });

  window.matchMedia = (query) => {
    const key = String(query).trim().toLowerCase();
    if (FORCED.has(key)) return forceMatch(nativeMM('all'), FORCED.get(key), query);

    const clauses = String(query).split(/\s+and\s+/i);
    const devices = clauses.map(evalDevice);
    if (devices.some((v) => v !== null)) {
      const deviceOk = devices.every((v) => v !== false);
      const rest = clauses.filter((_, i) => devices[i] === null);
      const restOk = rest.length ? nativeMM(rest.join(' and ')).matches : true;
      return forceMatch(nativeMM('all'), deviceOk && restOk, query);
    }
    return nativeMM(query);
  };
})();
A

cat > rules/10-input.js <<'A'
(() => {
  'use strict';
  const state = window.__xr;
  if (!state || state.inputDone) return;
  state.inputDone = true;

  const def = (target, prop, value) => {
    try { Object.defineProperty(target, prop, { get: () => value, configurable: true }); } catch (_) {}
  };

  if (!state.hadTouch) {
    def(window, 'ontouchstart', null);
    def(Document.prototype, 'ontouchstart', null);
    def(HTMLElement.prototype, 'ontouchstart', null);
  }

  const pointerType = Object.getOwnPropertyDescriptor(PointerEvent.prototype, 'pointerType');
  if (pointerType && pointerType.get) {
    Object.defineProperty(PointerEvent.prototype, 'pointerType', {
      configurable: true,
      get() {
        const native = pointerType.get.call(this);
        return native === 'mouse' ? 'touch' : native;
      },
    });
  }

  if (state.hadTouch) return;

  let identifier = 0;
  const active = new Map();
  const byPointer = new Map();

  const buildTouch = (target, event) => new Touch({
    identifier: ++identifier,
    target,
    clientX: event.clientX,
    clientY: event.clientY,
    pageX: event.pageX,
    pageY: event.pageY,
    screenX: event.screenX,
    screenY: event.screenY,
    radiusX: 12,
    radiusY: 12,
    rotationAngle: 0,
    force: event.pressure || 0.5,
  });

  const emit = (target, type, changed) => {
    const all = [...active.values()];
    const remaining = type === 'touchend' || type === 'touchcancel'
      ? all.filter((t) => t !== changed)
      : all;
    target.dispatchEvent(new TouchEvent(type, {
      bubbles: true,
      cancelable: true,
      composed: true,
      touches: remaining,
      targetTouches: remaining.filter((t) => t.target === target),
      changedTouches: [changed],
    }));
  };

  addEventListener('pointerdown', (event) => {
    if (event.pointerType !== 'touch' && event.pointerType !== 'mouse') return;
    if (byPointer.has(event.pointerId)) return;
    const touch = buildTouch(event.target, event);
    byPointer.set(event.pointerId, touch);
    active.set(touch.identifier, touch);
    emit(event.target, 'touchstart', touch);
  }, true);

  addEventListener('pointermove', (event) => {
    const touch = byPointer.get(event.pointerId);
    if (touch) emit(touch.target, 'touchmove', touch);
  }, true);

  const release = (event, type) => {
    const touch = byPointer.get(event.pointerId);
    if (!touch) return;
    emit(touch.target, type, touch);
    byPointer.delete(event.pointerId);
    active.delete(touch.identifier);
  };

  addEventListener('pointerup', (event) => release(event, 'touchend'), true);
  addEventListener('pointercancel', (event) => release(event, 'touchcancel'), true);
})();
A

cat > rules/20-output.js <<'A'
(() => {
  'use strict';
  const state = window.__xr;
  if (!state || state.outputDone) return;
  state.outputDone = true;

  const nativeGUM = MediaDevices.prototype.getUserMedia;
  const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));

  const resolveBase = async () => {
    for (let i = 0; i < 100; i++) {
      const base = document.documentElement && document.documentElement.dataset.xrCam;
      if (base) return base;
      await sleep(50);
    }
    return '';
  };

  const devices = [
    { deviceId: 'xr-front', groupId: 'xr-cam', kind: 'videoinput', label: 'Front Camera' },
    { deviceId: 'xr-back', groupId: 'xr-cam', kind: 'videoinput', label: 'Back Camera' },
    { deviceId: 'xr-mic', groupId: 'xr-mic', kind: 'audioinput', label: 'iPhone Microphone' },
    { deviceId: 'xr-speaker', groupId: 'xr-mic', kind: 'audiooutput', label: 'iPhone' },
  ].map((device) => ({
    ...device,
    toJSON: () => ({ ...device }),
    getCapabilities: () => ({
      deviceId: device.deviceId,
      groupId: device.groupId,
      ...(device.kind === 'videoinput'
        ? { facingMode: [device.deviceId === 'xr-back' ? 'environment' : 'user'] }
        : {}),
    }),
  }));

  MediaDevices.prototype.enumerateDevices = async function () {
    return devices.slice();
  };

  const pick = (value, fallback) => {
    if (typeof value === 'number') return value;
    if (value && typeof value === 'object') return value.ideal || value.exact || value.max || fallback;
    return fallback;
  };

  const even = (n) => Math.max(2, Math.round(n / 2) * 2);

  const mount = async (source, width, height) => {
    const video = document.createElement('video');
    video.muted = true;
    video.loop = true;
    video.playsInline = true;
    video.autoplay = true;
    video.src = source;
    video.style.cssText =
      'position:fixed;left:-9999px;top:0;width:1px;height:1px;opacity:0;pointer-events:none';
    document.documentElement.appendChild(video);

    await new Promise((resolve) => {
      video.addEventListener('loadeddata', resolve, { once: true });
      video.addEventListener('error', resolve, { once: true });
      setTimeout(resolve, 3000);
    });
    video.play().catch(() => {});

    const canvas = document.createElement('canvas');
    canvas.width = width;
    canvas.height = height;
    const context = canvas.getContext('2d', { alpha: false });

    let frame = 0;
    const paint = () => {
      if (video.readyState >= 2 && video.videoWidth) {
        const sourceRatio = video.videoWidth / video.videoHeight;
        const ratio = width / height;
        let sw, sh, sx, sy;
        if (sourceRatio > ratio) {
          sh = video.videoHeight; sw = sh * ratio; sx = (video.videoWidth - sw) / 2; sy = 0;
        } else {
          sw = video.videoWidth; sh = sw / ratio; sx = 0; sy = (video.videoHeight - sh) / 2;
        }
        context.drawImage(video, sx, sy, sw, sh, 0, 0, width, height);
      } else {
        const gradient = context.createLinearGradient(0, 0, width, height);
        gradient.addColorStop(0, '#1b1b1f');
        gradient.addColorStop(1, '#3a3a42');
        context.fillStyle = gradient;
        context.fillRect(0, 0, width, height);
        context.fillStyle = '#8a8a95';
        context.font = `${Math.round(height / 12)}px sans-serif`;
        context.textAlign = 'center';
        context.fillText('iPhone XR', width / 2, height / 2);
      }
      frame = requestAnimationFrame(paint);
    };
    paint();

    const destroy = () => {
      cancelAnimationFrame(frame);
      video.pause();
      video.removeAttribute('src');
      video.load();
      video.remove();
    };

    return { canvas, destroy };
  };

  const videoTrack = async (constraints) => {
    const wants = constraints && typeof constraints === 'object' ? constraints : {};
    const rear = wants.facingMode === 'environment';
    const width = even(Math.min(3840, pick(wants.width, 1280)));
    const height = even(Math.min(2160, pick(wants.height, 720)));
    const base = await resolveBase();

    const { canvas, destroy } = await mount(base + (rear ? 'back.mp4' : 'front.mp4'), width, height);
    const track = canvas.captureStream(30).getVideoTracks()[0];
    if (!track) {
      destroy();
      throw new DOMException('Could not start video source', 'NotReadableError');
    }

    const settings = {
      deviceId: rear ? 'xr-back' : 'xr-front',
      groupId: 'xr-cam',
      facingMode: rear ? 'environment' : 'user',
      width,
      height,
      frameRate: 30,
      aspectRatio: +(width / height).toFixed(3),
    };
    const capabilities = {
      deviceId: settings.deviceId,
      groupId: 'xr-cam',
      facingMode: [settings.facingMode],
      width: { min: 320, max: rear ? 3840 : 1920, step: 2 },
      height: { min: 240, max: rear ? 2160 : 1080, step: 2 },
      frameRate: { min: 15, max: 60, step: 1 },
      aspectRatio: { min: 0.56, max: 1.78 },
    };

    const nativeStop = track.stop.bind(track);
    Object.defineProperties(track, {
      label: { get: () => (rear ? 'Back Camera' : 'Front Camera'), configurable: true },
      getSettings: { value: () => ({ ...settings }), configurable: true },
      getCapabilities: { value: () => ({ ...capabilities }), configurable: true },
      applyConstraints: { value: async () => {}, configurable: true },
      stop: { value: () => { nativeStop(); destroy(); }, configurable: true },
    });

    return track;
  };

  const audioTrack = async (constraints) => {
    try {
      const stream = await nativeGUM.call(navigator.mediaDevices, { audio: constraints || true });
      const track = stream.getAudioTracks()[0];
      if (track) {
        Object.defineProperty(track, 'label', { get: () => 'iPhone Microphone', configurable: true });
        return track;
      }
    } catch (_) {}

    const context = new AudioContext();
    const destination = context.createMediaStreamDestination();
    const oscillator = context.createOscillator();
    oscillator.connect(destination);
    oscillator.start();
    return destination.stream.getAudioTracks()[0];
  };

  MediaDevices.prototype.getUserMedia = async function (constraints = {}) {
    const tracks = [];
    if (constraints.video) {
      tracks.push(await videoTrack(constraints.video === true ? {} : constraints.video));
    }
    if (constraints.audio) tracks.push(await audioTrack(constraints.audio));
    if (!tracks.length) {
      throw new DOMException('At least one of audio and video must be requested', 'TypeError');
    }
    return new MediaStream(tracks);
  };
})();
A

cat > test.html <<'A'
<!doctype html>
<html lang="en">
<meta charset="utf-8">
<title>XR surface check</title>
<style>
  body { font: 14px/1.5 ui-monospace, monospace; margin: 2rem; }
  td { padding: 2px 12px 2px 0; vertical-align: top; }
  .bad { color: #b00; font-weight: 700; }
  video { width: 240px; border: 1px solid #ccc; }
</style>
<h1>iPhone XR surface check</h1>
<table id="out"></table>
<p><button id="cam">getUserMedia</button></p>
<video id="v" autoplay playsinline muted></video>
<pre id="log"></pre>
<script>
const rows = {
  'screen.width': [screen.width, 414],
  'screen.height': [screen.height, 896],
  'screen.colorDepth': [screen.colorDepth, 24],
  'devicePixelRatio': [devicePixelRatio, 2],
  'screen.orientation.type': [screen.orientation.type, 'portrait-primary'],
  'maxTouchPoints': [navigator.maxTouchPoints, 5],
  'ontouchstart in window': ['ontouchstart' in window, true],
  'hardwareConcurrency': [navigator.hardwareConcurrency, 6],
  'deviceMemory': [navigator.deviceMemory, undefined],
  'platform': [navigator.platform, 'iPhone'],
  'vendor': [navigator.vendor, 'Apple Computer, Inc.'],
  'userAgentData': [typeof navigator.userAgentData, 'undefined'],
  'plugins.length': [navigator.plugins.length, 0],
  'pointer: coarse': [matchMedia('(pointer: coarse)').matches, true],
  'hover: none': [matchMedia('(hover: none)').matches, true],
  '(min-device-width: 375px)': [matchMedia('(min-device-width: 375px)').matches, true],
  '(max-device-width: 360px)': [matchMedia('(max-device-width: 360px)').matches, false],
};
const out = document.getElementById('out');
let failures = 0;
for (const [key, [actual, expected]] of Object.entries(rows)) {
  const ok = String(actual) === String(expected);
  if (!ok) failures++;
  const tr = document.createElement('tr');
  tr.dataset.ok = String(ok);
  tr.innerHTML = `<td>${key}</td><td class="${ok ? '' : 'bad'}">${String(actual)}</td><td>${String(expected)}</td>`;
  out.append(tr);
}
document.documentElement.dataset.failures = String(failures);

document.getElementById('cam').onclick = async () => {
  const log = document.getElementById('log');
  try {
    const list = await navigator.mediaDevices.enumerateDevices();
    log.textContent = list.map((d) => `${d.kind}\t${d.label}`).join('\n') + '\n\n';
    const stream = await navigator.mediaDevices.getUserMedia({ video: true });
    document.getElementById('v').srcObject = stream;
    log.textContent += JSON.stringify(stream.getVideoTracks()[0].getSettings(), null, 2);
  } catch (error) {
    log.textContent = String(error);
  }
};
</script>
A

cat > deploy/build.sh <<'A'
#!/usr/bin/env bash
set -euo pipefail
cd "$(dirname "$0")/.."

for file in boot.js rules/00-core.js rules/10-input.js rules/20-output.js; do
  node --check "$file"
done
for file in manifest.json cam/front.mp4 cam/back.mp4; do
  [ -s "$file" ] || { echo "missing: $file"; exit 1; }
done

mkdir -p dist
rm -f dist/iphone-xr-surface.zip
zip -qr dist/iphone-xr-surface.zip manifest.json boot.js rules cam
echo "built dist/iphone-xr-surface.zip"
A
chmod +x deploy/build.sh

cat > deploy/nginx.conf <<'A'
server {
    listen 80;
    listen [::]:80;
    server_name DOMAIN;

    root /srv/xr-ext;
    autoindex on;

    location /cam/ {
        types { video/mp4 mp4; }
        add_header Cache-Control "public, max-age=31536000, immutable";
        add_header Accept-Ranges bytes;
    }

    location ~ \.(zip|crx)$ {
        add_header Content-Disposition "attachment";
    }

    location / {
        add_header Cache-Control "no-cache";
        try_files $uri $uri/ =404;
    }
}
A

echo "scaffold ok"
