@availity/api-axios
Version:
Wrappers for axios designed to work with the Availity portal
1,446 lines (1,413 loc) • 46.8 kB
JavaScript
"use strict";
var __create = Object.create;
var __defProp = Object.defineProperty;
var __defProps = Object.defineProperties;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropDescs = Object.getOwnPropertyDescriptors;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __getOwnPropSymbols = Object.getOwnPropertySymbols;
var __getProtoOf = Object.getPrototypeOf;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __propIsEnum = Object.prototype.propertyIsEnumerable;
var __reflectGet = Reflect.get;
var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
var __spreadValues = (a, b) => {
for (var prop in b || (b = {}))
if (__hasOwnProp.call(b, prop))
__defNormalProp(a, prop, b[prop]);
if (__getOwnPropSymbols)
for (var prop of __getOwnPropSymbols(b)) {
if (__propIsEnum.call(b, prop))
__defNormalProp(a, prop, b[prop]);
}
return a;
};
var __spreadProps = (a, b) => __defProps(a, __getOwnPropDescs(b));
var __objRest = (source, exclude) => {
var target = {};
for (var prop in source)
if (__hasOwnProp.call(source, prop) && exclude.indexOf(prop) < 0)
target[prop] = source[prop];
if (source != null && __getOwnPropSymbols)
for (var prop of __getOwnPropSymbols(source)) {
if (exclude.indexOf(prop) < 0 && __propIsEnum.call(source, prop))
target[prop] = source[prop];
}
return target;
};
var __export = (target, all) => {
for (var name in all)
__defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
if (from && typeof from === "object" || typeof from === "function") {
for (let key of __getOwnPropNames(from))
if (!__hasOwnProp.call(to, key) && key !== except)
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
}
return to;
};
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
// If the importer is in node compatibility mode or this is not an ESM
// file that has been converted to a CommonJS file using a Babel-
// compatible transform (i.e. "__esModule" has not been set), then set
// "default" to the CommonJS "module.exports" for node compatibility.
isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
mod
));
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
var __superGet = (cls, obj, key) => __reflectGet(__getProtoOf(cls), key, obj);
var __async = (__this, __arguments, generator) => {
return new Promise((resolve, reject) => {
var fulfilled = (value) => {
try {
step(generator.next(value));
} catch (e) {
reject(e);
}
};
var rejected = (value) => {
try {
step(generator.throw(value));
} catch (e) {
reject(e);
}
};
var step = (x) => x.done ? resolve(x.value) : Promise.resolve(x.value).then(fulfilled, rejected);
step((generator = generator.apply(__this, __arguments)).next());
});
};
// src/index.js
var index_exports = {};
__export(index_exports, {
AvCodesApi: () => AvCodesApi,
AvDisclaimersApi: () => AvDisclaimersApi,
AvFilesApi: () => AvFilesApi,
AvFilesDeliveryApi: () => AvFilesDeliveryApi,
AvLogMessagesApi: () => AvLogMessagesApi,
AvLogMessagesApiV2: () => AvLogMessagesApiV2,
AvLogMessagesApiV3: () => AvLogMessagesApiV3,
AvMicroserviceApi: () => AvMicroserviceApi,
AvNavigationApi: () => AvNavigationApi,
AvNotificationsApi: () => AvNotificationsApi,
AvOrganizationsApi: () => AvOrganizationsApi,
AvPdfApi: () => AvPdfApi,
AvPdfMicroserviceApi: () => AvPdfMicroserviceApi,
AvPermissionsApi: () => AvPermissionsApi,
AvProvidersApi: () => AvProvidersApi,
AvProxyApi: () => AvProxyApi,
AvRegionsApi: () => AvRegionsApi,
AvRouteConfigurationsApi: () => AvRouteConfigurationsApi,
AvSettingsApi: () => AvSettingsApi,
AvSlotMachineApi: () => AvSlotMachineApi,
AvSpacesApi: () => AvSpacesApi,
AvTelemetryApi: () => AvTelemetryApi,
AvUserApi: () => AvUserApi,
AvUserPermissionsApi: () => AvUserPermissionsApi,
AvWebQLApi: () => AvWebQLApi,
avCodesApi: () => avCodesApi,
avDisclaimersApi: () => avDisclaimersApi,
avFilesApi: () => avFilesApi,
avFilesDeliveryApi: () => avFilesDeliveryApi,
avLogMessagesApi: () => avLogMessagesApi,
avLogMessagesApiV2: () => avLogMessagesApiV2,
avLogMessagesApiV3: () => avLogMessagesApiV3,
avNavigationApi: () => avNavigationApi,
avNotificationsApi: () => avNotificationsApi,
avOrganizationsApi: () => avOrganizationsApi,
avPdfApi: () => avPdfApi,
avPdfMicroserviceApi: () => avPdfMicroserviceApi,
avPermissionsApi: () => avPermissionsApi,
avProvidersApi: () => avProvidersApi,
avRegionsApi: () => avRegionsApi,
avRouteConfigurationsApi: () => avRouteConfigurationsApi,
avSettingsApi: () => avSettingsApi,
avSlotMachineApi: () => avSlotMachineApi,
avSpacesApi: () => avSpacesApi,
avTelemetryApi: () => avTelemetryApi,
avUserApi: () => avUserApi,
avUserPermissionsApi: () => avUserPermissionsApi,
avWebQLApi: () => avWebQLApi,
default: () => index_default
});
module.exports = __toCommonJS(index_exports);
// src/api.js
var import_qs = __toESM(require("qs"));
var import_resolve_url = __toESM(require("@availity/resolve-url"));
var import_axios = __toESM(require("axios"));
var import_merge = __toESM(require("lodash/merge"));
// src/options.js
var API_OPTIONS = {
API: {
// default base segment for Availity API endpoints
path: "/api",
// full url to api resource
url: null,
// name of resource
name: null,
// defaults version for api
version: "/v1",
// cache all request by default
cache: true,
// flag used to enable behaviors around the Availity Rest API
api: true,
polling: true,
// 1s, 2s, 5s, 10s
pollingIntervals: [1e3, 2e3, 5e3, 1e4],
// in ms
pollingMethod: "GET",
// default headers
headers: {
// Turn off content encoding for angular apis
"X-Response-Encoding-Context": "NONE"
},
sessionBust: true,
// send credentials on CORS requests
withCredentials: true
},
MS: {
// default base segment for Availity API endpoints
path: "/ms/api/availity/internal",
// full url to api resource
url: null,
// name of resource
name: null,
// defaults version for api
version: null,
// cache all request by default
cache: false,
// flag used to enable behaviors around the Availity Rest API
api: true,
polling: false,
// 1s, 2s, 5s, 10s
pollingIntervals: [1e3, 2e3, 5e3, 1e4],
// in ms
pollingMethod: "POST",
// default headers
headers: {
// Turn off content encoding for angular apis
"X-Response-Encoding-Context": "NONE"
},
sessionBust: false,
// send credentials on CORS requests
withCredentials: true
}
};
var options_default = API_OPTIONS;
// src/api.js
var AvApi = class {
constructor(config) {
if (!config) {
throw new Error("[config] must be defined");
}
const _a = config, { http } = _a, options = __objRest(_a, ["http"]);
this.http = http || import_axios.default;
this.defaultConfig = (0, import_merge.default)({}, options_default.API, options);
}
// Get the merged config
config(config = {}) {
return (0, import_merge.default)({}, this.defaultConfig, config);
}
addParams(params = {}, config = {}, newObj = true) {
const output = newObj ? __spreadValues({ params: {} }, config) : config;
if (!newObj) {
output.params = output.params || {};
}
output.params = __spreadValues(__spreadValues({}, output.params), params);
return output;
}
// Set the cache parameters
cacheParams(config) {
const params = {};
if (config.cacheBust) {
params.cacheBust = this.getCacheBustVal(config.cacheBust, () => Date.now());
}
if (config.pageBust) {
params.pageBust = this.getCacheBustVal(config.pageBust, () => this.getPageBust());
}
if (config.sessionBust) {
params.sessionBust = this.getCacheBustVal(config.sessionBust, () => this.getSessionBust() || this.getPageBust());
}
return this.addParams(params, config, false);
}
getSessionBust() {
return window.localStorage.getItem("avCacheBust");
}
// Get the cache value with default function
getCacheBustVal(cacheBust, defaultFn) {
if (!cacheBust) {
return void 0;
}
if (typeof cacheBust === "boolean" && defaultFn) {
return defaultFn();
}
if (typeof cacheBust === "function") {
return cacheBust();
}
return cacheBust;
}
// Get pagebust value, make sure it is instantiated first
getPageBust() {
if (this.pageBustValue === void 0) {
this.setPageBust();
}
return this.pageBustValue;
}
// Set the page bust value to given value or timestamp
setPageBust(value) {
this.pageBustValue = value === void 0 ? Date.now() : value;
}
// Get final url from config
getUrl(config, id = "") {
if (!config.api) {
return config.url;
}
const { path, version, name, url } = config;
let parts = [];
parts = name ? ["", path, version, name, id] : [url, id];
return parts.join("/").replaceAll(/\/+/g, "/").replace(/\/$/, "");
}
getRequestUrl() {
return this.getUrl(this.config());
}
// Return location if should poll otherwise false
getLocation(response) {
const { config, headers = {} } = response;
const { getHeader, base } = config;
const { location, Location } = headers;
const locationUrl = getHeader ? getHeader(response, "Location") : location || Location;
return (0, import_resolve_url.default)({ relative: locationUrl, base });
}
// Condition for calls that should continue polling
shouldPoll(response) {
if (!(response == null ? void 0 : response.config)) return false;
const { attempt = 0, polling, pollingIntervals = [] } = response.config;
return polling && response.status === 202 && attempt < pollingIntervals.length;
}
getQueryResultKey(data) {
return Object.keys(data).find((key) => Array.isArray(data[key]));
}
getResult(data) {
return data[this.getQueryResultKey(data)];
}
// Make request with axios
request(config, afterResponse) {
return __async(this, null, function* () {
if (config.polling) {
config.attempt = config.attempt || 0;
config.attempt += 1;
}
const response = yield this.http(config);
return this.onResponse(response, afterResponse);
});
}
// Handle response with possible polling
onResponse(response, afterResponse) {
return __async(this, null, function* () {
if (this.shouldPoll(response)) {
const newConfig = this.config(response.config);
const pollingUrl = this.getLocation(response);
if (pollingUrl) {
newConfig.method = newConfig.pollingMethod;
newConfig.url = pollingUrl;
newConfig.cache = false;
yield new Promise((resolve) => {
setTimeout(resolve, newConfig.pollingIntervals[newConfig.attempt] || 1e3);
});
return this.request(newConfig, afterResponse);
}
}
return afterResponse ? afterResponse(response) : response;
});
}
// Send request with browser's navigator.sendBeacon
sendBeacon(data, config) {
return __async(this, null, function* () {
if (!data) {
throw new Error("called method without [data]");
}
config = this.config(config);
config.method = "POST";
config.url = this.getUrl(config);
config.data = data;
const beforeFunc = this.beforeCreate || this.beforePost;
if (beforeFunc) {
config.data = beforeFunc(config.data);
}
if (navigator.sendBeacon) {
const result = navigator.sendBeacon(
config.url,
new Blob([config.data], {
type: "application/x-www-form-urlencoded"
})
);
if (result) return Promise.resolve();
}
return this.request(config, this.afterCreate || this.afterPost);
});
}
// create
create(data, config) {
return __async(this, null, function* () {
if (!data) {
throw new Error("called method without [data]");
}
config = this.config(config);
config.method = "POST";
config.url = this.getUrl(config);
config.data = data;
const beforeFunc = this.beforeCreate || this.beforePost;
if (beforeFunc) {
config.data = beforeFunc(config.data);
}
return this.request(config, this.afterCreate || this.afterPost);
});
}
post(data, config) {
return __async(this, null, function* () {
return this.create(data, config);
});
}
// post request with method-override to get
postGet(data, config) {
return __async(this, null, function* () {
if (!data) {
throw new Error("called method without [data]");
}
config = this.config(config);
config.method = "POST";
config.headers = config.headers || {};
config.headers["X-HTTP-Method-Override"] = "GET";
config.headers["Content-Type"] = config.headers["Content-Type"] || "application/x-www-form-urlencoded";
config.url = this.getUrl(config);
config.data = data;
if (this.beforePostGet) {
config.data = this.beforePostGet(config.data);
}
if (typeof config.data !== "string" && config.headers["Content-Type"] === "application/x-www-form-urlencoded") {
config.data = import_qs.default.stringify(config.data, {
encode: false,
arrayFormat: "repeat",
indices: false,
allowDots: true
});
}
return this.request(config, this.afterPostGet);
});
}
// read
get(id, config) {
return __async(this, null, function* () {
if (!id) {
throw new Error("called method without [id]");
}
config = this.config(config);
config.method = "GET";
config.url = this.getUrl(config, id);
config = this.cacheParams(config);
return this.request(config, this.afterGet);
});
}
// get request with params
query(config) {
return __async(this, null, function* () {
config = this.config(config);
config.method = "GET";
config.url = this.getUrl(config);
config = this.cacheParams(config);
return this.request(config, this.afterQuery);
});
}
getPage() {
return __async(this, arguments, function* (page = 1, config = {}, limit) {
var _a;
limit = limit || ((_a = config.params) == null ? void 0 : _a.limit) || 50;
const offset = (page - 1) * limit;
return this.query(this.addParams({ offset, limit }, config, false));
});
}
all(config) {
return __async(this, null, function* () {
const response = yield this.query(config);
const key = this.getQueryResultKey(response.data);
const result = response.data[key] || [];
const limit = response.data.limit || result.length <= response.data.totalCount ? Math.min(result.length, response.data.totalCount) || 1 : 1;
const totalPages = Math.ceil(response.data.totalCount / limit);
if (totalPages > 1) {
const otherPages = [];
for (let i = 0; i < totalPages - 1; i += 1) {
otherPages[i] = i + 2;
}
const pages = yield Promise.all(
otherPages.map((page) => __async(this, null, function* () {
const resp = yield this.getPage(page, config, limit);
return resp.data[key] || [];
}))
);
return [...result, ...pages].flat();
}
return result;
});
}
// update
update(id, data, config) {
return __async(this, null, function* () {
if (typeof id !== "string" && typeof id !== "number") {
config = data;
data = id;
id = "";
}
config = this.config(config);
config.method = "PUT";
config.url = this.getUrl(config, id);
config.data = data;
const beforeFunc = this.beforeUpdate || this.beforePut;
if (beforeFunc) {
config.data = beforeFunc(config.data);
}
return this.request(config, this.afterUpdate || this.afterPut);
});
}
put(...args) {
return __async(this, null, function* () {
return this.update(...args);
});
}
patch(id, data, config) {
return __async(this, null, function* () {
if (typeof id !== "string" && typeof id !== "number") {
config = data;
data = id;
id = "";
}
config = this.config(config);
config.method = "PATCH";
config.url = this.getUrl(config, id);
config.data = data;
const beforeFunc = this.beforePatch;
if (beforeFunc) {
config.data = beforeFunc(config.data);
}
return this.request(config, this.afterPatch);
});
}
// delete
remove(id, config) {
return __async(this, null, function* () {
if (typeof id !== "string" && typeof id !== "number") {
config = id;
id = "";
}
config = this.config(config);
config.method = "DELETE";
config.url = this.getUrl(config, id);
const beforeFunc = this.beforeRemove || this.beforeDelete;
if (beforeFunc) {
config = beforeFunc(config);
}
return this.request(config, this.afterRemove || this.afterDelete);
});
}
delete(...args) {
return __async(this, null, function* () {
return this.remove(...args);
});
}
};
// src/ms.js
var import_merge2 = __toESM(require("lodash/merge"));
var AvMicroserviceApi = class extends AvApi {
constructor(config) {
super(config);
const _a = config, { http } = _a, options = __objRest(_a, ["http"]);
this.defaultConfig = (0, import_merge2.default)({}, options_default.MS, options);
}
getUrl(config, id = "") {
const { path, version, name, id: configId, url } = this.config(config);
const parts = url ? [url, path, version || "", name] : [path, version || "", name];
if (id || configId) {
parts.push(id || configId);
}
const newUrl = parts.join("/");
if (url) {
return newUrl.replaceAll(/([^:]\/)\/+/g, "$1");
}
return newUrl.replaceAll(/\/+/g, "/").replace(/^\/+/, "/").replace(/\/+$/, "");
}
};
// src/proxy.js
var AvProxyApi = class extends AvApi {
constructor(config) {
if (!(config == null ? void 0 : config.tenant)) {
throw new Error("[config.tenant] must be defined");
}
super(__spreadValues({
path: `api/v1/proxy/${config.tenant}`,
version: ""
}, config));
}
};
// src/resources/codes.js
var AvCodesApi = class extends AvApi {
constructor(config) {
super(__spreadValues({
name: "codes"
}, config));
}
};
var avCodesApi = new AvCodesApi();
// src/resources/disclaimers.js
var AvDisclaimersApi = class extends AvApi {
constructor(config) {
super(__spreadValues({
path: "/api/sdk/platform",
name: "/disclaimers"
}, config));
}
getDisclaimers(id, config) {
return __async(this, null, function* () {
const queryConfig = this.addParams({ id }, config);
return this.query(queryConfig);
});
}
};
var avDisclaimersApi = new AvDisclaimersApi();
// src/flatten-object.js
var parseValue = (value) => value === void 0 || value === null ? value : value.toString();
var flattenObject = (ob) => Object.keys(ob).reduce((toReturn, k) => {
if (Object.prototype.toString.call(ob[k]) === "[object Date]") {
toReturn[k] = ob[k].toJSON();
} else if (ob[k] && typeof ob[k] === "object") {
const flatObject = flattenObject(ob[k]);
const isArray = Array.isArray(ob[k]);
for (const k2 of Object.keys(flatObject)) {
toReturn[`${k}${isArray ? k2.replace(/^(\d+)(\..*)?/, "[$1]$2") : `.${k2}`}`] = parseValue(flatObject[k2]);
}
} else {
toReturn[k] = parseValue(ob[k]);
}
return toReturn;
}, {});
var flatten_object_default = flattenObject;
// src/resources/dma.js
var AvLogMessagesApiV2 = class extends AvMicroserviceApi {
constructor(config) {
super(__spreadValues({
name: "spc/analytics/log"
}, config));
}
send(level, entries) {
delete entries.level;
const payload = { level, entries };
const flattened = flatten_object_default(payload);
flattened.X_Client_ID = this.clientId;
flattened.X_XSRF_TOKEN = document.cookie.replace(/(?:(?:^|.*;\s*)XSRF-TOKEN\s*=\s*([^;]*).*$)|^.*$/, "$1");
const fields = Object.keys(flattened).map((key) => {
const name = key.replaceAll(/\[\d+]/g, "[]");
const value = flattened[key];
return `${name}=${encodeURIComponent(value)}`;
}).join("&");
return fields;
}
debug(entries) {
return __async(this, null, function* () {
return this.sendBeacon(this.send("debug", entries));
});
}
info(entries) {
return __async(this, null, function* () {
return this.sendBeacon(this.send("info", entries));
});
}
warn(entries) {
return __async(this, null, function* () {
return this.sendBeacon(this.send("warn", entries));
});
}
error(entries) {
return __async(this, null, function* () {
return this.sendBeacon(this.send("error", entries));
});
}
};
var avLogMessagesApiV2 = new AvLogMessagesApiV2();
// src/resources/dma-cloud.js
var AvLogMessagesApiV3 = class extends AvMicroserviceApi {
constructor(config) {
super(__spreadValues({
name: "appl/analytics/log",
path: "/cloud/web/"
}, config));
}
send(level, entries) {
delete entries.level;
const payload = { level, entries };
const flattened = flatten_object_default(payload);
flattened.X_Client_ID = this.clientId;
flattened.X_XSRF_TOKEN = document.cookie.replace(/(?:(?:^|.*;\s*)XSRF-TOKEN\s*=\s*([^;]*).*$)|^.*$/, "$1");
const fields = Object.keys(flattened).map((key) => {
const name = key.replaceAll(/\[\d+]/g, "[]");
const value = flattened[key];
return `${name}=${encodeURIComponent(value)}`;
}).join("&");
return fields;
}
debug(entries) {
return __async(this, null, function* () {
return this.sendBeacon(this.send("debug", entries));
});
}
info(entries) {
return __async(this, null, function* () {
return this.sendBeacon(this.send("info", entries));
});
}
warn(entries) {
return __async(this, null, function* () {
return this.sendBeacon(this.send("warn", entries));
});
}
error(entries) {
return __async(this, null, function* () {
return this.sendBeacon(this.send("error", entries));
});
}
};
var avLogMessagesApiV3 = new AvLogMessagesApiV3();
// src/resources/files.js
var import_upload_core = __toESM(require("@availity/upload-core"));
var AvFilesApi = class extends AvMicroserviceApi {
constructor(config) {
super(__spreadValues({
name: "core/vault/upload/v1",
headers: {
"Content-Type": void 0
}
}, config));
}
hashData(data) {
const str = JSON.stringify(data);
let hash = 0;
for (let i = 0; i < str.length; i++) {
const char = str.codePointAt(i);
hash = (hash << 5) - hash + char;
hash &= hash;
}
return Math.abs(hash).toString(36);
}
uploadFile(data, config) {
return __async(this, null, function* () {
if (!config.customerId || !config.clientId) {
throw new Error("[config.customerId] and [config.clientId] must be defined");
}
const file = new File([JSON.stringify(data)], config.fileName || `${this.hashData(data)}.json`, {
type: "application/json"
});
const upload = new import_upload_core.default(file, {
bucketId: config.id,
customerId: config.customerId,
clientId: config.clientId,
endpoint: "/cloud/web/appl/vault/upload/v1/resumable"
});
yield upload.generateId();
return new Promise((resolve, reject) => {
upload.onSuccess.push(() => resolve(upload));
upload.onError.push((error) => reject(error));
upload.start();
});
});
}
};
var avFilesApi = new AvFilesApi();
// src/resources/filesDelivery.js
var AvFilesDeliveryApi = class extends AvMicroserviceApi {
constructor(config) {
super(__spreadValues({
name: "platform/file-upload-delivery/v1/batch/deliveries",
headers: {
"Content-Type": "application/json"
},
polling: true,
pollingMethod: "GET"
}, config));
}
uploadFilesDelivery(data, config) {
return __async(this, null, function* () {
if (!config.customerId || !config.clientId) {
throw new Error("[config.customerId] and [config.clientId] must be defined");
}
config = this.config(config);
config.headers["X-Availity-Customer-ID"] = config.customerId;
config.headers["X-Client-ID"] = config.clientId;
return this.create(data || {}, config);
});
}
getLocation(response) {
const baseUrl = super.getLocation(response);
const { id } = response.data;
return !id || baseUrl.endsWith(id) ? `${baseUrl}` : `${baseUrl}/${id}`;
}
};
var avFilesDeliveryApi = new AvFilesDeliveryApi();
// src/resources/logs.js
var AvLogMessagesApi = class extends AvApi {
constructor(config) {
super(__spreadValues({
name: "log-messages"
}, config));
}
send(level, entries) {
delete entries.level;
const payload = { level, entries };
const flattened = flatten_object_default(payload);
flattened.X_Client_ID = this.clientId;
flattened.X_XSRF_TOKEN = document.cookie.replace(/(?:(?:^|.*;\s*)XSRF-TOKEN\s*=\s*([^;]*).*$)|^.*$/, "$1");
const fields = Object.keys(flattened).map((key) => {
const name = key.replaceAll(/\[\d+]/g, "[]");
const value = flattened[key];
return `${name}=${encodeURIComponent(value)}`;
}).join("&");
return fields;
}
debug(entries) {
return __async(this, null, function* () {
return this.sendBeacon(this.send("debug", entries));
});
}
info(entries) {
return __async(this, null, function* () {
return this.sendBeacon(this.send("info", entries));
});
}
warn(entries) {
return __async(this, null, function* () {
return this.sendBeacon(this.send("warn", entries));
});
}
error(entries) {
return __async(this, null, function* () {
return this.sendBeacon(this.send("error", entries));
});
}
};
var avLogMessagesApi = new AvLogMessagesApi();
// src/resources/navigation.js
var AvNavigationApi = class extends AvApi {
constructor(config) {
super(__spreadValues({
path: "api/sdk/platform",
name: "navigation/spaces"
}, config));
}
};
var avNavigationApi = new AvNavigationApi();
// src/resources/notifications.js
var AvNotificationsApi = class extends AvApi {
constructor(config) {
super(__spreadValues({
path: "api",
name: "notifications"
}, config));
}
deleteByTopic(topic, config) {
return __async(this, null, function* () {
const removeConfig = this.addParams({ topicId: topic }, config);
return this.remove(removeConfig);
});
}
};
var avNotificationsApi = new AvNotificationsApi();
// src/resources/organizations.js
var import_qs3 = __toESM(require("qs"));
// src/resources/user.js
var AvUserApi = class extends AvApi {
constructor(config) {
super(__spreadValues({
path: "api/sdk/platform",
name: "users"
}, config));
}
me(config) {
return __async(this, null, function* () {
const response = yield this.get("me", config);
return response.data;
});
}
};
var avUserApi = new AvUserApi();
// src/resources/userPermissions.js
var import_qs2 = __toESM(require("qs"));
var AvUserPermissionsApi = class extends AvApi {
constructor(config) {
super(__spreadValues({
path: "api/internal",
name: "axi-user-permissions",
paramsSerializer: (params) => import_qs2.default.stringify(params, { arrayFormat: "repeat" })
}, config));
}
afterQuery(response) {
var _a;
return ((_a = response == null ? void 0 : response.data) == null ? void 0 : _a.axiUserPermissions) || [];
}
getPermissions(permissionId, region) {
return __async(this, null, function* () {
return this.query({
params: { permissionId, region }
});
});
}
};
var avUserPermissionsApi = new AvUserPermissionsApi();
// src/resources/organizations.js
var AvOrganizationsApi = class _AvOrganizationsApi extends AvApi {
constructor(config) {
super(__spreadValues({
path: "api/sdk/platform",
name: "organizations"
}, config));
// Instance variables to help with caching for filtered organizations
__publicField(this, "previousPermissionIds", []);
__publicField(this, "previousRegionId", "");
__publicField(this, "userPermissions", []);
}
queryOrganizations(user, config) {
return __async(this, null, function* () {
const queryConfig = this.addParams({ userId: user.id }, config);
return this.query(queryConfig);
});
}
getOrganizations(config) {
return __async(this, null, function* () {
var _a;
if ((_a = config == null ? void 0 : config.params) == null ? void 0 : _a.userId) {
return this.query(config);
}
const user = yield avUserApi.me();
return this.queryOrganizations(user, config);
});
}
postGet(data, config, additionalPostGetArgs) {
return __async(this, null, function* () {
if (additionalPostGetArgs) {
this.region = void 0;
const { permissionIds } = additionalPostGetArgs;
if (typeof data === "string") {
const dataTemp = import_qs3.default.parse(data);
const { region } = dataTemp;
if (region) {
this.region = region;
delete dataTemp.region;
}
if (permissionIds) {
dataTemp.permissionId = permissionIds;
}
data = import_qs3.default.stringify(dataTemp, { arrayFormat: "repeat" });
} else if (typeof data === "object") {
const { region } = data;
if (region) {
this.region = region;
delete data.region;
}
if (permissionIds) {
data.permissionId = permissionIds;
}
}
const { data: organizationsData } = yield __superGet(_AvOrganizationsApi.prototype, this, "postGet").call(this, data, config);
const { organizations, limit, offset, totalCount } = organizationsData;
const authorizedOrgs = yield this.getFilteredOrganizations(additionalPostGetArgs, data);
const authorizedFilteredOrgs = organizations.filter(
(org) => authorizedOrgs.some((authOrg) => authOrg.id === org.id)
);
return {
data: {
authorizedFilteredOrgs,
totalCount,
limit,
offset
}
};
}
return __superGet(_AvOrganizationsApi.prototype, this, "postGet").call(this, data, config);
});
}
getFilteredOrganizations(additionalPostGetArgs, data) {
return __async(this, null, function* () {
const { resourceIds = [], permissionIds } = additionalPostGetArgs;
if (typeof data === "string") {
data = import_qs3.default.parse(data);
}
const { permissionId } = data;
let permissionIdsToUse = permissionIds || permissionId;
permissionIdsToUse = this.sanitizeIds(permissionIdsToUse);
const resourceIdsToUse = this.sanitizeIds(resourceIds);
const resourceIdsArray = Array.isArray(resourceIdsToUse) ? resourceIdsToUse : [resourceIdsToUse];
const permissionIdsOR = Array.isArray(permissionIdsToUse) ? permissionIdsToUse : [permissionIdsToUse];
if (this.region !== this.previousRegionId || !this.arePermissionsEqual(permissionIdsOR)) {
const {
data: { axiUserPermissions: userPermissions }
} = yield avUserPermissionsApi.postGet({
permissionId: permissionIdsOR,
region: this.region
});
if (userPermissions) {
this.userPermissions = userPermissions.reduce((accum, cur) => {
accum[cur.id] = cur;
return accum;
}, {});
this.previousPermissionIds = permissionIdsOR;
this.previousRegionId = this.region;
} else {
throw new Error("avUserPermissions call failed");
}
}
const authorizedOrgs = permissionIdsOR.reduce((accum, permissionIdOR) => {
if (Array.isArray(permissionIdOR)) {
const matchedOrgs = permissionIdOR.reduce((matchedANDOrgsByPerm, permissionIdAND, index) => {
if (this.userPermissions[permissionIdAND]) {
for (const org of this.userPermissions[permissionIdAND].organizations) {
if (index === 0) {
matchedANDOrgsByPerm[org.id] = org;
} else if (matchedANDOrgsByPerm[org.id]) {
matchedANDOrgsByPerm[org.id].resources = [...matchedANDOrgsByPerm[org.id].resources, ...org.resources];
}
}
}
matchedANDOrgsByPerm = Object.keys(matchedANDOrgsByPerm).filter((orgId) => {
if (this.userPermissions[permissionIdAND]) {
return this.userPermissions[permissionIdAND].organizations.some((org) => org.id === orgId);
}
return false;
}).reduce((obj, orgId) => {
obj[orgId] = matchedANDOrgsByPerm[orgId];
return obj;
}, {});
return matchedANDOrgsByPerm;
}, {});
for (const orgId of Object.keys(matchedOrgs)) {
if (!accum[orgId]) {
accum[orgId] = matchedOrgs[orgId];
accum[orgId].match = false;
} else {
accum[orgId].resources = [...accum[orgId].resources, ...matchedOrgs[orgId].resources];
}
}
} else if (this.userPermissions[permissionIdOR]) {
for (const org of this.userPermissions[permissionIdOR].organizations) {
if (!accum[org.id]) {
accum[org.id] = org;
accum[org.id].match = false;
} else {
accum[org.id].resources = [...accum[org.id].resources, ...org.resources];
}
}
}
return accum;
}, {});
if (resourceIdsArray.length === 0) {
for (const orgId of Object.keys(authorizedOrgs)) {
authorizedOrgs[orgId].match = true;
}
} else {
resourceIdsArray.forEach((resourceIdOR) => {
if (Array.isArray(resourceIdOR)) {
for (const orgId of Object.keys(authorizedOrgs)) {
if (authorizedOrgs[orgId]) {
const isMatch = resourceIdOR.every(
(resId) => authorizedOrgs[orgId].resources.some((res) => res.id === resId)
);
if (isMatch) {
authorizedOrgs[orgId].match = true;
}
}
}
} else {
for (const orgId of Object.keys(authorizedOrgs)) {
const isMatch = authorizedOrgs[orgId].resources.some((res) => res.id === resourceIdOR);
if (isMatch || !resourceIdOR) {
authorizedOrgs[orgId].match = true;
}
}
}
});
}
return Object.keys(authorizedOrgs).reduce((accum, orgId) => {
if (authorizedOrgs[orgId].match) {
accum.push(authorizedOrgs[orgId]);
}
return accum;
}, []);
});
}
arePermissionsEqual(permissionId) {
const permissionArray = [];
if (typeof permissionId === "string" || typeof permissionId === "number") {
permissionArray.push(permissionId);
} else if (Array.isArray(permissionId)) {
for (const permissionOR of permissionId) {
if (Array.isArray(permissionOR)) {
for (const permissionAND of permissionOR) {
permissionArray.push(permissionAND);
}
} else {
permissionArray.push(permissionOR);
}
}
}
const prevPermissionArray = [];
if (typeof this.previousPermissionIds === "string" || typeof this.previousPermissionIds === "number") {
prevPermissionArray.push(this.previousPermissionIds);
} else if (Array.isArray(this.previousPermissionIds)) {
for (const permissionOR of this.previousPermissionIds) {
if (Array.isArray(permissionOR)) {
for (const permissionAND of permissionOR) {
prevPermissionArray.push(permissionAND);
}
} else {
prevPermissionArray.push(permissionOR);
}
}
}
const idSet = new Set(permissionArray);
const idSetPrev = new Set(prevPermissionArray);
const idSetCombined = /* @__PURE__ */ new Set([...permissionArray, ...prevPermissionArray]);
return idSet.size === idSetPrev.size && idSet.size === idSetCombined.size;
}
sanitizeIds(unsanitized) {
if (typeof unsanitized === "string") {
return unsanitized;
}
if (typeof unsanitized === "number") {
return `${unsanitized}`;
}
if (Array.isArray(unsanitized)) {
return unsanitized.map((dirty) => this.sanitizeIds(dirty));
}
throw new TypeError("permission/resourcesId(s) must be either an array of ids, a string, or a number");
}
};
var avOrganizationsApi = new AvOrganizationsApi();
// src/resources/pdf.js
var AvPdfApi = class extends AvApi {
constructor(config) {
super(__spreadValues({
path: "api/utils",
name: "pdfs"
}, config));
}
onPdf(response) {
window.location = response.data.links.pdf.href;
}
getPdf(data, config) {
return __async(this, null, function* () {
if (!data.applicationId || !data.fileName || !data.html) {
throw new Error("[applicationId], [fileName] and [html] must be defined");
}
const response = yield this.post(data, config);
this.onPdf(response);
return response;
});
}
};
var avPdfApi = new AvPdfApi();
// src/resources/pdfv2.js
var AvPdfMicroserviceApi = class extends AvMicroserviceApi {
constructor(config) {
super(__spreadProps(__spreadValues({}, config), {
name: "spc/pdf/"
}));
}
getUrl(config, id = "") {
const { path, version, name, id: configId } = this.config(config);
let parts = [path, version || "", name];
if (id || configId) {
parts = [path, version || "", name, id || configId];
}
return parts.join("/").replaceAll(/\/+/g, "/");
}
};
var avPdfMicroserviceApi = new AvPdfMicroserviceApi();
// src/resources/permissions.js
var AvPermissionsApi = class extends AvApi {
constructor(config) {
super(__spreadValues({
path: "api/sdk/platform",
name: "permissions"
}, config));
}
getPermissions(id, region) {
return __async(this, null, function* () {
return this.query({
params: { id, region }
});
});
}
};
var avPermissionsApi = new AvPermissionsApi();
// src/resources/providers.js
var AvProvidersApi = class extends AvApi {
constructor(config) {
super(__spreadValues({
path: "api/internal",
name: "providers"
}, config));
}
getProviders(customerId, config) {
return __async(this, null, function* () {
const queryConfig = this.addParams({ customerId }, config);
return this.query(queryConfig);
});
}
normalize(providers) {
const cloned = [...providers];
for (const provider of cloned) {
provider.name = provider.businessName || `${provider.lastName}, ${provider.firstName}`;
}
return cloned;
}
};
var avProvidersApi = new AvProvidersApi();
// src/resources/regions.js
var AvRegionsApi = class extends AvApi {
constructor(config) {
super(__spreadValues({
path: "api/sdk/platform",
name: "regions",
sessionBust: false,
pageBust: true
}, config));
__publicField(this, "afterUpdate", (response) => {
this.setPageBust();
return response;
});
}
getQueryResultKey() {
return "regions";
}
getRegions(config) {
return __async(this, null, function* () {
var _a;
if ((_a = config == null ? void 0 : config.params) == null ? void 0 : _a.userId) {
return this.query(config);
}
const user = yield avUserApi.me();
const queryConfig = this.addParams({ userId: user.id }, config);
return this.query(queryConfig);
});
}
getCurrentRegion() {
return __async(this, null, function* () {
return this.query({
params: {
currentlySelected: true
}
});
});
}
};
var avRegionsApi = new AvRegionsApi();
// src/resources/routeConfigurations.js
var AvRouteConfigurationsApi = class extends AvMicroserviceApi {
constructor(config) {
super(__spreadValues({
name: "epdm/configuration-service/epdm/v1/route-configuration"
}, config));
}
getConfiguration(transactionTypeCode, submissionModeCode, payerId) {
return __async(this, null, function* () {
return this.query({
params: { transactionTypeCode, submissionModeCode, payerId }
});
});
}
};
var avRouteConfigurationsApi = new AvRouteConfigurationsApi();
// src/resources/settings.js
var AvSettingsApi = class extends AvApi {
constructor(config) {
super(__spreadValues({
path: "api/utils",
name: "settings",
sessionBust: false,
pageBust: true
}, config));
}
getApplication(applicationId, config) {
return __async(this, null, function* () {
var _a;
if (!applicationId) {
throw new Error("[applicationId] must be defined");
}
if ((_a = config == null ? void 0 : config.params) == null ? void 0 : _a.userId) {
const queryConfig2 = this.addParams({ applicationId }, config);
return this.query(queryConfig2);
}
const user = yield avUserApi.me();
const queryConfig = this.addParams({ applicationId, userId: user.id }, config);
return this.query(queryConfig);
});
}
setApplication(applicationId, data, config) {
return __async(this, null, function* () {
var _a, _b;
if (typeof applicationId !== "string" && typeof applicationId !== "number") {
config = data;
data = applicationId;
applicationId = "";
}
if (!applicationId && !((_a = data == null ? void 0 : data.scope) == null ? void 0 : _a.applicationId)) {
throw new Error("[applicationId] must be defined");
}
if ((_b = data == null ? void 0 : data.scope) == null ? void 0 : _b.userId) {
data.scope.applicationId = applicationId;
return this.update(data, config);
}
const user = yield avUserApi.me();
data = data || {};
data.scope = data.scope || {};
data.scope.applicationId = applicationId;
data.scope.userId = user.id;
return this.update(data, config);
});
}
};
var avSettingsApi = new AvSettingsApi();
// src/resources/slotmachine.js
var AvSlotMachineApi = class extends AvMicroserviceApi {
constructor(config) {
super(__spreadValues({
name: "spc/slotmachine/graphql"
}, config));
}
query(data, variables) {
return this.create({ query: data, variables });
}
};
var avSlotMachineApi = new AvSlotMachineApi();
// src/resources/spaces.js
var AvSpacesApi = class extends AvApi {
constructor(config) {
super(__spreadValues({
path: "api/sdk/platform",
name: "spaces"
}, config));
}
parseSpaceId(query) {
const pairs = query.substr(1).split("&");
let spaceId = "";
if (Array.isArray(pairs)) {
for (const item of pairs) {
const pair = item.split("=");
const key = pair[0];
if (key === "spaceId") {
spaceId = pair[1] && decodeURIComponent(pair[1]);
}
}
}
return spaceId;
}
getSpaceName(spaceId) {
return __async(this, null, function* () {
if (!spaceId) {
throw new Error("[spaceId] must be defined");
}
const response = yield this.get(spaceId);
return response.data.name;
});
}
};
var avSpacesApi = new AvSpacesApi();
// src/resources/telemetry.js
var import_set = __toESM(require("lodash/set"));
var AvTelemetryApi = class extends AvMicroserviceApi {
constructor(config) {
super(__spreadValues({
name: "spc/analytics/telemetry"
}, config));
}
send(level, data) {
(0, import_set.default)(data, "telemetryBody.level", level);
const flattened = flatten_object_default(data);
const fields = Object.keys(flattened).map((key) => {
const name = key.replaceAll(/\[\d+]/g, "[]");
const value = flattened[key];
return `${name}=${encodeURIComponent(value)}`;
}).join("&");
return fields;
}
debug(data) {
return this.sendBeacon(this.send("debug", data));
}
info(data) {
return this.sendBeacon(this.send("info", data));
}
warn(data) {
return this.sendBeacon(this.send("warn", data));
}
error(data) {
return this.sendBeacon(this.send("error", data));
}
};
var avTelemetryApi = new AvTelemetryApi();
// src/resources/webQL.js
var AvWebQLApi = class extends AvMicroserviceApi {
constructor(config) {
super(__spreadValues({
name: "spc/web/graphql"
}, config));
}
};
var avWebQLApi = new AvWebQLApi();
// src/index.js
var index_default = AvApi;
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
AvCodesApi,
AvDisclaimersApi,
AvFilesApi,
AvFilesDeliveryApi,
AvLogMessagesApi,
AvLogMessagesApiV2,
AvLogMessagesApiV3,
AvMicroserviceApi,
AvNavigationApi,
AvNotificationsApi,
AvOrganizationsApi,
AvPdfApi,
AvPdfMicroserviceApi,
AvPermissionsApi,
AvProvidersApi,
AvProxyApi,
AvRegionsApi,
AvRouteConfigurationsApi,
AvSettingsApi,
AvSlotMachineApi,
AvSpacesApi,
AvTelemetryApi,
AvUserApi,
AvUserPermissionsApi,
AvWebQLApi,
avCodesApi,
avDisclaimersApi,
avFilesApi,
avFilesDeliveryApi,
avLogMessagesApi,
avLogMessagesApiV2,
avLogMessagesApiV3,
avNavigationApi,
avNotificationsApi,
avOrganizationsApi,
avPdfApi,
avPdfMicroserviceApi,
avPermissionsApi,
avProvidersApi,
avRegionsApi,
avRouteConfigurationsApi,
avSettingsApi,
avSlotMachineApi,
avSpacesApi,
avTelemetryApi,
avUserApi,
avUserPermissionsApi,
avWebQLApi
});