Refactor XHR interceptor

In preparation for future work on the XHR interceptor.

Bug: twpowertools:153
Change-Id: Id8df1486c033ba02429a17d161e2bcc87a0f1de5
diff --git a/src/xhrInterceptor/utils.js b/src/xhrInterceptor/utils.js
new file mode 100644
index 0000000..909549b
--- /dev/null
+++ b/src/xhrInterceptor/utils.js
@@ -0,0 +1,77 @@
+import {correctArrayKeys} from '../common/protojs';
+
+import xhrInterceptors from './interceptors.json5';
+
+export {xhrInterceptors};
+
+export function matchInterceptors(interceptFilter, url) {
+  return xhrInterceptors.interceptors.filter(interceptor => {
+    var regex = new RegExp(interceptor.urlRegex);
+    return interceptor.intercepts == interceptFilter && regex.test(url);
+  });
+}
+
+export function getResponseText(xhr, transformArrayPb = true) {
+  let response;
+  if (xhr.responseType === 'arraybuffer') {
+    var arrBuffer = xhr.response;
+    if (!arrBuffer) {
+      console.error('No array buffer.');
+      return undefined;
+    }
+    let byteArray = new Uint8Array(arrBuffer);
+    let dec = new TextDecoder('utf-8');
+    response = dec.decode(byteArray);
+  } else if (xhr.responseType === 'text' || xhr.responseType === '') {
+    response = xhr.responseText;
+  } else if (xhr.responseType === 'json') {
+    response = JSON.stringify(xhr.response);
+  } else {
+    console.error(
+        'Unexpected responseType ' + xhr.responseType + '. Request url: ',
+        xhr.$TWPTRequestURL);
+    return undefined;
+  }
+
+  if (xhr.$isArrayProto && transformArrayPb)
+    response = correctArrayKeys(response);
+
+  return response;
+}
+
+export function getResponseJSON(xhr) {
+  let response;
+  if (xhr.responseType === 'arraybuffer') {
+    var arrBuffer = xhr.response;
+    if (!arrBuffer) {
+      console.error('No array buffer.');
+      return undefined;
+    }
+    let byteArray = new Uint8Array(arrBuffer);
+    let dec = new TextDecoder('utf-8');
+    let rawResponse = dec.decode(byteArray);
+    response = JSON.parse(rawResponse);
+  } else if (xhr.responseType === 'text' || xhr.responseType === '') {
+    response = JSON.parse(xhr.responseText);
+  } else if (xhr.responseType === 'json') {
+    response = xhr.response;
+  } else {
+    console.error(
+        'Unexpected responseType ' + xhr.responseType + '. Request url: ',
+        xhr.$TWPTRequestURL);
+    return undefined;
+  }
+
+  if (xhr.$isArrayProto) response = correctArrayKeys(response);
+  return response;
+}
+
+export function triggerEvent(eventName, body, id) {
+  var evt = new CustomEvent('TWPT_' + eventName, {
+    detail: {
+      body,
+      id,
+    }
+  });
+  window.dispatchEvent(evt);
+}