@mikezimm/fps-core-v7
Version:
Library of reusable core interfaces, types and constants migrated from fps-library-v2
383 lines • 17.8 kB
JavaScript
import { roundRatio, } from '../../../logic/Math/rounding';
import { getSizeLabel } from '../../../logic/Math/labels';
import { LoadPerformanceOps } from '../../../components/molecules/Performance/IPerformance';
import { getCurrentPageLink, getUrlParamsWithBloatCheck, getWebUrlFromLink } from '../../../logic/Links/UrlFunctions';
import { getSiteCollectionUrlFromLink, } from '../../../logic/Strings/urlServices';
import { upperFirstLetter, } from '../../../logic/Strings/stringCase';
import { getHelpfullError } from '../../../logic/Errors/friendly';
import { check4Gulp } from '../../../logic/Links/CheckGulping';
import { postSourceItemAPI } from '../../lists/items/postSourceItemAPI';
import { createAnalyticsSourceProps } from '../../../components/atoms/easy-analytics/functions/createAnalyticsSourceProps';
import { AnalyticsWeb } from '../interfaces/constants';
/**
* 2025-01-03: Migrated from fps-library-v2/lib/pnpjs/Logging, pnp2/lib/services/sp/perms
* combination of v2: saveAnalytics2D
*
* import { savePermissionHistory } from "@mikezimm/fps-core-v7/lib/restAPIs/logging/Permissions/savePermissionHistory";
*
*/
export function getMinPerformanceString(performanceObj, capMS = 7000, capValue = 'paused?') {
let minPerformanceString = '';
if (performanceObj) {
const minPerformance = getMinPerformance(performanceObj, capMS, capValue);
minPerformanceString = JSON.stringify(minPerformance);
}
return minPerformanceString;
}
/**
*
* @param performanceObj: ILoadPerformance
* @capMS - max Milliseconds to save.... else return 'error' or null for that value.
* @capValue - if ms value exceeds capMS, return this value in place of value
* @returns
*/
export function getMinPerformance(performanceObj, capMS = 7000, capValue = 'paused?') {
const minPerformance = {
mode: null,
sets: {},
ops: {},
};
if (performanceObj && performanceObj.mode) {
minPerformance.mode = performanceObj.mode;
}
const keys = [...Object.keys(performanceObj), ...Object.keys(performanceObj.sets ? performanceObj.sets : {}), ...Object.keys(performanceObj.ops ? performanceObj.ops : {})];
keys.map((key) => {
if (LoadPerformanceOps.indexOf(key) > -1) {
const thisKey = key;
const ops = performanceObj.ops;
const sets = performanceObj.sets;
const minSets = minPerformance.sets;
const minOps = minPerformance.ops;
const thisPart = ops[key];
const performanceX = ops[key];
if (key.indexOf('setting') === 0) {
minSets[key] = sets[key]; // NOTE: This line does not TS Error out when in an actual project.
}
else if (performanceX) {
const ms = performanceX['ms'] === 0 || (performanceX['ms'] && performanceX['ms'] <= capMS) ? performanceX['ms'] : capValue;
const count = performanceX.c ? performanceX.c : undefined;
minOps[thisKey] = {
label: performanceX['label'],
ms: ms,
c: count ? count : undefined,
a: count ? Math.round((ms / count) * 10) / 10 : undefined,
};
}
}
});
if (performanceObj.getAllProps === true || performanceObj.getAllProps === false) {
minPerformance.getAllProps = performanceObj.getAllProps;
}
return minPerformance;
}
/**
* saveAnalytics4 is the same as 3 except you do not need the WebUrl... it's either Legacy or New depending on the tenant
*
* import { saveAnalytics4 } from "@mikezimm/fps-core-v7/lib/restAPIs/logging/Analytics/saveAnalyticsAPI";
*
* @param analyticsList
* @param saveObject
* @param muteConsole
* @param language
*/
export function saveAnalytics4(fpsSpService, analyticsList, saveObject, muteConsole, language) {
saveObject.AnalyticsVersion = 'saveAnalytics4';
saveAnalytics3(fpsSpService, AnalyticsWeb, `${analyticsList}`, saveObject, muteConsole, language);
}
/**
* Same as 2 but also adds the language to the object
* @param analyticsWeb
* @param analyticsList
* @param saveObject
* @param muteConsole
*/
export function saveAnalytics3(fpsSpService, analyticsWeb, analyticsList, saveObject, muteConsole, language) {
const fpsWindow = window;
if (language && language.length > 0) {
saveObject.language = navigator.language;
}
else if (navigator && navigator.language) {
saveObject.language = navigator.language;
}
else {
saveObject.language = 'Unknown';
}
if (fpsWindow.FPSUser)
saveObject.FPSUser = fpsWindow.FPSUser.simple;
saveObject.AnalyticsVersion = saveObject.AnalyticsVersion ? saveObject.AnalyticsVersion : 'saveAnalytics3';
saveAnalytics2(fpsSpService, analyticsWeb, analyticsList, saveObject, muteConsole);
}
/**
* 2025-03-17: Added this to build the loadProperties object using the default context.
* If needed, you can then tweak certain properties if you want.
* @param context
* @returns
*/
export function getContextLoadPropertiesObject(context) {
var _a, _b;
const loadProperties = {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
SiteID: context.pageContext.site.id['_guid'],
// eslint-disable-next-line @typescript-eslint/no-explicit-any
WebID: context.pageContext.web.id['_guid'],
// eslint-disable-next-line @typescript-eslint/no-explicit-any
SiteTitle: context.pageContext.web.title,
// https://github.com/fps-solutions/fps-core-v7/issues/15
// 2025-12-28: @1.22.x added conditionals when testing on workbench.
ListID: `${(_a = context.pageContext.list) === null || _a === void 0 ? void 0 : _a.id}`,
ListTitle: (_b = context.pageContext.list) === null || _b === void 0 ? void 0 : _b.title,
TargetList: `${context.pageContext.web.serverRelativeUrl}`, //Saved as link column. Displayed as Relative Url
};
return loadProperties;
}
export async function saveAnalytics2(fpsSpService, analyticsWeb, analyticsList, saveObject, muteConsole) {
let saveOjbectCopy = saveObject ? JSON.parse(JSON.stringify(saveObject)) : {};
let finalSaveObject = saveOjbectCopy;
finalSaveObject.AnalyticsVersion = finalSaveObject.AnalyticsVersion ? finalSaveObject.AnalyticsVersion : 'saveAnalytics2';
// 2023-09-17: Added if so that if loadProperties did not exist, it would not even do this loop.
if (saveObject.loadProperties) {
delete finalSaveObject['loadProperties'];
['SiteID', 'WebID', 'SiteTitle', 'ListID', 'ListTitle',].map((key) => {
if (saveObject.loadProperties[key])
finalSaveObject[key] = saveObject.loadProperties[key];
});
// 2023-09-17: Simplified this code with map and also added check so that it does not set a property if it does not exist in the loadProperties object
// finalSaveObject.SiteID = saveObject.loadProperties.SiteID; //Current site collection ID for easy filtering in large list
// finalSaveObject.WebID = saveObject.loadProperties.WebID; //Current web ID for easy filtering in large list
// finalSaveObject.SiteTitle = saveObject.loadProperties.SiteTitle; //Web Title
// finalSaveObject.ListID = saveObject.loadProperties.ListID; //Current list ID for easy filtering in large list
// finalSaveObject.ListTitle = saveObject.loadProperties.ListTitle;
}
if (typeof saveObject.zzzRichText1 === 'object') {
finalSaveObject.zzzRichText1 = JSON.stringify(saveObject.zzzRichText1);
if (check4Gulp() === true)
console.log('Length of zzzRichText1:', finalSaveObject.zzzRichText1.length);
}
else if (typeof saveObject.zzzRichText1 === 'string') {
finalSaveObject.zzzRichText1 = saveObject.zzzRichText1;
}
if (typeof saveObject.zzzRichText2 === 'object') {
finalSaveObject.zzzRichText2 = JSON.stringify(saveObject.zzzRichText2);
if (check4Gulp() === true)
console.log('Length of zzzRichText2:', finalSaveObject.zzzRichText2.length);
}
else if (typeof saveObject.zzzRichText2 === 'string') {
finalSaveObject.zzzRichText2 = saveObject.zzzRichText2;
}
if (typeof saveObject.zzzRichText3 === 'object') {
finalSaveObject.zzzRichText3 = JSON.stringify(saveObject.zzzRichText3);
if (check4Gulp() === true)
console.log('Length of zzzRichText3:', finalSaveObject.zzzRichText3.length);
}
else if (typeof saveObject.zzzRichText3 === 'string') {
finalSaveObject.zzzRichText3 = saveObject.zzzRichText3;
}
//Convert TargetSite to actual link object
if (typeof saveObject.loadProperties.TargetSite === 'string') {
finalSaveObject.TargetSite = {
'Url': saveObject.loadProperties.TargetSite,
'Description': saveObject.loadProperties.SiteTitle,
};
}
//Convert TargetSite to actual link TargetList
if (typeof saveObject.loadProperties.TargetList === 'string') {
finalSaveObject.TargetList = {
'Url': saveObject.loadProperties.TargetList,
'Description': saveObject.loadProperties.ListTitle,
};
}
//Convert TargetSite to actual link TargetItem - RTF Fixer Updates
if (typeof saveObject.loadProperties.TargetItem === 'string') {
finalSaveObject.TargetItem = {
'Url': saveObject.loadProperties.TargetItem,
'Description': saveObject.loadProperties.ItemTitle || saveObject.loadProperties.TargetItem,
};
}
//Create CollectionUrl string from TargetSite
if (saveObject.loadProperties.TargetSite && !finalSaveObject.CollectionUrl) {
if (typeof saveObject.loadProperties.TargetSite === 'string') {
finalSaveObject.CollectionUrl = getSiteCollectionUrlFromLink(saveObject.loadProperties.TargetSite); // Should be target Site Collection Url
}
else if (typeof saveObject.loadProperties.TargetSite === 'object') {
finalSaveObject.CollectionUrl = getSiteCollectionUrlFromLink(saveObject.loadProperties.TargetSite); // Should be target Site Collection Url
}
}
//Add current Page Link and Url
finalSaveObject.PageLink = getCurrentPageLink();
//Fix issue: https://github.com/mikezimm/SecureScript7/issues/52
let PageURLpieces = finalSaveObject.PageLink.Url.split('?');
finalSaveObject.PageURL = PageURLpieces[0];
// Fix issue: https://github.com/mikezimm/PageInfo/issues/108
if (finalSaveObject.PageLink.Url && finalSaveObject.PageLink.Url.length > 254) {
finalSaveObject.PageLink.Url = finalSaveObject.PageLink.Url.substring(0, 254);
finalSaveObject.PageLink.Description += ' - ( Trimmed Url )';
}
//Add parameters
finalSaveObject.getParams = getUrlParamsWithBloatCheck();
if (!finalSaveObject.SiteLink) {
let SiteLink = getWebUrlFromLink('', 'abs');
let SiteTitle = SiteLink.substring(SiteLink.lastIndexOf("/") + 1);
finalSaveObject.SiteLink = {
'Url': SiteLink,
'Description': SiteTitle,
};
}
/**
* Get Memory usage information
*/
//Courtesy of https://trackjs.com/blog/monitoring-javascript-memory/
const windowAny = window;
let memoryObj = windowAny.performance['memory'];
if (memoryObj) {
memoryObj.usedPerTotal = memoryObj.totalJSHeapSize && memoryObj.totalJSHeapSize !== 0 ? memoryObj.usedJSHeapSize / memoryObj.totalJSHeapSize : null;
memoryObj.totalPerLimit = memoryObj.jsHeapSizeLimit && memoryObj.jsHeapSizeLimit !== 0 ? memoryObj.totalJSHeapSize / memoryObj.jsHeapSizeLimit : null;
memoryObj.usedPerLimit = memoryObj.jsHeapSizeLimit && memoryObj.jsHeapSizeLimit !== 0 ? memoryObj.usedJSHeapSize / memoryObj.jsHeapSizeLimit : null;
memoryObj.Limit = getSizeLabel(memoryObj.jsHeapSizeLimit);
memoryObj.Total = getSizeLabel(memoryObj.totalJSHeapSize);
memoryObj.Used = getSizeLabel(memoryObj.usedJSHeapSize);
finalSaveObject.memory = JSON.stringify(memoryObj);
finalSaveObject.browser = 'Chromium';
finalSaveObject.JSHeapSize = memoryObj.totalJSHeapSize;
}
else {
finalSaveObject.browser = 'Not Chromium';
}
/**
* Get screen information
*/
let screen = null;
if (window && window.screen) {
screen = {
screenWidth: window.screen.width,
screenHeight: window.screen.height,
outerWidth: window.outerWidth,
outerHeight: window.outerHeight,
innerWidth: window.innerWidth,
innerHeight: window.innerHeight,
ratio: window.screen.width / window.screen.height,
aspect: getAspectRatio(window.screen.width, window.screen.height),
};
}
finalSaveObject.screen = JSON.stringify(screen);
finalSaveObject.screenSize = `${innerHeight} x ${innerWidth}`;
/**
* Always capitalized the first letter of the metadata.type
* https://github.com/fps-solutions/eXTreme-Storage-2/issues/3
*/
if (finalSaveObject.__metadata && finalSaveObject.__metadata.type) {
let contentType = finalSaveObject.__metadata.type.split('.');
if (contentType.length === 3) {
contentType[2] = upperFirstLetter(contentType[2], false);
}
finalSaveObject.__metadata = { type: contentType.join('.') };
}
/**
* get device information
*/
// const navigatorAny : any = navigator;
// let device = null;
// if ( navigator && navigator.appVersion ) {
// let OSName = null;
// if ( navigator.appVersion ) {
// if ( navigator.appVersion.indexOf("Win")!=-1) OSName="Windows";
// else if (navigator.appVersion.indexOf("Mac")!=-1) OSName="MacOS";
// else if (navigator.appVersion.indexOf("X11")!=-1) OSName="UNIX";
// else if (navigator.appVersion.indexOf("Linux")!=-1) OSName="Linux";
// }
// device = {
// OSName: OSName,
// platform: navigator.platform,
// maxTouchPoints: navigator.maxTouchPoints,
// vendor: navigator.vendor,
// language: navigator.language,
// deviceMemory: navigatorAny['deviceMemory'],
// };
// }
// finalSaveObject.device = JSON.stringify( device );
// https://github.com/mikezimm/pivottiles7/issues/417
const sourceProps = createAnalyticsSourceProps(fpsSpService, `${analyticsList}`, analyticsWeb);
// 2024-12-22: digestValue not required when using SpHTTPClient
// sourceProps.digestValue = await getThisFPSDigestValueFromUrl(analyticsWeb);
if (!finalSaveObject.zzzText7) {
finalSaveObject.zzzText7 = `API: fps-core-v7`;
}
else {
finalSaveObject.Title = `JsSp: ${finalSaveObject.Title}`;
}
const result = await postSourceItemAPI(sourceProps, finalSaveObject, false, true);
// const result = await saveThisLogItemAsync( analyticsWeb, analyticsList, finalSaveObject, muteConsole );
// https://github.com/mikezimm/pivottiles7/issues/417
if (result.status !== 'Success') {
const err = getHelpfullError(result, false, false, true);
if (check4Gulp() === true) {
console.log(`fps-library-v2 ERROR: saveAnalytics2 ~ 280`, err);
alert(`saveThisLogItemError\n\n${err.friendly}`);
}
;
}
}
export function getAspectRatio(width, height) {
if (height === 0 || width === 0) {
return 'na';
}
else {
let result = `${width} / ${height}`;
let ratio = roundRatio(width / height);
if (ratio === roundRatio(16 / 9)) {
result = '16 / 9';
}
else if (ratio === roundRatio(9 / 16)) {
result = '9 / 16';
}
else if (ratio === roundRatio(4 / 3)) {
result = '4 / 3';
}
else if (ratio === roundRatio(3 / 4)) {
result = '3 / 4';
}
else if (ratio === roundRatio(21 / 9)) {
result = '21 / 9';
}
else if (ratio === roundRatio(9 / 21)) {
result = '9 / 21';
}
else if (ratio === roundRatio(14 / 9)) {
result = '14 / 9';
}
else if (ratio === roundRatio(9 / 14)) {
result = '9 / 14';
}
else if (ratio === roundRatio(18 / 9)) {
result = '18 / 9';
}
else if (ratio === roundRatio(9 / 18)) {
result = '9 / 18';
}
else if (ratio === roundRatio(23 / 16)) {
result = '23 / 16';
} // Ipad Air 4
else if (ratio === roundRatio(16 / 23)) {
result = '16 / 23';
} // Ipad Air 4
else if (ratio === roundRatio(19.5 / 9)) {
result = '19.5 / 9';
} // Iphone 11-12-XR
else if (ratio === roundRatio(9 / 23)) {
result = '9 / 19.5';
} // Iphone 11-12-XR
else if (ratio === roundRatio(4 / 5)) {
result = '4 / 5';
}
else if (ratio === roundRatio(5 / 4)) {
result = '5 / 4';
}
else if (ratio === roundRatio(32 / 9)) {
result = '32 / 9';
}
else if (ratio === roundRatio(9 / 32)) {
result = '9 / 32';
}
return result;
}
}
//# sourceMappingURL=saveAnalyticsAPI.js.map