@crimson-education/browser-logger 2.0.2-cognito.2 → 2.0.2

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 (57) hide show
  1. package/README.md +127 -1
  2. package/lib/index.d.ts +69 -13
  3. package/lib/index.d.ts.map +1 -1
  4. package/lib/index.js +130 -57
  5. package/lib/index.js.map +1 -1
  6. package/lib/reporters/amplifyReporter.d.ts +40 -14
  7. package/lib/reporters/amplifyReporter.d.ts.map +1 -1
  8. package/lib/reporters/amplifyReporter.js +4 -11
  9. package/lib/reporters/amplifyReporter.js.map +1 -1
  10. package/lib/reporters/amplifyReporter.test.js +0 -11
  11. package/lib/reporters/amplifyReporter.test.js.map +1 -1
  12. package/lib/reporters/datadogReporter.d.ts +58 -10
  13. package/lib/reporters/datadogReporter.d.ts.map +1 -1
  14. package/lib/reporters/datadogReporter.js +26 -18
  15. package/lib/reporters/datadogReporter.js.map +1 -1
  16. package/lib/reporters/gtmReporter.d.ts +3 -2
  17. package/lib/reporters/gtmReporter.d.ts.map +1 -1
  18. package/lib/reporters/gtmReporter.js +24 -5
  19. package/lib/reporters/gtmReporter.js.map +1 -1
  20. package/lib/reporters/index.d.ts +3 -28
  21. package/lib/reporters/index.d.ts.map +1 -1
  22. package/lib/reporters/index.js +17 -0
  23. package/lib/reporters/index.js.map +1 -1
  24. package/lib/types/index.d.ts +3 -0
  25. package/lib/types/index.d.ts.map +1 -0
  26. package/lib/types/index.js +19 -0
  27. package/lib/types/index.js.map +1 -0
  28. package/lib/{types.d.ts → types/logger.d.ts} +4 -15
  29. package/lib/types/logger.d.ts.map +1 -0
  30. package/lib/{types.js → types/logger.js} +1 -1
  31. package/lib/types/logger.js.map +1 -0
  32. package/lib/types/reporter.d.ts +103 -0
  33. package/lib/types/reporter.d.ts.map +1 -0
  34. package/lib/types/reporter.js +3 -0
  35. package/lib/types/reporter.js.map +1 -0
  36. package/lib/utils.d.ts +5 -1
  37. package/lib/utils.d.ts.map +1 -1
  38. package/lib/utils.js +8 -3
  39. package/lib/utils.js.map +1 -1
  40. package/lib/utils.test.d.ts +2 -0
  41. package/lib/utils.test.d.ts.map +1 -0
  42. package/lib/utils.test.js +19 -0
  43. package/lib/utils.test.js.map +1 -0
  44. package/package.json +5 -4
  45. package/src/index.ts +148 -57
  46. package/src/reporters/amplifyReporter.test.ts +1 -14
  47. package/src/reporters/amplifyReporter.ts +53 -23
  48. package/src/reporters/datadogReporter.ts +93 -17
  49. package/src/reporters/gtmReporter.ts +39 -7
  50. package/src/reporters/index.ts +3 -32
  51. package/src/types/index.ts +2 -0
  52. package/src/{types.ts → types/logger.ts} +3 -13
  53. package/src/types/reporter.ts +107 -0
  54. package/src/utils.test.ts +18 -0
  55. package/src/utils.ts +16 -1
  56. package/lib/types.d.ts.map +0 -1
  57. package/lib/types.js.map +0 -1
@@ -0,0 +1,103 @@
1
+ import { ReporterType } from '..';
2
+ import { LogLevel, Metadata } from './logger';
3
+ export declare type Metrics = Record<string, number>;
4
+ export declare type ServiceInfo = {
5
+ /** The Application's name. */
6
+ service: string;
7
+ /** The Application's Environment */
8
+ environment: string;
9
+ /** The Application's Version. */
10
+ version: string;
11
+ /**
12
+ * Default metadata to add to Reporter events.
13
+ */
14
+ defaultMetadata?: Metadata;
15
+ };
16
+ export declare type ReportUser = {
17
+ id: string;
18
+ email?: string;
19
+ username?: string;
20
+ name?: string;
21
+ };
22
+ export declare type ReportError = Error | string;
23
+ export interface ReporterFilters {
24
+ /**
25
+ * Send only to these Reporters.
26
+ */
27
+ toReporters?: ReporterType[];
28
+ /**
29
+ * Don't send to these Reporters.
30
+ */
31
+ excludeReporters?: ReporterType[];
32
+ }
33
+ export interface ReporterEvent extends ReporterFilters {
34
+ /**
35
+ * The Severity of this event.
36
+ */
37
+ level?: LogLevel;
38
+ /**
39
+ * The event message/name.
40
+ */
41
+ message: string;
42
+ /**
43
+ * Event metadata.
44
+ */
45
+ metadata?: Metadata | undefined;
46
+ /**
47
+ * Event tags, if supported by the Reporter. (Otherwise, they will be added to metadata)
48
+ */
49
+ tags?: Metadata | undefined;
50
+ /**
51
+ * Event metrics, if supported by the Reporter. (Otherwise, they will be added to metadata)
52
+ * Metrics are numbers, and are used for aggregations.
53
+ */
54
+ metrics?: Metrics | undefined;
55
+ }
56
+ export interface TrackedReporterEvent extends ReporterEvent {
57
+ /**
58
+ * The time this event was created.
59
+ */
60
+ occurred: Date;
61
+ }
62
+ export interface ReporterBreadcrumb extends ReporterFilters {
63
+ /**
64
+ * The breadcrumb event message/name.
65
+ */
66
+ message: string;
67
+ /**
68
+ * The category of this breadcrumb (Useful for filtering out in specific reporters).
69
+ */
70
+ category?: string | undefined;
71
+ /**
72
+ * Breadcrumb metadata.
73
+ */
74
+ metadata?: Metadata | undefined;
75
+ }
76
+ export interface ReporterConfigBase {
77
+ /**
78
+ * Categories of breadcrumbs to ignore sending to Amplify.
79
+ * This is useful to prevent data of no use for amplify.
80
+ */
81
+ ignoreBreadcrumbCategories?: string[];
82
+ /**
83
+ * Ignore specific metadata keys from being sent to Amplify.
84
+ * This can be a regular expression, or a string to exact match.
85
+ * This is useful to prevent data of no use for amplify, or if the data keys are too long.
86
+ */
87
+ ignoreMetadataPatterns?: (string | RegExp)[];
88
+ }
89
+ /**
90
+ * A Reporter is a service that can receive Analytics data.
91
+ */
92
+ export interface IReporter {
93
+ trackEvent(event: ReporterEvent): void;
94
+ addBreadcrumb(breadcrumb: ReporterBreadcrumb): void;
95
+ addMetadata(metadata: Metadata): void;
96
+ setUser(user: ReportUser | null): void;
97
+ setRouteName(routeName: string): void;
98
+ setPageName(pageName: string): void;
99
+ reportError?(error: ReportError, metadata?: Metadata): void;
100
+ recordSession?(): void;
101
+ recordSessionStop?(): void;
102
+ }
103
+ //# sourceMappingURL=reporter.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"reporter.d.ts","sourceRoot":"","sources":["../../src/types/reporter.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,YAAY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AM,CAAC;IAChB;;OAEG;IACH,QAAQ,CAAC,EAAE,MAAM,GAAG,SAAS,CAAC;IAC9B;;OAEG;IACH,QAAQ,CAAC,EAAE,QAAQ,GAAG,SAAS,CAAC;CACjC;AAED,MAAM,WAAW,kBAAkB;IACjC;;;OAGG;IACH,0BAA0B,CAAC,EAAE,MAAM,EAAE,CAAC;IACtC;;;;OAIG;IACH,sBAAsB,CAAC,EAAE,CAAC,MAAM,GAAG,MAAM,CAAC,EAAE,CAAC;CAC9C;AAED;;GAEG;AACH,MAAM,WAAW,SAAS;IACxB,UAAU,CAAC,KAAK,EAAE,aAAa,GAAG,IAAI,CAAC;IACvC,aAAa,CAAC,UAAU,EAAE,kBAAkB,GAAG,IAAI,CAAC;IACpD,WAAW,CAAC,QAAQ,EAAE,QAAQ,GAAG,IAAI,CAAC;IACtC,OAAO,CAAC,IAAI,EAAE,UAAU,GAAG,IAAI,GAAG,IAAI,CAAC;IACvC,YAAY,CAAC,SAAS,EAAE,MAAM,GAAG,IAAI,CAAC;IACtC,WAAW,CAAC,QAAQ,EAAE,MAAM,GAAG,IAAI,CAAC;IACpC,WAAW,CAAC,CAAC,KAAK,EAAE,WAAW,EAAE,QAAQ,CAAC,EAAE,QAAQ,GAAG,IAAI,CAAC;IAC5D,aAAa,CAAC,IAAI,IAAI,CAAC;IACvB,iBAAiB,CAAC,IAAI,IAAI,CAAC;CAC5B"}
@@ -0,0 +1,3 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ //# sourceMappingURL=reporter.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"reporter.js","sourceRoot":"","sources":["../../src/types/reporter.ts"],"names":[],"mappings":""}
package/lib/utils.d.ts CHANGED
@@ -1,5 +1,9 @@
1
- import { ILogger, Metadata } from '.';
1
+ import { ILogger, Metadata } from './types';
2
+ export declare type AttributeMap = Record<string, string[] | string | null>;
2
3
  export declare function consoleLogger(name?: string, options?: {
3
4
  metadata?: Metadata;
4
5
  }): ILogger;
6
+ export declare function filterAttributeMap(attributes: AttributeMap | Record<string, string>, ignorePatterns: (string | RegExp)[]): {
7
+ [k: string]: string | string[] | null;
8
+ };
5
9
  //# sourceMappingURL=utils.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"utils.d.ts","sourceRoot":"","sources":["../src/utils.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,OAAO,EAAuC,QAAQ,EAAY,MAAM,GAAG,CAAC;AAErF,wBAAgB,aAAa,CAAC,IAAI,CAAC,EAAE,MAAM,EAAE,OAAO,CAAC,EAAE;IAAE,QAAQ,CAAC,EAAE,QAAQ,CAAA;CAAE,GAAG,OAAO,CA6CvF"}
1
+ {"version":3,"file":"utils.d.ts","sourceRoot":"","sources":["../src/utils.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,OAAO,EAAY,QAAQ,EAAY,MAAM,SAAS,CAAC;AAEhE,oBAAY,YAAY,GAAG,MAAM,CAAC,MAAM,EAAE,MAAM,EAAE,GAAG,MAAM,GAAG,IAAI,CAAC,CAAC;AAEpE,wBAAgB,aAAa,CAAC,IAAI,CAAC,EAAE,MAAM,EAAE,OAAO,CAAC,EAAE;IAAE,QAAQ,CAAC,EAAE,QAAQ,CAAA;CAAE,GAAG,OAAO,CA6CvF;AAED,wBAAgB,kBAAkB,CAChC,UAAU,EAAE,YAAY,GAAG,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,EACjD,cAAc,EAAE,CAAC,MAAM,GAAG,MAAM,CAAC,EAAE;;EASpC"}
package/lib/utils.js CHANGED
@@ -1,9 +1,9 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.consoleLogger = void 0;
3
+ exports.filterAttributeMap = exports.consoleLogger = void 0;
4
4
  /* eslint-disable @typescript-eslint/no-unused-vars */
5
5
  /* eslint-disable @typescript-eslint/no-explicit-any */
6
- const _1 = require(".");
6
+ const types_1 = require("./types");
7
7
  function consoleLogger(name, options) {
8
8
  const logger = {
9
9
  startTimer() {
@@ -13,7 +13,7 @@ function consoleLogger(name, options) {
13
13
  done: (args) => {
14
14
  var _a, _b;
15
15
  const duration = new Date().getTime() - start.getTime();
16
- logger[(_a = args === null || args === void 0 ? void 0 : args.level) !== null && _a !== void 0 ? _a : _1.LogLevel.Info](`${(_b = args === null || args === void 0 ? void 0 : args.message) !== null && _b !== void 0 ? _b : 'Timer'} completed in: ${duration}`);
16
+ logger[(_a = args === null || args === void 0 ? void 0 : args.level) !== null && _a !== void 0 ? _a : types_1.LogLevel.Info](`${(_b = args === null || args === void 0 ? void 0 : args.message) !== null && _b !== void 0 ? _b : 'Timer'} completed in: ${duration}`);
17
17
  return true;
18
18
  },
19
19
  };
@@ -44,4 +44,9 @@ function consoleLogger(name, options) {
44
44
  return logger;
45
45
  }
46
46
  exports.consoleLogger = consoleLogger;
47
+ function filterAttributeMap(attributes, ignorePatterns) {
48
+ const entries = Object.entries(attributes);
49
+ return Object.fromEntries(entries.filter(([key]) => !ignorePatterns.some((pattern) => (typeof pattern === 'string' ? pattern === key : pattern.test(key)))));
50
+ }
51
+ exports.filterAttributeMap = filterAttributeMap;
47
52
  //# sourceMappingURL=utils.js.map
package/lib/utils.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"utils.js","sourceRoot":"","sources":["../src/utils.ts"],"names":[],"mappings":";;;AAAA,sDAAsD;AACtD,uDAAuD;AACvD,wBAAqF;AAErF,SAAgB,aAAa,CAAC,IAAa,EAAE,OAAiC;IAC5E,MAAM,MAAM,GAAY;QACtB,UAAU;YACR,MAAM,KAAK,GAAG,IAAI,IAAI,EAAE,CAAC;YAEzB,OAAO;gBACL,MAAM,EAAE,IAAI;gBACZ,IAAI,EAAE,CAAC,IAAI,EAAE,EAAE;;oBACb,MAAM,QAAQ,GAAG,IAAI,IAAI,EAAE,CAAC,OAAO,EAAE,GAAG,KAAK,CAAC,OAAO,EAAE,CAAC;oBACxD,MAAM,CAAC,MAAA,IAAI,aAAJ,IAAI,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,CAAC;QAChB,CAAC;QAED,KAAK,EAAE,CAAC,GAAG,IAAW,EAAE,EAAE;YACxB,OAAO,CAAC,KAAK,CAAC,GAAG,IAAI,CAAC,CAAC;YACvB,OAAO,MAAM,CAAC;QAChB,CAAC;KACF,CAAC;IAEF,OAAO,MAAM,CAAC;AAChB,CAAC;AA7CD,sCA6CC;AAED,SAAgB,kBAAkB,CAChC,UAAiD,EACjD,cAAmC;IAEnC,MAAM,OAAO,GAAG,MAAM,CAAC,OAAO,CAAC,UAAU,CAAC,CAAC;IAE3C,OAAO,MAAM,CAAC,WAAW,CACvB,OAAO,CAAC,MAAM,CACZ,CAAC,CAAC,GAAG,CAAC,EAAE,EAAE,CAAC,CAAC,cAAc,CAAC,IAAI,CAAC,CAAC,OAAO,EAAE,EAAE,CAAC,CAAC,OAAO,OAAO,KAAK,QAAQ,CAAC,CAAC,CAAC,OAAO,KAAK,GAAG,CAAC,CAAC,CAAC,OAAO,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC,CAAC,CAClH,CACF,CAAC;AACJ,CAAC;AAXD,gDAWC"}
@@ -0,0 +1,2 @@
1
+ export {};
2
+ //# sourceMappingURL=utils.test.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"utils.test.d.ts","sourceRoot":"","sources":["../src/utils.test.ts"],"names":[],"mappings":""}
@@ -0,0 +1,19 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ const utils_1 = require("./utils");
4
+ describe('utils', () => {
5
+ describe('filterAttributeMap', () => {
6
+ it('should remove attributes which match the ignore patterns', () => {
7
+ const inputAttributeMap = {
8
+ includeme: '5',
9
+ excludeme: 'false',
10
+ differentProp: 'boo',
11
+ };
12
+ const filtered = (0, utils_1.filterAttributeMap)(inputAttributeMap, [/exclude/g, /Prop/g]);
13
+ expect(filtered['includeme']).toBeTruthy();
14
+ expect(filtered['excludeme']).toBeFalsy();
15
+ expect(filtered['differentProp']).toBeFalsy();
16
+ });
17
+ });
18
+ });
19
+ //# sourceMappingURL=utils.test.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"utils.test.js","sourceRoot":"","sources":["../src/utils.test.ts"],"names":[],"mappings":";;AAAA,mCAA6C;AAE7C,QAAQ,CAAC,OAAO,EAAE,GAAG,EAAE;IACrB,QAAQ,CAAC,oBAAoB,EAAE,GAAG,EAAE;QAClC,EAAE,CAAC,0DAA0D,EAAE,GAAG,EAAE;YAClE,MAAM,iBAAiB,GAAG;gBACxB,SAAS,EAAE,GAAG;gBACd,SAAS,EAAE,OAAO;gBAClB,aAAa,EAAE,KAAK;aACrB,CAAC;YAEF,MAAM,QAAQ,GAAG,IAAA,0BAAkB,EAAC,iBAAiB,EAAE,CAAC,UAAU,EAAE,OAAO,CAAC,CAAC,CAAC;YAC9E,MAAM,CAAC,QAAQ,CAAC,WAAW,CAAC,CAAC,CAAC,UAAU,EAAE,CAAC;YAC3C,MAAM,CAAC,QAAQ,CAAC,WAAW,CAAC,CAAC,CAAC,SAAS,EAAE,CAAC;YAC1C,MAAM,CAAC,QAAQ,CAAC,eAAe,CAAC,CAAC,CAAC,SAAS,EAAE,CAAC;QAChD,CAAC,CAAC,CAAC;IACL,CAAC,CAAC,CAAC;AACL,CAAC,CAAC,CAAC"}
package/package.json CHANGED
@@ -1,15 +1,16 @@
1
1
  {
2
2
  "name": "@crimson-education/browser-logger",
3
- "version": "2.0.2-cognito.2",
3
+ "version": "2.0.2",
4
4
  "description": "An abstract logger and reporting utility for browser environments",
5
5
  "scripts": {
6
6
  "prepack": "npm run build",
7
7
  "clean": "rimraf lib",
8
8
  "prebuild": "npm run clean",
9
9
  "build": "tsc",
10
+ "ts-check": "tsc --noEmit",
10
11
  "lint": "eslint src",
11
12
  "fixlint": "npm run lint -- --fix",
12
- "test": "jest --config jest.config.js --passWithNoTests"
13
+ "test": "jest --config jest.config.js"
13
14
  },
14
15
  "repository": {
15
16
  "type": "git",
@@ -28,8 +29,8 @@
28
29
  "homepage": "https://github.com/crimson-education/browser-logger#readme",
29
30
  "dependencies": {
30
31
  "@aws-amplify/analytics": "^5.2.22",
31
- "@datadog/browser-logs": "^4.4.0",
32
- "@datadog/browser-rum": "^4.4.0"
32
+ "@datadog/browser-logs": "^4.21.0",
33
+ "@datadog/browser-rum": "^4.21.0"
33
34
  },
34
35
  "devDependencies": {
35
36
  "@crimson-education/eslint-config": "^2.1.0",
package/src/index.ts CHANGED
@@ -1,14 +1,32 @@
1
- import { ILogger, Metadata, ReportError, ReportUser, ServiceInfo } from './types';
2
- import { IReporter, ReporterBreadcrumb, ReporterEvent, TrackedReporterEvent } from './reporters';
1
+ import {
2
+ ILogger,
3
+ IReporter,
4
+ Metadata,
5
+ ReporterBreadcrumb,
6
+ ReporterEvent,
7
+ ReporterFilters,
8
+ ReportError,
9
+ ReportUser,
10
+ ServiceInfo,
11
+ TrackedReporterEvent,
12
+ } from './types';
3
13
  import { consoleLogger } from './utils';
4
- import { datadogLogger, datadogReporter, DatadogReporterConfig } from './reporters/datadogReporter';
5
- import { gtmReporter } from './reporters/gtmReporter';
6
- import { amplifyReporter, AmplifyReporterConfig } from './reporters/amplifyReporter';
14
+ import {
15
+ datadogLogger,
16
+ datadogReporter,
17
+ DatadogReporterConfig,
18
+ gtmReporter,
19
+ GTMReporterConfig,
20
+ amplifyReporter,
21
+ AmplifyReporterConfig,
22
+ } from './reporters';
7
23
 
8
24
  export * from './types';
9
25
 
10
26
  export let logger: ILogger | null = null;
11
27
 
28
+ export type ReporterType = 'datadog' | 'gtm' | 'amplify';
29
+
12
30
  export type ReporterConfig = ServiceInfo & {
13
31
  // Datadog
14
32
  datadog?: DatadogReporterConfig;
@@ -17,31 +35,35 @@ export type ReporterConfig = ServiceInfo & {
17
35
  amplify?: AmplifyReporterConfig;
18
36
 
19
37
  // Google Tag Manager
20
- gtm?: boolean;
38
+ gtm?: true | GTMReporterConfig;
21
39
  };
22
40
 
23
- const reporters: IReporter[] = [];
41
+ const reporters: Partial<Record<ReporterType, IReporter>> = {};
24
42
  let initialized = false;
25
43
  let ddInitialized = false;
26
44
 
45
+ /**
46
+ * Initializes the logger and reporters.
47
+ * @param config Reporter config options.
48
+ */
27
49
  export function init(config: ReporterConfig) {
28
50
  initialized = true;
29
51
 
30
52
  if (config.datadog) {
31
- reporters.push(datadogReporter(config, config.datadog));
53
+ reporters['datadog'] = datadogReporter(config, config.datadog);
32
54
  ddInitialized = true;
33
55
  }
34
56
 
35
57
  if (config.amplify) {
36
- reporters.push(amplifyReporter(config, config.amplify));
58
+ reporters['amplify'] = amplifyReporter(config, config.amplify);
37
59
  }
38
60
 
39
61
  if (config.gtm) {
40
- reporters.push(gtmReporter());
62
+ reporters['gtm'] = gtmReporter(config, typeof config.gtm === 'boolean' ? {} : config.gtm);
41
63
  }
42
64
 
43
65
  if (config.defaultMetadata) {
44
- for (const reporter of reporters) {
66
+ for (const reporter of Object.values(reporters)) {
45
67
  reporter.addMetadata(config.defaultMetadata);
46
68
  }
47
69
  }
@@ -49,87 +71,156 @@ export function init(config: ReporterConfig) {
49
71
  logger = createLogger('Reporter');
50
72
  }
51
73
 
74
+ /**
75
+ * Gets reporters, optionally with filters.
76
+ * @param filters Filters to remove or specify specific reporters.
77
+ * @returns Selected reporters, or all registered reporters.
78
+ */
79
+ function getReporters(filters?: ReporterFilters) {
80
+ let result = Object.entries(reporters);
81
+ if (filters?.excludeReporters) {
82
+ result = result.filter(([key]) => !filters?.excludeReporters?.includes(key as ReporterType));
83
+ }
84
+ if (filters?.toReporters) {
85
+ result = result.filter(([key]) => filters?.toReporters?.includes(key as ReporterType));
86
+ }
87
+ return result.map(([, reporter]) => reporter);
88
+ }
89
+
90
+ /**
91
+ * Tracks an Analytics event.
92
+ */
52
93
  export function trackEvent(event: ReporterEvent): void {
53
- for (const reporter of reporters) {
94
+ for (const reporter of getReporters(event)) {
54
95
  reporter.trackEvent(event);
55
96
  }
56
97
  }
57
98
 
99
+ /**
100
+ * Tracks an Analytics event, recording the time since the last event, if available.
101
+ */
102
+ export function trackEventSinceLastAction(event: ReporterEvent): void {
103
+ const lastEvent = getLastTrackedEvent();
104
+ if (lastEvent) {
105
+ const duration = new Date().getTime() - lastEvent.occurred.getTime();
106
+ trackEvent({
107
+ ...event,
108
+ metadata: {
109
+ ...event.metadata,
110
+ lastEventName: lastEvent.message,
111
+ timeSinceLastEvent: duration,
112
+ },
113
+ });
114
+ } else {
115
+ trackEvent(event);
116
+ }
117
+ sessionStorage.setItem('loggerLastEvent', JSON.stringify({ ...event, occurred: new Date() }));
118
+ }
119
+
120
+ /**
121
+ * Gets the last tracked event, if available.
122
+ */
123
+ export function getLastTrackedEvent(): TrackedReporterEvent | null {
124
+ const eventStr = sessionStorage.getItem('loggerLastEvent');
125
+ if (!eventStr) return null;
126
+
127
+ const event: TrackedReporterEvent = JSON.parse(eventStr);
128
+ event.occurred = new Date(event.occurred);
129
+ return event;
130
+ }
131
+
132
+ /**
133
+ * Breadcrumbs to create a trail of events that happened prior to an issue.
134
+ * These events are very similar to traditional logs, but can record more rich structured data.
135
+ */
58
136
  export function addBreadcrumb(breadcrumb: ReporterBreadcrumb): void {
59
- for (const reporter of reporters) {
137
+ for (const reporter of getReporters(breadcrumb)) {
60
138
  reporter.addBreadcrumb(breadcrumb);
61
139
  }
62
140
  }
63
141
 
64
- export function addMetadata(metadata: Metadata): void {
65
- for (const reporter of reporters) {
142
+ /**
143
+ * Adds global metadata to all events.
144
+ * @param metadata Metadata to add.
145
+ * @param filters Optional filters to specify which reporters to add metadata to.
146
+ */
147
+ export function addMetadata(metadata: Metadata, filters?: ReporterFilters): void {
148
+ for (const reporter of getReporters(filters)) {
66
149
  reporter.addMetadata(metadata);
67
150
  }
68
151
  }
69
152
 
70
- export function setUser(user: ReportUser | null): void {
71
- for (const reporter of reporters) {
153
+ /**
154
+ * Sets the user information in Analytics.
155
+ * @param user User information, or null to clear.
156
+ * @param filters Optional filters to specify which reporters to set the user for.
157
+ */
158
+ export function setUser(user: ReportUser | null, filters?: ReporterFilters): void {
159
+ for (const reporter of getReporters(filters)) {
72
160
  reporter.setUser(user);
73
161
  }
74
162
  }
75
163
 
76
- export function setRouteName(routeName: string): void {
77
- for (const reporter of reporters) {
164
+ /**
165
+ * Sets the route name in Analytics.
166
+ * Some Analytics services use this differentiate SPA Route vs Page changes.
167
+ * @param routeName Name of the Route.
168
+ * @param filters Optional filters to specify which reporters to set the route name for.
169
+ */
170
+ export function setRouteName(routeName: string, filters?: ReporterFilters): void {
171
+ for (const reporter of getReporters(filters)) {
78
172
  reporter.setRouteName(routeName);
79
173
  }
80
174
  }
81
175
 
82
- export function setPageName(pageName: string): void {
83
- for (const reporter of reporters) {
176
+ /**
177
+ * Sets the page name in Analytics.
178
+ * @param pageName Name of the Page.
179
+ * @param filters Optional filters to specify which reporters to set the page name for.
180
+ */
181
+ export function setPageName(pageName: string, filters?: ReporterFilters): void {
182
+ for (const reporter of getReporters(filters)) {
84
183
  reporter.setPageName(pageName);
85
184
  }
86
185
  }
87
186
 
88
- export function reportError(error: ReportError, metadata?: Metadata): void {
89
- for (const reporter of reporters) {
90
- reporter.reportError(error, metadata);
187
+ /**
188
+ * Reports an Error in Reporters that support error tracking.
189
+ * @param error Error data.
190
+ * @param metadata Metadata to add to the error.
191
+ * @param filters Optional filters to specify which reporters to report the error to.
192
+ */
193
+ export function reportError(error: ReportError, metadata?: Metadata, filters?: ReporterFilters): void {
194
+ for (const reporter of getReporters(filters)) {
195
+ reporter.reportError?.(error, metadata);
91
196
  }
92
197
  }
93
198
 
94
- export function recordSession(): void {
95
- for (const reporter of reporters) {
96
- reporter.recordSession();
199
+ /**
200
+ * Starts a session recording in Analytics, e.g. RUM Session Replay
201
+ * @param filters Optional filters to specify which reporters to start a session recording for.
202
+ */
203
+ export function recordSession(filters?: ReporterFilters): void {
204
+ for (const reporter of getReporters(filters)) {
205
+ reporter.recordSession?.();
97
206
  }
98
207
  }
99
208
 
100
- export function recordSessionStop(): void {
101
- for (const reporter of reporters) {
102
- reporter.recordSessionStop();
209
+ /**
210
+ * Stops a session recording in Analytics, e.g. RUM Session Replay
211
+ * @param filters Optional filters to specify which reporters to stop a session recording for.
212
+ */
213
+ export function recordSessionStop(filters?: ReporterFilters): void {
214
+ for (const reporter of getReporters(filters)) {
215
+ reporter.recordSessionStop?.();
103
216
  }
104
217
  }
105
218
 
106
- export function trackEventSinceLastAction(event: ReporterEvent): void {
107
- const lastEvent = getLastTrackedEvent();
108
- if (lastEvent) {
109
- const duration = new Date().getTime() - lastEvent.occurred.getTime();
110
- trackEvent({
111
- ...event,
112
- metadata: {
113
- ...event.metadata,
114
- lastEventName: lastEvent.message,
115
- timeSinceLastEvent: duration,
116
- },
117
- });
118
- } else {
119
- trackEvent(event);
120
- }
121
- sessionStorage.setItem('loggerLastEvent', JSON.stringify({ ...event, occurred: new Date() }));
122
- }
123
-
124
- export function getLastTrackedEvent(): TrackedReporterEvent | null {
125
- const eventStr = sessionStorage.getItem('loggerLastEvent');
126
- if (!eventStr) return null;
127
-
128
- const event: TrackedReporterEvent = JSON.parse(eventStr);
129
- event.occurred = new Date(event.occurred);
130
- return event;
131
- }
132
-
219
+ /**
220
+ * Creates a Logger instance.
221
+ * @param name Name of the Logger.
222
+ * @param options Logger configuration options.
223
+ */
133
224
  export function createLogger(name?: string, options?: { metadata?: Metadata }): ILogger {
134
225
  if (!initialized) {
135
226
  throw new Error('You must call init on BrowserLogger before creating a logger');
@@ -1,4 +1,4 @@
1
- import { asAttributeMap, filterAttributeMap } from './amplifyReporter';
1
+ import { asAttributeMap } from './amplifyReporter';
2
2
 
3
3
  describe('amplifyReporter', () => {
4
4
  it('should convert all attribute values to arrays of strings', () => {
@@ -58,17 +58,4 @@ describe('amplifyReporter', () => {
58
58
  const attributeMap = asAttributeMap(testMetadata, false);
59
59
  expect(attributeMap.a).toEqual('5');
60
60
  });
61
-
62
- it('should remove attributes which match the ignore patterns', () => {
63
- const inputAttributeMap = {
64
- includeme: '5',
65
- excludeme: 'false',
66
- differentProp: 'boo',
67
- };
68
-
69
- const filtered = filterAttributeMap(inputAttributeMap, [/exclude/g, /Prop/g]);
70
- expect(filtered['includeme']).toBeTruthy();
71
- expect(filtered['excludeme']).toBeFalsy();
72
- expect(filtered['differentProp']).toBeFalsy();
73
- });
74
61
  });
@@ -1,26 +1,67 @@
1
- import { IReporter, ReporterBreadcrumb, ReporterEvent } from '.';
2
- import { Metadata, ReportUser, ServiceInfo } from '../types';
1
+ import {
2
+ IReporter,
3
+ Metadata,
4
+ ReporterBreadcrumb,
5
+ ReporterConfigBase,
6
+ ReporterEvent,
7
+ ReportUser,
8
+ ServiceInfo,
9
+ } from '../types';
3
10
  import { Auth } from '@aws-amplify/auth';
4
11
  import { Analytics } from '@aws-amplify/analytics';
12
+ import { AttributeMap, filterAttributeMap } from '../utils';
5
13
 
6
- export type AmplifyReporterConfig = {
14
+ export interface AmplifyReporterConfig extends ReporterConfigBase {
15
+ /**
16
+ * AWS Region for Amplify.
17
+ */
7
18
  region: string;
8
19
  /**
9
- * The Identity Pool ID to use for reporting, if set to false, Auth.configure is not called.
20
+ * The Identity Pool Id to use for reporting, if set to false, Auth.configure is not called.
10
21
  * This must be called manually for the reporter to work.
11
22
  */
12
23
  identityPoolId: string | false;
24
+ /**
25
+ * The Pinpoint App Id to report to.
26
+ */
13
27
  analyticsAppId: string;
28
+ /**
29
+ * The Cognito User Pool to configure in Auth.configure.
30
+ * If you are using Cognito, it is better to set identityPoolId to false and configure Auth manually.
31
+ */
32
+ userPoolId?: string;
33
+ /**
34
+ * The Cognito Web Client Id to configure in Auth.configure.
35
+ * If you are using Cognito, it is better to set identityPoolId to false and configure Auth manually.
36
+ */
37
+ userPoolWebClientId?: string;
38
+
39
+ /**
40
+ * If you want to track which page/url in your webapp is the most frequently viewed one, you can use this feature.
41
+ * It will automatically send events containing url information when the page is visited.
42
+ */
14
43
  autoTrackPageViews?: boolean;
44
+ /**
45
+ * If you want to track user interactions with elements on the page, you can use this feature.
46
+ * All you need to do is attach the specified selectors to your dom element and turn on the auto tracking.
47
+ */
15
48
  autoTrackEvents?: boolean;
49
+ /**
50
+ * A web session can be defined in different ways.
51
+ * To keep it simple we define that the web session is active when the page is not hidden and inactive when the page is hidden.
52
+ */
16
53
  autoTrackSessions?: boolean;
54
+
55
+ /**
56
+ * The data tag prefix to use for attributing HTML elements. Defaults to data-analytics-
57
+ */
17
58
  selectorPrefix?: string;
18
- ignoreBreadcrumbCategories?: string[];
59
+
60
+ /**
61
+ * Modify how the reporter sends events to Amplify.
62
+ */
19
63
  buffering?: AmplifyReporterBufferingConfig;
20
- userPoolId?: string;
21
- userPoolWebClientId?: string;
22
- ignoreMetadataPatterns?: RegExp[];
23
- };
64
+ }
24
65
 
25
66
  /**
26
67
  * Configuration options for the buffering behavior of Pinpoint's event tracker.
@@ -52,7 +93,7 @@ export function amplifyReporter(info: ServiceInfo, config: AmplifyReporterConfig
52
93
  appName: info.service,
53
94
  service: info.service,
54
95
  domain: window.location.host,
55
- environment: info.service,
96
+ environment: info.environment,
56
97
  version: info.version,
57
98
  });
58
99
 
@@ -139,24 +180,19 @@ export function amplifyReporter(info: ServiceInfo, config: AmplifyReporterConfig
139
180
  setPageName: function (pageName: string): void {
140
181
  reporter.addMetadata({ pageName });
141
182
  },
142
- reportError: function (): void {},
143
- recordSession: function (): void {},
144
- recordSessionStop: function (): void {},
145
183
  };
146
184
 
147
185
  return reporter;
148
186
  }
149
187
 
150
- type AttributeMap = Record<string, string[] | string | null>;
151
-
152
188
  /**
153
189
  * Pinpoint has strict attribute name and value length limits
154
190
  */
155
191
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
156
192
  export function asAttributeMap(
157
- values: Record<string, any>,
193
+ values: Record<string, unknown>,
158
194
  groupValues = true,
159
- ignorePatterns: RegExp[] = [],
195
+ ignorePatterns: (string | RegExp)[] = [],
160
196
  ): AttributeMap {
161
197
  const attributeMap = buildAttributeMap(values, undefined, groupValues);
162
198
  const filteredAttributeMap = filterAttributeMap(attributeMap, ignorePatterns);
@@ -206,9 +242,3 @@ export function buildAttributeMap(
206
242
 
207
243
  return valuesWithStringArrays;
208
244
  }
209
-
210
- export function filterAttributeMap(attributes: AttributeMap | Record<string, string>, ignorePatterns: RegExp[]) {
211
- const entries = Object.entries(attributes);
212
-
213
- return Object.fromEntries(entries.filter(([key]) => !ignorePatterns.some((pattern) => pattern.test(key))));
214
- }