Skip to content

Commit

Permalink
feat: OneSignal.setSWLogging; improved message testability
Browse files Browse the repository at this point in the history
  • Loading branch information
onethirtyfive committed Mar 6, 2023
1 parent 90b257e commit e25ece3
Show file tree
Hide file tree
Showing 11 changed files with 444 additions and 164 deletions.
8 changes: 8 additions & 0 deletions src/OneSignal.ts
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,7 @@ import { AppUserConfigNotifyButton, DelayedPromptType } from './models/Prompts';
import LocalStorage from './utils/LocalStorage';
import { AuthHashOptionsValidatorHelper } from './helpers/page/AuthHashOptionsValidatorHelper';
import { TagsObject } from './models/Tags';
import { WorkerMessengerCommand } from './libraries/WorkerMessenger';

export default class OneSignal {
/**
Expand Down Expand Up @@ -844,6 +845,13 @@ export default class OneSignal {
});
}

public static async setSWLogging(enable: boolean): Promise<void> {
OneSignal.context.workerMessenger.directPostMessageToSW(
WorkerMessengerCommand.SetLogging,
{ shouldLog: !!enable }
);
}

static __doNotShowWelcomeNotification: boolean;
static VERSION = Environment.version();
static _VERSION = Environment.version();
Expand Down
2 changes: 1 addition & 1 deletion src/helpers/ServiceWorkerHelper.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { OneSignalApiSW } from "../OneSignalApiSW";
import Log from "../libraries/sw/Log";
import Log from "../libraries/Log";
import Path from "../models/Path";
import { Session, initializeNewSession, SessionOrigin, SessionStatus } from "../models/Session";
import { OneSignalUtils } from "../utils/OneSignalUtils";
Expand Down
16 changes: 8 additions & 8 deletions src/helpers/sw/CancelableTimeout.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,12 @@
import Log from "../../libraries/sw/Log";
import SWLog from "../../libraries/SWLog";

export interface CancelableTimeoutPromise {
cancel: () => void;
promise: Promise<void>;
}

const doNothing = () => {
Log.debug("Do nothing");
SWLog.debug("Do nothing");
};

export function cancelableTimeout(callback: () => Promise<void>, delayInSeconds: number): CancelableTimeoutPromise {
Expand All @@ -25,23 +25,23 @@ export function cancelableTimeout(callback: () => Promise<void>, delayInSeconds:
await callback();
resolve();
} catch(e) {
Log.error("Failed to execute callback", e);
SWLog.error("Failed to execute callback", e);
reject();
}
},
},
delayInMilliseconds);

clearTimeoutHandle = () => {
Log.debug("Cancel called");
self.clearTimeout(timerId);
SWLog.debug("Cancel called");
self.clearTimeout(timerId);
if (!startedExecution) {
resolve();
}
};
});

if (!clearTimeoutHandle) {
Log.warn("clearTimeoutHandle was not assigned.");
SWLog.warn("clearTimeoutHandle was not assigned.");
return {
promise,
cancel: doNothing,
Expand Down
97 changes: 97 additions & 0 deletions src/libraries/SWLog.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,97 @@

export interface SWLogOptions {
console?: SWLogConsole;
};

export type SWConsoleLoggerFn = (...args: any[]) => void;

export interface SWLogConsole extends Partial<Console> {
log: SWConsoleLoggerFn;
debug: SWConsoleLoggerFn;
trace: SWConsoleLoggerFn;
info: SWConsoleLoggerFn;
warn: SWConsoleLoggerFn;
error: SWConsoleLoggerFn;
};

const NOOP = () => {};

type SWLogBuiltinConsoles = "env" | "null" | "default";


// class semantics here are for compat -- the singleton is `SWConsoleLog`
export default class SWLog {
private static _nullConsole: SWLogConsole | undefined
private static _singletonConsole: SWLogConsole | undefined;

public static get nullConsole(): SWLogConsole {
// test spies need an invariant object reference for `called`
SWLog._nullConsole =
SWLog._nullConsole ||
["log", "debug", "trace", "info", "warn", "error"].reduce(
(l, m) => ({ ...l, [m]: NOOP }),
{}
) as SWLogConsole;

return SWLog._nullConsole;
}

// NB properties' being calculated just in time mitigates hard-to-debug
// sequencing errors from TestEnvironment's twiddling of global state
public static get consoles(): Record<SWLogBuiltinConsoles, SWLogConsole> {
return {
env: (() => {
const console: Console = (global !== undefined)
? global.console
: window.console;
return console as SWLogConsole;
})(),

null: this.nullConsole,
default: this.nullConsole, // quiet by default, change if desired
}
}

// NB built-in `Console` interface is freely castable to `SWLogConsole`
public static resetConsole(console?: SWLogConsole): void {
SWLog._singletonConsole = console;
}

public static get singletonConsole(): SWLogConsole {
if (SWLog._singletonConsole === undefined)
SWLog.resetConsole(SWLog.consoles.default);
return SWLog._singletonConsole!; // runtime-ensured; safe
}

public static get enabled(): boolean {
const singletonConsole = SWLog.singletonConsole
return !!singletonConsole && singletonConsole !== SWLog.consoles.null;
}

// below are relays to "a `SWLogConsole`" (iow "a `Partial<Console>`"):
// removing class semantics would make them redundant

static log(...args: any[]): void {
SWLog.singletonConsole.log(...args);
}

static trace(...args: any[]): void {
SWLog.singletonConsole.trace(...args);
}

static debug(...args: any[]): void {
SWLog.singletonConsole.debug(...args);
}

static info(...args: any[]): void {
SWLog.singletonConsole.info(...args);
}

static warn(...args: any[]): void {
SWLog.singletonConsole.warn(...args);
}

static error(...args: any[]): void {
SWLog.singletonConsole.error(...args);
}
}
31 changes: 0 additions & 31 deletions src/libraries/sw/Log.ts

This file was deleted.

Loading

0 comments on commit e25ece3

Please sign in to comment.