@mhubcloud/tms_core 1.7.6 → 2.0.0-beta.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (44) hide show
  1. package/.eslintignore +3 -0
  2. package/.eslintrc.cjs +87 -0
  3. package/.prettierignore +3 -0
  4. package/.prettierrc +10 -0
  5. package/.vscode/extensions.json +12 -0
  6. package/.vscode/settings.json +52 -0
  7. package/dist/index.js +609 -0
  8. package/index.js +1 -0
  9. package/{lib → js/lib}/defaultPublisher.js +26 -24
  10. package/js/lib/utils.js +349 -0
  11. package/js/publishers/AffiliatePort.js +78 -0
  12. package/{publishers → js/publishers}/CJ.js +7 -5
  13. package/{publishers → js/publishers}/Facebook.js +6 -4
  14. package/{publishers → js/publishers}/GoogleAnalytics4.js +8 -6
  15. package/js/publishers/HttpPublisher.js +64 -0
  16. package/{publishers → js/publishers}/Piano.js +6 -4
  17. package/{publishers → js/publishers}/UniversalAnalytics.js +7 -5
  18. package/package.json +46 -29
  19. package/releasePlan.md +3 -0
  20. package/src/defaultPublisher.ts +132 -0
  21. package/src/index.ts +25 -0
  22. package/src/publishers/affiliatePort.ts +69 -0
  23. package/src/publishers/cj.ts +67 -0
  24. package/src/publishers/facebook.ts +49 -0
  25. package/src/publishers/googleAnalytics4.ts +60 -0
  26. package/src/publishers/piano.ts +71 -0
  27. package/src/publishers/universalAnalytics.ts +63 -0
  28. package/src/types/EventHubMessage.ts +8 -0
  29. package/src/types/EventPublisher.ts +9 -0
  30. package/src/types/PlatformPublisher.ts +19 -0
  31. package/src/types/UtilTypes.ts +1 -0
  32. package/src/types/global.d.ts +3 -0
  33. package/src/utils/utils.ts +358 -0
  34. package/tests/AffiliatePort.js +107 -85
  35. package/tests/CJ.js +144 -119
  36. package/tests/Facebook.js +124 -103
  37. package/tests/GoogleAnalytics4.js +82 -74
  38. package/tests/Piano.js +112 -99
  39. package/tests/UniversalAnalytics.js +90 -77
  40. package/tests/testUtils.js +7 -0
  41. package/tsconfig.eslint.json +43 -0
  42. package/tsconfig.json +26 -0
  43. package/lib/utils.js +0 -307
  44. package/publishers/AffiliatePort.js +0 -61
package/lib/utils.js DELETED
@@ -1,307 +0,0 @@
1
- const crypto = require('crypto');
2
- const Ajv = require("ajv");
3
- const fs = require('fs');
4
- const https = require('https');
5
-
6
- let aiClient;
7
- if (process.env.APPINSIGHTS_INSTRUMENTATIONKEY) {
8
- const appInsights = require("applicationinsights");
9
- appInsights
10
- .setup() //Set einvironmet variable APPINSIGHTS_INSTRUMENTATIONKEY, so setup() can be called w/o parameters
11
- .setAutoCollectDependencies(false)
12
- .setAutoCollectConsole(true, true)
13
- .setSendLiveMetrics(false)
14
- .setAutoCollectRequests(false)
15
- .setAutoCollectPerformance(false)
16
- .setUseDiskRetryCaching(false)
17
- .start();
18
- aiClient = appInsights.defaultClient;
19
- }
20
-
21
- /**
22
- * Base class for Event Publisher classes
23
- * Facilitates registration and configuration
24
- */
25
- class EventPublisherBase {
26
- /**
27
- * Createa new insatnce of the @see EventPublisherBase class
28
- * @param {Object} config Publisher configuration (in platform-specific format)
29
- */
30
- constructor(config) {
31
- this.config = config;
32
- }
33
-
34
- /**
35
- * Validates input data that they can be passed to mapper
36
- * @param {Object} data Input data to validate
37
- * @returns {boolean} Validation result
38
- */
39
- validate(data) {
40
- return true; //Override this method in custom publisher for custom validation
41
- }
42
-
43
- /**
44
- * Registers a new instance of @see EventPublisherBase -derived class with array of publishers
45
- * @param {EventPublisher[]} publishers Tha publishers array to register with
46
- * @param {Object} config Configuration to pass to new instance
47
- * Call this static method on @see EventPublisherBase -derived class.
48
- * It will create its instance and pass @param config to its constructor.
49
- * Than it will add resulting instance of @param publishers.
50
- */
51
- static register(publishers, config) {
52
- publishers.push(new this(config) /* Trick: Creates instance of the specific derived class `register` has been called on */);
53
- }
54
- }
55
-
56
- module.exports = {
57
- EventPublisherBase: EventPublisherBase,
58
-
59
- /**
60
- * Provides access to Application Insights logging (event reporting)
61
- * @type {appInsights.TelemetryClient|null}
62
- */
63
- appInsights: aiClient || null,
64
-
65
- /**
66
- * Computes SHA-256 hash of a string
67
- * @param {string} email The vaue to hash
68
- * @returns {string} @param email SHA-256 hash; returns email if it is 𝑓𝑎𝑙𝑠𝑒 (null, undefined etc.)
69
- */
70
- encodeEmail: function encodeEmail(email) {
71
- if (!email) return email;
72
- return crypto.createHash('sha256').update(email.toLowerCase(), "ascii").digest('hex').toLowerCase();
73
- },
74
-
75
- /**
76
- * Handles HTTP response from node-fetch
77
- * @param {*} response Node-fetch response object
78
- * @param {string} event for which response is
79
- * @returns {Object} Deserialized response JSON
80
- * Throws exception in case of response error code
81
- */
82
- handleResponse: async function handleResponse(response, event) {
83
- if (!response.ok) {
84
- throw new Error(`HTTP Error code: ${response.status}, event: ${event}, body: ${await response.text()}`);
85
- }
86
- const body = await response.text();
87
- try {
88
- return JSON.parse(body);
89
- } catch (ex) {
90
- return body;
91
- }
92
- },
93
-
94
- /**
95
- * Creates a deep copy of given object removing any properties or array items with undefined value
96
- * @param {*} obj Objec or array to copy. If value is neither array nor object it's returned as passed.
97
- * @returns Deep copy of @param obj (providing array or object has bee passed in). Any properties or array item with undefined value are skipped when making the copy, recursively. Returns @param obj untouched if neither array nor object has been passed in.
98
- */
99
- removeUndefined: function removeUndefined(obj) {
100
- let ret;
101
- if (obj instanceof Array) {
102
- ret = [];
103
- for (let i = 0; i < obj.length; i++) {
104
- if (obj[i] !== undefined)
105
- ret.push(removeUndefined(obj[i]));
106
- }
107
- } else if (obj instanceof Object) {
108
- ret = {};
109
- for (const prp in obj) {
110
- if (obj.hasOwnProperty(prp) && obj[prp] !== undefined)
111
- ret[prp] = removeUndefined(obj[prp]);
112
- }
113
- } else {
114
- return obj;
115
- }
116
- return ret;
117
- },
118
-
119
- /**
120
- * Validates an object against the schema it states or given schema
121
- * @param {Object} data An object to validate. The shema must be provided in its `$schema` property if ot passed in @param schema
122
- * @param {string} schemaSource Name of a folder to look for schemas. Schemas JSON format are looked for in subfolder `customizable/schemas` of given folder.
123
- * @param {string} schema Full URL id (i.e. URL starting with https://schema.measurementhub.net/), or just relative part of that URL to resolve schem in @param schemaSource`/customizable/schemas`
124
- * @returns {boolean} Validation result, true if successful, Exception if unsuccessfull
125
- */
126
- validate: function validate(data, schemaSource, schema = null) {
127
- schema = schema || data.$schema;
128
- if (!schema) {
129
- throw ("Data doesn't have schema and schema not passed");
130
- }
131
- if (schema.indexOf("https://schema.measurementhub.net/") !== 0 && (schema.indexOf("http://") === 0 || schema.indexOf("https://") == 0)) {
132
- throw (`Schema ${data.$schema} is not supported, only https://schema.measurementhub.net/... and schemas identified by relative URL shemas are supported`);
133
- }
134
- let parts = schema.split('/');
135
- if (parts.indexOf('..') >= 0) { //Directory traversal attack protection
136
- throw (`It's invalid for schema URI to contain '..' segment, such as in ${schema}`);
137
- }
138
- if (schema.indexOf("http://") === 0 || schema.indexOf("https://") == 0)
139
- parts = parts.slice(3);
140
-
141
- const schemaLocation = `${schemaSource}/customizable/schemas/${parts.join('/')}.json`;
142
- if (!fs.existsSync(schemaLocation)) {
143
- throw (`Schema file ${schemaLocation} not found`);
144
- }
145
-
146
- let schemaStr;
147
- try {
148
- schemaStr = fs.readFileSync(schemaLocation).toString();
149
- } catch (ex) {
150
- throw (`Failed to load schema ${schema}`);
151
- }
152
-
153
- let schemaObj;
154
- try {
155
- schemaObj = JSON.parse(schemaStr);
156
- } catch (ex) {
157
- throw (`Failed to deserialize ${schema}`);
158
- }
159
-
160
- const ajv = new Ajv({ allErrors: true });
161
- let validate;
162
- try {
163
- validate = ajv.compile(schemaObj);
164
- } catch (ex) {
165
- throw (`Failed to compile schema ${schema}`);
166
- }
167
-
168
- const valid = validate(data);
169
- if (!valid) {
170
- throw (`Schema vaidation failed for schema ${schema}, ${validate.errors.length} errors: ${JSON.stringify(validate.errors)}`);
171
- }
172
- return true;
173
- },
174
-
175
- /**
176
- * Enhances header before sending test request to secondary target (like Pipedream)
177
- * @param {Object} headers Request header dictionary. This contains the original headers and will be ehnanced.
178
- * @param {string} origUrl Original URL the request has been sent to
179
- * @param {*} origRequest The entire original request options
180
- * @param {*} origResponse Response recievend from original request
181
- */
182
- prepareTestRequestHeaders: function prepareTestRequestHeaders(headers, origUrl, origRequest, origResponse) {
183
- headers["x-mhub-orig-url"] = origUrl;
184
- headers["x-mhub-orig-method"] = origRequest.method;
185
- headers["x-mhub-orig-response-status-code"] = origResponse.status;
186
- headers["x-mhub-orig-response-status-message"] = origResponse.statusText;
187
- },
188
-
189
- /**
190
- * Extracts ad code from standardly structured event data (in legacy or new format)
191
- * @param {{ads:(LegacyAd|Ad)[]}} data Event data to extract ad code from. As you can see the `ads` field is accepted in 2 formats the first being legacy and the later being new one.
192
- * @param {string} adPlatform value of `data.ads.adPlatform` field to filter ad codes by platform (this is for new style data; ignored for legacy data)
193
- * @param {string} adCode value of `data.ads.adType` field to filter items in `data.ads` by (this is for legacy style data); als used for new style data to identify the main parameter from `data.ads.adCodes` to obtain
194
- * @param {(code: AdCodeInfo, ad: LegacyAd|Ad) => string|any} format If this custom function is provided it forats the code returned, so the function does not return object but string formated by this function. But nothing prevents it from returning object if the consumer can hanlde it.
195
- * @returns {AdCodeInfo|string|null|any} Ad code and time when it was recorded of newest event (by `visitAt`) with given ad code from @param data.ads; when @param format is provided returns string result of that function.
196
- */
197
- extractAdCode: function extractAdCode(data, adPlatform, adCode, format = null) {
198
- const ad = data.ads.filter(x => x.adType === adCode /*legacy*/ || x.adPlatform === adPlatform /*new*/)
199
- .sort((a, b) => b.visitAt - a.visitAt)[0];
200
- const code = ad?.adCode /*legacy*/ || (ad?.adCodes ? ad.adCodes[adCode] : null);
201
- if (code) {
202
- const ret = { code: code, visitAt: ad.visitAt };
203
- if (format) return format(ret, ad);
204
- return ret;
205
- }
206
- return null;
207
- },
208
-
209
- /**
210
- * Logs message to Azure Function context and to Application Insights (if configured)
211
- * @param {*} context Azure Function context
212
- * @param {0|1|2|3|4} level Application Insights log level according to https://docs.microsoft.com/en-us/dotnet/api/microsoft.applicationinsights.datacontracts.severitylevel?view=azure-dotnet
213
- * @param {string} message The message to log
214
- * @param {Object} properties Properties to pass to Application Insights trace
215
- */
216
- log2: function log2(context, level, message, properties) {
217
- context.log(message);
218
- aiClient?.trackTrace(
219
- {
220
- message: message,
221
- severityLevel: level,
222
- properties: properties
223
- }
224
- );
225
- },
226
-
227
- /**
228
- * Logs exception to Azure Function context and to Application Insights (if configured)
229
- * @param {object} exception
230
- */
231
- logException: function logException(exception) {
232
- console.log(exception);
233
- aiClient?.trackException({ exception: exception });
234
- //raise exception if it is running under mocha test
235
- if(typeof global.it === 'function'){
236
- throw(exception);
237
- }
238
- },
239
-
240
- /**
241
- * For http request. This function is for edge cases. Use Fetch if possible.
242
- * @param {object} params (hostname, port, path, method)
243
- * @param {object} postData
244
- * @returns
245
- */
246
- httpRequest: function httpRequest(params, postData) {
247
- return new Promise(function (resolve, reject) {
248
- var req = https.request(params, function (res) {
249
- // reject on bad status
250
- if (res.statusCode < 200 || res.statusCode >= 300) {
251
- return reject(new Error('statusCode=' + res.statusCode));
252
- }
253
- // cumulate data
254
- var body = [];
255
- res.on('data', function (chunk) {
256
- body.push(chunk);
257
- });
258
- // resolve on end
259
- res.on('end', function () {
260
- try {
261
- if (body.length > 0) {
262
- body = JSON.parse(Buffer.concat(body).toString());
263
- }
264
- } catch (e) {
265
- reject(e);
266
- }
267
- resolve(body);
268
- });
269
- });
270
- // reject on request error
271
- req.on('error', function (err) {
272
- // This is not a "Second reject", just a different sort of failure
273
- reject(err);
274
- });
275
- if (postData) {
276
- req.write(postData);
277
- }
278
- // IMPORTANT
279
- req.end();
280
- });
281
- },
282
-
283
- /**
284
- * Transforms an object to be flat, for instance for GA4
285
- * @param {object} event Event that is received
286
- * @param {sring} separator Separator that will be used to unnest the structure. The default separator is underscore _
287
- * @returns
288
- */
289
- flatten: function flatten(event, separator) {
290
- return Object.assign(
291
- {},
292
- ...function _flatten(o, separator = '_', parent) {
293
- return [].concat(...Object.keys(o)
294
- .map(key => {
295
- if (typeof o[key] === 'object' && o[key] !== null) {
296
- const newParent = parent ? (parent + separator + key) : key;
297
- return _flatten(o[key], separator, newParent);
298
- }
299
- else {
300
- const newKey = parent ? (parent + separator + key) : key;
301
- return { [newKey]: o[key] }
302
- }
303
- })
304
- );
305
- }(event, separator))
306
- }
307
- };
@@ -1,61 +0,0 @@
1
- const fetch = require('node-fetch');
2
- const utils = require("../lib/utils");
3
- const SOURCE = "f_AffiliatePort";
4
-
5
- module.exports = {
6
- /**
7
- * Processed data comming from EventHub to data for further processing
8
- * @param {Object} data The data comming from EventHub
9
- * @returns {Object} Data for further processing
10
- */
11
- parse: function parse(data, context) {
12
- //ConsumerBase.cs:ConsumeOneEventAsync
13
- data.enqueuedAt = context.test ? 1600000000000 : Date.now();
14
- return data;
15
- },
16
-
17
- /**
18
- * Publishes data to AffiliatePort
19
- * @param {{id: string, access_token: string}} config Publisher configuration
20
- * @param {Object} data Data in publisher-friendly format to be published
21
- * @param {string} event for which is it triggered
22
- */
23
- publish: async function publish(config, data, event) {
24
- data = utils.removeUndefined(data);
25
- const reqOpts = {
26
- method: "get"
27
- };
28
-
29
- for(let product of data.products){
30
-
31
- //https://tracking.affiliateclub.cz/aff_lsr?offer_id=OFFER_ID&adv_sub=TID_SUB_ID&amount=AMOUNT&transaction_id=TRANSACTION_ID&adv_sub2=CATEGORY&adv_sub3=MASTER_TYPE
32
- const url = "https://tracking.affiliateclub.cz/aff_lsr?offer_id=" + encodeURIComponent(config.offerId) + "&adv_sub=TID_" + data.orderId + "&amount=" + product.quantity * product.price + "&transaction_id=" + data.transactionID + "&adv_sub2=" + product.category + "&adv_sub3=" + product.masterType;
33
- const resp = await fetch(url, reqOpts);
34
-
35
- if (process.env.PUBLISHER_TESTURL) {
36
- try {
37
- utils.prepareTestRequestHeaders(reqOpts.headers, url, reqOpts, resp);
38
- await fetch(process.env.PUBLISHER_TESTURL + query, reqOpts);
39
- } catch { }
40
- }
41
-
42
- await utils.handleResponse(resp, event);
43
-
44
- console.log(`AffiliatePort - ${event} - sent`);
45
-
46
- }
47
- },
48
-
49
- /**
50
- * Validates an object against given schema
51
- * @param {Object} data An object to validate.
52
- * @param {string} schema Name of the schema. That's name of a file with `.schema.json` extension in `customizable/schemas` subfolder of current publisher folder
53
- * @returns {boolean} Validation result, true if successful, false if unsuccessfull (in which case more info is written to console)
54
- */
55
- validate: function validate(data, schema) {
56
- if (!schema) throw new Error("Schema parameters not provided");
57
- if (schema.indexOf("/") >= 0) throw new Error("Schema must be provided as schema name, not schema path");
58
- //More validation done by utils.validate
59
- return utils.validate(data, SOURCE, schema);
60
- }
61
- };