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

[ECO-4204] Remove code that's supporting older platforms (in v2) #1629

Merged
merged 38 commits into from
Feb 28, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
38 commits
Select commit Hold shift + click to select a range
4d657fb
Removes IE8 related comment
VeskeR Feb 21, 2024
e55a33b
Removes Date.now polyfill for IE8
VeskeR Feb 21, 2024
29984da
Removes `Utils.now` function
VeskeR Feb 21, 2024
2a9fd38
Removes IE10 specific needJsonEnvelope check from web xhrrequest
VeskeR Feb 21, 2024
c92c283
Removes IE specific statusCode check from web xhrrequest
VeskeR Feb 21, 2024
3b68aeb
Removes IE specific console checks from logger
VeskeR Feb 21, 2024
c49fc76
Removes IE msCrypto from web config
VeskeR Feb 21, 2024
2fb5128
Removes IE8 only `noUpgrade` Platform.Config option
VeskeR Feb 21, 2024
5106b00
Make IPlatformConfig.getRandomArrayBuffer non-optional
VeskeR Feb 21, 2024
a7a9620
Removes fallbacks to `Math.random` in utils and web crypto
VeskeR Feb 21, 2024
59ce70a
Removes IPlatformConfig.getRandomValues function in favour of getRand…
VeskeR Feb 21, 2024
103f8ef
Fix comment
VeskeR Feb 21, 2024
07601b5
Removes unnecessary hasOwnProperty is nullish check
VeskeR Feb 21, 2024
ad0857e
Improves comments in utils
VeskeR Feb 21, 2024
b88ec14
Remove polyfill for Array.isArray in utils
VeskeR Feb 21, 2024
397523b
Remove Utils.isArray function in favour of Array.isArray
VeskeR Feb 21, 2024
37fe738
Change Utils.isEmptyArg to Utils.isNil
VeskeR Feb 21, 2024
d9ec0af
Change Utils.isNil to shorter check
VeskeR Feb 21, 2024
fc9698e
Remove polyfill for Array.prototype.indexOf in Utils
VeskeR Feb 21, 2024
1836bdd
Change Transport.shortName type to TransportName from string
VeskeR Feb 21, 2024
bc4a494
Remove Utils.arrIndexOf in favour of native Array.prototype.indexOf
VeskeR Feb 21, 2024
e5961ea
Remove Utils.arrIn in favour of native Array.prototype.includes
VeskeR Feb 21, 2024
011310a
Remove polyfill for Array.prototype.forEach in Utils
VeskeR Feb 21, 2024
42ab6cc
Remove Utils.arrForEach in favour of native Array.prototype.forEach
VeskeR Feb 21, 2024
8a8e93f
Remove Utils.safeArrForEach
VeskeR Feb 21, 2024
fcda7d3
Remove polyfill for Array.prototype.map in Utils
VeskeR Feb 21, 2024
7d2ed22
Remove Utils.arrMap in favour of native Array.prototype.map
VeskeR Feb 21, 2024
ea6992c
Remove polyfill for Array.prototype.filter in Utils
VeskeR Feb 21, 2024
218a6cd
Remove Utils.arrFilter in favour of native Array.prototype.filter
VeskeR Feb 21, 2024
7f275ce
Remove Array.prototype.find polyfill from shared_helper
VeskeR Feb 21, 2024
e5aa106
Remove polyfill for Array.prototype.every in Utils
VeskeR Feb 21, 2024
2072302
Remove Utils.arrEvery in favour of native Array.prototype.every
VeskeR Feb 21, 2024
335007d
Remove polyfill for String.prototype.trim in Utils
VeskeR Feb 21, 2024
d5fcd67
Remove Utils.trim in favour of native String.prototype.trim
VeskeR Feb 21, 2024
85f0469
Change minimal raw bundle size threshold to 95 KiB
VeskeR Feb 21, 2024
809aced
Remove IE specific code from tests
VeskeR Feb 23, 2024
9a05dc8
Remove "comma-dangle" eslint rule used for old browsers compatibility
VeskeR Feb 23, 2024
2fc88a3
Remove node 0.8.x specific code from node platform crypto
VeskeR Feb 27, 2024
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
3 changes: 0 additions & 3 deletions .eslintrc.js
Original file line number Diff line number Diff line change
Expand Up @@ -19,8 +19,6 @@ module.exports = {
"plugin:security/recommended",
],
rules: {
// comma-dangle used for browser compatibility for browsers that don't support trailing commas
"comma-dangle": ["error", "always-multiline"],
"eol-last": "error",
// security/detect-object-injection just gives a lot of false positives
// see https://github.com/nodesecurity/eslint-plugin-security/issues/21
Expand All @@ -35,7 +33,6 @@ module.exports = {
{
files: ["**/*.{ts,tsx}"],
rules: {
"comma-dangle": ["error", "only-multiline"],
"@typescript-eslint/no-unused-vars": ["error", { "varsIgnorePattern": "^_" }],
// TypeScript already enforces these rules better than any eslint setup can
"no-undef": "off",
Expand Down
2 changes: 1 addition & 1 deletion scripts/moduleReport.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ import { gzip } from 'zlib';
import Table from 'cli-table';

// The maximum size we allow for a minimal useful Realtime bundle (i.e. one that can subscribe to a channel)
const minimalUsefulRealtimeBundleSizeThresholdsKiB = { raw: 96, gzip: 29 };
const minimalUsefulRealtimeBundleSizeThresholdsKiB = { raw: 95, gzip: 29 };

const baseClientNames = ['BaseRest', 'BaseRealtime'];

Expand Down
4 changes: 2 additions & 2 deletions src/common/lib/client/auth.ts
Original file line number Diff line number Diff line change
Expand Up @@ -441,7 +441,7 @@ class Auth {
);
} else {
const contentTypeHeaderOrHeaders = result.headers!['content-type'] ?? null;
if (Utils.isArray(contentTypeHeaderOrHeaders)) {
if (Array.isArray(contentTypeHeaderOrHeaders)) {
// Combine multiple header values into a comma-separated list per https://datatracker.ietf.org/doc/html/rfc9110#section-5.2; see https://github.com/ably/ably-js/issues/1616 for doing this consistently across the codebase.
contentType = contentTypeHeaderOrHeaders.join(', ');
} else {
Expand Down Expand Up @@ -830,7 +830,7 @@ class Auth {
}

getTimestampUsingOffset() {
return Utils.now() + (this.client.serverTimeOffset || 0);
return Date.now() + (this.client.serverTimeOffset || 0);
}

isTimeOffsetSet() {
Expand Down
2 changes: 1 addition & 1 deletion src/common/lib/client/baserealtime.ts
Original file line number Diff line number Diff line change
Expand Up @@ -154,7 +154,7 @@ class Channels extends EventEmitter {

for (const channelId in this.all) {
const channel = this.all[channelId];
if (Utils.arrIn(fromChannelStates, channel.state)) {
if (fromChannelStates.includes(channel.state)) {
channel.notifyState(toChannelState, reason);
}
}
Expand Down
10 changes: 5 additions & 5 deletions src/common/lib/client/realtimechannel.ts
Original file line number Diff line number Diff line change
Expand Up @@ -45,15 +45,15 @@ function validateChannelOptions(options?: API.ChannelOptions) {
return new ErrorInfo('options.params must be an object', 40000, 400);
}
if (options && 'modes' in options) {
if (!Utils.isArray(options.modes)) {
if (!Array.isArray(options.modes)) {
return new ErrorInfo('options.modes must be an array', 40000, 400);
}
for (let i = 0; i < options.modes.length; i++) {
const currentMode = options.modes[i];
if (
!currentMode ||
typeof currentMode !== 'string' ||
!Utils.arrIn(channelModes, String.prototype.toUpperCase.call(currentMode))
!channelModes.includes(String.prototype.toUpperCase.call(currentMode))
) {
return new ErrorInfo('Invalid channel mode: ' + currentMode, 40000, 400);
}
Expand Down Expand Up @@ -222,7 +222,7 @@ class RealtimeChannel extends EventEmitter {
}
if (argCount == 1) {
if (Utils.isObject(messages)) messages = [messageFromValues(messages)];
else if (Utils.isArray(messages)) messages = messagesFromValuesArray(messages);
else if (Array.isArray(messages)) messages = messagesFromValuesArray(messages);
else
throw new ErrorInfo(
'The single-argument form of publish() expects a message object or an array of message objects',
Expand Down Expand Up @@ -467,7 +467,7 @@ class RealtimeChannel extends EventEmitter {
const msg = protocolMessageFromValues({
action: actions.PRESENCE,
channel: this.name,
presence: Utils.isArray(presence)
presence: Array.isArray(presence)
? this.client._RealtimePresence!.presenceMessagesFromValuesArray(presence)
: [this.client._RealtimePresence!.presenceMessageFromValues(presence)],
});
Expand Down Expand Up @@ -696,7 +696,7 @@ class RealtimeChannel extends EventEmitter {
this.clearStateTimer();

// RTP5a1
if (Utils.arrIn(['detached', 'suspended', 'failed'], state)) {
if (['detached', 'suspended', 'failed'].includes(state)) {
this.properties.channelSerial = null;
}

Expand Down
4 changes: 2 additions & 2 deletions src/common/lib/client/realtimepresence.ts
Original file line number Diff line number Diff line change
Expand Up @@ -445,14 +445,14 @@ class RealtimePresence extends EventEmitter {

_synthesizeLeaves(items: PresenceMessage[]): void {
const subscriptions = this.subscriptions;
Utils.arrForEach(items, function (item) {
items.forEach(function (item) {
const presence = presenceMessageFromValues({
action: 'leave',
connectionId: item.connectionId,
clientId: item.clientId,
data: item.data,
encoding: item.encoding,
timestamp: Utils.now(),
timestamp: Date.now(),
});
subscriptions.emit('leave', presence);
});
Expand Down
8 changes: 4 additions & 4 deletions src/common/lib/client/rest.ts
Original file line number Diff line number Diff line change
Expand Up @@ -86,7 +86,7 @@ export class Rest {
throw new ErrorInfo('Internal error (unexpected result type from GET /time)', 50000, 500);
}
/* calculate time offset only once for this device by adding to the prototype */
this.client.serverTimeOffset = time - Utils.now();
this.client.serverTimeOffset = time - Date.now();
return time;
}

Expand Down Expand Up @@ -134,11 +134,11 @@ export class Rest {
/* useHttpPaginatedResponse: */ true
);

if (!Utils.arrIn(Platform.Http.methods, _method)) {
if (!Platform.Http.methods.includes(_method)) {
throw new ErrorInfo('Unsupported method ' + _method, 40500, 405);
}

if (Utils.arrIn(Platform.Http.methodsWithBody, _method)) {
if (Platform.Http.methodsWithBody.includes(_method)) {
return paginatedResource[_method as HttpMethods.Post](params, body as RequestBody) as Promise<
HttpPaginatedResponse<unknown>
>;
Expand All @@ -154,7 +154,7 @@ export class Rest {
): Promise<T extends BatchPublishSpec ? BatchPublishResult : BatchPublishResult[]> {
let requestBodyDTO: BatchPublishSpec[];
let singleSpecMode: boolean;
if (Utils.isArray(specOrSpecs)) {
if (Array.isArray(specOrSpecs)) {
requestBodyDTO = specOrSpecs;
singleSpecMode = false;
} else {
Expand Down
8 changes: 4 additions & 4 deletions src/common/lib/client/restchannel.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ import { RequestBody } from 'common/types/http';
const MSG_ID_ENTROPY_BYTES = 9;

function allEmptyIds(messages: Array<Message>) {
return Utils.arrEvery(messages, function (message: Message) {
return messages.every(function (message: Message) {
return !message.id;
});
}
Expand Down Expand Up @@ -63,7 +63,7 @@ class RestChannel {
} else if (Utils.isObject(first)) {
messages = [messageFromValues(first)];
params = args[1];
} else if (Utils.isArray(first)) {
} else if (Array.isArray(first)) {
messages = messagesFromValuesArray(first);
params = args[1];
} else {
Expand All @@ -88,8 +88,8 @@ class RestChannel {
Utils.mixin(headers, options.headers);

if (idempotentRestPublishing && allEmptyIds(messages)) {
const msgIdBase = Utils.randomString(MSG_ID_ENTROPY_BYTES);
Utils.arrForEach(messages, function (message, index) {
const msgIdBase = await Utils.randomString(MSG_ID_ENTROPY_BYTES);
messages.forEach(function (message, index) {
message.id = msgIdBase + ':' + index.toString();
});
}
Expand Down
2 changes: 1 addition & 1 deletion src/common/lib/transport/comettransport.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ function shouldBeErrorAction(err: ErrorInfo) {
const UNRESOLVABLE_ERROR_CODES = [80015, 80017, 80030];
if (err.code) {
if (Auth.isTokenErr(err)) return false;
if (Utils.arrIn(UNRESOLVABLE_ERROR_CODES, err.code)) return true;
if (UNRESOLVABLE_ERROR_CODES.includes(err.code)) return true;
return err.code >= 40000 && err.code < 50000;
} else {
/* Likely a network or transport error of some kind. Certainly not fatal to the connection */
Expand Down
56 changes: 30 additions & 26 deletions src/common/lib/transport/connectionmanager.ts
Original file line number Diff line number Diff line change
Expand Up @@ -44,8 +44,8 @@ function clearSessionRecoverData() {

function betterTransportThan(a: Transport, b: Transport) {
return (
Utils.arrIndexOf(Platform.Defaults.transportPreferenceOrder, a.shortName) >
Utils.arrIndexOf(Platform.Defaults.transportPreferenceOrder, b.shortName)
Platform.Defaults.transportPreferenceOrder.indexOf(a.shortName) >
Platform.Defaults.transportPreferenceOrder.indexOf(b.shortName)
);
}

Expand Down Expand Up @@ -75,7 +75,7 @@ function bundleWith(dest: ProtocolMessage, src: ProtocolMessage, maxSize: number
return false;
}
if (
!Utils.arrEvery(proposed, function (msg: Message) {
!proposed.every(function (msg: Message) {
return !msg.id;
})
) {
Expand Down Expand Up @@ -346,7 +346,6 @@ class ConnectionManager extends EventEmitter {
if (addEventListener) {
/* intercept close event in browser to persist connection id if requested */
if (haveSessionStorage() && typeof options.recover === 'function') {
/* Usually can't use bind as not supported in IE8, but IE doesn't support sessionStorage, so... */
addEventListener('beforeunload', this.persistConnection.bind(this));
}

Expand Down Expand Up @@ -416,7 +415,7 @@ class ConnectionManager extends EventEmitter {
if (initialiseWebSocketTransport) {
initialiseWebSocketTransport(storage);
}
Utils.arrForEach(Platform.Transports.order, function (transportName) {
Platform.Transports.order.forEach(function (transportName) {
const initFn = implementations[transportName];
if (initFn) {
initFn(storage);
Expand Down Expand Up @@ -591,7 +590,7 @@ class ConnectionManager extends EventEmitter {
/* if ws and xhrs are connecting in parallel, delay xhrs activation to let ws go ahead */
if (
transport.shortName !== optimalTransport &&
Utils.arrIn(this.getUpgradePossibilities(), optimalTransport) &&
this.getUpgradePossibilities().includes(optimalTransport) &&
this.activeProtocol
) {
setTimeout(() => {
Expand Down Expand Up @@ -930,9 +929,9 @@ class ConnectionManager extends EventEmitter {
}
}

/* Terminate any other pending transport(s), and
* abort any not-yet-pending transport attempts */
Utils.safeArrForEach(this.pendingTransports, (pendingTransport) => {
// terminate any other pending transport(s), and abort any not-yet-pending transport attempts
// need to use .slice() here, since we intend to mutate the array during .forEach() iteration
this.pendingTransports.slice().forEach((pendingTransport) => {
if (pendingTransport === transport) {
const msg =
'Assumption violated: activating a transport that is still marked as a pending transport; transport = ' +
Expand All @@ -945,7 +944,8 @@ class ConnectionManager extends EventEmitter {
pendingTransport.disconnect();
}
});
Utils.safeArrForEach(this.proposedTransports, (proposedTransport: Transport) => {
// need to use .slice() here, since we intend to mutate the array during .forEach() iteration
this.proposedTransports.slice().forEach((proposedTransport: Transport) => {
if (proposedTransport === transport) {
Logger.logAction(
Logger.LOG_ERROR,
Expand Down Expand Up @@ -1132,7 +1132,7 @@ class ConnectionManager extends EventEmitter {
return;
}

const sinceLast = Utils.now() - this.lastActivity;
const sinceLast = Date.now() - this.lastActivity;
if (sinceLast > this.connectionStateTtl + (this.maxIdleInterval as number)) {
Logger.logAction(
Logger.LOG_MINOR,
Expand All @@ -1154,7 +1154,7 @@ class ConnectionManager extends EventEmitter {
if (recoveryKey) {
setSessionRecoverData({
recoveryKey: recoveryKey,
disconnectedAt: Utils.now(),
disconnectedAt: Date.now(),
location: globalObject.location,
clientId: this.realtime.auth.clientId,
});
Expand Down Expand Up @@ -1358,11 +1358,11 @@ class ConnectionManager extends EventEmitter {
if (retryImmediately) {
const autoReconnect = () => {
if (this.state === this.states.disconnected) {
this.lastAutoReconnectAttempt = Utils.now();
this.lastAutoReconnectAttempt = Date.now();
this.requestState({ state: 'connecting' });
}
};
const sinceLast = this.lastAutoReconnectAttempt && Utils.now() - this.lastAutoReconnectAttempt + 1;
const sinceLast = this.lastAutoReconnectAttempt && Date.now() - this.lastAutoReconnectAttempt + 1;
if (sinceLast && sinceLast < 1000) {
Logger.logAction(
Logger.LOG_MICRO,
Expand Down Expand Up @@ -1559,7 +1559,7 @@ class ConnectionManager extends EventEmitter {
const preference = this.getTransportPreference();
let preferenceTimeoutExpired = false;

if (!Utils.arrIn(this.transports, preference)) {
if (!this.transports.includes(preference)) {
this.unpersistTransportPreference();
this.connectImpl(transportParams, connectCount);
}
Expand Down Expand Up @@ -1696,7 +1696,7 @@ class ConnectionManager extends EventEmitter {
* transport in upgradeTransports (if it's in there - if not, currentSerial
* will be -1, so return upgradeTransports.slice(0) == upgradeTransports */
const current = (this.activeProtocol as Protocol).getTransport().shortName;
const currentSerial = Utils.arrIndexOf(this.upgradeTransports, current);
const currentSerial = this.upgradeTransports.indexOf(current);
return this.upgradeTransports.slice(currentSerial + 1);
}

Expand All @@ -1712,7 +1712,7 @@ class ConnectionManager extends EventEmitter {
return;
}

Utils.arrForEach(upgradePossibilities, (upgradeTransport: TransportName) => {
upgradePossibilities.forEach((upgradeTransport: TransportName) => {
/* Note: the transport may mutate the params, so give each transport a fresh one */
const upgradeTransportParams = this.createTransportParams(transportParams.host, 'upgrade');
this.tryATransport(upgradeTransportParams, upgradeTransport, noop);
Expand All @@ -1724,12 +1724,14 @@ class ConnectionManager extends EventEmitter {
this.cancelSuspendTimer();
this.startTransitionTimer(this.states.closing);

Utils.safeArrForEach(this.pendingTransports, function (transport) {
// need to use .slice() here, since we intend to mutate the array during .forEach() iteration
this.pendingTransports.slice().forEach(function (transport) {
Logger.logAction(Logger.LOG_MICRO, 'ConnectionManager.closeImpl()', 'Closing pending transport: ' + transport);
if (transport) transport.close();
});

Utils.safeArrForEach(this.proposedTransports, function (transport) {
// need to use .slice() here, since we intend to mutate the array during .forEach() iteration
this.proposedTransports.slice().forEach(function (transport) {
Logger.logAction(
Logger.LOG_MICRO,
'ConnectionManager.closeImpl()',
Expand Down Expand Up @@ -1865,7 +1867,8 @@ class ConnectionManager extends EventEmitter {
/* This will prevent any connection procedure in an async part of one of its early stages from continuing */
this.connectCounter++;

Utils.safeArrForEach(this.pendingTransports, function (transport) {
// need to use .slice() here, since we intend to mutate the array during .forEach() iteration
this.pendingTransports.slice().forEach(function (transport) {
Logger.logAction(
Logger.LOG_MICRO,
'ConnectionManager.disconnectAllTransports()',
Expand All @@ -1875,7 +1878,8 @@ class ConnectionManager extends EventEmitter {
});
this.pendingTransports = [];

Utils.safeArrForEach(this.proposedTransports, function (transport) {
// need to use .slice() here, since we intend to mutate the array during .forEach() iteration
this.proposedTransports.slice().forEach(function (transport) {
Logger.logAction(
Logger.LOG_MICRO,
'ConnectionManager.disconnectAllTransports()',
Expand Down Expand Up @@ -2026,7 +2030,7 @@ class ConnectionManager extends EventEmitter {

private async processChannelMessage(message: ProtocolMessage, transport: Transport) {
const onActiveTransport = this.activeProtocol && transport === this.activeProtocol.getTransport(),
onUpgradeTransport = Utils.arrIn(this.pendingTransports, transport) && this.state == this.states.synchronizing;
onUpgradeTransport = this.pendingTransports.includes(transport) && this.state == this.states.synchronizing;

/* As the lib now has a period where the upgrade transport is synced but
* before it's become active (while waiting for the old one to become
Expand All @@ -2037,7 +2041,7 @@ class ConnectionManager extends EventEmitter {
// Message came in on a defunct transport. Allow only acks, nacks, & errors for outstanding
// messages, no new messages (as sync has been sent on new transport so new messages will
// be resent there, or connection has been closed so don't want new messages)
if (Utils.arrIndexOf([actions.ACK, actions.NACK, actions.ERROR], message.action) > -1) {
if ([actions.ACK, actions.NACK, actions.ERROR].includes(message.action!)) {
await this.realtime.channels.processChannelMessage(message);
} else {
Logger.logAction(
Expand All @@ -2059,14 +2063,14 @@ class ConnectionManager extends EventEmitter {
callback(new ErrorInfo('Timeout waiting for heartbeat response', 50000, 500));
};

const pingStart = Utils.now(),
const pingStart = Date.now(),
id = Utils.cheapRandStr();

const onHeartbeat = function (responseId: string) {
if (responseId === id) {
transport.off('heartbeat', onHeartbeat);
clearTimeout(timer);
const responseTime = Utils.now() - pingStart;
const responseTime = Date.now() - pingStart;
callback(null, responseTime);
}
};
Expand Down Expand Up @@ -2124,7 +2128,7 @@ class ConnectionManager extends EventEmitter {
}

persistTransportPreference(transport: Transport): void {
if (Utils.arrIn(Defaults.upgradeTransports, transport.shortName)) {
if (Defaults.upgradeTransports.includes(transport.shortName)) {
this.transportPreference = transport.shortName;
if (haveWebStorage()) {
Platform.WebStorage?.set?.(transportPreferenceName, transport.shortName);
Expand Down
Loading
Loading