Skip to content

Commit

Permalink
Use helper util for global object
Browse files Browse the repository at this point in the history
This makes the library use `self` when `global` and `window` are
undefined, fixing a compatibility issue with some service worker
contexts.
  • Loading branch information
owenpearson committed Jun 29, 2022
1 parent 885a9ad commit 76af760
Show file tree
Hide file tree
Showing 3 changed files with 26 additions and 24 deletions.
7 changes: 4 additions & 3 deletions src/common/lib/util/logger.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import Platform from 'common/platform';
import * as Utils from 'common/lib/util/utils';

export type LoggerOptions = {
handler: LoggerFunction;
Expand All @@ -7,7 +8,7 @@ export type LoggerOptions = {
type LoggerFunction = (...args: string[]) => void;

// Workaround for salesforce lightning locker compatibility
let globalOrWindow = global || window;
let globalObject = Utils.getGlobalObject();

enum LogLevels {
None = 0,
Expand Down Expand Up @@ -47,7 +48,7 @@ const getDefaultLoggers = (): [Function, Function] => {
/* Can't just check for console && console.log; fails in IE <=9 */
if (
(typeof Window === 'undefined' && typeof WorkerGlobalScope === 'undefined') /* node */ ||
typeof globalOrWindow?.console?.log?.apply === 'function' /* sensible browsers */
typeof globalObject?.console?.log?.apply === 'function' /* sensible browsers */
) {
consoleLogger = function (...args: unknown[]) {
console.log.apply(console, args);
Expand All @@ -57,7 +58,7 @@ const getDefaultLoggers = (): [Function, Function] => {
console.warn.apply(console, args);
}
: consoleLogger;
} else if (globalOrWindow?.console.log as unknown) {
} else if (globalObject?.console.log as unknown) {
/* IE <= 9 with the console open -- console.log does not
* inherit from Function, so has no apply method */
consoleLogger = errorLogger = function () {
Expand Down
6 changes: 3 additions & 3 deletions src/platform/web/lib/transport/jsonptransport.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,14 +13,14 @@ import { TryConnectCallback } from 'common/lib/transport/transport';
import XHRStates from 'common/constants/XHRStates';

// Workaround for salesforce lightning locker compatibility
let globalOrWindow = (global || window) as unknown as {
let globalObject = Utils.getGlobalObject() as unknown as {
_ablyjs_jsonp: Record<string, unknown>;
JSONPTransport: typeof JSONPTransport;
};

const noop = function () {};
/* Can't just use window.Ably, as that won't exist if using the commonjs version. */
const _: Record<string, unknown> = (globalOrWindow._ablyjs_jsonp = {});
const _: Record<string, unknown> = (globalObject._ablyjs_jsonp = {});

/* express strips out parantheses from the callback!
* Kludge to still alow its responses to work, while not keeping the
Expand Down Expand Up @@ -264,7 +264,7 @@ export class Request extends EventEmitter {
}

export default function (connectionManager: typeof ConnectionManager): typeof JSONPTransport {
globalOrWindow.JSONPTransport = JSONPTransport;
globalObject.JSONPTransport = JSONPTransport;
if (JSONPTransport.isAvailable()) {
connectionManager.supportedTransports[shortName] = JSONPTransport;
}
Expand Down
37 changes: 19 additions & 18 deletions src/platform/web/platform.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,9 @@
import msgpack from './lib/util/msgpack';
import { IPlatform, TypedArray } from '../../common/types/IPlatform';
import * as Utils from 'common/lib/util/utils';

// Workaround for salesforce lightning locker compat
const globalOrWindow = global || window;
const globalObject = Utils.getGlobalObject();

declare var msCrypto: typeof crypto; // for IE11

Expand All @@ -16,12 +17,12 @@ function allowComet() {
/* xhr requests from local files are unreliable in some browsers, such as Chrome 65 and higher -- see eg
* https://stackoverflow.com/questions/49256429/chrome-65-unable-to-make-post-requests-from-local-files-to-flask
* So if websockets are supported, then just forget about comet transports and use that */
const loc = globalOrWindow.location;
return !globalOrWindow.WebSocket || !loc || !loc.origin || loc.origin.indexOf('http') > -1;
const loc = globalObject.location;
return !globalObject.WebSocket || !loc || !loc.origin || loc.origin.indexOf('http') > -1;
}

const userAgent = globalOrWindow.navigator && globalOrWindow.navigator.userAgent.toString();
const currentUrl = globalOrWindow.location && globalOrWindow.location.href;
const userAgent = globalObject.navigator && globalObject.navigator.userAgent.toString();
const currentUrl = globalObject.location && globalObject.location.href;

const Platform: IPlatform = {
agent: 'browser',
Expand All @@ -30,36 +31,36 @@ const Platform: IPlatform = {
currentUrl: currentUrl,
noUpgrade: userAgent && !!userAgent.match(/MSIE\s8\.0/),
binaryType: 'arraybuffer',
WebSocket: globalOrWindow.WebSocket,
xhrSupported: globalOrWindow.XMLHttpRequest && 'withCredentials' in new XMLHttpRequest(),
WebSocket: globalObject.WebSocket,
xhrSupported: globalObject.XMLHttpRequest && 'withCredentials' in new XMLHttpRequest(),
jsonpSupported: typeof document !== 'undefined',
allowComet: allowComet(),
streamingSupported: true,
useProtocolHeartbeats: true,
createHmac: null,
msgpack: msgpack,
supportsBinary: !!globalOrWindow.TextDecoder,
supportsBinary: !!globalObject.TextDecoder,
preferBinary: false,
ArrayBuffer: globalOrWindow.ArrayBuffer,
atob: globalOrWindow.atob,
ArrayBuffer: globalObject.ArrayBuffer,
atob: globalObject.atob,
nextTick:
typeof globalOrWindow.setImmediate !== 'undefined'
? globalOrWindow.setImmediate.bind(globalOrWindow)
typeof globalObject.setImmediate !== 'undefined'
? globalObject.setImmediate.bind(globalObject)
: function (f: () => void) {
setTimeout(f, 0);
},
addEventListener: globalOrWindow.addEventListener,
addEventListener: globalObject.addEventListener,
inspect: JSON.stringify,
stringByteSize: function (str: string) {
/* str.length will be an underestimate for non-ascii strings. But if we're
* in a browser too old to support TextDecoder, not much we can do. Better
* to underestimate, so if we do go over-size, the server will reject the
* message */
return (globalOrWindow.TextDecoder && new globalOrWindow.TextEncoder().encode(str).length) || str.length;
return (globalObject.TextDecoder && new globalObject.TextEncoder().encode(str).length) || str.length;
},
TextEncoder: globalOrWindow.TextEncoder,
TextDecoder: globalOrWindow.TextDecoder,
Promise: globalOrWindow.Promise,
TextEncoder: globalObject.TextEncoder,
TextDecoder: globalObject.TextDecoder,
Promise: globalObject.Promise,
getRandomValues: (function (crypto) {
if (crypto === undefined) {
return undefined;
Expand All @@ -70,7 +71,7 @@ const Platform: IPlatform = {
callback(null);
}
};
})(globalOrWindow.crypto || msCrypto),
})(globalObject.crypto || msCrypto),
};

export default Platform;

0 comments on commit 76af760

Please sign in to comment.