add some support for tickets, introspection method, minor fixes
[squeep-indieauth-helper] / lib / common.js
index 0a8723b0115a5c2ba2cbd21313e0ad367b6a59fe..f199b4947ed1ba537a29350c617322cf64678512 100644 (file)
@@ -15,23 +15,10 @@ const fileScope = (filename) => {
 }
 
 
-/**
- * Convert Base64 to Base64URL.
- * @param {String} input
- * @returns {String}
- */
-const base64ToBase64URL = (input) => {
-  return input
-    .replace(/=/g, '')
-    .replace(/\+/g, '-')
-    .replace(/\//g, '_');
-};
-
-
 /**
  * Pick out useful axios response fields.
- * @param {*} res
- * @returns
+ * @param {AxiosResponse} res
+ * @returns {Object}
  */
 const axiosResponseLogData = (res) => {
   const data = pick(res, [
@@ -77,10 +64,56 @@ const pick = (obj, props) => {
 };
 
 
+/**
+ * Return a set containing non-shared items between two sets.
+ * @param {Set} a
+ * @param {Set} b
+ * @returns {Set}
+ */
+const setSymmetricDifference = (a, b) => {
+  const d = new Set(a);
+  for (const x of b) {
+    if (d.has(x)) {
+      d.delete(x);
+    } else {
+      d.add(x);
+    }
+  }
+  return d;
+};
+
+
+/**
+ * URL objects have weird names.
+ * @param {String} component
+ * @returns {String}
+ */
+const properURLComponentName = (component) => {
+  // eslint-disable-next-line security/detect-object-injection
+  return {
+    hash: 'fragment',
+    protocol: 'scheme',
+  }[component] || component;
+}
+
+
+/**
+ * Encodes single-level object as form data string.
+ * @param {Object} data
+ */
+const formData = (data) => {
+  const formData = new URLSearchParams();
+  Object.entries(data).forEach(([name, value]) => formData.set(name, value));
+  return formData.toString();
+};
+
+
 module.exports = {
   fileScope,
-  base64ToBase64URL,
   axiosResponseLogData,
   logTruncate,
   pick,
+  setSymmetricDifference,
+  properURLComponentName,
+  formData,
 };
\ No newline at end of file