Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Debugger enhancements #5288

Draft
wants to merge 3 commits into
base: main
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 14 additions & 7 deletions clients/fides-js/src/fides-tcf.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,6 @@ import type { TCData } from "@iabtechlabtcf/cmpapi";
import { TCString } from "@iabtechlabtcf/core";

import {
debugLog,
defaultShowModal,
FidesCookie,
isPrivacyExperience,
Expand Down Expand Up @@ -51,10 +50,13 @@ import {
} from "./lib/tcf/utils";
import { customGetConsentPreferences } from "./services/external/preferences";

type ConsoleLogParameters = Parameters<typeof console.log>;
declare global {
function fidesLogger(...args: ConsoleLogParameters): void;
interface Window {
Fides: FidesGlobal;
fides_overrides: FidesOptions;
fidesLogger: (...args: any[]) => void;
__tcfapiLocator?: Window;
__tcfapi?: (
command: string,
Expand All @@ -71,17 +73,24 @@ const updateWindowFides = (fidesGlobal: FidesGlobal) => {
if (typeof window !== "undefined") {
window.Fides = fidesGlobal;
}

// Set up the global debugger function if it doesn't already exist
if (typeof window !== "undefined" && !window.global?.fidesLogger) {
window.global = {
...window.global,
// eslint-disable-next-line no-console
fidesLogger: fidesGlobal.options?.debug ? console.log : () => {},
};
}
};

const updateExperience = ({
cookie,
experience,
debug = false,
isExperienceClientSideFetched,
}: {
cookie: FidesCookie;
experience: PrivacyExperience;
debug?: boolean;
isExperienceClientSideFetched: boolean;
}): Partial<PrivacyExperience> => {
if (!isExperienceClientSideFetched) {
Expand All @@ -93,8 +102,7 @@ const updateExperience = ({
// We need the cookie.fides_string to attach user preference to an experience.
// If this does not exist, we should assume no user preference has been given and leave the experience as is.
if (cookie.fides_string) {
debugLog(
debug,
global.fidesLogger(
"Overriding preferences from client-side fetched experience with cookie fides_string consent",
cookie.fides_string,
);
Expand Down Expand Up @@ -190,8 +198,7 @@ async function init(this: FidesGlobal, providedConfig?: FidesConfig) {
};
this.cookie = { ...this.cookie, ...updatedCookie };
} catch (error) {
debugLog(
config.options.debug,
global.fidesLogger(
`Could not decode tcString from ${fidesString}, it may be invalid. ${error}`,
);
}
Expand Down
14 changes: 12 additions & 2 deletions clients/fides-js/src/fides.ts
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,9 @@ import {
import { renderOverlay } from "./lib/renderOverlay";
import { customGetConsentPreferences } from "./services/external/preferences";

type ConsoleLogParameters = Parameters<typeof console.log>;
declare global {
function fidesLogger(...args: ConsoleLogParameters): void;
interface Window {
Fides: FidesGlobal;
fides_overrides: FidesOptions;
Expand All @@ -51,13 +53,21 @@ declare global {
const updateWindowFides = (fidesGlobal: FidesGlobal) => {
if (typeof window !== "undefined") {
window.Fides = fidesGlobal;

// Set up the global debugger function if it doesn't already exist
if (typeof window !== "undefined" && !window.global?.fidesLogger) {
window.global = {
...window.global,
// eslint-disable-next-line no-console
fidesLogger: fidesGlobal.options?.debug ? console.log : () => {},
};
}
}
};

const updateExperience: UpdateExperienceFn = ({
cookie,
experience,
debug,
isExperienceClientSideFetched,
}): Partial<PrivacyExperience> => {
let updatedExperience: PrivacyExperience = experience;
Expand All @@ -70,7 +80,6 @@ const updateExperience: UpdateExperienceFn = ({
updatedExperience = updateExperienceFromCookieConsentNotices({
experience,
cookie,
debug,
});
}
return updatedExperience;
Expand Down Expand Up @@ -144,6 +153,7 @@ async function init(this: FidesGlobal, providedConfig?: FidesConfig) {
if (initialFides) {
Object.assign(this, initialFides);
updateWindowFides(this);

dispatchFidesEvent("FidesInitialized", this.cookie, config.options.debug, {
shouldShowExperience: this.shouldShowExperience(),
});
Expand Down
44 changes: 18 additions & 26 deletions clients/fides-js/src/lib/consent-utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -86,12 +86,11 @@
*/
export const constructFidesRegionString = (
geoLocation?: UserGeolocation | null,
debug: boolean = false,

Check failure on line 89 in clients/fides-js/src/lib/consent-utils.ts

View workflow job for this annotation

GitHub Actions / Clients-Unit (20.x, admin-ui)

'debug' is assigned a value but never used. Allowed unused vars must match /^_/u

Check failure on line 89 in clients/fides-js/src/lib/consent-utils.ts

View workflow job for this annotation

GitHub Actions / Clients-Unit (20.x, privacy-center)

'debug' is assigned a value but never used. Allowed unused vars must match /^_/u

Check failure on line 89 in clients/fides-js/src/lib/consent-utils.ts

View workflow job for this annotation

GitHub Actions / Clients-Unit (20.x, fides-js)

'debug' is assigned a value but never used. Allowed unused vars must match /^_/u
): string | null => {
debugLog(debug, "constructing geolocation...");
global.fidesLogger("constructing geolocation...");
if (!geoLocation) {
debugLog(
debug,
global.fidesLogger(
"cannot construct user location since geoLocation is undefined or null",
);
return null;
Expand All @@ -101,13 +100,16 @@
VALID_ISO_3166_LOCATION_REGEX.test(geoLocation.location)
) {
// Fides backend requires underscore deliminator
return geoLocation.location.replace("-", "_").toLowerCase();
const regionString = geoLocation.location.replace("-", "_").toLowerCase();
global.fidesLogger(`using geolocation: ${regionString}`);
return regionString;
}
if (geoLocation.country && geoLocation.region) {
return `${geoLocation.country.toLowerCase()}_${geoLocation.region.toLowerCase()}`;
const regionString = `${geoLocation.country.toLowerCase()}_${geoLocation.region.toLowerCase()}`;
global.fidesLogger(`using geolocation: ${regionString}`);
return regionString;
}
debugLog(
debug,
global.fidesLogger(
"cannot construct user location from provided geoLocation params...",
);
return null;
Expand All @@ -118,22 +120,18 @@
*/
export const validateOptions = (options: FidesInitOptions): boolean => {
// Check if options is an invalid type
debugLog(
options.debug,
"Validating Fides consent overlay options...",
options,
);
global.fidesLogger("Validating Fides consent overlay options...", options);
if (typeof options !== "object") {
return false;
}

if (!options.fidesApiUrl) {
debugLog(options.debug, "Invalid options: fidesApiUrl is required!");
global.fidesLogger("Invalid options: fidesApiUrl is required!");
return false;
}

if (!options.privacyCenterUrl) {
debugLog(options.debug, "Invalid options: privacyCenterUrl is required!");
global.fidesLogger("Invalid options: privacyCenterUrl is required!");
return false;
}

Expand All @@ -143,8 +141,7 @@
// eslint-disable-next-line no-new
new URL(options.fidesApiUrl);
} catch (e) {
debugLog(
options.debug,
global.fidesLogger(
"Invalid options: privacyCenterUrl or fidesApiUrl is an invalid URL!",
options.privacyCenterUrl,
);
Expand Down Expand Up @@ -176,19 +173,17 @@
*/
export const experienceIsValid = (
effectiveExperience: PrivacyExperience | undefined | EmptyExperience,
options: FidesInitOptions,

Check failure on line 176 in clients/fides-js/src/lib/consent-utils.ts

View workflow job for this annotation

GitHub Actions / Clients-Unit (20.x, admin-ui)

'options' is defined but never used

Check failure on line 176 in clients/fides-js/src/lib/consent-utils.ts

View workflow job for this annotation

GitHub Actions / Clients-Unit (20.x, privacy-center)

'options' is defined but never used

Check failure on line 176 in clients/fides-js/src/lib/consent-utils.ts

View workflow job for this annotation

GitHub Actions / Clients-Unit (20.x, fides-js)

'options' is defined but never used
): boolean => {
if (!isPrivacyExperience(effectiveExperience)) {
debugLog(
options.debug,
global.fidesLogger(
"No relevant experience found. Skipping overlay initialization.",
);
return false;
}
const expConfig = effectiveExperience.experience_config;
if (!expConfig) {
debugLog(
options.debug,
global.fidesLogger(
"No experience config found for experience. Skipping overlay initialization.",
);
return false;
Expand All @@ -200,8 +195,7 @@
expConfig.component === ComponentType.TCF_OVERLAY
)
) {
debugLog(
options.debug,
global.fidesLogger(
"No experience found with modal, banner_and_modal, or tcf_overlay component. Skipping overlay initialization.",
);
return false;
Expand All @@ -213,8 +207,7 @@
effectiveExperience.privacy_notices.length > 0
)
) {
debugLog(
options.debug,
global.fidesLogger(
`Privacy experience has no notices. Skipping overlay initialization.`,
);
return false;
Expand Down Expand Up @@ -330,8 +323,7 @@
};

export const defaultShowModal = () => {
debugLog(
window.Fides.options.debug,
global.fidesLogger(
"The current experience does not support displaying a modal.",
);
};
4 changes: 1 addition & 3 deletions clients/fides-js/src/lib/events.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
import type { FidesEventType } from "../docs";
import { FidesCookie } from "./consent-types";
import { debugLog } from "./consent-utils";

// Bonus points: update the WindowEventMap interface with our custom event types
declare global {
Expand Down Expand Up @@ -66,8 +65,7 @@ export const dispatchFidesEvent = (
detail: { ...cookie, debug, extraDetails: constructedExtraDetails },
});
const perfMark = performance?.mark(type);
debugLog(
debug,
global.fidesLogger(
`Dispatching event type ${type} ${
constructedExtraDetails?.servingComponent
? `from ${constructedExtraDetails.servingComponent} `
Expand Down
8 changes: 5 additions & 3 deletions clients/fides-js/src/lib/initialize.ts
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,6 @@ import {
export type UpdateExperienceFn = (args: {
cookie: FidesCookie;
experience: PrivacyExperience;
debug?: boolean;
isExperienceClientSideFetched: boolean;
}) => Partial<PrivacyExperience>;

Expand All @@ -68,7 +67,10 @@ const retrieveEffectiveRegionString = async (
) => {
// Prefer the provided geolocation if available and valid; otherwise, fallback to automatically
// geolocating the user by calling the geolocation API
const fidesRegionString = constructFidesRegionString(geolocation);
const fidesRegionString = constructFidesRegionString(
geolocation,
options.debug,
);
if (!fidesRegionString) {
// we always need a region str so that we can PATCH privacy preferences to Fides Api
return constructFidesRegionString(
Expand All @@ -78,6 +80,7 @@ const retrieveEffectiveRegionString = async (
options.geolocationApiUrl,
options.debug,
),
options.debug,
);
}
return fidesRegionString;
Expand Down Expand Up @@ -391,7 +394,6 @@ export const initialize = async ({
const updatedExperience = updateExperience({
cookie: fides.cookie!,
experience: fides.experience,
debug: options.debug,
isExperienceClientSideFetched: fetchedClientSideExperience,
});
debugLog(
Expand Down
11 changes: 4 additions & 7 deletions clients/privacy-center/app/server-environment.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ import { URL } from "url";
import getPropertyFromUrl from "~/app/server-utils/getPropertyFromUrl";
import loadEnvironmentVariables from "~/app/server-utils/loadEnvironmentVariables";
import { PrivacyCenterSettings } from "~/app/server-utils/PrivacyCenterSettings";
import { debugLog } from "~/common/debugger";
import {
isV1ConsentConfig,
translateV1ConfigToV2,
Expand Down Expand Up @@ -116,17 +117,15 @@ const loadConfigFile = async (
path = urlString.replace("file:", "");
}
const file = await fsPromises.readFile(path || url, "utf-8");
if (process.env.NODE_ENV === "development") {
console.log(`Loaded configuration file: ${urlString}`);
}
debugLog(`Loaded configuration file: ${urlString}`);
return file;
} catch (err: any) {
// Catch "file not found" errors (ENOENT)
if (err.code === "ENOENT") {
continue;
}
// Log everything else and continue
console.log(
console.error(
`Failed to load configuration file from ${urlString}. Error: `,
err,
);
Expand Down Expand Up @@ -294,9 +293,7 @@ export const loadPrivacyCenterEnvironment = async ({
);
}
// DEFER: Log a version number here (see https://github.com/ethyca/fides/issues/3171)
if (process.env.NODE_ENV === "development") {
console.log("Load Privacy Center environment for session...");
}
debugLog("Load Privacy Center environment for session...");

// Load environment variables
const settings = loadEnvironmentVariables();
Expand Down
5 changes: 5 additions & 0 deletions clients/privacy-center/common/debugger.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
/* eslint-disable no-console */
export const debugLog =
process.env.FIDES_PRIVACY_CENTER__DEBUG === "true"
? (...args: unknown[]) => console.log("\x1b[34m%s\x1b[0m", "=>", ...args)
: () => {};
5 changes: 4 additions & 1 deletion clients/privacy-center/features/consent/consent.slice.ts
Original file line number Diff line number Diff line change
Expand Up @@ -228,7 +228,10 @@ export const selectUserRegion = createSelector(
settings.GEOLOCATION_API_URL,
)(RootState)?.data;
}
return constructFidesRegionString(geolocation) as PrivacyNoticeRegion;
return constructFidesRegionString(
geolocation,
settings?.DEBUG,
) as PrivacyNoticeRegion;
}
return undefined;
},
Expand Down
3 changes: 3 additions & 0 deletions clients/privacy-center/next.config.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,9 @@
const path = require("path");
const { version } = require("./package.json");

global.fidesLogger =
process.env.FIDES_PRIVACY_CENTER__DEBUG === "true" ? console.log : () => {};

const withBundleAnalyzer = require("@next/bundle-analyzer")({
enabled: process.env.ANALYZE === "true",
});
Expand Down
Loading
Loading