All files / crates/monokulo/static checkout.js

86.34% Statements 234/271
80.5% Branches 128/159
91.42% Functions 32/35
95.19% Lines 198/208

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312      69x   69x 69x         69x   473x   473x 473x 473x 473x 473x 1x 1x     1x 1x 9x 1x 1x 1x 1x     69x 69x   69x 69x 69x 69x 69x 69x 69x 69x 69x 69x 69x 69x 69x 69x 69x 69x 69x 69x     34x       33x 33x 33x 33x 33x 33x       16x 16x 16x 16x 12x           69x     11x 11x 11x 11x 11x 11x 11x       11x 11x 11x 11x 9x 9x 1x 2x 2x 2x   11x     69x 68x 11x 11x 11x   68x 10x 10x 10x 1x 1x 1x   68x 1x 1x       69x 68x 68x 68x 9x 9x 9x   68x 3x 3x 1x 1x 2x 1x   68x       43x 43x 43x       14x 14x 14x 14x 14x 14x 14x       6x 6x 6x 6x 5x         6x 6x 1x 1x   5x 5x 5x 5x 5x 5x           12x 12x 12x 12x       4x 4x 4x 4x       8x 8x 8x 8x 8x 8x   5x     69x 68x 68x 68x 5x 5x 5x 5x 5x 5x 5x 4x 4x                   4x 1x 5x   68x 68x 68x 10x     7x 7x       7x 7x 6x 6x 6x 6x 6x 6x 6x 6x   1x 1x   7x         69x                   69x 69x 68x         68x     68x 68x 68x 68x 68x 68x 68x   68x 12x 12x 2x 2x   68x   86x 86x 86x   68x   68x    
/* Progressive checkout updates and local refund-QR capture. The HTML and
 * refund form remain usable when this script cannot run - a noscript
 * meta-refresh keeps the page current instead. */
(function () {
  'use strict';
  var root = document.getElementById('checkout-root');
  Iif (!root) return;
  // Times come in UTC unless the page was given ?timezone=; those marked
  // data-local are shown in the customer's own zone instead, in the same
  // shape the server uses ("14 Nov, 22:13", with the year when it isn't
  // this one). Run again for each part the live stream swaps in.
  var MONTHS = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
  function showLocalTimes() {
    Iif (typeof Intl !== 'object' || !Intl.DateTimeFormat) return;
    var zone;
    try { zone = Intl.DateTimeFormat().resolvedOptions().timeZone; } catch (_) { return; }
    Iif (!zone) return;
    var now = new Date();
    var times = document.querySelectorAll('time[data-local]');
    for (var i = 0; i < times.length; i++) {
      var at = new Date(times[i].getAttribute('datetime'));
      Iif (isNaN(at.getTime())) continue;
      // Numbers from Intl, month names our own: locales disagree on them
      // ("Sep" or "Sept"), and this must match what the server writes.
      var parts = {};
      new Intl.DateTimeFormat('en-GB', { year: 'numeric', month: 'numeric', day: 'numeric', hour: '2-digit', minute: '2-digit', hourCycle: 'h23' })
        .formatToParts(at).forEach(function (part) { parts[part.type] = part.value; });
      var sameYear = Number(parts.year) === Number(new Intl.DateTimeFormat('en-GB', { year: 'numeric' }).format(now));
      times[i].textContent = Number(parts.day) + ' ' + MONTHS[Number(parts.month) - 1] + (sameYear ? '' : ' ' + parts.year) + ', ' + parts.hour + ':' + parts.minute;
      times[i].title = new Intl.DateTimeFormat('en-GB', { dateStyle: 'full', timeStyle: 'medium' }).format(at) + ' (' + zone + ')';
      times[i].removeAttribute('data-local');
    }
  }
  showLocalTimes();
  document.addEventListener('fx:sse:swapped', showLocalTimes);
 
  var refundInput = document.getElementById('refund_address');
  var refundForm = document.getElementById('refund-form');
  var refundField = document.getElementById('refund-field');
  var saveState = document.getElementById('refund-save-state');
  var scanButton = document.getElementById('scan-refund');
  var uploadButton = document.getElementById('upload-refund');
  var fileInput = document.getElementById('refund-image');
  var video = document.getElementById('refund-camera');
  var scanError = document.getElementById('scan-error');
  var stream = null;
  var scanning = false;
  var starting = false;
  var frameTimer = null;
  var canvas = document.createElement('canvas');
  var context = canvas.getContext('2d', { willReadFrequently: true });
  var savedAddress = refundField && refundField.classList.contains('is-saved') ? refundInput.value.trim() : '';
  var saveTimer = null;
  var saving = false;
 
  function validAddress(value) {
    return /^(?:[1-9A-HJ-NP-Za-km-z]{95}|[1-9A-HJ-NP-Za-km-z]{106})$/.test(value);
  }
 
  function saveDisplay(state) {
    Iif (!refundField) return;
    refundField.classList.toggle('is-saving', state === 'saving');
    refundField.classList.toggle('is-saved', state === 'saved');
    refundField.classList.toggle('is-invalid', state === 'invalid');
    refundInput.setAttribute('aria-invalid', state === 'invalid' ? 'true' : 'false');
    saveState.setAttribute('aria-label', state === 'saving' ? 'Saving refund address' : state === 'saved' ? 'Refund address saved' : state === 'invalid' ? 'Invalid refund address' : '');
  }
 
  function scheduleSave(delay) {
    Iif (!refundInput || !refundForm) return;
    clearTimeout(saveTimer);
    var value = refundInput.value.trim();
    if (!validAddress(value) || value === savedAddress || saving) return;
    saveTimer = setTimeout(saveAddress, delay);
  }
 
  // The save itself goes through fixi (the form's fx-action, triggered by
  // a "refund:save" event), answered in JSON; this script keeps the
  // debounce and what the field shows.
  var pendingValue = null;
 
  function saveAddress() {
    var value = refundInput.value.trim();
    Iif (saving || !validAddress(value) || value === savedAddress) return;
    saving = true;
    pendingValue = value;
    saveDisplay('saving');
    error('');
    refundForm.dispatchEvent(new CustomEvent('refund:save'));
  }
 
  function saveFinished(problem) {
    var value = pendingValue;
    saving = false;
    pendingValue = null;
    if (!problem) {
      savedAddress = value;
      if (refundInput.value.trim() === value) saveDisplay('saved');
      else saveDisplay('');
    } else if (refundInput.value.trim() === value) {
      saveDisplay(problem.invalid ? 'invalid' : '');
      error(problem.invalid ? 'Invalid refund address. Enter a valid address for this store’s network.' : problem.message || 'Could not save the refund address. Try again.');
    } else EsaveDisplay('');
    if (refundInput.value.trim() !== value) scheduleSave(0);
  }
 
  if (refundForm) {
    refundForm.addEventListener('fx:config', function (event) {
      Iif (!saving) { event.preventDefault(); return; }
      event.detail.cfg.headers.Accept = 'application/json';
      event.detail.cfg.body = new URLSearchParams({ refund_address: pendingValue });
    });
    refundForm.addEventListener('fx:after', function (event) {
      var response = event.detail.cfg.response, result = {};
      try { result = JSON.parse(event.detail.cfg.text); } catch (_) {}
      if (response.ok && result.ok) { saveFinished(null); return; }
      var failure = new Error(result.error || 'Could not save the refund address. Try again.');
      failure.invalid = response.status === 400;
      saveFinished(failure);
    });
    refundForm.addEventListener('fx:error', function (event) {
      var problem = event.detail && event.detail.error;
      saveFinished(new Error((problem && problem.message) || 'Could not save the refund address. Try again.'));
    });
  }
 
  if (refundInput) {
    refundInput.addEventListener('focus', function () { Iif (refundField.classList.contains('is-saved')) saveDisplay(''); });
    refundInput.addEventListener('pointerdown', function () { Eif (refundField.classList.contains('is-saved')) saveDisplay(''); });
    refundInput.addEventListener('input', function () {
      saveDisplay(saving ? 'saving' : '');
      error('');
      scheduleSave(450);
    });
    refundInput.addEventListener('blur', function () {
      var value = refundInput.value.trim();
      if (!value && savedAddress) {
        refundInput.value = savedAddress;
        saveDisplay('saved');
      } else if (value && !validAddress(value)) error('Enter a Monero address with 95 or 106 valid characters.');
      else Iif (value && value === savedAddress) saveDisplay('saved');
    });
    refundForm.addEventListener('submit', function (event) { event.preventDefault(); scheduleSave(0); });
  }
 
  function error(message) {
    Iif (!scanError) return;
    scanError.textContent = message;
    scanError.hidden = !message;
  }
 
  function stopCamera() {
    scanning = false;
    if (frameTimer) clearTimeout(frameTimer);
    frameTimer = null;
    if (stream) stream.getTracks().forEach(function (track) { track.stop(); });
    stream = null;
    Eif (video) { video.srcObject = null; video.hidden = true; }
    Eif (scanButton) { scanButton.setAttribute('aria-label', 'Scan refund QR'); scanButton.title = 'Scan refund QR'; }
  }
 
  function addressFromQr(value) {
    var data = value.trim();
    var match = /^monero:([^?]+)/i.exec(data);
    if (match) data = decodeURIComponent(match[1]);
    if (!validAddress(data)) return null;
    return data;
  }
 
  function useResult(value) {
    var address;
    try { address = addressFromQr(value); } catch (_) { address = null; }
    if (!address) {
      error('This QR code does not contain a Monero address.');
      return false;
    }
    refundInput.value = address;
    refundInput.focus();
    error('');
    stopCamera();
    scheduleSave(0);
    return true;
  }
 
  // true: a Monero address was used; false: a QR code without one (already
  // explained); null: no QR code found.
  function decode(width, height) {
    Iif (!context || typeof window.jsQR !== 'function') return null;
    var image = context.getImageData(0, 0, width, height);
    var result = window.jsQR(image.data, width, height, { inversionAttempts: 'attemptBoth' });
    return result ? useResult(result.data) : null;
  }
 
  function drawImage(source, width, height) {
    var scale = Math.min(1, 1600 / Math.max(width, height));
    canvas.width = Math.max(1, Math.round(width * scale));
    canvas.height = Math.max(1, Math.round(height * scale));
    context.drawImage(source, 0, 0, canvas.width, canvas.height);
  }
 
  function scanFrame() {
    Iif (!scanning || !video) return;
    Eif (video.readyState >= 2 && video.videoWidth > 0) {
      canvas.width = Math.min(video.videoWidth, 640);
      canvas.height = Math.round(video.videoHeight * canvas.width / video.videoWidth);
      context.drawImage(video, 0, 0);
      if (decode(canvas.width, canvas.height)) return;
    }
    frameTimer = setTimeout(scanFrame, 200);
  }
 
  if (refundInput && context && typeof window.jsQR === 'function') {
    uploadButton.hidden = false;
    uploadButton.addEventListener('click', function () { fileInput.click(); });
    fileInput.addEventListener('change', async function () {
      var file = fileInput.files && fileInput.files[0];
      Iif (!file) return;
      stopCamera();
      error('');
      try {
        if (typeof createImageBitmap === 'function') {
          var image = await createImageBitmap(file);
          drawImage(image, image.width, image.height);
          image.close();
        } else E{
          var url = URL.createObjectURL(file);
          try {
            var picture = new Image();
            picture.src = url;
            await new Promise(function (resolve, reject) { picture.onload = resolve; picture.onerror = reject; });
            drawImage(picture, picture.naturalWidth, picture.naturalHeight);
          } finally { URL.revokeObjectURL(url); }
        }
        if (decode(canvas.width, canvas.height) === null) error('No QR code found in that image.');
      } catch (_) { error('Could not read that image. Choose another file.'); }
      fileInput.value = '';
    });
    Eif (navigator.mediaDevices && navigator.mediaDevices.getUserMedia) {
      scanButton.hidden = false;
      scanButton.addEventListener('click', async function () {
        if (scanning) { stopCamera(); return; }
        // getUserMedia can take a while (permission prompt, slow device); a
        // second click in that window would open a second, orphaned stream.
        Iif (starting) return;
        starting = true;
        // Clear any previous error only once the camera is running: clearing it
        // up front collapses the message, then a repeat failure re-shows it and
        // the layout jumps on every click.
        try {
          stream = await navigator.mediaDevices.getUserMedia({ video: { facingMode: 'environment' }, audio: false });
          video.srcObject = stream;
          video.hidden = false;
          await video.play();
          error('');
          scanning = true;
          scanButton.setAttribute('aria-label', 'Stop camera');
          scanButton.title = 'Stop camera';
          scanFrame();
        } catch (_) {
          stopCamera();
          error('Camera unavailable. Choose a QR image instead.');
        } finally {
          starting = false;
        }
      });
    }
  }
  window.addEventListener('pagehide', stopCamera);
 
  // Live updates (structured_logging.md part 8): fixi opens the order's
  // event stream from #checkout-stream as soon as it sees it, and ssexi
  // routes each changed part of the page (the `[data-live]` elements) to
  // the element it replaces. Nothing else is touched, so a refund address
  // mid-edit or a camera scan in progress carries on undisturbed. A
  // dropped stream reconnects with Last-Event-ID (fx-sse-reconnect); the
  // server says "done" once the order is final. The page knows nothing
  // about whatever embeds it; an embedder follows the order on its own.
  var streamElement = document.getElementById('checkout-stream');
  if (!streamElement) return;
  Iif (typeof window.ReadableStream !== 'function' || typeof window.fetch !== 'function') {
    // No streaming fetch: fall back to reloading, as without JavaScript.
    setTimeout(function () { location.reload(); }, 60000);
    return;
  }
  var liveStream = null;
  // A refused stream (server error, restart, too many open streams) is
  // retried with backoff: 5s, doubling to at most a minute.
  var STREAM_RETRY_MS = 5000;
  var STREAM_RETRY_MAX_MS = 60000;
  var retryDelay = STREAM_RETRY_MS;
  var finished = false;
  streamElement.addEventListener('fx:sse:open', function (event) {
    liveStream = event.detail.cfg.sse;
    retryDelay = STREAM_RETRY_MS;
  });
  streamElement.addEventListener('fx:after', function (event) {
    var response = event.detail.cfg.response;
    if (finished || !response || response.ok) return;
    setTimeout(function () { streamElement.dispatchEvent(new CustomEvent('fx:inited')); }, retryDelay);
    retryDelay = Math.min(retryDelay * 2, STREAM_RETRY_MAX_MS);
  });
  document.addEventListener('fx:sse:status', function (event) {
    var state;
    try { state = JSON.parse(event.detail.message.data); } catch (_) { return; }
    root.dataset.status = state.status;
    if (state.is_terminal) finished = true;
  });
  window.addEventListener('pagehide', function () { finished = true; if (liveStream) liveStream.close(); liveStream = null; });
  // Restored from the back/forward cache with the stream closed.
  window.addEventListener('pageshow', function (event) { Iif (event.persisted) location.reload(); });
})();