const qs = require('querystring'); const spliceString = (string, index, removals = 0, insert = '') => { return ( string.slice(0, index) + insert + string.slice(index + Math.abs(removals)) ); }; const DBUC_REGEX = /^[0-9a-fA-F]{2}$/; const decodeComponent = (string) => { let percentIndex; while ((percentIndex = string.indexOf('%')) !== -1) { const encodedByte = string.substr(percentIndex + 1, 2); if (!DBUC_REGEX.test(encodedByte)) { throw new Error('Invalid input (not URI encoded?)'); } string = spliceString( string, percentIndex, 3, String.fromCharCode(parseInt(encodedByte, 16)), ); } return string; }; const parse = (query, maxKeys = 12) => { return qs.parse(query, '&', '=', { decodeURIComponent: decodeComponent, maxKeys, }); }; const fromUrl = (url, max) => { const splitUrl = url.split('?'); if (splitUrl.length > 2) { throw new Error('Invalid URL'); } if (splitUrl.length === 1) { return {}; } return parse(splitUrl[1]); }; module.exports = { decodeURIComponent: decodeComponent, decodeUriComponent: decodeComponent, parse, fromUrl, __test: (cb) => { cb({ spliceString, DBUC_REGEX, decodeComponent, parse, fromUrl, }); }, };