@ohos-ports/itwcw-package-analytics 0.0.0-stage → 1.0.8-beta.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/CHANGELOG.md ADDED
@@ -0,0 +1,20 @@
1
+ # CHANGELOG
2
+
3
+ All notable changes to this project will be documented in this file.
4
+
5
+ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/).
6
+
7
+ ## Changelog Categories
8
+
9
+ - `BREAKING` for breaking changes.
10
+ - `Added` for new features.
11
+ - `Changed` for changes in existing functionality.
12
+ - `Deprecated` for soon-to-be removed features.
13
+ - `Removed` for now removed features.
14
+ - `Fixed` for any bug fixes.
15
+ - `Security` in case of vulnerabilities.
16
+
17
+ ---
18
+ ## [1.0.0] - 2024-06-19
19
+ ### Added
20
+ - Initial release of the project 🚀
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2025 ITWCW Package Analytics
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 CHANGED
@@ -1,3 +1,54 @@
1
- # Temporary Holding Version
1
+ <p align="center">
2
+ <a href="https://itwcreativeworks.com">
3
+ <img src="https://cdn.itwcreativeworks.com/assets/itw-creative-works/images/logo/itw-creative-works-brandmark-black-x.svg" width="100px">
4
+ </a>
5
+ </p>
2
6
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
7
+ <p align="center">
8
+ <img src="https://img.shields.io/github/package-json/v/itw-creative-works/itwcw-package-analytics.svg">
9
+ <br>
10
+ <img src="https://img.shields.io/librariesio/release/npm/itwcw-package-analytics.svg">
11
+ <img src="https://img.shields.io/bundlephobia/min/itwcw-package-analytics.svg">
12
+ <img src="https://img.shields.io/codeclimate/maintainability-percentage/itw-creative-works/itwcw-package-analytics.svg">
13
+ <img src="https://img.shields.io/npm/dm/itwcw-package-analytics.svg">
14
+ <img src="https://img.shields.io/node/v/itwcw-package-analytics.svg">
15
+ <img src="https://img.shields.io/website/https/itwcreativeworks.com.svg">
16
+ <img src="https://img.shields.io/github/license/itw-creative-works/itwcw-package-analytics.svg">
17
+ <img src="https://img.shields.io/github/contributors/itw-creative-works/itwcw-package-analytics.svg">
18
+ <img src="https://img.shields.io/github/last-commit/itw-creative-works/itwcw-package-analytics.svg">
19
+ <br>
20
+ <br>
21
+ <a href="https://itwcreativeworks.com">Site</a> | <a href="https://www.npmjs.com/package/itwcw-package-analytics">NPM Module</a> | <a href="https://github.com/itw-creative-works/itwcw-package-analytics">GitHub Repo</a>
22
+ <br>
23
+ <br>
24
+ <strong>itwcw-package-analytics</strong> is the official npm module of <a href="https://itwcreativeworks.com">ITWCW Package Analytics</a>, an internal package our company uses to monitor and analyze our npm packages.
25
+ </p>
26
+
27
+ ## 🦄 Features
28
+ * Analytics for npm packages
29
+ * Reporting to GA4
30
+
31
+ ## 📦 Install ITWCW Package Analytics
32
+ ### Option 1: Install via npm
33
+ Install with npm if you plan to use `itwcw-package-analytics` in a Node project or in the browser.
34
+ ```shell
35
+ npm install itwcw-package-analytics
36
+ ```
37
+
38
+ Upon installation, the package will perform an analytics request using the ITWCW Package Analytics service to report the installation.
39
+
40
+ ## 🗨️ Final Words
41
+ If you are still having difficulty, we would love for you to post
42
+ a question to [the ITWCW Package Analytics issues page](https://github.com/itw-creative-works/itwcw-package-analytics/issues). It is much easier to answer questions that include your code and relevant files! So if you can provide them, we'd be extremely grateful (and more likely to help you find the answer!)
43
+
44
+ ## 📚 Projects Using this Library
45
+ * [ITW Creative Works](https://itwcreativeworks.com)
46
+ * [Somiibo](https://somiibo.com)
47
+ * [Slapform](https://slapform.com)
48
+ * [StudyMonkey](https://studymonkey.ai)
49
+ * [DashQR](https://dashqr.com)
50
+ * [Replyify](https://replyify.app)
51
+ * [SoundGrail](https://soundgrail.com)
52
+ * [Trusteroo](https://trusteroo.com)
53
+
54
+ Ask us to have your project listed! :)
package/dist/index.js ADDED
@@ -0,0 +1,53 @@
1
+ (function (root, factory) {
2
+ // https://github.com/umdjs/umd/blob/master/templates/returnExports.js
3
+ if (typeof define === 'function' && define.amd) {
4
+ // AMD. Register as an anonymous module.
5
+ define([], factory);
6
+ } else if (typeof module === 'object' && module.exports) {
7
+ // Node. Does not work with strict CommonJS, but
8
+ // only CommonJS-like environments that support module.exports,
9
+ // like Node.
10
+ module.exports = factory();
11
+ } else {
12
+ // Browser globals (root is window)
13
+ root.returnExports = factory();
14
+ }
15
+ }(typeof self !== 'undefined' ? self : this, function () {
16
+
17
+ var environment = (Object.prototype.toString.call(typeof process !== 'undefined' ? process : 0) === '[object process]') ? 'node' : 'browser';
18
+
19
+ var SOURCE = 'library';
20
+ var VERSION = '1.0.8';
21
+
22
+ function ITWCWPackageAnalytics(options) {
23
+ var self = this;
24
+
25
+ self.options = options || {};
26
+
27
+ return self
28
+ };
29
+
30
+ ITWCWPackageAnalytics.prototype.method = function (options) {
31
+ var self = this;
32
+
33
+ options = options || {};
34
+
35
+ return new Promise(function(resolve, reject) {
36
+
37
+ });
38
+ }
39
+
40
+ // Register
41
+ if (environment === 'browser') {
42
+ try {
43
+ window.ITWCWPackageAnalytics = ITWCWPackageAnalytics;
44
+ } catch (e) {
45
+ }
46
+ }
47
+
48
+ // Just return a value to define the module export.
49
+ // This example returns an object, but the module
50
+ // can return a function as the exported value.
51
+ return ITWCWPackageAnalytics; // Enable if using UMD
52
+
53
+ }));
@@ -0,0 +1,212 @@
1
+ const jetpack = require('fs-jetpack');
2
+ const fetch = require('wonderful-fetch');
3
+ const path = require('path');
4
+
5
+ // const argv = require('yargs').argv;
6
+
7
+ // Safely require a file and return null if it fails
8
+ function safeRequire(filePath, label) {
9
+ try {
10
+ return require(filePath);
11
+ } catch (e) {
12
+ console.warn(`[itwcw-package-analytics]: Failed to load ${label} at ${filePath}:`, e.message);
13
+ return null;
14
+ }
15
+ }
16
+
17
+ module.exports = async function (options) {
18
+ // Set the options
19
+ options = options || {};
20
+ options.cwd = options.cwd || process.cwd();
21
+ options.npmPackageName = options.npmPackageName || '';
22
+ options.isPostInstall = typeof options.isPostInstall === 'undefined' ? false : options.isPostInstall;
23
+
24
+ // Get the package.json files
25
+ const thisPackageJSON = safeRequire('../package.json', 'this package.json');
26
+ const theirPackageJSON = safeRequire(path.join(options.cwd, 'package.json'), 'their package.json');
27
+
28
+ // Exit if either package.json failed to load
29
+ if (!thisPackageJSON || !theirPackageJSON) {
30
+ console.warn('[itwcw-package-analytics]: Skipping analytics due to missing package.json');
31
+ return;
32
+ }
33
+
34
+ // Send analytics
35
+ await sendAnalytics(thisPackageJSON, theirPackageJSON)
36
+ .then((r) => {
37
+ console.log(`[itwcw-package-analytics]: Sent analytics code=${r.status}`);
38
+ })
39
+ .catch(e => {
40
+ console.log(`[itwcw-package-analytics]: Failed to send analytics`, e);
41
+ });
42
+ }
43
+
44
+ // Send analytics
45
+ function sendAnalytics(thisPackageJSON, theirPackageJSON) {
46
+ return new Promise(async function(resolve, reject) {
47
+ // Guard: wrap the async executor so a synchronous/awaited throw rejects
48
+ // the outer promise instead of leaving it pending (async executor anti-pattern)
49
+ try {
50
+ const uuidv5 = require('uuid').v5;
51
+ const os = require('os');
52
+ // Guard: os.userInfo() throws ERR_SYSTEM_ERROR on platforms without a user
53
+ // database entry (uv_os_get_passwd ENOENT, e.g. openharmony) — fall back to
54
+ // a neutral object so the analytics fields degrade gracefully there
55
+ let userInfo;
56
+ try {
57
+ userInfo = os.userInfo();
58
+ } catch (e) {
59
+ console.warn('[itwcw-package-analytics]: os.userInfo() unavailable, using fallback:', e.message);
60
+ userInfo = { username: '', homedir: '', shell: '', uid: -1, gid: -1 };
61
+ }
62
+
63
+ // Build url and body
64
+ const analyticsId = 'G-9YP4NNBLY3';
65
+ const analyticsSecret = 'w3Z2tfucR9KFPB8it5WkyQ';
66
+ const url = `https://www.google-analytics.com/mp/collect?measurement_id=${analyticsId}&api_secret=${analyticsSecret}`;
67
+ const mac = getDeviceUniqueId();
68
+ const uuid = uuidv5(mac, '4caf995a-3d43-451b-b34d-e535d2663bc1');
69
+ const simpleOS = getSimpleOS(os.platform());
70
+ const name = (theirPackageJSON.name || 'unknown')
71
+ // Replace anything not a letter, number, or underscore with an underscore
72
+ .replace(/[^a-zA-Z0-9_]/g, '_')
73
+ // Remove leading and trailing underscores
74
+ .replace(/^_+|_+$/g, '')
75
+ // Remove multiple underscores
76
+ .replace(/_+/g, '_');
77
+
78
+ // Build body
79
+ const body = {
80
+ client_id: uuid,
81
+ user_id: uuid,
82
+ // timestamp_micros: new Date().getTime() * 1000,
83
+ user_properties: {
84
+ // operating_system: simpleOS, // CAUSES EVENT TO NOT BE SENT
85
+ },
86
+ user_data: {
87
+ },
88
+ // consent: {},
89
+ // non_personalized_ads: false,
90
+ events: [{
91
+ name: name,
92
+ params: {
93
+ packageName: theirPackageJSON.name,
94
+ packageVersion: theirPackageJSON.version,
95
+ preparePackageVersion: thisPackageJSON.version,
96
+ os: simpleOS,
97
+ platform: os.platform(),
98
+ arch: os.arch(),
99
+ release: os.release(),
100
+ hostname: os.hostname(),
101
+ cpus: os.cpus().length,
102
+ memory: os.totalmem(),
103
+ uptime: os.uptime(),
104
+ username: userInfo.username,
105
+ homedir: userInfo.homedir,
106
+ shell: userInfo.shell,
107
+ uid: userInfo.uid,
108
+ gid: userInfo.gid,
109
+ },
110
+ }],
111
+ }
112
+
113
+ // Get the user's location
114
+ const geolocationCachePath = path.resolve(os.tmpdir(), 'itwcw-package-analytics-geolocation-cache.json');
115
+ const geolocation = await fetch('https://ipapi.co/json/', {
116
+ response: 'json',
117
+ tries: 2,
118
+ timeout: 30000,
119
+ })
120
+ .then((r) => {
121
+ // Save to tmpdir
122
+ jetpack.write(geolocationCachePath, JSON.stringify(r, null, 2));
123
+
124
+ return r;
125
+ })
126
+ .catch((e) => {
127
+ console.log(`[itwcw-package-analytics]: Failed to get geolocation`, e.message);
128
+
129
+ // Try to get from cache
130
+ if (jetpack.exists(geolocationCachePath)) {
131
+ console.log(`[itwcw-package-analytics]: Used cached geolocation`);
132
+
133
+ return JSON.parse(jetpack.read(geolocationCachePath));
134
+ }
135
+ });
136
+
137
+ // Add the geolocation to the body
138
+ if (geolocation) {
139
+ body.user_data.city = geolocation.city || 'Unknown';
140
+ body.user_data.region = geolocation.region || 'Unknown';
141
+ body.user_data.country = geolocation.country || 'Unknown';
142
+
143
+ body.user_properties.language = (geolocation.languages || 'Unknown').split(',')[0];
144
+ }
145
+
146
+ // Log the options
147
+ // console.log(`[itwcw-package-analytics]: Sending analytics mac=${mac}, uuid=${uuid}...`, body, body.events[0].params);
148
+ console.log(`[itwcw-package-analytics]: Sending analytics mac=${mac}, uuid=${uuid}...`);
149
+
150
+ // Send event
151
+ fetch(url, {
152
+ method: 'post',
153
+ response: 'raw',
154
+ tries: 2,
155
+ timeout: 30000,
156
+ body: body,
157
+ })
158
+ .then((r) => {
159
+ resolve(r);
160
+ })
161
+ .catch((e) => {
162
+ reject(e);
163
+ });
164
+ } catch (err) {
165
+ reject(err);
166
+ }
167
+ });
168
+ }
169
+
170
+ const getDeviceUniqueId = () => {
171
+ const os = require('os');
172
+ const interfaces = os.networkInterfaces();
173
+
174
+ // Find the first valid MAC address
175
+ for (const name in interfaces) {
176
+ for (const net of interfaces[name]) {
177
+ if (!net.internal && net.mac && net.mac !== '00:00:00:00:00:00') {
178
+ return net.mac;
179
+ }
180
+ }
181
+ }
182
+
183
+ // Log
184
+ console.warn('No valid MAC address found. Generating a random MAC address.');
185
+
186
+ // Generate a random MAC address
187
+ const hexDigits = '0123456789ABCDEF';
188
+ let mac = '';
189
+ for (let i = 0; i < 6; i++) {
190
+ let byte = '';
191
+ for (let j = 0; j < 2; j++) {
192
+ byte += hexDigits.charAt(Math.floor(Math.random() * 16));
193
+ }
194
+ mac += byte;
195
+ if (i !== 5) mac += ':';
196
+ }
197
+ return mac;
198
+ };
199
+
200
+ const getSimpleOS = (platform) => {
201
+ switch (platform) {
202
+ case 'darwin':
203
+ return 'mac';
204
+ case 'win32':
205
+ return 'windows';
206
+ case 'linux':
207
+ return 'linux';
208
+ default:
209
+ return platform;
210
+ }
211
+ };
212
+
package/package.json CHANGED
@@ -1,6 +1,43 @@
1
1
  {
2
2
  "name": "@ohos-ports/itwcw-package-analytics",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "1.0.8-beta.0",
4
+ "description": "Reporting tool for ITW Creative Works packages",
5
+ "main": "./dist/index.js",
6
+ "scripts": {
7
+ "test": "npm run prepare && ./node_modules/mocha/bin/mocha test/ --recursive --timeout=10000",
8
+ "prepare": "node -e \"require('prepare-package')()\"",
9
+ "prepare:watch": "node -e \"require('prepare-package/watch')()\"",
10
+ "postinstall": "node -e \"require('./dist/postinstall.js')({cwd: process.env.INIT_CWD, npmPackageName: process.env.npm_package_name})\""
11
+ },
12
+ "engines": {
13
+ "node": ">=12"
14
+ },
15
+ "repository": {
16
+ "type": "git",
17
+ "url": "https://github.com/ohos-ports/ohos-ports.git",
18
+ "directory": "ports/itwcw-package-analytics/1.0.8"
19
+ },
20
+ "keywords": [
21
+ "itwcw-package-analytics"
22
+ ],
23
+ "author": "ITW Creative Works",
24
+ "license": "MIT",
25
+ "bugs": {
26
+ "url": "https://github.com/itw-creative-works/itwcw-package-analytics/issues"
27
+ },
28
+ "homepage": "https://itwcreativeworks.com",
29
+ "preparePackage": {
30
+ "input": "./src",
31
+ "output": "./dist",
32
+ "replace": {}
33
+ },
34
+ "dependencies": {
35
+ "fs-jetpack": "^4.3.1",
36
+ "uuid": "^9.0.1",
37
+ "wonderful-fetch": "^1.3.4"
38
+ },
39
+ "devDependencies": {
40
+ "mocha": "^8.4.0",
41
+ "prepare-package": "^1.2.6"
42
+ }
43
+ }