# usage-stats

> A minimal, offline-friendly Google Analytics Measurement Protocol client for tracking statistics in shell and javascript applications

Latest version **0.9.5** (published 2023-01-16) · MIT license · 0 weekly downloads

> **Deprecated.** This package is deprecated.

## Install

```sh
npm install usage-stats
pnpm add usage-stats
yarn add usage-stats
bun add usage-stats
```

## Health

**Score 10/100 (F)** — status: deprecated.

Negative: deprecated.

## Facts

| | |
|---|---|
| Version | 0.9.5 |
| Published | 2023-01-16 |
| First published | 2016-08-07 |
| Weekly downloads | 0 |
| License | MIT |
| TypeScript types | none |
| Module format | CommonJS |
| Node | >=4.0.0 |
| Dependencies | 6 |
| Unpacked size | 56.5 KB |
| Known vulnerabilities | 0 (+1 in 1 direct dependencies) |
| Install scripts | no |
| GitHub stars | 13 |
| Author | Lloyd Brookes |
| Maintainers | 75lb |
| Keywords | google, analytics, measurement, protocol, tracking, usage, stats, app, application, ga |

## Links

- npm: https://www.npmjs.com/package/usage-stats
- Repository: https://github.com/75lb/usage-stats
- Homepage: https://github.com/75lb/usage-stats#readme
- Issues: https://github.com/75lb/usage-stats/issues
- npm.io page: https://npm.io/package/usage-stats

## Dependencies (6)

- [uuid](https://npm.io/package/uuid.md) ^3.1.0
- [mkdirp2](https://npm.io/package/mkdirp2.md) ^1.0.3
- [typical](https://npm.io/package/typical.md) ^2.6.1
- [req-then](https://npm.io/package/req-then.md) ^0.6.4
- [home-path](https://npm.io/package/home-path.md) ^1.0.5
- [array-back](https://npm.io/package/array-back.md) ^2.0.0

## Alternatives

- [@sentry/react-native](https://npm.io/package/@sentry/react-native.md) — 2.6M weekly downloads
- [@ardatan/aggregate-error](https://npm.io/package/@ardatan/aggregate-error.md) — 708.1K weekly downloads
- [custom-error-generator](https://npm.io/package/custom-error-generator.md) — 2.0K weekly downloads
- [@technik-sde/prosemirror-recreate-transform](https://npm.io/package/@technik-sde/prosemirror-recreate-transform.md) — 1.5K weekly downloads
- [@suchipi/error-utils](https://npm.io/package/@suchipi/error-utils.md) — 78 weekly downloads

## Recent versions

- 0.9.5 (latest) — 2023-01-16
- 0.8.6 (prev) — 2017-06-04
- 0.9.4 — 2017-07-10
- 0.9.3 — 2017-06-26
- 0.9.2 — 2017-06-26
- 0.9.1 — 2017-05-14
- 0.8.5 — 2017-05-06
- 0.8.4 — 2017-05-06
- 0.8.3 — 2017-05-06
- 0.9.0 — 2017-02-10
- 0.8.2 — 2016-11-23
- 0.8.1 — 2016-11-08
- 0.8.0 — 2016-11-01
- 0.7.0 — 2016-09-29
- 0.6.0 — 2016-09-20
- … 20 more at https://npm.io/package/usage-stats/versions

## README

[![view on npm](https://badgen.net/npm/v/usage-stats)](https://www.npmjs.org/package/usage-stats)
[![npm module downloads](https://badgen.net/npm/dt/usage-stats)](https://www.npmjs.org/package/usage-stats)
[![Gihub repo dependents](https://badgen.net/github/dependents-repo/75lb/usage-stats)](https://github.com/75lb/usage-stats/network/dependents?dependent_type=REPOSITORY)
[![Gihub package dependents](https://badgen.net/github/dependents-pkg/75lb/usage-stats)](https://github.com/75lb/usage-stats/network/dependents?dependent_type=PACKAGE)
[![Node.js CI](https://github.com/75lb/usage-stats/actions/workflows/node.js.yml/badge.svg)](https://github.com/75lb/usage-stats/actions/workflows/node.js.yml)
[![js-standard-style](https://img.shields.io/badge/code%20style-standard-brightgreen.svg)](https://github.com/feross/standard)

# usage-stats

A minimal, offline-friendly [Google Analytics Measurement Protocol](https://developers.google.com/analytics/devguides/collection/protocol/v1/) client for tracking usage statistics in shell and javascript applications.

This is a low-level API client, it doesn't hold any opinion of how usage tracking should be done. If you're looking for a convention which leverages the power and flexibility of [Custom Metrics and Dimensions](https://support.google.com/analytics/answer/2709828?hl=en&ref_topic=2709827), take a look at [app-usage-stats](https://github.com/75lb/app-usage-stats). For the command line client see [usage-stats-cli](https://github.com/75lb/usage-stats-cli).

## Synopsis

The most trivial example.

```js
const UsageStats = require('usage-stats')
const usageStats = new UsageStats('UA-98765432-1', { an: 'example' })

usageStats.screenView('screen name')
usageStats.event('category', 'action')
usageStats.send()
```

More realistic usage in a server application:

```js
const UsageStats = require('usage-stats')
const usageStats = new UsageStats('UA-98765432-1', {
  an: 'encode-video',
  av: '1.0.0'
})

// start a new session
usageStats.start()

// user set two options..
usageStats.event('option', 'verbose-level', 'infinite')
usageStats.event('option', 'preset', 'iPod')

try {
  // Begin. Track as a screenView.
  usageStats.screenView('encoding')
  beginEncoding(options)
} catch (err) {
  // Exception tracking
  usageStats.exception(err.message, true)
}

// finished - mark the session as complete
// and send stats (or store if offline).
usageStats.end().send()
```

## Protocol Parameters

See [here](https://developers.google.com/analytics/devguides/collection/protocol/v1/parameters) for the full list of Google Analytics Measurement Protocol parameters.

### Sent by default

All parameters are send on demand, beside this list.

* Operating System version (sent in the UserAgent)
* [Client ID](https://developers.google.com/analytics/devguides/collection/protocol/v1/parameters#cid) (a random UUID, generated once per OS user and stored)
* [Language](https://developers.google.com/analytics/devguides/collection/protocol/v1/parameters#ul) (`process.env.LANG`, if set)
* [Screen resolution](https://developers.google.com/analytics/devguides/collection/protocol/v1/parameters#sr) (terminal rows by columns, by default)

## API Reference

**Kind**: Exported class  
* [UsageStats](#exp_module_usage-stats--UsageStats) ⏏
    * [new UsageStats(trackingId, [options])](#new_module_usage-stats--UsageStats_new)
    * [.dir](#module_usage-stats--UsageStats.UsageStats+dir) : <code>string</code>
    * [.defaults](#module_usage-stats--UsageStats.UsageStats+defaults) : <code>Map</code>
    * [.start([sessionParams])](#module_usage-stats--UsageStats+start) ↩︎
    * [.end([sessionParams])](#module_usage-stats--UsageStats+end) ↩︎
    * [.disable()](#module_usage-stats--UsageStats+disable) ↩︎
    * [.enable()](#module_usage-stats--UsageStats+enable) ↩︎
    * [.event(category, action, [options])](#module_usage-stats--UsageStats+event) ⇒ <code>Map</code>
    * [.screenView(name, [options])](#module_usage-stats--UsageStats+screenView) ⇒ <code>Map</code>
    * [.exception([options])](#module_usage-stats--UsageStats+exception) ⇒ <code>Map</code>
    * [.send([options])](#module_usage-stats--UsageStats+send) ⇒ <code>Promise</code>
    * [.debug()](#module_usage-stats--UsageStats+debug) ⇒ <code>Promise</code>
    * [.abort()](#module_usage-stats--UsageStats+abort) ↩︎

<a name="new_module_usage-stats--UsageStats_new"></a>

### new UsageStats(trackingId, [options])

| Param | Type | Description |
| --- | --- | --- |
| trackingId | <code>string</code> | Google Analytics tracking ID (required). |
| [options] | <code>object</code> |  |
| [options.an] | <code>string</code> | App name |
| [options.av] | <code>string</code> | App version |
| [options.lang] | <code>string</code> | Language. Defaults to `process.env.LANG`. |
| [options.sr] | <code>string</code> | Screen resolution. Defaults to `${process.stdout.rows}x${process.stdout.columns}`. |
| [options.ua] | <code>string</code> | User Agent string to use. |
| [options.dir] | <code>string</code> | Path of the directory used for persisting clientID and queue. Defaults to `~/.usage-stats`. |
| [options.url] | <code>string</code> | Defaults to `'https://www.google-analytics.com/batch'`. |
| [options.debugUrl] | <code>string</code> | Defaults to `'https://www.google-analytics.com/debug/collect'`. |

**Example**  
```js
const usageStats = new UsageStats('UA-98765432-1', {
  an: 'sick app',
  av: '1.0.0'
})
```
<a name="module_usage-stats--UsageStats.UsageStats+dir"></a>

### usageStats.dir : <code>string</code>
Cache directory. Defaults to `~/.usage-stats`.

**Kind**: instance property of [<code>UsageStats</code>](#exp_module_usage-stats--UsageStats)  
<a name="module_usage-stats--UsageStats.UsageStats+defaults"></a>

### usageStats.defaults : <code>Map</code>
A list of parameters to be to sent with every hit.

**Kind**: instance property of [<code>UsageStats</code>](#exp_module_usage-stats--UsageStats)  
**Example**  
```js
usageStats.defaults
  .set('cd1', process.version)
  .set('cd2', os.type())
  .set('cd3', os.release())
  .set('cd4', 'api')
```
<a name="module_usage-stats--UsageStats+start"></a>

### usageStats.start([sessionParams]) ↩︎
Starts the [session](https://developers.google.com/analytics/devguides/collection/protocol/v1/parameters#sc).

**Kind**: instance method of [<code>UsageStats</code>](#exp_module_usage-stats--UsageStats)  
**Chainable**  

| Param | Type | Description |
| --- | --- | --- |
| [sessionParams] | <code>Array.&lt;Map&gt;</code> | An optional map of paramaters to send with each hit in the sesison. |

<a name="module_usage-stats--UsageStats+end"></a>

### usageStats.end([sessionParams]) ↩︎
Ends the [session](https://developers.google.com/analytics/devguides/collection/protocol/v1/parameters#sc).

**Kind**: instance method of [<code>UsageStats</code>](#exp_module_usage-stats--UsageStats)  
**Chainable**  

| Param | Type | Description |
| --- | --- | --- |
| [sessionParams] | <code>Array.&lt;Map&gt;</code> | An optional map of paramaters to send with the final hit of this sesison. |

<a name="module_usage-stats--UsageStats+disable"></a>

### usageStats.disable() ↩︎
Disable the module. While disabled, all operations are no-ops.

**Kind**: instance method of [<code>UsageStats</code>](#exp_module_usage-stats--UsageStats)  
**Chainable**  
<a name="module_usage-stats--UsageStats+enable"></a>

### usageStats.enable() ↩︎
Re-enable the module.

**Kind**: instance method of [<code>UsageStats</code>](#exp_module_usage-stats--UsageStats)  
**Chainable**  
<a name="module_usage-stats--UsageStats+event"></a>

### usageStats.event(category, action, [options]) ⇒ <code>Map</code>
Track an event. All event hits are queued until `.send()` is called.

**Kind**: instance method of [<code>UsageStats</code>](#exp_module_usage-stats--UsageStats)  

| Param | Type | Description |
| --- | --- | --- |
| category | <code>string</code> | Event category (required). |
| action | <code>string</code> | Event action (required). |
| [options] | <code>option</code> |  |
| [options.el] | <code>string</code> | Event label |
| [options.ev] | <code>string</code> | Event value |
| [options.hitParams] | <code>Array.&lt;map&gt;</code> | One or more additional params to send with the hit. |

<a name="module_usage-stats--UsageStats+screenView"></a>

### usageStats.screenView(name, [options]) ⇒ <code>Map</code>
Track a screenview. All screenview hits are queued until `.send()` is called. Returns the hit instance.

**Kind**: instance method of [<code>UsageStats</code>](#exp_module_usage-stats--UsageStats)  

| Param | Type | Description |
| --- | --- | --- |
| name | <code>string</code> | Screen name |
| [options] | <code>object</code> |  |
| [options.hitParams] | <code>Array.&lt;map&gt;</code> | One or more additional params to set on the hit. |

<a name="module_usage-stats--UsageStats+exception"></a>

### usageStats.exception([options]) ⇒ <code>Map</code>
Track a exception. All exception hits are queued until `.send()` is called.

**Kind**: instance method of [<code>UsageStats</code>](#exp_module_usage-stats--UsageStats)  

| Param | Type | Description |
| --- | --- | --- |
| [options] | <code>object</code> | optional params |
| [options.exd] | <code>string</code> | Error message |
| [options.exf] | <code>boolean</code> | Set true if the exception was fatal |
| [options.hitParams] | <code>Array.&lt;map&gt;</code> | One or more additional params to set on the hit. |

<a name="module_usage-stats--UsageStats+send"></a>

### usageStats.send([options]) ⇒ <code>Promise</code>
Send queued stats using as few requests as possible (typically a single request - a max of 20 events/screenviews may be sent per request). If offline, the stats will be stored and re-tried on next invocation.

**Kind**: instance method of [<code>UsageStats</code>](#exp_module_usage-stats--UsageStats)  
**Fulfil**: <code>response[]</code> - array of responses. Each response has `data` and the original node `res`.  
**Reject**: <code>Error</code> - Rejects with the first error encountered. The error is a standard node http error with a `name` of `request-fail` and a `hits` property showing what failed to send.  

| Param | Type |
| --- | --- |
| [options] | <code>object</code> | 
| [options.timeout] | <code>number</code> | 

<a name="module_usage-stats--UsageStats+debug"></a>

### usageStats.debug() ⇒ <code>Promise</code>
Send any hits (including queued) to the GA [validation server](https://developers.google.com/analytics/devguides/collection/protocol/v1/validating-hits), fulfilling with the result.

**Kind**: instance method of [<code>UsageStats</code>](#exp_module_usage-stats--UsageStats)  
**Fulfil**: <code>Response[]</code>  
**Reject**: <code>Error</code> - Error instance includes `hits`.  
<a name="module_usage-stats--UsageStats+abort"></a>

### usageStats.abort() ↩︎
Aborts the in-progress .send() operation, queuing any unsent hits.

**Kind**: instance method of [<code>UsageStats</code>](#exp_module_usage-stats--UsageStats)  
**Chainable**  

* * *

&copy; 2016-23 Lloyd Brookes \<75pound@gmail.com\>. Documented by [jsdoc-to-markdown](https://github.com/jsdoc2md/jsdoc-to-markdown).

---
_Source: https://npm.io/package/usage-stats · Machine-readable twin of the npm.io package page. Health data is recomputed on every publish._
