@flisk/analyze-tracking 0.1.0

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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2024 Flisk
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,119 @@
1
+ # @flisk/analyze-tracking
2
+ Analyzes tracking code in a project and generates data schemas
3
+
4
+ ## Usage
5
+ ```sh
6
+ npx @flisk/analyze-tracking /path/to/project
7
+ ```
8
+
9
+ Optional arguments:
10
+ - `--repository <repository_url>`: URL of the repository where the code is hosted (defaults to git remote origin in project directory)
11
+ - `--output <output_file>`: Name of the output file (default: `tracking-schema.yaml`)
12
+
13
+
14
+ ## Output Schema
15
+ A YAML file with the following structure is generated:
16
+
17
+ ```yaml
18
+ version: 1.0
19
+ events:
20
+ <event_name>:
21
+ sources:
22
+ - repository: <repository_name>
23
+ path: <path_to_file>
24
+ line: <line_number>
25
+ function: <function_name>
26
+ destinations:
27
+ - <destination_name>
28
+ properties:
29
+ <property_name>:
30
+ type: <property_type>
31
+ required: <property_required>
32
+ description: <property_description>
33
+ ```
34
+
35
+ See [schema.json](schema.json) for the output schema.
36
+
37
+
38
+ ## Supported tracking libraries
39
+
40
+ #### Google Analytics
41
+ ```js
42
+ gtag('event', '<event_name>', {
43
+ <event_parameters>
44
+ });
45
+ ```
46
+
47
+
48
+ #### Segment
49
+ ```js
50
+ analytics.track('<event_name>', {
51
+ <event_parameters>
52
+ });
53
+ ```
54
+
55
+
56
+ #### Mixpanel
57
+ ```js
58
+ mixpanel.track('<event_name>', {
59
+ <event_parameters>
60
+ });
61
+ ```
62
+
63
+
64
+ #### Amplitude
65
+ ```js
66
+ amplitude.logEvent('<event_name>', {
67
+ <event_parameters>
68
+ });
69
+ ```
70
+
71
+
72
+ #### Rudderstack
73
+ ```js
74
+ rudderanalytics.track('<event_name>', {
75
+ <event_parameters>
76
+ });
77
+ ```
78
+
79
+
80
+ #### mParticle
81
+ ```js
82
+ mParticle.logEvent('<event_name>', {
83
+ <event_parameters>
84
+ });
85
+ ```
86
+
87
+
88
+ #### Snowplow
89
+ ```js
90
+ snowplow('trackStructEvent', {
91
+ category: '<category>',
92
+ action: '<action>',
93
+ label: '<label>',
94
+ property: '<property>',
95
+ value: '<value> '
96
+ });
97
+ ```
98
+
99
+ ```js
100
+ trackStructEvent({
101
+ category: '<category>',
102
+ action: '<action>',
103
+ label: '<label>',
104
+ property: '<property>',
105
+ value: '<value>'
106
+ });
107
+ ```
108
+
109
+ ```js
110
+ buildStructEvent({
111
+ category: '<category>',
112
+ action: '<action>',
113
+ label: '<label>',
114
+ property: '<property>',
115
+ value: '<value>'
116
+ });
117
+ ```
118
+
119
+ _Note: Snowplow Self Describing Events are not supported yet._
@@ -0,0 +1,33 @@
1
+ #!/usr/bin/env node
2
+
3
+ const path = require('path');
4
+ const { execSync } = require('child_process');
5
+ const { run } = require('../src/index');
6
+
7
+ // Parse command-line arguments
8
+ const targetDir = process.argv[2];
9
+ const repositoryArgIndex = process.argv.indexOf('--repository');
10
+ const repositoryUrl = repositoryArgIndex !== -1 ? process.argv[repositoryArgIndex + 1] : null;
11
+ const outputArgIndex = process.argv.indexOf('--output');
12
+ const outputPath = outputArgIndex !== -1 ? process.argv[outputArgIndex + 1] : 'tracking-schema.yaml';
13
+
14
+ if (!targetDir) {
15
+ console.error('Please provide the path to the repository.');
16
+ process.exit(1);
17
+ }
18
+
19
+ // Function to get the repository URL using Git
20
+ function getRepositoryUrl() {
21
+ try {
22
+ const repoUrl = execSync('git config --get remote.origin.url', { cwd: targetDir, encoding: 'utf8' });
23
+ return repoUrl.trim();
24
+ } catch (error) {
25
+ console.warn('Could not retrieve repository URL. Using default value "unknown".');
26
+ return 'unknown';
27
+ }
28
+ }
29
+
30
+ // Determine the repository URL
31
+ const repository = repositoryUrl || getRepositoryUrl();
32
+
33
+ run(path.resolve(targetDir), repository, outputPath);
package/package.json ADDED
@@ -0,0 +1,30 @@
1
+ {
2
+ "name": "@flisk/analyze-tracking",
3
+ "version": "0.1.0",
4
+ "description": "Analyzes tracking code in a project and generates data schemas",
5
+ "main": "src/index.js",
6
+ "bin": {
7
+ "analyze-tracking": "bin/analyze-tracking.js"
8
+ },
9
+ "scripts": {
10
+ "start": "node bin/analyze-tracking.js",
11
+ "test": "echo \"Error: no test specified\" && exit 1"
12
+ },
13
+ "repository": {
14
+ "type": "git",
15
+ "url": "git+https://github.com/fliskdata/analyze-tracking.git"
16
+ },
17
+ "author": "Sameen Karim",
18
+ "license": "MIT",
19
+ "bugs": {
20
+ "url": "https://github.com/fliskdata/analyze-tracking/issues"
21
+ },
22
+ "homepage": "https://github.com/fliskdata/analyze-tracking#readme",
23
+ "dependencies": {
24
+ "@typescript-eslint/parser": "^8.1.0",
25
+ "acorn": "^8.12.1",
26
+ "acorn-walk": "^8.3.3",
27
+ "js-yaml": "^4.1.0",
28
+ "typescript": "^5.5.4"
29
+ }
30
+ }
package/schema.json ADDED
@@ -0,0 +1,106 @@
1
+ {
2
+ "$schema": "http://json-schema.org/draft-07/schema#",
3
+ "title": "@flisk/analyze-tracking output schema",
4
+ "type": "object",
5
+ "properties": {
6
+ "version": {
7
+ "type": "number",
8
+ "enum": [
9
+ 1.0
10
+ ],
11
+ "description": "Version of the schema"
12
+ },
13
+ "events": {
14
+ "type": "object",
15
+ "patternProperties": {
16
+ "^[a-zA-Z0-9_-]+$": {
17
+ "type": "object",
18
+ "properties": {
19
+ "sources": {
20
+ "type": "array",
21
+ "items": {
22
+ "type": "object",
23
+ "properties": {
24
+ "repository": {
25
+ "type": "string",
26
+ "description": "Repository URL or name"
27
+ },
28
+ "path": {
29
+ "type": "string",
30
+ "description": "Relative path to the file where the event is tracked"
31
+ },
32
+ "line": {
33
+ "type": "integer",
34
+ "description": "Line number in the file where the event is tracked"
35
+ },
36
+ "function": {
37
+ "type": "string",
38
+ "description": "Name of the function where the event is tracked"
39
+ }
40
+ },
41
+ "required": [
42
+ "repository",
43
+ "path",
44
+ "line",
45
+ "function"
46
+ ]
47
+ }
48
+ },
49
+ "destinations": {
50
+ "type": "array",
51
+ "items": {
52
+ "type": "string",
53
+ "enum": [
54
+ "googleanalytics",
55
+ "segment",
56
+ "mixpanel",
57
+ "amplitude",
58
+ "rudderstack",
59
+ "mparticle",
60
+ "snowplow",
61
+ "unknown"
62
+ ],
63
+ "description": "Destination analytics platform"
64
+ }
65
+ },
66
+ "properties": {
67
+ "type": "object",
68
+ "patternProperties": {
69
+ "^[a-zA-Z0-9_-]+$": {
70
+ "type": "object",
71
+ "properties": {
72
+ "type": {
73
+ "type": "string",
74
+ "description": "Data type of the property (e.g., string, number)"
75
+ },
76
+ "required": {
77
+ "type": "boolean",
78
+ "description": "Whether this property is required"
79
+ },
80
+ "description": {
81
+ "type": "string",
82
+ "description": "Description of the property"
83
+ }
84
+ },
85
+ "required": [
86
+ "type"
87
+ ]
88
+ }
89
+ }
90
+ }
91
+ },
92
+ "required": [
93
+ "sources",
94
+ "destinations",
95
+ "properties"
96
+ ]
97
+ }
98
+ },
99
+ "additionalProperties": false
100
+ }
101
+ },
102
+ "required": [
103
+ "version",
104
+ "events"
105
+ ]
106
+ }
@@ -0,0 +1,52 @@
1
+ const fs = require('fs');
2
+ const acorn = require('acorn');
3
+ const walk = require('acorn-walk');
4
+ const { detectSourceJs, findWrappingFunctionJs, extractJsProperties } = require('./helpers');
5
+
6
+ function analyzeJsFile(filePath) {
7
+ const code = fs.readFileSync(filePath, 'utf8');
8
+ const ast = acorn.parse(code, { ecmaVersion: 'latest', sourceType: 'module', locations: true });
9
+ const events = [];
10
+
11
+ walk.ancestor(ast, {
12
+ CallExpression(node, ancestors) {
13
+ const source = detectSourceJs(node);
14
+ if (source === 'unknown') return;
15
+
16
+ let eventName = null;
17
+ let propertiesNode = null;
18
+
19
+ if (source === 'googleanalytics' && node.arguments.length >= 3) {
20
+ eventName = node.arguments[1]?.value || null;
21
+ propertiesNode = node.arguments[2];
22
+ } else if (source === 'snowplow' && node.arguments.length >= 2) {
23
+ const actionProperty = node.arguments[1].properties.find(prop => prop.key.name === 'action');
24
+ eventName = actionProperty ? actionProperty.value.value : null;
25
+ propertiesNode = node.arguments[1];
26
+ } else if (node.arguments.length >= 2) {
27
+ eventName = node.arguments[0]?.value || null;
28
+ propertiesNode = node.arguments[1];
29
+ }
30
+
31
+ const line = node.loc.start.line;
32
+ const functionName = findWrappingFunctionJs(ancestors[ancestors.length - 2]);
33
+
34
+ if (eventName && propertiesNode && propertiesNode.type === 'ObjectExpression') {
35
+ const properties = extractJsProperties(propertiesNode);
36
+
37
+ events.push({
38
+ eventName,
39
+ source,
40
+ properties,
41
+ filePath,
42
+ line,
43
+ functionName
44
+ });
45
+ }
46
+ },
47
+ });
48
+
49
+ return events;
50
+ }
51
+
52
+ module.exports = { analyzeJsFile };
@@ -0,0 +1,52 @@
1
+ const ts = require('typescript');
2
+ const { detectSourceTs, findWrappingFunctionTs, extractProperties } = require('./helpers');
3
+
4
+ function analyzeTsFile(filePath, program) {
5
+ const sourceFile = program.getSourceFile(filePath);
6
+ const checker = program.getTypeChecker();
7
+ const events = [];
8
+
9
+ function visit(node) {
10
+ if (ts.isCallExpression(node)) {
11
+ const source = detectSourceTs(node);
12
+ if (source === 'unknown') return;
13
+
14
+ let eventName = null;
15
+ let propertiesNode = null;
16
+
17
+ if (source === 'googleanalytics' && node.arguments.length >= 3) {
18
+ eventName = node.arguments[1]?.text || null;
19
+ propertiesNode = node.arguments[2];
20
+ } else if (source === 'snowplow' && node.arguments.length >= 2) {
21
+ const actionProperty = node.arguments[1].properties.find(prop => prop.name.escapedText === 'action');
22
+ eventName = actionProperty ? actionProperty.initializer.text : null;
23
+ propertiesNode = node.arguments[1];
24
+ } else if (node.arguments.length >= 2) {
25
+ eventName = node.arguments[0]?.text || null;
26
+ propertiesNode = node.arguments[1];
27
+ }
28
+
29
+ const line = sourceFile.getLineAndCharacterOfPosition(node.getStart()).line + 1;
30
+ const functionName = findWrappingFunctionTs(node);
31
+
32
+ if (eventName && propertiesNode && ts.isObjectLiteralExpression(propertiesNode)) {
33
+ const properties = extractProperties(checker, propertiesNode);
34
+ events.push({
35
+ eventName,
36
+ source,
37
+ properties,
38
+ filePath,
39
+ line,
40
+ functionName
41
+ });
42
+ }
43
+ }
44
+ ts.forEachChild(node, visit);
45
+ }
46
+
47
+ ts.forEachChild(sourceFile, visit);
48
+
49
+ return events;
50
+ }
51
+
52
+ module.exports = { analyzeTsFile };
@@ -0,0 +1,139 @@
1
+ const ts = require('typescript');
2
+
3
+ function detectSourceJs(node) {
4
+ if (!node.callee) return 'unknown';
5
+
6
+ if (node.callee.type === 'Identifier' && node.callee.name === 'gtag') {
7
+ return 'googleanalytics';
8
+ } else if (node.callee.type === 'MemberExpression') {
9
+ const objectName = node.callee.object.name;
10
+ const methodName = node.callee.property.name;
11
+
12
+ if (objectName === 'analytics' && methodName === 'track') return 'segment';
13
+ if (objectName === 'mixpanel' && methodName === 'track') return 'mixpanel';
14
+ if (objectName === 'amplitude' && methodName === 'logEvent') return 'amplitude';
15
+ if (objectName === 'rudderanalytics' && methodName === 'track') return 'rudderstack';
16
+ if (objectName === 'mParticle' && methodName === 'logEvent') return 'mparticle';
17
+ } else if (node.callee.type === 'Identifier' && node.callee.name === 'snowplow') {
18
+ return 'snowplow';
19
+ }
20
+
21
+ return 'unknown';
22
+ }
23
+
24
+ function detectSourceTs(node) {
25
+ if (!node.expression) return 'unknown';
26
+
27
+ if (ts.isIdentifier(node.expression) && node.expression.escapedText === 'gtag') {
28
+ return 'googleanalytics';
29
+ } else if (ts.isPropertyAccessExpression(node.expression)) {
30
+ const objectName = node.expression.expression.escapedText;
31
+ const methodName = node.expression.name.escapedText;
32
+
33
+ if (objectName === 'analytics' && methodName === 'track') return 'segment';
34
+ if (objectName === 'mixpanel' && methodName === 'track') return 'mixpanel';
35
+ if (objectName === 'amplitude' && methodName === 'logEvent') return 'amplitude';
36
+ if (objectName === 'rudderanalytics' && methodName === 'track') return 'rudderstack';
37
+ if (objectName === 'mParticle' && methodName === 'logEvent') return 'mparticle';
38
+ } else if (ts.isIdentifier(node.expression) && node.expression.escapedText === 'snowplow') {
39
+ return 'snowplow';
40
+ }
41
+
42
+ return 'unknown';
43
+ }
44
+
45
+ function findWrappingFunctionTs(node) {
46
+ let current = node;
47
+ while (current) {
48
+ if (ts.isFunctionDeclaration(current) || ts.isMethodDeclaration(current) || ts.isArrowFunction(current)) {
49
+ return current.name ? current.name.escapedText : 'anonymous';
50
+ }
51
+ current = current.parent;
52
+ }
53
+ return 'global';
54
+ }
55
+
56
+ function findWrappingFunctionJs(node) {
57
+ let current = node;
58
+ while (current) {
59
+ if (current.type === 'FunctionDeclaration' || current.type === 'FunctionExpression' || current.type === 'ArrowFunctionExpression') {
60
+ return current.id ? current.id.name : 'anonymous';
61
+ }
62
+ current = current.parent;
63
+ }
64
+ return 'global';
65
+ }
66
+
67
+ function extractJsProperties(node) {
68
+ const properties = {};
69
+
70
+ node.properties.forEach((prop) => {
71
+ const key = prop.key?.name || prop.key?.value;
72
+ if (key) {
73
+ let valueType = typeof prop.value.value;
74
+ if (prop.value.type === 'ObjectExpression') {
75
+ properties[key] = {
76
+ type: 'object',
77
+ properties: extractJsProperties(prop.value),
78
+ };
79
+ } else {
80
+ if (valueType === 'undefined') {
81
+ valueType = 'any';
82
+ } else if (valueType === 'object') {
83
+ valueType = 'any';
84
+ }
85
+ properties[key] = { type: valueType };
86
+ }
87
+ }
88
+ });
89
+
90
+ return properties;
91
+ }
92
+
93
+ function extractProperties(checker, node) {
94
+ const properties = {};
95
+
96
+ node.properties.forEach((prop) => {
97
+ const key = prop.name ? prop.name.text : prop.key.text || prop.key.value;
98
+ let valueType = 'any';
99
+
100
+ if (prop.initializer) {
101
+ if (ts.isObjectLiteralExpression(prop.initializer)) {
102
+ properties[key] = {
103
+ type: 'object',
104
+ properties: extractProperties(checker, prop.initializer),
105
+ };
106
+ } else if (ts.isArrayLiteralExpression(prop.initializer)) {
107
+ properties[key] = {
108
+ type: 'array',
109
+ items: {
110
+ type: getTypeOfNode(checker, prop.initializer.elements[0]) || 'any',
111
+ },
112
+ };
113
+ } else {
114
+ valueType = getTypeOfNode(checker, prop.initializer) || 'any';
115
+ properties[key] = { type: valueType };
116
+ }
117
+ } else if (prop.type) {
118
+ valueType = checker.typeToString(checker.getTypeFromTypeNode(prop.type)) || 'any';
119
+ properties[key] = { type: valueType };
120
+ }
121
+ });
122
+
123
+ return properties;
124
+ }
125
+
126
+ function getTypeOfNode(checker, node) {
127
+ const type = checker.getTypeAtLocation(node);
128
+ return checker.typeToString(type);
129
+ }
130
+
131
+ module.exports = {
132
+ detectSourceJs,
133
+ detectSourceTs,
134
+ findWrappingFunctionTs,
135
+ findWrappingFunctionJs,
136
+ extractJsProperties,
137
+ extractProperties,
138
+ getTypeOfNode,
139
+ };
@@ -0,0 +1,58 @@
1
+ const { analyzeJsFile } = require('./analyzeJsFile');
2
+ const { analyzeTsFile } = require('./analyzeTsFile');
3
+ const { getAllFiles } = require('../fileProcessor');
4
+ const ts = require('typescript');
5
+ const path = require('path');
6
+
7
+ function analyzeDirectory(dirPath, repository) {
8
+ const files = getAllFiles(dirPath);
9
+ const allEvents = {};
10
+
11
+ const tsFiles = files.filter(file => file.endsWith('.ts'));
12
+ const program = ts.createProgram(tsFiles, {
13
+ target: ts.ScriptTarget.ESNext,
14
+ module: ts.ModuleKind.CommonJS,
15
+ });
16
+
17
+ files.forEach((file) => {
18
+ const isTsFile = file.endsWith('.ts');
19
+ const events = isTsFile ? analyzeTsFile(file, program) : analyzeJsFile(file);
20
+
21
+ events.forEach((event) => {
22
+ const relativeFilePath = path.relative(dirPath, event.filePath); // Calculate relative path
23
+
24
+ if (!allEvents[event.eventName]) {
25
+ allEvents[event.eventName] = {
26
+ sources: [{
27
+ repository: repository,
28
+ path: relativeFilePath,
29
+ line: event.line,
30
+ function: event.functionName
31
+ }],
32
+ destinations: [event.source],
33
+ properties: event.properties,
34
+ };
35
+ } else {
36
+ allEvents[event.eventName].sources.push({
37
+ repository: repository,
38
+ path: relativeFilePath,
39
+ line: event.line,
40
+ function: event.functionName
41
+ });
42
+
43
+ if (!allEvents[event.eventName].destinations.includes(event.source)) {
44
+ allEvents[event.eventName].destinations.push(event.source);
45
+ }
46
+
47
+ allEvents[event.eventName].properties = {
48
+ ...allEvents[event.eventName].properties,
49
+ ...event.properties,
50
+ };
51
+ }
52
+ });
53
+ });
54
+
55
+ return allEvents;
56
+ }
57
+
58
+ module.exports = { analyzeDirectory };
package/src/cli.js ADDED
@@ -0,0 +1,11 @@
1
+ #!/usr/bin/env node
2
+
3
+ const { run } = require('./index');
4
+ const targetDir = process.argv[2];
5
+
6
+ if (!targetDir) {
7
+ console.error('Please provide the path to the repository.');
8
+ process.exit(1);
9
+ }
10
+
11
+ run(path.resolve(targetDir));
@@ -0,0 +1,19 @@
1
+ const fs = require('fs');
2
+ const path = require('path');
3
+
4
+ function getAllFiles(dirPath, arrayOfFiles = []) {
5
+ const files = fs.readdirSync(dirPath);
6
+
7
+ files.forEach((file) => {
8
+ const fullPath = path.join(dirPath, file);
9
+ if (fs.statSync(fullPath).isDirectory()) {
10
+ arrayOfFiles = getAllFiles(fullPath, arrayOfFiles);
11
+ } else if (file.endsWith('.js') || file.endsWith('.ts')) {
12
+ arrayOfFiles.push(fullPath);
13
+ }
14
+ });
15
+
16
+ return arrayOfFiles;
17
+ }
18
+
19
+ module.exports = { getAllFiles };
package/src/index.js ADDED
@@ -0,0 +1,9 @@
1
+ const { analyzeDirectory } = require('./analyze');
2
+ const { generateYamlSchema } = require('./yamlGenerator');
3
+
4
+ function run(targetDir, repository, outputPath) {
5
+ const events = analyzeDirectory(targetDir, repository);
6
+ generateYamlSchema(events, outputPath);
7
+ }
8
+
9
+ module.exports = { run };
@@ -0,0 +1,15 @@
1
+ const fs = require('fs');
2
+ const yaml = require('js-yaml');
3
+
4
+ function generateYamlSchema(events, outputPath) {
5
+ const schema = {
6
+ version: 1.0,
7
+ events,
8
+ };
9
+
10
+ const yamlOutput = yaml.dump(schema, { noRefs: true });
11
+ fs.writeFileSync(outputPath, yamlOutput, 'utf8');
12
+ console.log(`Tracking schema YAML file generated: ${outputPath}`);
13
+ }
14
+
15
+ module.exports = { generateYamlSchema };