summaryrefslogtreecommitdiff
path: root/node_modules/@jet-app/app-store/tmp/src/foundation/metrics/metrics-identifiers-cache.js
blob: 96a487f283cdc3f0b90f8b982b14fe6dfcbb088e (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
import { isNothing, isSome } from "@jet/environment";
import * as validation from "@jet/environment/json/validation";
import { makeMetatype } from "@jet/environment/util/metatype";
/**
 * @public
 * Type to define which type of metrics identifier key to use to fetch identifiers, fields, etc.
 */
export var MetricsIdentifierType;
(function (MetricsIdentifierType) {
    MetricsIdentifierType["client"] = "clientId";
    MetricsIdentifierType["user"] = "userId";
    MetricsIdentifierType["canonical"] = "canonicalAccountIdentifierOverride";
})(MetricsIdentifierType || (MetricsIdentifierType = {}));
/**
 * @public
 * The default namespaces to provide to the native `MetricsIdStore` for fetching and caching
 */
export var MetricsIdentifiersDefaultBagNamespaces;
(function (MetricsIdentifiersDefaultBagNamespaces) {
    MetricsIdentifiersDefaultBagNamespaces["client"] = "APPSTORE_ENGAGEMENT_CLIENT";
    MetricsIdentifiersDefaultBagNamespaces["user"] = "APPSTORE_ENGAGEMENT";
})(MetricsIdentifiersDefaultBagNamespaces || (MetricsIdentifiersDefaultBagNamespaces = {}));
export var MetricsIdentifiersPaymentBagNamespaces;
(function (MetricsIdentifiersPaymentBagNamespaces) {
    MetricsIdentifiersPaymentBagNamespaces["client"] = "APPSTORE_PAYMENTS_ENGAGEMENT_CLIENT";
    MetricsIdentifiersPaymentBagNamespaces["user"] = "APPSTORE_PAYMENTS_ENGAGEMENT";
})(MetricsIdentifiersPaymentBagNamespaces || (MetricsIdentifiersPaymentBagNamespaces = {}));
export var MetricsIdentifiersPersonalizationBagNamespaces;
(function (MetricsIdentifiersPersonalizationBagNamespaces) {
    MetricsIdentifiersPersonalizationBagNamespaces["user"] = "APPSTORE_PERSONALIZATION";
})(MetricsIdentifiersPersonalizationBagNamespaces || (MetricsIdentifiersPersonalizationBagNamespaces = {}));
/**
 * The payment context mappings for a metrics identifier key.
 */
export const paymentIdentifierContextMapping = {
    [MetricsIdentifierType.client]: {
        keyType: MetricsIdentifierType.client,
        bagNamespace: MetricsIdentifiersPaymentBagNamespaces.client,
        crossSyncDevice: false,
    },
    [MetricsIdentifierType.user]: {
        keyType: MetricsIdentifierType.user,
        bagNamespace: MetricsIdentifiersPaymentBagNamespaces.user,
        crossSyncDevice: true,
    },
};
/**
 * The default context mappings for a metrics identifier key.
 */
const defaultIdentifierContextMapping = {
    [MetricsIdentifierType.client]: {
        keyType: MetricsIdentifierType.client,
        bagNamespace: MetricsIdentifiersDefaultBagNamespaces.client,
        crossSyncDevice: false,
    },
    [MetricsIdentifierType.user]: {
        keyType: MetricsIdentifierType.user,
        bagNamespace: MetricsIdentifiersDefaultBagNamespaces.user,
        crossSyncDevice: true,
    },
};
/**
 * The personalization context mappings for a metrics identifier key.
 */
export const personalizationIdentifierContextMapping = {
    [MetricsIdentifierType.user]: {
        keyType: MetricsIdentifierType.user,
        bagNamespace: MetricsIdentifiersPersonalizationBagNamespaces.user,
        crossSyncDevice: true,
    },
};
/**
 * Represents a cache for metrics identifiers and fields.
 */
export class MetricsIdentifiersCache {
    /**
     * Constructs a new instance of the MetricsIdentifiersCache class.
     * @param identifierContextMapping - The mapping of identifier types to key contexts.
     */
    constructor(identifierContextMapping = defaultIdentifierContextMapping) {
        this.cachedMetricsIds = {};
        this.cachedMetricsFields = {};
        /**
         * A flag indicating whether a DSID fallback field should be added to the event fields.
         */
        this.shouldAddDsIdFallbackField = false;
        /**
         * The DSID of the currently logged in user on this JS request.
         */
        this.userDsId = null;
        this.identifierContextMapping = identifierContextMapping;
    }
    /**
     * Loads the values for the specified identifier types.
     * @param objectGraph - The object graph.
     * @param idTypes - The identifier types.
     * @returns A promise that resolves to an array of loaded values.
     */
    async loadValues(objectGraph, idTypes) {
        if (objectGraph.bag.isMetricsUserIdFallbackEnabled && !objectGraph.user.isUnderThirteen) {
            this.shouldAddDsIdFallbackField = true;
            this.userDsId = objectGraph.user.dsid;
        }
        else {
            this.shouldAddDsIdFallbackField = false;
            this.userDsId = null;
        }
        const loadedValues = [];
        for (const idType of idTypes) {
            const idTypeLoadedValues = await this.loadValuesForIdType(objectGraph, idType);
            loadedValues.push(idTypeLoadedValues);
        }
        for (const { idType, id, fields } of loadedValues) {
            if (id) {
                this.cachedMetricsIds[idType] = id;
            }
            if (fields) {
                this.cachedMetricsFields[idType] = fields;
            }
        }
    }
    /**
     * @param objectGraph The app store object graph for all our native dependencies
     * @param idType The type of id we're loading values for
     * @returns The MetricsIdStore values for this id type
     */
    async loadValuesForIdType(objectGraph, idType) {
        const returnValues = {
            idType,
        };
        const context = this.identifierContextMapping[idType];
        if (context) {
            try {
                const fields = await validation.context("MetricsIdentifiersCache:loadValues:metricsFields", async () => {
                    return await objectGraph.metricsIdentifiers.getMetricsFieldsForContexts([context]);
                });
                if (isSome(fields)) {
                    returnValues["fields"] = fields;
                    const extractedIdValue = fields[idType];
                    if (isSome(extractedIdValue) &&
                        typeof extractedIdValue === "string" &&
                        extractedIdValue.length > 0) {
                        returnValues["id"] = extractedIdValue;
                    }
                }
            }
            catch (error) {
                objectGraph.console.error(`Unable to fetch metrics fields for idType ${idType}`, error);
            }
            if (isNothing(returnValues["id"])) {
                try {
                    const id = await validation.context("MetricsIdentifiersCache:loadValues:metricsIdentifier", async () => {
                        return await objectGraph.metricsIdentifiers.getIdentifierForContext(context);
                    });
                    if (isSome(id)) {
                        returnValues["id"] = id;
                    }
                }
                catch (error) {
                    objectGraph.console.error(`Unable to fetch metrics identifier for idType ${idType}`, error);
                }
            }
        }
        return returnValues;
    }
    /**
     * Gets the metrics identifier for the specified identifier type.
     * @param idType - The identifier type.
     * @returns The metrics identifier, or undefined if not found.
     */
    getMetricsIdForType(idType) {
        return this.cachedMetricsIds[idType];
    }
    /**
     * Gets the metrics fields for the specified identifier types.
     * @param idTypes - The identifier types.
     * @returns The metrics fields, or undefined if not found.
     */
    getMetricsFieldsForTypes(idTypes) {
        const fieldsForTypes = idTypes.map((idType) => { var _a; return (_a = this.cachedMetricsFields[idType]) !== null && _a !== void 0 ? _a : {}; });
        const eventFields = Object.assign({}, ...fieldsForTypes);
        if (this.shouldAddDsIdFallbackField && idTypes.indexOf(MetricsIdentifierType.user) !== -1) {
            this.addDsIdFallbackFieldIfNecessary(eventFields);
        }
        return eventFields;
    }
    /**
     * Adds a DSID fallback field to the event fields if necessary.
     * @param eventFields - The event fields.
     */
    addDsIdFallbackFieldIfNecessary(eventFields) {
        const existingUserId = eventFields[MetricsIdentifierType.user];
        const isExistingUserIdInvalid = isNothing(existingUserId) ||
            typeof existingUserId !== "string" ||
            existingUserId.length === 0 ||
            existingUserId.length === MetricsIdentifiersCache.clientGeneratedUserIdLength;
        if (isExistingUserIdInvalid && isSome(this.userDsId) && this.userDsId.length > 0) {
            eventFields["dsId"] = this.userDsId;
        }
    }
    /**
     * Allows the setting of an app-level canonical account override for downstream metrics computations
     * @param canonicalAccountIdentifier - The identifier to use when operated with canonical account overides
     */
    setCanonicalAccountIdentifierOverride(canonicalAccountIdentifier) {
        if (canonicalAccountIdentifier.length >= 0) {
            this.cachedMetricsFields[MetricsIdentifierType.canonical] = {
                [MetricsIdentifierType.canonical]: canonicalAccountIdentifier,
            };
        }
    }
}
/**
 * The metatype of the MetricsIdentifiersCache class.
 */
MetricsIdentifiersCache.defaultMetatype = makeMetatype("app-store:metricsIdentifiersCache");
MetricsIdentifiersCache.paymentMetatype = makeMetatype("app-store:paymentMetricsIdentifiersCache");
MetricsIdentifiersCache.personalizationMetatype = makeMetatype("app-store:personalizationMetricsIdentifiersCache");
/**
 * The length of a client generated user ID.
 */
MetricsIdentifiersCache.clientGeneratedUserIdLength = 24;
export class MockMetricsIdentifiersCache extends MetricsIdentifiersCache {
    constructor() {
        super();
        this.cachedMetricsIds = {
            [MetricsIdentifierType.client]: "1a2b3c4d5e",
            [MetricsIdentifierType.user]: "1a2b3c4d5e",
        };
        this.cachedMetricsFields = {
            [MetricsIdentifierType.client]: {
                clientId: "1a2b3c4d5e",
            },
            [MetricsIdentifierType.user]: {
                userNs: "mockuserNs",
                userId: "1a2b3c4d5e",
                metricsId: 2,
            },
            [MetricsIdentifierType.canonical]: {
                canonicalAccountIdentifierOverride: "mockCanonicalAccountIdentifier",
            },
        };
    }
}
//# sourceMappingURL=metrics-identifiers-cache.js.map