2020-03-31 12:09:33 +02:00
|
|
|
/**
|
|
|
|
* Return an endpoint URL that has a protocol, domain and path
|
|
|
|
*/
|
|
|
|
function normalizedEndpoint(endpoint) {
|
|
|
|
let matches = endpoint.match(/^(https?:\/\/)?([^\/]+)(\/.*)?$/i);
|
|
|
|
if (!matches) throw Error("Invalid endpoint URL");
|
|
|
|
|
|
|
|
let protocol = matches[1] || "https://";
|
|
|
|
let domain = matches[2];
|
|
|
|
let path = matches[3] || "/api/v4";
|
|
|
|
|
|
|
|
return `${protocol}${domain}${path}`;
|
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Return the endpoint as it should be shown to the user
|
|
|
|
*/
|
|
|
|
function humanReadableEndpoint(endpoint) {
|
|
|
|
let matches = endpoint.match(/^(https?:\/\/.+)\/api\/v4$/i);
|
|
|
|
if (!matches) throw Error("Invalid endpoint URL");
|
|
|
|
|
|
|
|
return matches[1];
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Shorthand for document.getElementById
|
|
|
|
*/
|
|
|
|
function byId(id, nullOk=false) {
|
|
|
|
const el = document.getElementById(id);
|
|
|
|
if (!el && !nullOk) {
|
|
|
|
console.error(`No element #${id}`);
|
|
|
|
}
|
|
|
|
return el;
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Wrap a function so that it receives `this` as first argument
|
|
|
|
*/
|
|
|
|
function thisToArg(f) {
|
|
|
|
return function(...rest) {
|
|
|
|
return f(this, ...rest);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2020-03-31 18:12:03 +02:00
|
|
|
|
|
|
|
class AssertionError extends Error {}
|
|
|
|
/**
|
|
|
|
* Throw an AssertionError if the first argument is not true
|
|
|
|
*/
|
|
|
|
function assert(condition, message) {
|
|
|
|
if (!condition) {
|
|
|
|
if (message) {
|
|
|
|
throw new AssertionError(`Assertion failed: ${message}`);
|
|
|
|
} else {
|
|
|
|
throw new AssertionError("Assertion failed");
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
const MATTERMOST_ID_REGEXP = /^[a-z0-9]{26}$/;
|
|
|
|
function assertIsMattermostId(string, name="") {
|
|
|
|
assert(MATTERMOST_ID_REGEXP.test(string), `${name} has the form of a Mattermost ID`);
|
|
|
|
}
|
|
|
|
function assertIsNullOrMattermostId(string, name="") {
|
|
|
|
assert(string === null || MATTERMOST_ID_REGEXP.test(string), `${name} is null or has the form of a Mattermost ID`);
|
|
|
|
}
|