Skip to content

Commit c13ea83

Browse files
refactor: Migrate mParticle Instance to TypeScript
1 parent 78a0cb2 commit c13ea83

File tree

10 files changed

+210
-91
lines changed

10 files changed

+210
-91
lines changed

src/batchUploader.ts

Lines changed: 8 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@ import {
1212
IFetchPayload,
1313
} from './uploaders';
1414
import { IMParticleUser } from './identity-user-interfaces';
15+
import { IMParticleWebSDKInstance } from './mp-instance';
1516

1617
/**
1718
* BatchUploader contains all the logic to store/retrieve events and batches
@@ -36,7 +37,7 @@ export class BatchUploader {
3637
uploadIntervalMillis: number;
3738
eventsQueuedForProcessing: SDKEvent[];
3839
batchesQueuedForProcessing: Batch[];
39-
mpInstance: MParticleWebSDK;
40+
mpInstance: IMParticleWebSDKInstance;
4041
uploadUrl: string;
4142
batchingEnabled: boolean;
4243
private eventVault: SessionStorageVault<SDKEvent[]>;
@@ -46,10 +47,10 @@ export class BatchUploader {
4647

4748
/**
4849
* Creates an instance of a BatchUploader
49-
* @param {MParticleWebSDK} mpInstance - the mParticle SDK instance
50+
* @param {IMParticleWebSDKInstance} mpInstance - the mParticle SDK instance
5051
* @param {number} uploadInterval - the desired upload interval in milliseconds
5152
*/
52-
constructor(mpInstance: MParticleWebSDK, uploadInterval: number) {
53+
constructor(mpInstance: IMParticleWebSDKInstance, uploadInterval: number) {
5354
this.mpInstance = mpInstance;
5455
this.uploadIntervalMillis = uploadInterval;
5556
this.batchingEnabled =
@@ -208,7 +209,7 @@ export class BatchUploader {
208209
private static createNewBatches(
209210
sdkEvents: SDKEvent[],
210211
defaultUser: IMParticleUser,
211-
mpInstance: MParticleWebSDK
212+
mpInstance: IMParticleWebSDKInstance
212213
): Batch[] | null {
213214
if (!defaultUser || !sdkEvents || !sdkEvents.length) {
214215
return null;
@@ -280,9 +281,9 @@ export class BatchUploader {
280281
* @param triggerFuture whether to trigger the loop again - for manual/forced uploads this should be false
281282
* @param useBeacon whether to use the beacon API - used when the page is being unloaded
282283
*/
283-
private async prepareAndUpload(
284-
triggerFuture: boolean,
285-
useBeacon: boolean
284+
public async prepareAndUpload(
285+
triggerFuture?: boolean,
286+
useBeacon?: boolean
286287
): Promise<void> {
287288
// Fetch current user so that events can be grouped by MPID
288289
const currentUser = this.mpInstance.Identity.getCurrentUser();

src/consent.ts

Lines changed: 0 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -36,12 +36,6 @@ export interface SDKConsentApi {
3636
createGDPRConsent: ICreatePrivacyConsentFunction;
3737
createCCPAConsent: ICreatePrivacyConsentFunction;
3838
createConsentState: (consentState?: ConsentState) => ConsentState;
39-
ConsentSerialization: IConsentSerialization;
40-
createPrivacyConsent: ICreatePrivacyConsentFunction;
41-
isEnabledForUserConsent: (
42-
consentRules: IConsentRules,
43-
user: IMParticleUser
44-
) => boolean;
4539
}
4640

4741
export interface IConsentSerialization {

src/events.interfaces.ts

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -53,7 +53,7 @@ export interface IEvents {
5353
logOptOut(): void;
5454
logProductActionEvent(
5555
productActionType: valueof<typeof ProductActionType>,
56-
product: SDKProduct,
56+
product: SDKProduct | SDKProduct[],
5757
attrs?: SDKEventAttrs,
5858
customFlags?: SDKEventCustomFlags,
5959
transactionAttributes?: TransactionAttributes,
@@ -68,13 +68,13 @@ export interface IEvents {
6868
): void;
6969
logPurchaseEvent(
7070
transactionAttributes: TransactionAttributes,
71-
product: SDKProduct,
71+
product: SDKProduct | SDKProduct[],
7272
attrs?: SDKEventAttrs,
7373
customFlags?: SDKEventCustomFlags
7474
): void;
7575
logRefundEvent(
7676
transactionAttributes: TransactionAttributes,
77-
product: SDKProduct,
77+
product: SDKProduct | SDKProduct[],
7878
attrs?: SDKEventAttrs,
7979
customFlags?: SDKEventCustomFlags
8080
): void;

src/identity-user-interfaces.ts

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -115,10 +115,10 @@ export interface IdentityModifyResultBody {
115115
}
116116

117117
export interface mParticleUserCart {
118-
add(product: Product, logEvent: boolean): void;
119-
remove(product: Product, logEvent: boolean): void;
118+
add(product: SDKProduct | SDKProduct[], logEvent: boolean): void;
119+
remove(product: SDKProduct | SDKProduct[], logEvent: boolean): void;
120120
clear(): void;
121-
getCartProducts(): Product[];
121+
getCartProducts(): SDKProduct[];
122122
}
123123

124124
// https://go.mparticle.com/work/SQDSDKS-5196
Lines changed: 99 additions & 28 deletions
Original file line numberDiff line numberDiff line change
@@ -16,31 +16,99 @@
1616
// Uses portions of code from jQuery
1717
// jQuery v1.10.2 | (c) 2005, 2013 jQuery Foundation, Inc. | jquery.org/license
1818

19-
import Types from './types';
19+
import { EventType, IdentityType, CommerceEventType, PromotionActionType, ProductActionType, MessageType } from './types';
2020
import Constants from './constants';
21-
import APIClient from './apiClient';
21+
import APIClient, { IAPIClient } from './apiClient';
2222
import Helpers from './helpers';
2323
import NativeSdkHelpers from './nativeSdkHelpers';
24-
import CookieSyncManager from './cookieSyncManager';
25-
import SessionManager from './sessionManager';
24+
import CookieSyncManager, { ICookieSyncManager, IPixelConfiguration } from './cookieSyncManager';
25+
import SessionManager, { ISessionManager } from './sessionManager';
2626
import Ecommerce from './ecommerce';
27-
import Store from './store';
27+
import Store, { IntegrationAttribute, IStore } from './store';
2828
import Logger from './logger';
2929
import Persistence from './persistence';
3030
import Events from './events';
3131
import Forwarders from './forwarders';
32-
import ServerModel from './serverModel';
32+
import ServerModel, { IServerModel } from './serverModel';
3333
import ForwardingStatsUploader from './forwardingStatsUploader';
3434
import Identity from './identity';
35-
import Consent from './consent';
35+
import Consent, { IConsent } from './consent';
3636
import KitBlocker from './kitBlocking';
3737
import ConfigAPIClient from './configAPIClient';
3838
import IdentityAPIClient from './identityApiClient';
39-
import { isFunction } from './utils';
39+
import { isFunction, valueof } from './utils';
4040
import { LocalStorageVault } from './vault';
4141
import { removeExpiredIdentityCacheDates } from './identity-utils';
4242
import IntegrationCapture from './integrationCapture';
43-
import { processReadyQueue } from './pre-init-utils';
43+
import { IPreInit, processReadyQueue } from './pre-init-utils';
44+
import { BaseEvent, MParticleWebSDK, SDKEventCustomFlags, SDKHelpersApi, } from './sdkRuntimeModels';
45+
import { Callback, SDKEventAttrs, SDKEventOptions } from '@mparticle/web-sdk';
46+
import { IIdentity } from './identity.interfaces';
47+
import { IEvents } from './events.interfaces';
48+
import { IECommerce } from './ecommerce.interfaces';
49+
import { INativeSdkHelpers } from './nativeSdkHelpers.interfaces';
50+
import { IPersistence } from './persistence.interfaces';
51+
52+
export interface IErrorLogMessage {
53+
message?: string;
54+
name?: string;
55+
stack?: string;
56+
}
57+
58+
export interface IErrorLogMessageMinified {
59+
m?: string;
60+
s?: string;
61+
t?: string;
62+
}
63+
64+
export type IntegrationDelays = { [key: number]: boolean };
65+
66+
// https://go.mparticle.com/work/SQDSDKS-6949
67+
export interface IMParticleWebSDKInstance extends MParticleWebSDK {
68+
_instanceName: string;
69+
_preInit: IPreInit;
70+
71+
_APIClient: IAPIClient;
72+
_CookieSyncManager: ICookieSyncManager;
73+
_Consent: IConsent;
74+
_Ecommerce: IECommerce;
75+
_Events: IEvents;
76+
_Forwarders: any;
77+
_ForwardingStatsUploader: ForwardingStatsUploader;
78+
_Helpers: SDKHelpersApi;
79+
_Identity: IIdentity;
80+
_IdentityAPIClient: typeof IdentityAPIClient;
81+
_IntegrationCapture: IntegrationCapture;
82+
_NativeSdkHelpers: INativeSdkHelpers;
83+
_Persistence: IPersistence;
84+
_SessionManager: ISessionManager;
85+
_Store: IStore;
86+
_ServerModel: IServerModel;
87+
88+
89+
90+
configurePixel(config: IPixelConfiguration): void;
91+
reset(instance: IMParticleWebSDKInstance): void;
92+
ready(f: Function): void;
93+
isInitialized(): boolean;
94+
getEnvironment(): valueof<typeof Constants.Environment>;
95+
getVersion(): string;
96+
setAppVersion(version: string): void;
97+
setAppName(name: string): void;
98+
startTrackingLocation(callback?: Callback): void;
99+
stopTrackingLocation(): void;
100+
logError(error: IErrorLogMessage | string, attrs?: any): void;
101+
102+
// TODO: Define EventInfo
103+
logLink(selector: string, eventName: string, eventType: valueof<typeof EventType>, eventInfo: any): void;
104+
logForm(selector: string, eventName: string, eventType: valueof<typeof EventType>, eventInfo: any): void;
105+
logPageView(eventName: string, attrs?: SDKEventAttrs, customFlags?: SDKEventCustomFlags, eventOptions?: SDKEventOptions): void;
106+
setOptOut(isOptingOut: boolean): void;
107+
108+
// QUESTION: Should integration ID be a number or a string?
109+
setIntegrationAttribute(integrationId: number, attrs: IntegrationAttribute): void;
110+
getIntegrationAttributes(integrationId: number): IntegrationAttribute;
111+
}
44112

45113
const { Messages, HTTPCodes, FeatureFlags } = Constants;
46114
const { ReportBatching, CaptureIntegrationSpecificIds } = FeatureFlags;
@@ -59,7 +127,7 @@ const { StartingInitialization } = Messages.InformationMessages;
59127
* @class mParticle & mParticleInstance
60128
*/
61129

62-
export default function mParticleInstance(instanceName) {
130+
export default function mParticleInstance(this: IMParticleWebSDKInstance, instanceName: string) {
63131
var self = this;
64132
// These classes are for internal use only. Not documented for public consumption
65133
this._instanceName = instanceName;
@@ -82,11 +150,12 @@ export default function mParticleInstance(instanceName) {
82150
this._IntegrationCapture = new IntegrationCapture();
83151

84152
// required for forwarders once they reference the mparticle instance
85-
this.IdentityType = Types.IdentityType;
86-
this.EventType = Types.EventType;
87-
this.CommerceEventType = Types.CommerceEventType;
88-
this.PromotionType = Types.PromotionActionType;
89-
this.ProductActionType = Types.ProductActionType;
153+
this.IdentityType = IdentityType;
154+
this.EventType = EventType as unknown as valueof<typeof EventType>;
155+
this.CommerceEventType = CommerceEventType as unknown as valueof<typeof CommerceEventType>;
156+
this.PromotionType = PromotionActionType as unknown as valueof<typeof PromotionActionType>;
157+
this.ProductActionType = ProductActionType as unknown as valueof<typeof ProductActionType>;
158+
90159

91160
this._Identity = new Identity(this);
92161
this.Identity = this._Identity.IdentityAPI;
@@ -372,7 +441,7 @@ export default function mParticleInstance(instanceName) {
372441
}
373442

374443
if (!event.eventType) {
375-
event.eventType = Types.EventType.Unknown;
444+
event.eventType = EventType.Unknown;
376445
}
377446

378447
if (!self._Helpers.canLog()) {
@@ -417,15 +486,15 @@ export default function mParticleInstance(instanceName) {
417486
}
418487

419488
if (!eventType) {
420-
eventType = Types.EventType.Unknown;
489+
eventType = EventType.Unknown;
421490
}
422491

423492
if (!self._Helpers.isEventType(eventType)) {
424493
self.Logger.error(
425494
'Invalid event type: ' +
426495
eventType +
427496
', must be one of: \n' +
428-
JSON.stringify(Types.EventType)
497+
JSON.stringify(EventType)
429498
);
430499
return;
431500
}
@@ -437,12 +506,12 @@ export default function mParticleInstance(instanceName) {
437506

438507
self._Events.logEvent(
439508
{
440-
messageType: Types.MessageType.PageEvent,
509+
messageType: MessageType.PageEvent,
441510
name: eventName,
442511
data: eventInfo,
443512
eventType: eventType,
444513
customFlags: customFlags,
445-
},
514+
} as BaseEvent,
446515
eventOptions
447516
);
448517
};
@@ -471,8 +540,9 @@ export default function mParticleInstance(instanceName) {
471540
};
472541
}
473542

474-
var data = {
475-
m: error.message ? error.message : error,
543+
// FIXME: Replace var with const/let
544+
var data: IErrorLogMessageMinified = {
545+
m: error.message ? error.message : error as string,
476546
s: 'Error',
477547
t: error.stack || null,
478548
};
@@ -485,10 +555,11 @@ export default function mParticleInstance(instanceName) {
485555
}
486556

487557
self._Events.logEvent({
488-
messageType: Types.MessageType.CrashReport,
558+
messageType: MessageType.CrashReport,
489559
name: error.name ? error.name : 'Error',
490-
data: data,
491-
eventType: Types.EventType.Other,
560+
// data: data, // QUESTION: Is this a bug? This should be eventType
561+
eventType: EventType.Other,
562+
data: data as { [key: string]: string },
492563
});
493564
};
494565
/**
@@ -571,10 +642,10 @@ export default function mParticleInstance(instanceName) {
571642

572643
self._Events.logEvent(
573644
{
574-
messageType: Types.MessageType.PageView,
645+
messageType: MessageType.PageView,
575646
name: eventName,
576-
data: attrs,
577-
eventType: Types.EventType.Unknown,
647+
data: attrs as { [key: string]: string },
648+
eventType: EventType.Unknown,
578649
customFlags: customFlags,
579650
},
580651
eventOptions

src/nativeSdkHelpers.interfaces.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,7 @@ export interface INativeSdkHelpers {
66
minWebviewBridgeVersion: number
77
) => boolean;
88
isBridgeV1Available: () => boolean;
9-
sendToNative: (path: string, value: string) => void;
9+
sendToNative: (path: string, value?: string) => void;
1010
sendViaBridgeV1: (path: string, value: string) => void;
1111
sendViaIframeToIOS: (path: string, value: string) => void;
1212
sendViaBridgeV2: (path: string, value: string, requiredWebviewBridgeName: boolean) => void;

src/pre-init-utils.ts

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,16 @@
1+
import { IPixelConfiguration } from './cookieSyncManager';
2+
import { MPForwarder } from './forwarders.interfaces';
3+
import { IntegrationDelays } from './mp-instance';
14
import { isEmpty, isFunction } from './utils';
25

6+
export interface IPreInit {
7+
readyQueue: Function[];
8+
integrationDelays: IntegrationDelays;
9+
forwarderConstructors: MPForwarder[];
10+
pixelConfigurations?: IPixelConfiguration[];
11+
isDevelopmentMode?: boolean;
12+
}
13+
314
export const processReadyQueue = (readyQueue): Function[] => {
415
if (!isEmpty(readyQueue)) {
516
readyQueue.forEach(readyQueueItem => {

0 commit comments

Comments
 (0)