@codaco/analytics 2.0.0 → 2.1.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.
- package/.eslintrc.js +4 -4
- package/.turbo/turbo-build.log +13 -13
- package/README.md +9 -9
- package/dist/index.d.mts +2 -2
- package/dist/index.mjs.map +1 -1
- package/jest.config.js +198 -198
- package/package.json +24 -24
- package/src/index.ts +188 -186
- package/src/utils.ts +36 -36
- package/tsconfig.json +10 -10
- package/.turbo/turbo-test.log +0 -31
package/.eslintrc.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
module.exports = {
|
|
2
|
-
root: true,
|
|
3
|
-
extends: ["custom/next"],
|
|
4
|
-
};
|
|
1
|
+
module.exports = {
|
|
2
|
+
root: true,
|
|
3
|
+
extends: ["custom/next"],
|
|
4
|
+
};
|
package/.turbo/turbo-build.log
CHANGED
|
@@ -1,16 +1,16 @@
|
|
|
1
1
|
|
|
2
|
-
> @codaco/analytics@2.0.0 build
|
|
2
|
+
> @codaco/analytics@2.0.0 build D:\Projects\Network Canvas\error-analytics-microservice\packages\analytics
|
|
3
3
|
> tsup src/index.ts --format esm --dts --clean --sourcemap
|
|
4
4
|
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
5
|
+
[34mCLI[39m Building entry: src/index.ts
|
|
6
|
+
[34mCLI[39m Using tsconfig: tsconfig.json
|
|
7
|
+
[34mCLI[39m tsup v7.2.0
|
|
8
|
+
[34mCLI[39m Target: es2022
|
|
9
|
+
[34mCLI[39m Cleaning output folder
|
|
10
|
+
[34mESM[39m Build start
|
|
11
|
+
[32mESM[39m [1mdist\index.mjs [22m[32m4.06 KB[39m
|
|
12
|
+
[32mESM[39m [1mdist\index.mjs.map [22m[32m8.81 KB[39m
|
|
13
|
+
[32mESM[39m ⚡️ Build success in 17ms
|
|
14
|
+
[34mDTS[39m Build start
|
|
15
|
+
[32mDTS[39m ⚡️ Build success in 1007ms
|
|
16
|
+
[32mDTS[39m [1mdist\index.d.mts [22m[32m1.38 KB[39m
|
package/README.md
CHANGED
|
@@ -1,9 +1,9 @@
|
|
|
1
|
-
# @codaco/analytics
|
|
2
|
-
|
|
3
|
-
This npm package implements methods and types for sending analytics and errors from Fresco instances to a custom error and analytics microservice.
|
|
4
|
-
|
|
5
|
-
It exports two functions:
|
|
6
|
-
|
|
7
|
-
**createRouteHandler** - A function that creates a NextJs route handler which geolocates requests, and forwards the event payload to the microservice.
|
|
8
|
-
|
|
9
|
-
**makeEventTracker** - A function that returns a `trackEvent` function, which attaches timestamp data to an event, and then calls the route handler.
|
|
1
|
+
# @codaco/analytics
|
|
2
|
+
|
|
3
|
+
This npm package implements methods and types for sending analytics and errors from Fresco instances to a custom error and analytics microservice.
|
|
4
|
+
|
|
5
|
+
It exports two functions:
|
|
6
|
+
|
|
7
|
+
**createRouteHandler** - A function that creates a NextJs route handler which geolocates requests, and forwards the event payload to the microservice.
|
|
8
|
+
|
|
9
|
+
**makeEventTracker** - A function that returns a `trackEvent` function, which attaches timestamp data to an event, and then calls the route handler.
|
package/dist/index.d.mts
CHANGED
|
@@ -5,10 +5,10 @@ type GeoLocation = {
|
|
|
5
5
|
countryCode: string;
|
|
6
6
|
};
|
|
7
7
|
type AnalyticsEventBase = {
|
|
8
|
-
type: "InterviewCompleted" | "InterviewStarted" | "ProtocolInstalled" | "AppSetup" | "Error";
|
|
8
|
+
type: "DataExported" | "InterviewCompleted" | "InterviewStarted" | "ProtocolInstalled" | "AppSetup" | "Error";
|
|
9
9
|
};
|
|
10
10
|
type AnalyticsEvent = AnalyticsEventBase & {
|
|
11
|
-
type: "InterviewCompleted" | "InterviewStarted" | "ProtocolInstalled" | "AppSetup";
|
|
11
|
+
type: "InterviewCompleted" | "DataExported" | "InterviewStarted" | "ProtocolInstalled" | "AppSetup";
|
|
12
12
|
metadata?: Record<string, unknown>;
|
|
13
13
|
};
|
|
14
14
|
type AnalyticsError = AnalyticsEventBase & {
|
package/dist/index.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/utils.ts","../src/index.ts"],"sourcesContent":["// Helper function that ensures that a value is an Error\nexport function ensureError(value: unknown): Error {\n if (!value) return new Error(\"No value was thrown\");\n\n if (value instanceof Error) return value;\n\n // Test if value inherits from Error\n if (value.isPrototypeOf(Error)) return value as Error & typeof value;\n\n let stringified = \"[Unable to stringify the thrown value]\";\n try {\n stringified = JSON.stringify(value);\n } catch {}\n\n const error = new Error(\n `This value was thrown as is, not through an Error: ${stringified}`\n );\n return error;\n}\n\nexport function getBaseUrl() {\n if (typeof window !== \"undefined\")\n // browser should use relative path\n return \"\";\n\n if (process.env.VERCEL_URL)\n // reference for vercel.com\n return `https://${process.env.VERCEL_URL}`;\n\n if (process.env.NEXT_PUBLIC_URL)\n // Manually set deployment URL from env\n return process.env.NEXT_PUBLIC_URL;\n\n // assume localhost\n return `http://127.0.0.1:3000`;\n}\n","import type { NextRequest } from \"next/server\";\nimport { WebServiceClient } from \"@maxmind/geoip2-node\";\nimport { ensureError, getBaseUrl } from \"./utils\";\n\ntype GeoLocation = {\n countryCode: string;\n};\n\nexport type AnalyticsEventBase = {\n type:\n | \"InterviewCompleted\"\n | \"InterviewStarted\"\n | \"ProtocolInstalled\"\n | \"AppSetup\"\n | \"Error\";\n};\n\nexport type AnalyticsEvent = AnalyticsEventBase & {\n type:\n | \"InterviewCompleted\"\n | \"InterviewStarted\"\n | \"ProtocolInstalled\"\n | \"AppSetup\";\n metadata?: Record<string, unknown>;\n};\n\nexport type AnalyticsError = AnalyticsEventBase & {\n type: \"Error\";\n error: {\n message: string;\n details: string;\n stacktrace: string;\n path: string;\n };\n};\n\nexport type AnalyticsEventOrError = AnalyticsEvent | AnalyticsError;\n\nexport type AnalyticsEventOrErrorWithTimestamp = AnalyticsEventOrError & {\n timestamp: Date;\n};\n\nexport type DispatchableAnalyticsEvent = AnalyticsEventOrErrorWithTimestamp & {\n installationId: string;\n geolocation?: GeoLocation;\n};\n\ntype RouteHandlerConfiguration = {\n platformUrl?: string;\n installationId: string;\n maxMindClient: WebServiceClient;\n};\n\nexport const createRouteHandler = ({\n platformUrl = \"https://analytics.networkcanvas.com\",\n installationId,\n maxMindClient,\n}: RouteHandlerConfiguration) => {\n return async (request: NextRequest) => {\n try {\n const event =\n (await request.json()) as AnalyticsEventOrErrorWithTimestamp;\n\n const ip = await fetch(\"https://api64.ipify.org\").then((res) =>\n res.text()\n );\n\n const { country } = await maxMindClient.country(ip);\n const countryCode = country?.isoCode ?? \"Unknown\";\n\n const dispatchableEvent: DispatchableAnalyticsEvent = {\n ...event,\n installationId,\n geolocation: {\n countryCode,\n },\n };\n\n // Forward to microservice\n const response = await fetch(`${platformUrl}/api/event`, {\n keepalive: true,\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n },\n body: JSON.stringify(dispatchableEvent),\n });\n\n if (!response.ok) {\n if (response.status === 404) {\n console.error(\n `Analytics platform not found. Please specify a valid platform URL.`\n );\n } else if (response.status === 500) {\n console.error(\n `Internal server error on analytics platform when forwarding event: ${response.statusText}.`\n );\n } else {\n console.error(\n `General error when forwarding event: ${response.statusText}`\n );\n }\n\n return new Response(\n JSON.stringify({ error: \"Internal Server Error\" }),\n {\n status: 500,\n headers: {\n \"Content-Type\": \"application/json\",\n },\n }\n );\n }\n\n console.info(`🚀 Analytics event forwarded successfully.`);\n console.info(JSON.stringify(dispatchableEvent, null, 2));\n\n return new Response(\n JSON.stringify({ message: \"Event forwarded successfully\" }),\n {\n status: 200,\n headers: {\n \"Content-Type\": \"application/json\",\n },\n }\n );\n } catch (e) {\n const error = ensureError(e);\n console.error(\"Error in route handler:\", error);\n\n // Return an appropriate error response\n return new Response(JSON.stringify({ error: \"Internal Server Error\" }), {\n status: 500,\n headers: {\n \"Content-Type\": \"application/json\",\n },\n });\n }\n };\n};\n\nexport const makeEventTracker =\n (endpoint: string = \"/api/analytics\") =>\n async (event: AnalyticsEventOrError) => {\n const endpointWithHost = getBaseUrl() + endpoint;\n\n const eventWithTimeStamp = {\n ...event,\n timestamp: new Date(),\n };\n\n try {\n const response = await fetch(endpointWithHost, {\n method: \"POST\",\n keepalive: true,\n body: JSON.stringify(eventWithTimeStamp),\n headers: {\n \"Content-Type\": \"application/json\",\n },\n });\n\n if (!response.ok) {\n if (response.status === 404) {\n console.error(\n `Analytics endpoint not found, did you forget to add the route?`\n );\n return;\n }\n\n if (response.status === 500) {\n console.error(\n `Internal server error when sending analytics event: ${response.statusText}. Check the route handler implementation.`\n );\n return;\n }\n\n console.error(\n `General error sending analytics event: ${response.statusText}`\n );\n }\n } catch (e) {\n const error = ensureError(e);\n\n console.error(\"Internal error with analytics:\", error.message);\n }\n };\n"],"mappings":";AACO,SAAS,YAAY,OAAuB;AACjD,MAAI,CAAC;AAAO,WAAO,IAAI,MAAM,qBAAqB;AAElD,MAAI,iBAAiB;AAAO,WAAO;AAGnC,MAAI,MAAM,cAAc,KAAK;AAAG,WAAO;AAEvC,MAAI,cAAc;AAClB,MAAI;AACF,kBAAc,KAAK,UAAU,KAAK;AAAA,EACpC,QAAQ;AAAA,EAAC;AAET,QAAM,QAAQ,IAAI;AAAA,IAChB,sDAAsD,WAAW;AAAA,EACnE;AACA,SAAO;AACT;AAEO,SAAS,aAAa;AAC3B,MAAI,OAAO,WAAW;AAEpB,WAAO;AAET,MAAI,QAAQ,IAAI;AAEd,WAAO,WAAW,QAAQ,IAAI,UAAU;AAE1C,MAAI,QAAQ,IAAI;AAEd,WAAO,QAAQ,IAAI;AAGrB,SAAO;AACT;;;
|
|
1
|
+
{"version":3,"sources":["../src/utils.ts","../src/index.ts"],"sourcesContent":["// Helper function that ensures that a value is an Error\r\nexport function ensureError(value: unknown): Error {\r\n if (!value) return new Error(\"No value was thrown\");\r\n\r\n if (value instanceof Error) return value;\r\n\r\n // Test if value inherits from Error\r\n if (value.isPrototypeOf(Error)) return value as Error & typeof value;\r\n\r\n let stringified = \"[Unable to stringify the thrown value]\";\r\n try {\r\n stringified = JSON.stringify(value);\r\n } catch {}\r\n\r\n const error = new Error(\r\n `This value was thrown as is, not through an Error: ${stringified}`\r\n );\r\n return error;\r\n}\r\n\r\nexport function getBaseUrl() {\r\n if (typeof window !== \"undefined\")\r\n // browser should use relative path\r\n return \"\";\r\n\r\n if (process.env.VERCEL_URL)\r\n // reference for vercel.com\r\n return `https://${process.env.VERCEL_URL}`;\r\n\r\n if (process.env.NEXT_PUBLIC_URL)\r\n // Manually set deployment URL from env\r\n return process.env.NEXT_PUBLIC_URL;\r\n\r\n // assume localhost\r\n return `http://127.0.0.1:3000`;\r\n}\r\n","import type { NextRequest } from \"next/server\";\r\nimport { WebServiceClient } from \"@maxmind/geoip2-node\";\r\nimport { ensureError, getBaseUrl } from \"./utils\";\r\n\r\ntype GeoLocation = {\r\n countryCode: string;\r\n};\r\n\r\nexport type AnalyticsEventBase = {\r\n type:\r\n | \"DataExported\"\r\n | \"InterviewCompleted\"\r\n | \"InterviewStarted\"\r\n | \"ProtocolInstalled\"\r\n | \"AppSetup\"\r\n | \"Error\";\r\n};\r\n\r\nexport type AnalyticsEvent = AnalyticsEventBase & {\r\n type:\r\n | \"InterviewCompleted\"\r\n | \"DataExported\"\r\n | \"InterviewStarted\"\r\n | \"ProtocolInstalled\"\r\n | \"AppSetup\";\r\n metadata?: Record<string, unknown>;\r\n};\r\n\r\nexport type AnalyticsError = AnalyticsEventBase & {\r\n type: \"Error\";\r\n error: {\r\n message: string;\r\n details: string;\r\n stacktrace: string;\r\n path: string;\r\n };\r\n};\r\n\r\nexport type AnalyticsEventOrError = AnalyticsEvent | AnalyticsError;\r\n\r\nexport type AnalyticsEventOrErrorWithTimestamp = AnalyticsEventOrError & {\r\n timestamp: Date;\r\n};\r\n\r\nexport type DispatchableAnalyticsEvent = AnalyticsEventOrErrorWithTimestamp & {\r\n installationId: string;\r\n geolocation?: GeoLocation;\r\n};\r\n\r\ntype RouteHandlerConfiguration = {\r\n platformUrl?: string;\r\n installationId: string;\r\n maxMindClient: WebServiceClient;\r\n};\r\n\r\nexport const createRouteHandler = ({\r\n platformUrl = \"https://analytics.networkcanvas.com\",\r\n installationId,\r\n maxMindClient,\r\n}: RouteHandlerConfiguration) => {\r\n return async (request: NextRequest) => {\r\n try {\r\n const event =\r\n (await request.json()) as AnalyticsEventOrErrorWithTimestamp;\r\n\r\n const ip = await fetch(\"https://api64.ipify.org\").then((res) =>\r\n res.text()\r\n );\r\n\r\n const { country } = await maxMindClient.country(ip);\r\n const countryCode = country?.isoCode ?? \"Unknown\";\r\n\r\n const dispatchableEvent: DispatchableAnalyticsEvent = {\r\n ...event,\r\n installationId,\r\n geolocation: {\r\n countryCode,\r\n },\r\n };\r\n\r\n // Forward to microservice\r\n const response = await fetch(`${platformUrl}/api/event`, {\r\n keepalive: true,\r\n method: \"POST\",\r\n headers: {\r\n \"Content-Type\": \"application/json\",\r\n },\r\n body: JSON.stringify(dispatchableEvent),\r\n });\r\n\r\n if (!response.ok) {\r\n if (response.status === 404) {\r\n console.error(\r\n `Analytics platform not found. Please specify a valid platform URL.`\r\n );\r\n } else if (response.status === 500) {\r\n console.error(\r\n `Internal server error on analytics platform when forwarding event: ${response.statusText}.`\r\n );\r\n } else {\r\n console.error(\r\n `General error when forwarding event: ${response.statusText}`\r\n );\r\n }\r\n\r\n return new Response(\r\n JSON.stringify({ error: \"Internal Server Error\" }),\r\n {\r\n status: 500,\r\n headers: {\r\n \"Content-Type\": \"application/json\",\r\n },\r\n }\r\n );\r\n }\r\n\r\n console.info(`🚀 Analytics event forwarded successfully.`);\r\n console.info(JSON.stringify(dispatchableEvent, null, 2));\r\n\r\n return new Response(\r\n JSON.stringify({ message: \"Event forwarded successfully\" }),\r\n {\r\n status: 200,\r\n headers: {\r\n \"Content-Type\": \"application/json\",\r\n },\r\n }\r\n );\r\n } catch (e) {\r\n const error = ensureError(e);\r\n console.error(\"Error in route handler:\", error);\r\n\r\n // Return an appropriate error response\r\n return new Response(JSON.stringify({ error: \"Internal Server Error\" }), {\r\n status: 500,\r\n headers: {\r\n \"Content-Type\": \"application/json\",\r\n },\r\n });\r\n }\r\n };\r\n};\r\n\r\nexport const makeEventTracker =\r\n (endpoint: string = \"/api/analytics\") =>\r\n async (event: AnalyticsEventOrError) => {\r\n const endpointWithHost = getBaseUrl() + endpoint;\r\n\r\n const eventWithTimeStamp = {\r\n ...event,\r\n timestamp: new Date(),\r\n };\r\n\r\n try {\r\n const response = await fetch(endpointWithHost, {\r\n method: \"POST\",\r\n keepalive: true,\r\n body: JSON.stringify(eventWithTimeStamp),\r\n headers: {\r\n \"Content-Type\": \"application/json\",\r\n },\r\n });\r\n\r\n if (!response.ok) {\r\n if (response.status === 404) {\r\n console.error(\r\n `Analytics endpoint not found, did you forget to add the route?`\r\n );\r\n return;\r\n }\r\n\r\n if (response.status === 500) {\r\n console.error(\r\n `Internal server error when sending analytics event: ${response.statusText}. Check the route handler implementation.`\r\n );\r\n return;\r\n }\r\n\r\n console.error(\r\n `General error sending analytics event: ${response.statusText}`\r\n );\r\n }\r\n } catch (e) {\r\n const error = ensureError(e);\r\n\r\n console.error(\"Internal error with analytics:\", error.message);\r\n }\r\n };\r\n"],"mappings":"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","names":[]}
|
package/jest.config.js
CHANGED
|
@@ -1,198 +1,198 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* For a detailed explanation regarding each configuration property, visit:
|
|
3
|
-
* https://jestjs.io/docs/configuration
|
|
4
|
-
*/
|
|
5
|
-
|
|
6
|
-
/** @type {import('jest').Config} */
|
|
7
|
-
const config = {
|
|
8
|
-
// All imported modules in your tests should be mocked automatically
|
|
9
|
-
// automock: false,
|
|
10
|
-
|
|
11
|
-
// Stop running tests after `n` failures
|
|
12
|
-
// bail: 0,
|
|
13
|
-
|
|
14
|
-
// The directory where Jest should store its cached dependency information
|
|
15
|
-
// cacheDirectory: "/private/var/folders/vc/szx71k5j5sqcmrljl1w44ryddl7zmw/T/jest_pb0330",
|
|
16
|
-
|
|
17
|
-
// Automatically clear mock calls, instances, contexts and results before every test
|
|
18
|
-
// clearMocks: false,
|
|
19
|
-
|
|
20
|
-
// Indicates whether the coverage information should be collected while executing the test
|
|
21
|
-
// collectCoverage: false,
|
|
22
|
-
|
|
23
|
-
// An array of glob patterns indicating a set of files for which coverage information should be collected
|
|
24
|
-
// collectCoverageFrom: undefined,
|
|
25
|
-
|
|
26
|
-
// The directory where Jest should output its coverage files
|
|
27
|
-
// coverageDirectory: undefined,
|
|
28
|
-
|
|
29
|
-
// An array of regexp pattern strings used to skip coverage collection
|
|
30
|
-
// coveragePathIgnorePatterns: [
|
|
31
|
-
// "/node_modules/"
|
|
32
|
-
// ],
|
|
33
|
-
|
|
34
|
-
// Indicates which provider should be used to instrument code for coverage
|
|
35
|
-
coverageProvider: "v8",
|
|
36
|
-
|
|
37
|
-
// A list of reporter names that Jest uses when writing coverage reports
|
|
38
|
-
// coverageReporters: [
|
|
39
|
-
// "json",
|
|
40
|
-
// "text",
|
|
41
|
-
// "lcov",
|
|
42
|
-
// "clover"
|
|
43
|
-
// ],
|
|
44
|
-
|
|
45
|
-
// An object that configures minimum threshold enforcement for coverage results
|
|
46
|
-
// coverageThreshold: undefined,
|
|
47
|
-
|
|
48
|
-
// A path to a custom dependency extractor
|
|
49
|
-
// dependencyExtractor: undefined,
|
|
50
|
-
|
|
51
|
-
// Make calling deprecated APIs throw helpful error messages
|
|
52
|
-
// errorOnDeprecated: false,
|
|
53
|
-
|
|
54
|
-
// The default configuration for fake timers
|
|
55
|
-
// fakeTimers: {
|
|
56
|
-
// "enableGlobally": false
|
|
57
|
-
// },
|
|
58
|
-
|
|
59
|
-
// Force coverage collection from ignored files using an array of glob patterns
|
|
60
|
-
// forceCoverageMatch: [],
|
|
61
|
-
|
|
62
|
-
// A path to a module which exports an async function that is triggered once before all test suites
|
|
63
|
-
// globalSetup: undefined,
|
|
64
|
-
|
|
65
|
-
// A path to a module which exports an async function that is triggered once after all test suites
|
|
66
|
-
// globalTeardown: undefined,
|
|
67
|
-
|
|
68
|
-
// A set of global variables that need to be available in all test environments
|
|
69
|
-
// globals: {},
|
|
70
|
-
|
|
71
|
-
// The maximum amount of workers used to run your tests. Can be specified as % or a number. E.g. maxWorkers: 10% will use 10% of your CPU amount + 1 as the maximum worker number. maxWorkers: 2 will use a maximum of 2 workers.
|
|
72
|
-
// maxWorkers: "50%",
|
|
73
|
-
|
|
74
|
-
// An array of directory names to be searched recursively up from the requiring module's location
|
|
75
|
-
// moduleDirectories: [
|
|
76
|
-
// "node_modules"
|
|
77
|
-
// ],
|
|
78
|
-
|
|
79
|
-
// An array of file extensions your modules use
|
|
80
|
-
// moduleFileExtensions: [
|
|
81
|
-
// "js",
|
|
82
|
-
// "mjs",
|
|
83
|
-
// "cjs",
|
|
84
|
-
// "jsx",
|
|
85
|
-
// "ts",
|
|
86
|
-
// "tsx",
|
|
87
|
-
// "json",
|
|
88
|
-
// "node"
|
|
89
|
-
// ],
|
|
90
|
-
|
|
91
|
-
// A map from regular expressions to module names or to arrays of module names that allow to stub out resources with a single module
|
|
92
|
-
// moduleNameMapper: {},
|
|
93
|
-
|
|
94
|
-
// An array of regexp pattern strings, matched against all module paths before considered 'visible' to the module loader
|
|
95
|
-
// modulePathIgnorePatterns: [],
|
|
96
|
-
|
|
97
|
-
// Activates notifications for test results
|
|
98
|
-
// notify: false,
|
|
99
|
-
|
|
100
|
-
// An enum that specifies notification mode. Requires { notify: true }
|
|
101
|
-
// notifyMode: "failure-change",
|
|
102
|
-
|
|
103
|
-
// A preset that is used as a base for Jest's configuration
|
|
104
|
-
// preset: undefined,
|
|
105
|
-
|
|
106
|
-
// Run tests from one or more projects
|
|
107
|
-
// projects: undefined,
|
|
108
|
-
|
|
109
|
-
// Use this configuration option to add custom reporters to Jest
|
|
110
|
-
// reporters: undefined,
|
|
111
|
-
|
|
112
|
-
// Automatically reset mock state before every test
|
|
113
|
-
// resetMocks: false,
|
|
114
|
-
|
|
115
|
-
// Reset the module registry before running each individual test
|
|
116
|
-
// resetModules: false,
|
|
117
|
-
|
|
118
|
-
// A path to a custom resolver
|
|
119
|
-
// resolver: undefined,
|
|
120
|
-
|
|
121
|
-
// Automatically restore mock state and implementation before every test
|
|
122
|
-
// restoreMocks: false,
|
|
123
|
-
|
|
124
|
-
// The root directory that Jest should scan for tests and modules within
|
|
125
|
-
// rootDir: undefined,
|
|
126
|
-
|
|
127
|
-
// A list of paths to directories that Jest should use to search for files in
|
|
128
|
-
// roots: [
|
|
129
|
-
// "<rootDir>"
|
|
130
|
-
// ],
|
|
131
|
-
|
|
132
|
-
// Allows you to use a custom runner instead of Jest's default test runner
|
|
133
|
-
// runner: "jest-runner",
|
|
134
|
-
|
|
135
|
-
// The paths to modules that run some code to configure or set up the testing environment before each test
|
|
136
|
-
// setupFiles: [],
|
|
137
|
-
|
|
138
|
-
// A list of paths to modules that run some code to configure or set up the testing framework before each test
|
|
139
|
-
// setupFilesAfterEnv: [],
|
|
140
|
-
|
|
141
|
-
// The number of seconds after which a test is considered as slow and reported as such in the results.
|
|
142
|
-
// slowTestThreshold: 5,
|
|
143
|
-
|
|
144
|
-
// A list of paths to snapshot serializer modules Jest should use for snapshot testing
|
|
145
|
-
// snapshotSerializers: [],
|
|
146
|
-
|
|
147
|
-
// The test environment that will be used for testing
|
|
148
|
-
testEnvironment: "node",
|
|
149
|
-
|
|
150
|
-
// Options that will be passed to the testEnvironment
|
|
151
|
-
// testEnvironmentOptions: {},
|
|
152
|
-
|
|
153
|
-
// Adds a location field to test results
|
|
154
|
-
// testLocationInResults: false,
|
|
155
|
-
|
|
156
|
-
// The glob patterns Jest uses to detect test files
|
|
157
|
-
testMatch: [
|
|
158
|
-
"**/__tests__/**/*.[jt]s?(x)",
|
|
159
|
-
"**/?(*.)+(spec|test).m[tj]s?(x)"
|
|
160
|
-
],
|
|
161
|
-
|
|
162
|
-
// An array of regexp pattern strings that are matched against all test paths, matched tests are skipped
|
|
163
|
-
// testPathIgnorePatterns: [
|
|
164
|
-
// "/node_modules/"
|
|
165
|
-
// ],
|
|
166
|
-
|
|
167
|
-
// The regexp pattern or array of patterns that Jest uses to detect test files
|
|
168
|
-
// testRegex: [],
|
|
169
|
-
|
|
170
|
-
// This option allows the use of a custom results processor
|
|
171
|
-
// testResultsProcessor: undefined,
|
|
172
|
-
|
|
173
|
-
// This option allows use of a custom test runner
|
|
174
|
-
// testRunner: "jest-circus/runner",
|
|
175
|
-
|
|
176
|
-
// A map from regular expressions to paths to transformers
|
|
177
|
-
// transform: undefined,
|
|
178
|
-
|
|
179
|
-
// An array of regexp pattern strings that are matched against all source file paths, matched files will skip transformation
|
|
180
|
-
// transformIgnorePatterns: [
|
|
181
|
-
// "/node_modules/",
|
|
182
|
-
// "\\.pnp\\.[^\\/]+$"
|
|
183
|
-
// ],
|
|
184
|
-
|
|
185
|
-
// An array of regexp pattern strings that are matched against all modules before the module loader will automatically return a mock for them
|
|
186
|
-
// unmockedModulePathPatterns: undefined,
|
|
187
|
-
|
|
188
|
-
// Indicates whether each individual test should be reported during the run
|
|
189
|
-
// verbose: undefined,
|
|
190
|
-
|
|
191
|
-
// An array of regexp patterns that are matched against all source file paths before re-running tests in watch mode
|
|
192
|
-
// watchPathIgnorePatterns: [],
|
|
193
|
-
|
|
194
|
-
// Whether to use watchman for file crawling
|
|
195
|
-
// watchman: true,
|
|
196
|
-
};
|
|
197
|
-
|
|
198
|
-
module.exports = config;
|
|
1
|
+
/**
|
|
2
|
+
* For a detailed explanation regarding each configuration property, visit:
|
|
3
|
+
* https://jestjs.io/docs/configuration
|
|
4
|
+
*/
|
|
5
|
+
|
|
6
|
+
/** @type {import('jest').Config} */
|
|
7
|
+
const config = {
|
|
8
|
+
// All imported modules in your tests should be mocked automatically
|
|
9
|
+
// automock: false,
|
|
10
|
+
|
|
11
|
+
// Stop running tests after `n` failures
|
|
12
|
+
// bail: 0,
|
|
13
|
+
|
|
14
|
+
// The directory where Jest should store its cached dependency information
|
|
15
|
+
// cacheDirectory: "/private/var/folders/vc/szx71k5j5sqcmrljl1w44ryddl7zmw/T/jest_pb0330",
|
|
16
|
+
|
|
17
|
+
// Automatically clear mock calls, instances, contexts and results before every test
|
|
18
|
+
// clearMocks: false,
|
|
19
|
+
|
|
20
|
+
// Indicates whether the coverage information should be collected while executing the test
|
|
21
|
+
// collectCoverage: false,
|
|
22
|
+
|
|
23
|
+
// An array of glob patterns indicating a set of files for which coverage information should be collected
|
|
24
|
+
// collectCoverageFrom: undefined,
|
|
25
|
+
|
|
26
|
+
// The directory where Jest should output its coverage files
|
|
27
|
+
// coverageDirectory: undefined,
|
|
28
|
+
|
|
29
|
+
// An array of regexp pattern strings used to skip coverage collection
|
|
30
|
+
// coveragePathIgnorePatterns: [
|
|
31
|
+
// "/node_modules/"
|
|
32
|
+
// ],
|
|
33
|
+
|
|
34
|
+
// Indicates which provider should be used to instrument code for coverage
|
|
35
|
+
coverageProvider: "v8",
|
|
36
|
+
|
|
37
|
+
// A list of reporter names that Jest uses when writing coverage reports
|
|
38
|
+
// coverageReporters: [
|
|
39
|
+
// "json",
|
|
40
|
+
// "text",
|
|
41
|
+
// "lcov",
|
|
42
|
+
// "clover"
|
|
43
|
+
// ],
|
|
44
|
+
|
|
45
|
+
// An object that configures minimum threshold enforcement for coverage results
|
|
46
|
+
// coverageThreshold: undefined,
|
|
47
|
+
|
|
48
|
+
// A path to a custom dependency extractor
|
|
49
|
+
// dependencyExtractor: undefined,
|
|
50
|
+
|
|
51
|
+
// Make calling deprecated APIs throw helpful error messages
|
|
52
|
+
// errorOnDeprecated: false,
|
|
53
|
+
|
|
54
|
+
// The default configuration for fake timers
|
|
55
|
+
// fakeTimers: {
|
|
56
|
+
// "enableGlobally": false
|
|
57
|
+
// },
|
|
58
|
+
|
|
59
|
+
// Force coverage collection from ignored files using an array of glob patterns
|
|
60
|
+
// forceCoverageMatch: [],
|
|
61
|
+
|
|
62
|
+
// A path to a module which exports an async function that is triggered once before all test suites
|
|
63
|
+
// globalSetup: undefined,
|
|
64
|
+
|
|
65
|
+
// A path to a module which exports an async function that is triggered once after all test suites
|
|
66
|
+
// globalTeardown: undefined,
|
|
67
|
+
|
|
68
|
+
// A set of global variables that need to be available in all test environments
|
|
69
|
+
// globals: {},
|
|
70
|
+
|
|
71
|
+
// The maximum amount of workers used to run your tests. Can be specified as % or a number. E.g. maxWorkers: 10% will use 10% of your CPU amount + 1 as the maximum worker number. maxWorkers: 2 will use a maximum of 2 workers.
|
|
72
|
+
// maxWorkers: "50%",
|
|
73
|
+
|
|
74
|
+
// An array of directory names to be searched recursively up from the requiring module's location
|
|
75
|
+
// moduleDirectories: [
|
|
76
|
+
// "node_modules"
|
|
77
|
+
// ],
|
|
78
|
+
|
|
79
|
+
// An array of file extensions your modules use
|
|
80
|
+
// moduleFileExtensions: [
|
|
81
|
+
// "js",
|
|
82
|
+
// "mjs",
|
|
83
|
+
// "cjs",
|
|
84
|
+
// "jsx",
|
|
85
|
+
// "ts",
|
|
86
|
+
// "tsx",
|
|
87
|
+
// "json",
|
|
88
|
+
// "node"
|
|
89
|
+
// ],
|
|
90
|
+
|
|
91
|
+
// A map from regular expressions to module names or to arrays of module names that allow to stub out resources with a single module
|
|
92
|
+
// moduleNameMapper: {},
|
|
93
|
+
|
|
94
|
+
// An array of regexp pattern strings, matched against all module paths before considered 'visible' to the module loader
|
|
95
|
+
// modulePathIgnorePatterns: [],
|
|
96
|
+
|
|
97
|
+
// Activates notifications for test results
|
|
98
|
+
// notify: false,
|
|
99
|
+
|
|
100
|
+
// An enum that specifies notification mode. Requires { notify: true }
|
|
101
|
+
// notifyMode: "failure-change",
|
|
102
|
+
|
|
103
|
+
// A preset that is used as a base for Jest's configuration
|
|
104
|
+
// preset: undefined,
|
|
105
|
+
|
|
106
|
+
// Run tests from one or more projects
|
|
107
|
+
// projects: undefined,
|
|
108
|
+
|
|
109
|
+
// Use this configuration option to add custom reporters to Jest
|
|
110
|
+
// reporters: undefined,
|
|
111
|
+
|
|
112
|
+
// Automatically reset mock state before every test
|
|
113
|
+
// resetMocks: false,
|
|
114
|
+
|
|
115
|
+
// Reset the module registry before running each individual test
|
|
116
|
+
// resetModules: false,
|
|
117
|
+
|
|
118
|
+
// A path to a custom resolver
|
|
119
|
+
// resolver: undefined,
|
|
120
|
+
|
|
121
|
+
// Automatically restore mock state and implementation before every test
|
|
122
|
+
// restoreMocks: false,
|
|
123
|
+
|
|
124
|
+
// The root directory that Jest should scan for tests and modules within
|
|
125
|
+
// rootDir: undefined,
|
|
126
|
+
|
|
127
|
+
// A list of paths to directories that Jest should use to search for files in
|
|
128
|
+
// roots: [
|
|
129
|
+
// "<rootDir>"
|
|
130
|
+
// ],
|
|
131
|
+
|
|
132
|
+
// Allows you to use a custom runner instead of Jest's default test runner
|
|
133
|
+
// runner: "jest-runner",
|
|
134
|
+
|
|
135
|
+
// The paths to modules that run some code to configure or set up the testing environment before each test
|
|
136
|
+
// setupFiles: [],
|
|
137
|
+
|
|
138
|
+
// A list of paths to modules that run some code to configure or set up the testing framework before each test
|
|
139
|
+
// setupFilesAfterEnv: [],
|
|
140
|
+
|
|
141
|
+
// The number of seconds after which a test is considered as slow and reported as such in the results.
|
|
142
|
+
// slowTestThreshold: 5,
|
|
143
|
+
|
|
144
|
+
// A list of paths to snapshot serializer modules Jest should use for snapshot testing
|
|
145
|
+
// snapshotSerializers: [],
|
|
146
|
+
|
|
147
|
+
// The test environment that will be used for testing
|
|
148
|
+
testEnvironment: "node",
|
|
149
|
+
|
|
150
|
+
// Options that will be passed to the testEnvironment
|
|
151
|
+
// testEnvironmentOptions: {},
|
|
152
|
+
|
|
153
|
+
// Adds a location field to test results
|
|
154
|
+
// testLocationInResults: false,
|
|
155
|
+
|
|
156
|
+
// The glob patterns Jest uses to detect test files
|
|
157
|
+
testMatch: [
|
|
158
|
+
"**/__tests__/**/*.[jt]s?(x)",
|
|
159
|
+
"**/?(*.)+(spec|test).m[tj]s?(x)"
|
|
160
|
+
],
|
|
161
|
+
|
|
162
|
+
// An array of regexp pattern strings that are matched against all test paths, matched tests are skipped
|
|
163
|
+
// testPathIgnorePatterns: [
|
|
164
|
+
// "/node_modules/"
|
|
165
|
+
// ],
|
|
166
|
+
|
|
167
|
+
// The regexp pattern or array of patterns that Jest uses to detect test files
|
|
168
|
+
// testRegex: [],
|
|
169
|
+
|
|
170
|
+
// This option allows the use of a custom results processor
|
|
171
|
+
// testResultsProcessor: undefined,
|
|
172
|
+
|
|
173
|
+
// This option allows use of a custom test runner
|
|
174
|
+
// testRunner: "jest-circus/runner",
|
|
175
|
+
|
|
176
|
+
// A map from regular expressions to paths to transformers
|
|
177
|
+
// transform: undefined,
|
|
178
|
+
|
|
179
|
+
// An array of regexp pattern strings that are matched against all source file paths, matched files will skip transformation
|
|
180
|
+
// transformIgnorePatterns: [
|
|
181
|
+
// "/node_modules/",
|
|
182
|
+
// "\\.pnp\\.[^\\/]+$"
|
|
183
|
+
// ],
|
|
184
|
+
|
|
185
|
+
// An array of regexp pattern strings that are matched against all modules before the module loader will automatically return a mock for them
|
|
186
|
+
// unmockedModulePathPatterns: undefined,
|
|
187
|
+
|
|
188
|
+
// Indicates whether each individual test should be reported during the run
|
|
189
|
+
// verbose: undefined,
|
|
190
|
+
|
|
191
|
+
// An array of regexp patterns that are matched against all source file paths before re-running tests in watch mode
|
|
192
|
+
// watchPathIgnorePatterns: [],
|
|
193
|
+
|
|
194
|
+
// Whether to use watchman for file crawling
|
|
195
|
+
// watchman: true,
|
|
196
|
+
};
|
|
197
|
+
|
|
198
|
+
module.exports = config;
|
package/package.json
CHANGED
|
@@ -1,24 +1,24 @@
|
|
|
1
|
-
{
|
|
2
|
-
"name": "@codaco/analytics",
|
|
3
|
-
"version": "2.
|
|
4
|
-
"module": "./dist/index.mjs",
|
|
5
|
-
"types": "./dist/index.d.mts",
|
|
6
|
-
"author": "Complex Data Collective <developers@coda.co>",
|
|
7
|
-
"description": "Utilities for tracking analytics and error reporting in Fresco",
|
|
8
|
-
"scripts": {
|
|
9
|
-
"build": "tsup src/index.ts --format esm --dts --clean --sourcemap",
|
|
10
|
-
"lint": "eslint .",
|
|
11
|
-
"dev": "npm run build -- --watch"
|
|
12
|
-
},
|
|
13
|
-
"peerDependencies": {
|
|
14
|
-
"next": "13 || 14",
|
|
15
|
-
"@maxmind/geoip2-node": "^5.0.0"
|
|
16
|
-
},
|
|
17
|
-
"devDependencies": {
|
|
18
|
-
"eslint-config-custom": "workspace:*",
|
|
19
|
-
"tsconfig": "workspace:*",
|
|
20
|
-
"tsup": "^7.2.0",
|
|
21
|
-
"typescript": "^5.3.2"
|
|
22
|
-
},
|
|
23
|
-
"dependencies": {}
|
|
24
|
-
}
|
|
1
|
+
{
|
|
2
|
+
"name": "@codaco/analytics",
|
|
3
|
+
"version": "2.1.1",
|
|
4
|
+
"module": "./dist/index.mjs",
|
|
5
|
+
"types": "./dist/index.d.mts",
|
|
6
|
+
"author": "Complex Data Collective <developers@coda.co>",
|
|
7
|
+
"description": "Utilities for tracking analytics and error reporting in Fresco",
|
|
8
|
+
"scripts": {
|
|
9
|
+
"build": "tsup src/index.ts --format esm --dts --clean --sourcemap",
|
|
10
|
+
"lint": "eslint .",
|
|
11
|
+
"dev": "npm run build -- --watch"
|
|
12
|
+
},
|
|
13
|
+
"peerDependencies": {
|
|
14
|
+
"next": "13 || 14",
|
|
15
|
+
"@maxmind/geoip2-node": "^5.0.0"
|
|
16
|
+
},
|
|
17
|
+
"devDependencies": {
|
|
18
|
+
"eslint-config-custom": "workspace:*",
|
|
19
|
+
"tsconfig": "workspace:*",
|
|
20
|
+
"tsup": "^7.2.0",
|
|
21
|
+
"typescript": "^5.3.2"
|
|
22
|
+
},
|
|
23
|
+
"dependencies": {}
|
|
24
|
+
}
|
package/src/index.ts
CHANGED
|
@@ -1,186 +1,188 @@
|
|
|
1
|
-
import type { NextRequest } from "next/server";
|
|
2
|
-
import { WebServiceClient } from "@maxmind/geoip2-node";
|
|
3
|
-
import { ensureError, getBaseUrl } from "./utils";
|
|
4
|
-
|
|
5
|
-
type GeoLocation = {
|
|
6
|
-
countryCode: string;
|
|
7
|
-
};
|
|
8
|
-
|
|
9
|
-
export type AnalyticsEventBase = {
|
|
10
|
-
type:
|
|
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
|
-
export type
|
|
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
|
-
const
|
|
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
|
-
const
|
|
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
|
-
|
|
1
|
+
import type { NextRequest } from "next/server";
|
|
2
|
+
import { WebServiceClient } from "@maxmind/geoip2-node";
|
|
3
|
+
import { ensureError, getBaseUrl } from "./utils";
|
|
4
|
+
|
|
5
|
+
type GeoLocation = {
|
|
6
|
+
countryCode: string;
|
|
7
|
+
};
|
|
8
|
+
|
|
9
|
+
export type AnalyticsEventBase = {
|
|
10
|
+
type:
|
|
11
|
+
| "DataExported"
|
|
12
|
+
| "InterviewCompleted"
|
|
13
|
+
| "InterviewStarted"
|
|
14
|
+
| "ProtocolInstalled"
|
|
15
|
+
| "AppSetup"
|
|
16
|
+
| "Error";
|
|
17
|
+
};
|
|
18
|
+
|
|
19
|
+
export type AnalyticsEvent = AnalyticsEventBase & {
|
|
20
|
+
type:
|
|
21
|
+
| "InterviewCompleted"
|
|
22
|
+
| "DataExported"
|
|
23
|
+
| "InterviewStarted"
|
|
24
|
+
| "ProtocolInstalled"
|
|
25
|
+
| "AppSetup";
|
|
26
|
+
metadata?: Record<string, unknown>;
|
|
27
|
+
};
|
|
28
|
+
|
|
29
|
+
export type AnalyticsError = AnalyticsEventBase & {
|
|
30
|
+
type: "Error";
|
|
31
|
+
error: {
|
|
32
|
+
message: string;
|
|
33
|
+
details: string;
|
|
34
|
+
stacktrace: string;
|
|
35
|
+
path: string;
|
|
36
|
+
};
|
|
37
|
+
};
|
|
38
|
+
|
|
39
|
+
export type AnalyticsEventOrError = AnalyticsEvent | AnalyticsError;
|
|
40
|
+
|
|
41
|
+
export type AnalyticsEventOrErrorWithTimestamp = AnalyticsEventOrError & {
|
|
42
|
+
timestamp: Date;
|
|
43
|
+
};
|
|
44
|
+
|
|
45
|
+
export type DispatchableAnalyticsEvent = AnalyticsEventOrErrorWithTimestamp & {
|
|
46
|
+
installationId: string;
|
|
47
|
+
geolocation?: GeoLocation;
|
|
48
|
+
};
|
|
49
|
+
|
|
50
|
+
type RouteHandlerConfiguration = {
|
|
51
|
+
platformUrl?: string;
|
|
52
|
+
installationId: string;
|
|
53
|
+
maxMindClient: WebServiceClient;
|
|
54
|
+
};
|
|
55
|
+
|
|
56
|
+
export const createRouteHandler = ({
|
|
57
|
+
platformUrl = "https://analytics.networkcanvas.com",
|
|
58
|
+
installationId,
|
|
59
|
+
maxMindClient,
|
|
60
|
+
}: RouteHandlerConfiguration) => {
|
|
61
|
+
return async (request: NextRequest) => {
|
|
62
|
+
try {
|
|
63
|
+
const event =
|
|
64
|
+
(await request.json()) as AnalyticsEventOrErrorWithTimestamp;
|
|
65
|
+
|
|
66
|
+
const ip = await fetch("https://api64.ipify.org").then((res) =>
|
|
67
|
+
res.text()
|
|
68
|
+
);
|
|
69
|
+
|
|
70
|
+
const { country } = await maxMindClient.country(ip);
|
|
71
|
+
const countryCode = country?.isoCode ?? "Unknown";
|
|
72
|
+
|
|
73
|
+
const dispatchableEvent: DispatchableAnalyticsEvent = {
|
|
74
|
+
...event,
|
|
75
|
+
installationId,
|
|
76
|
+
geolocation: {
|
|
77
|
+
countryCode,
|
|
78
|
+
},
|
|
79
|
+
};
|
|
80
|
+
|
|
81
|
+
// Forward to microservice
|
|
82
|
+
const response = await fetch(`${platformUrl}/api/event`, {
|
|
83
|
+
keepalive: true,
|
|
84
|
+
method: "POST",
|
|
85
|
+
headers: {
|
|
86
|
+
"Content-Type": "application/json",
|
|
87
|
+
},
|
|
88
|
+
body: JSON.stringify(dispatchableEvent),
|
|
89
|
+
});
|
|
90
|
+
|
|
91
|
+
if (!response.ok) {
|
|
92
|
+
if (response.status === 404) {
|
|
93
|
+
console.error(
|
|
94
|
+
`Analytics platform not found. Please specify a valid platform URL.`
|
|
95
|
+
);
|
|
96
|
+
} else if (response.status === 500) {
|
|
97
|
+
console.error(
|
|
98
|
+
`Internal server error on analytics platform when forwarding event: ${response.statusText}.`
|
|
99
|
+
);
|
|
100
|
+
} else {
|
|
101
|
+
console.error(
|
|
102
|
+
`General error when forwarding event: ${response.statusText}`
|
|
103
|
+
);
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
return new Response(
|
|
107
|
+
JSON.stringify({ error: "Internal Server Error" }),
|
|
108
|
+
{
|
|
109
|
+
status: 500,
|
|
110
|
+
headers: {
|
|
111
|
+
"Content-Type": "application/json",
|
|
112
|
+
},
|
|
113
|
+
}
|
|
114
|
+
);
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
console.info(`🚀 Analytics event forwarded successfully.`);
|
|
118
|
+
console.info(JSON.stringify(dispatchableEvent, null, 2));
|
|
119
|
+
|
|
120
|
+
return new Response(
|
|
121
|
+
JSON.stringify({ message: "Event forwarded successfully" }),
|
|
122
|
+
{
|
|
123
|
+
status: 200,
|
|
124
|
+
headers: {
|
|
125
|
+
"Content-Type": "application/json",
|
|
126
|
+
},
|
|
127
|
+
}
|
|
128
|
+
);
|
|
129
|
+
} catch (e) {
|
|
130
|
+
const error = ensureError(e);
|
|
131
|
+
console.error("Error in route handler:", error);
|
|
132
|
+
|
|
133
|
+
// Return an appropriate error response
|
|
134
|
+
return new Response(JSON.stringify({ error: "Internal Server Error" }), {
|
|
135
|
+
status: 500,
|
|
136
|
+
headers: {
|
|
137
|
+
"Content-Type": "application/json",
|
|
138
|
+
},
|
|
139
|
+
});
|
|
140
|
+
}
|
|
141
|
+
};
|
|
142
|
+
};
|
|
143
|
+
|
|
144
|
+
export const makeEventTracker =
|
|
145
|
+
(endpoint: string = "/api/analytics") =>
|
|
146
|
+
async (event: AnalyticsEventOrError) => {
|
|
147
|
+
const endpointWithHost = getBaseUrl() + endpoint;
|
|
148
|
+
|
|
149
|
+
const eventWithTimeStamp = {
|
|
150
|
+
...event,
|
|
151
|
+
timestamp: new Date(),
|
|
152
|
+
};
|
|
153
|
+
|
|
154
|
+
try {
|
|
155
|
+
const response = await fetch(endpointWithHost, {
|
|
156
|
+
method: "POST",
|
|
157
|
+
keepalive: true,
|
|
158
|
+
body: JSON.stringify(eventWithTimeStamp),
|
|
159
|
+
headers: {
|
|
160
|
+
"Content-Type": "application/json",
|
|
161
|
+
},
|
|
162
|
+
});
|
|
163
|
+
|
|
164
|
+
if (!response.ok) {
|
|
165
|
+
if (response.status === 404) {
|
|
166
|
+
console.error(
|
|
167
|
+
`Analytics endpoint not found, did you forget to add the route?`
|
|
168
|
+
);
|
|
169
|
+
return;
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
if (response.status === 500) {
|
|
173
|
+
console.error(
|
|
174
|
+
`Internal server error when sending analytics event: ${response.statusText}. Check the route handler implementation.`
|
|
175
|
+
);
|
|
176
|
+
return;
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
console.error(
|
|
180
|
+
`General error sending analytics event: ${response.statusText}`
|
|
181
|
+
);
|
|
182
|
+
}
|
|
183
|
+
} catch (e) {
|
|
184
|
+
const error = ensureError(e);
|
|
185
|
+
|
|
186
|
+
console.error("Internal error with analytics:", error.message);
|
|
187
|
+
}
|
|
188
|
+
};
|
package/src/utils.ts
CHANGED
|
@@ -1,36 +1,36 @@
|
|
|
1
|
-
// Helper function that ensures that a value is an Error
|
|
2
|
-
export function ensureError(value: unknown): Error {
|
|
3
|
-
if (!value) return new Error("No value was thrown");
|
|
4
|
-
|
|
5
|
-
if (value instanceof Error) return value;
|
|
6
|
-
|
|
7
|
-
// Test if value inherits from Error
|
|
8
|
-
if (value.isPrototypeOf(Error)) return value as Error & typeof value;
|
|
9
|
-
|
|
10
|
-
let stringified = "[Unable to stringify the thrown value]";
|
|
11
|
-
try {
|
|
12
|
-
stringified = JSON.stringify(value);
|
|
13
|
-
} catch {}
|
|
14
|
-
|
|
15
|
-
const error = new Error(
|
|
16
|
-
`This value was thrown as is, not through an Error: ${stringified}`
|
|
17
|
-
);
|
|
18
|
-
return error;
|
|
19
|
-
}
|
|
20
|
-
|
|
21
|
-
export function getBaseUrl() {
|
|
22
|
-
if (typeof window !== "undefined")
|
|
23
|
-
// browser should use relative path
|
|
24
|
-
return "";
|
|
25
|
-
|
|
26
|
-
if (process.env.VERCEL_URL)
|
|
27
|
-
// reference for vercel.com
|
|
28
|
-
return `https://${process.env.VERCEL_URL}`;
|
|
29
|
-
|
|
30
|
-
if (process.env.NEXT_PUBLIC_URL)
|
|
31
|
-
// Manually set deployment URL from env
|
|
32
|
-
return process.env.NEXT_PUBLIC_URL;
|
|
33
|
-
|
|
34
|
-
// assume localhost
|
|
35
|
-
return `http://127.0.0.1:3000`;
|
|
36
|
-
}
|
|
1
|
+
// Helper function that ensures that a value is an Error
|
|
2
|
+
export function ensureError(value: unknown): Error {
|
|
3
|
+
if (!value) return new Error("No value was thrown");
|
|
4
|
+
|
|
5
|
+
if (value instanceof Error) return value;
|
|
6
|
+
|
|
7
|
+
// Test if value inherits from Error
|
|
8
|
+
if (value.isPrototypeOf(Error)) return value as Error & typeof value;
|
|
9
|
+
|
|
10
|
+
let stringified = "[Unable to stringify the thrown value]";
|
|
11
|
+
try {
|
|
12
|
+
stringified = JSON.stringify(value);
|
|
13
|
+
} catch {}
|
|
14
|
+
|
|
15
|
+
const error = new Error(
|
|
16
|
+
`This value was thrown as is, not through an Error: ${stringified}`
|
|
17
|
+
);
|
|
18
|
+
return error;
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
export function getBaseUrl() {
|
|
22
|
+
if (typeof window !== "undefined")
|
|
23
|
+
// browser should use relative path
|
|
24
|
+
return "";
|
|
25
|
+
|
|
26
|
+
if (process.env.VERCEL_URL)
|
|
27
|
+
// reference for vercel.com
|
|
28
|
+
return `https://${process.env.VERCEL_URL}`;
|
|
29
|
+
|
|
30
|
+
if (process.env.NEXT_PUBLIC_URL)
|
|
31
|
+
// Manually set deployment URL from env
|
|
32
|
+
return process.env.NEXT_PUBLIC_URL;
|
|
33
|
+
|
|
34
|
+
// assume localhost
|
|
35
|
+
return `http://127.0.0.1:3000`;
|
|
36
|
+
}
|
package/tsconfig.json
CHANGED
|
@@ -1,11 +1,11 @@
|
|
|
1
|
-
{
|
|
2
|
-
"extends": "tsconfig/react-library.json",
|
|
3
|
-
"include": [
|
|
4
|
-
"."
|
|
5
|
-
],
|
|
6
|
-
"exclude": [
|
|
7
|
-
"dist",
|
|
8
|
-
"build",
|
|
9
|
-
"node_modules"
|
|
10
|
-
]
|
|
1
|
+
{
|
|
2
|
+
"extends": "tsconfig/react-library.json",
|
|
3
|
+
"include": [
|
|
4
|
+
"."
|
|
5
|
+
],
|
|
6
|
+
"exclude": [
|
|
7
|
+
"dist",
|
|
8
|
+
"build",
|
|
9
|
+
"node_modules"
|
|
10
|
+
]
|
|
11
11
|
}
|
package/.turbo/turbo-test.log
DELETED
|
@@ -1,31 +0,0 @@
|
|
|
1
|
-
|
|
2
|
-
> @codaco/analytics@0.6.0-alpha test /Users/jmh629/Projects/error-analytics-microservice/packages/analytics
|
|
3
|
-
> NODE_OPTIONS=--experimental-vm-modules jest "--watch"
|
|
4
|
-
|
|
5
|
-
(node:55883) ExperimentalWarning: VM Modules is an experimental feature and might change at any time
|
|
6
|
-
(Use `node --trace-warnings ...` to show where the warning was created)
|
|
7
|
-
FAIL src/index.test.mjs
|
|
8
|
-
Analytics client package
|
|
9
|
-
✕ should be able to create a new client (1 ms)
|
|
10
|
-
|
|
11
|
-
● Analytics client package › should be able to create a new client
|
|
12
|
-
|
|
13
|
-
TypeError: Cannot read properties of undefined (reading 'platformUrl')
|
|
14
|
-
|
|
15
|
-
50 | private platformUrl?: string = "https://analytics.networkcanvas.dev";
|
|
16
|
-
51 | private installationId: string | null = null;
|
|
17
|
-
> 52 |
|
|
18
|
-
| ^
|
|
19
|
-
53 | private dispatchQueue: QueueObject<AnalyticsEventOrError>;
|
|
20
|
-
54 |
|
|
21
|
-
55 | private enabled: boolean = true;
|
|
22
|
-
|
|
23
|
-
at new s (src/index.ts:52:11)
|
|
24
|
-
at Object.<anonymous> (src/index.test.mjs:6:20)
|
|
25
|
-
|
|
26
|
-
Test Suites: 1 failed, 1 total
|
|
27
|
-
Tests: 1 failed, 1 total
|
|
28
|
-
Snapshots: 0 total
|
|
29
|
-
Time: 0.215 s, estimated 1 s
|
|
30
|
-
Ran all test suites related to changed files.
|
|
31
|
-
|