<?xml version="1.0" encoding="UTF-8"?>
<feature name="tolerant-paste" version="0.1">
  <description>
    Pre-cleans paste/load input before the canvas parses it. Strips: BOM (U+FEFF),
    leading and trailing whitespace, markdown code fences (```xml ... ```), and any
    prose preamble before the first '&lt;' character. Runs in the click capture phase
    of the modal action button so cleaning happens before the canvas's own parser sees
    the input. Idempotent (cleaning already-clean input is a no-op).
  </description>
  <requires>
    <feature name="registries"/>
  </requires>
  <implementation lang="js"><![CDATA[
    function cleanPasteInput(raw) {
      let s = String(raw || '');
      const before = s.length;

      // 1. Strip BOM
      if (s.charCodeAt(0) === 0xFEFF) s = s.slice(1);

      // 2. Trim outer whitespace
      s = s.trim();

      // 3. Strip markdown code fences (```xml ... ```, ``` ... ```)
      //    Be careful: only at the very start/end, not mid-content
      const fenceStart = s.match(/^```[a-zA-Z0-9_-]*\s*\n/);
      if (fenceStart) {
        s = s.slice(fenceStart[0].length).trimEnd();
      }
      if (s.endsWith('```')) {
        s = s.slice(0, -3).trimEnd();
      }

      // 4. If there's prose preamble before the first '<', strip it (only up to 200 chars)
      const firstAngle = s.indexOf('<');
      if (firstAngle > 0 && firstAngle < 200) {
        s = s.slice(firstAngle);
      }

      const stripped = before - s.length;
      return { cleaned: s, stripped: stripped };
    }

    // Intercept the modal-action click in the CAPTURE phase, so we clean before
    // the canvas's own bound handler reads the textarea value.
    document.addEventListener('click', function(ev) {
      if (!ev.target || ev.target.id !== 'modal-action') return;
      const ta = document.getElementById('ld-xml');
      if (!ta || !ta.value) return;
      const result = cleanPasteInput(ta.value);
      if (result.stripped > 0) {
        ta.value = result.cleaned;
        MR.console.log('TOLERANT-PASTE stripped ' + result.stripped + ' chars (whitespace/fences/preamble)', 'admit');
      }
    }, true);  // capture = true means this runs before bubbling handlers

    MR.console.log('TOLERANT-PASTE active · trims BOM, whitespace, ```fences, prose preamble', 'info');
  ]]></implementation>
</feature>
