Skip to content

Commit

Permalink
Allow loading of script to be deferred (#2)
Browse files Browse the repository at this point in the history
  • Loading branch information
pichfl committed Jan 21, 2022
1 parent 5bb11a1 commit e80894f
Show file tree
Hide file tree
Showing 9 changed files with 218 additions and 124 deletions.
3 changes: 2 additions & 1 deletion .npmignore
Original file line number Diff line number Diff line change
Expand Up @@ -5,4 +5,5 @@
.release-it.js
node_modules
RELEASE.md
rollup.config.js
rollup.config.js
src
122 changes: 79 additions & 43 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,76 +1,112 @@
# Telemetry Deck JavaScript SDK

This package allows you to send signals to [TelemetryDeck](https://telemetrydeck.com) from your JavaScript code.
This package allows you to send signals to [TelemetryDeck](https://telemetrydeck.com) from your JavaScript code.

It has no package dependencies and supports modern evergreen browsers which support [cryptography](https://caniuse.com/cryptography).
It has no package dependencies and supports **modern evergreen browsers** which support [cryptography](https://caniuse.com/cryptography).

Signals sent with this version of the SDK automatically send the following payload items:

- url
- useragent
- locale
- platform
- `url`
- `useragent`
- `locale`
- `platform`

You can filter and show these values in the TelemetryDeck dashboard.

Test Mode is currently not supported.

## Usage

### 📄 Usage via Script Tag
### 📄 Usage via Script tag

For regular websites and to try out the code quickly, you can use [UNPKG](https://unpkg.com), a free CDN which allows you to load files from any npm package.
For websites and to try out the code quickly, you can use [UNPKG](https://unpkg.com), a free CDN which allows you to load files from any npm package.

Include the following snippet in your page header:
Include the following snippet inside the `<head>` of your HTML page:

```html
<script src="https://unpkg.com/@telemtrydeck/sdk/dist/telemetrydeck.min.js">
<script src="https://unpkg.com/@telemtrydeck/sdk/dist/telemetrydeck.min.js" defer></script>
```

then include a script tag at the bottom of your page like this to send a signal once every time the page loads:
Then add a second script tag after it like this to send a signal once every time the page loads:

```html
<script>
signal(
// required options to identify your app and the user
{
appID: 'YOUR_APP_ID',
userIdentifier: 'ANONYMOUS',
},
// optional: custom payload stored with the signal
{
route: 'some/page/path',
}
);
window.td = window.td || [];
td.push(['app', YOUR_APP_ID], ['user', USER_IDENTIFIER], ['signal']);
</script>
```

Please replace `YOUR_APP_ID` with the app ID you received from TelemetryDeck, and set a user identifier if possible.
Please replace `YOUR_APP_ID` with the app ID you received from TelemetryDeck, and `USER_IDENTIFIER` with a user identifier. If you have none, consider `anonymous`.

### 📦 Usage for applications that use a bundler (like Webpack, Rollup, …)
You can add as many signals as you need to track different interactions with your page. Once the page and script are fully loaded, signals will be sent immediatlty.

```js
// basic signal
td.push('signal');

// with custom data
td.push('signal', { route: '/' });
```

#### Alternative usage for more complex tracking needs

```html
<script>
// Required: queue setup
td = window.td || [];
// Required: Set your application id
td.push(['app', YOUR_APP_ID]);
// Required: Set a user idenfitier. `anonymous` is a recommended default
td.push(['user', USER_IDENTIFIER ?? 'anonymous']);
// Custom payload sent with the signal
td.push(['signal']);
td.push([
'signal',
{
route: 'some/page/path',
},
]);
</script>
```
### 📦 Advanced usage for applications that use a bundler (like Webpack, Rollup, …)
After installing the package via NPM, use it like this:
```js
import { signal } from 'telemetry-deck';

//
signal(
// required options to identify your app and the user
{
appID: 'YOUR_APP_ID',
userIdentifier: 'ANONYMOUS',
},
// custom payload stored with the signal
{
route: 'some/page/path',
}
);
import { TelemetryDeck } from 'telemetry-deck';
const td = new TelemetryDeck({ app: YOUR_APP_ID, user: YOUR_USER_IDENTIFIER });
// Process any events that have been qeued up
// Queued signals do not contain a client side timestamp and will be timestamped
// on the server at the time of arrival. Consider adding a timestamp value to
// your payloads if you need to be able to correlate them.
const queuedEvents = [
['app', YOUR_APP_ID],
['user', YOUR_USER_IDENTIFIER],
['signal'],
['signal', { route: 'some/page/path' }],
];
td.ingest(qeuedEvents);
// Basic signal
td.signal();
// Update app or user identifier
td.app(YOUR_NEW_APP_ID);
td.user(YOUR_NEW_USER_IDENTIFIER);
// Signal with custom payload
td.signal({
route: 'some/page/path',
});
```
Please replace `YOUR_APP_ID` with the app ID you received from TelemetryDeck. If you have any string that identifies your user, such as an email address, pass it into `userIdentifier` – it will be cryptographically anonymized with a hash function.
Please replace `YOUR_APP_ID` with the app ID you received from TelemetryDeck. If you have any string that identifies your user, such as an email address, use it as `YOUR_USER_IDENTIFIER` – it will be cryptographically anonymized with a hash function.
If you want to pass optional parameters to the signal being sent, add them to the optional paylaod object.
If you want to pass optional parameters to the signal being sent, add them to the optional payload object.
## More Info
Expand All @@ -80,14 +116,14 @@ Every application and website registered to TelemetryDeck has its own unique ID
### 👤 Optional: User Identifiers
TelemetryDeck can count users if you assign it a unique identifier for each user that doesn't change. This identifier can be any string that is unique to the user, such as their email address, or a randomly generated UUID.
TelemetryDeck can count users if you assign it a unique identifier for each user that doesn't change. This identifier can be any string that is unique to the user, such as their email address, or a randomly generated UUID.
Feel free to use personally identifiable information as the user identifier: We use a cryptographically secure double-hasing process on client and server to make sure the data that arrives at our servers is anonymized and can not be traced back to individual users via their identifiers. A user's identifier is hashed inside the library, and then salted+hashed again on arrival at the server. This way the data is anonymized as defined by the GDPR and you don't have to ask for user consent for procesing or storing this data.
### 🚛 Optional: Payload
You can optionally attach an object with string values to the signal. This will allow you to filter and aggregate signal by these values in the dashboard.
You can optionally attach an object with string values to the signal. This will allow you to filter and aggregate signal by these values in the dashboard.
### 📚 Full Docs
Go to [docs.telemetrydeck.com](https://docs.telemetrydeck.com) to see all documentation articles
Go to [docs.telemetrydeck.com](https://docs.telemetrydeck.com) to see all documentation articles
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
"version": "0.1.0",
"description": "JavaScript package to send TelemetryDeck signals",
"main": "dist/telemetrydeck.js",
"module": "src/telemetrydeck.mjs",
"module": "dist/telemetrydeck.mjs",
"scripts": {
"build": "rollup -c",
"changelog": "lerna-changelog",
Expand Down
20 changes: 20 additions & 0 deletions rollup.config.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import json from '@rollup/plugin-json';
import { terser } from 'rollup-plugin-terser';

export default [
// CommonJS build for Node.js
{
input: 'src/telemetrydeck.mjs',
output: {
Expand All @@ -10,6 +11,25 @@ export default [
},
plugins: [json()],
},
// ES module build for browsers
{
input: 'src/telemetrydeck.mjs',
output: {
file: 'dist/telemtrydeck.mjs',
format: 'module',
},
plugins: [json()],
},
// minified ES module build
{
input: 'src/telemetrydeck.mjs',
output: {
file: 'dist/telemtrydeck.min.mjs',
format: 'module',
},
plugins: [json(), terser()],
},
// minified UMD build for most browsers
{
input: 'src/telemetrydeck.mjs',
output: {
Expand Down
106 changes: 62 additions & 44 deletions src/telemetrydeck.mjs
Original file line number Diff line number Diff line change
@@ -1,61 +1,68 @@
import { version } from '../package.json';
import sha256 from './utils/sha256.mjs';
import assertKeyValue from './utils/assert-key-value.mjs';
import transformPayload from './utils/transform-payload.mjs';

const transformPayload = (payload) => Object.entries(payload).map((entry) => entry.join(':'));
const APP = 'app';
const USER = 'user';
const SIGNAL = 'signal';

const assertKeyValue = (key, value) => {
if (!value) {
throw new Error(`TelemetryDeck: ${key} is not set`);
}
};

// https://stackoverflow.com/a/48161723/54547
async function sha256(message) {
// encode as UTF-8
const messageBuffer = new TextEncoder().encode(message);
export class TelemetryDeck {
constructor(options = {}) {
const { target, app, user } = options;

// hash the message
const hashBuffer = await crypto.subtle.digest('SHA-256', messageBuffer);
this.target = target ?? 'https://nom.telemetrydeck.com/v1/';
this._app = app;
this._user = user;
}

// convert ArrayBuffer to Array
const hashArray = [...new Uint8Array(hashBuffer)];
async ingest(queue) {
for (const [method, data] of queue) {
try {
await this[method].call(this, data);
} catch (error) {
console.error(error);
}
}
}

// convert bytes to hex string
const hashHex = hashArray.map((b) => b.toString(16).padStart(2, '0')).join('');
return hashHex;
}
[APP](appId) {
this._app = appId;
}

class TelemetryDeck {
constructor(appID, target) {
this.appID = appID;
this.target = target ?? 'https://nom.telemetrydeck.com/v1/';
[USER](identifier) {
this._user = identifier;
}

assertKeyValue('appID', appID);
/**
* This method is used to queue messages to be sent by TelemtryDeck
* @param {string} type
* @param {string} [payload]
*
* @returns {Promise<void>}
*/
push([method, data] = []) {
return this[method](data);
}

/**
*
* @paam {string} userIdentifier to be hashed
* @param {Object?} payload custom payload to be stored with each signal
* @returns <Promise<Response>> a promise with the response from the server, echoing the sent data
*/
async signal(userIdentifier, payload) {
async [SIGNAL](payload = {}) {
const { href: url } = location;
const { userAgent: useragent, language: locale, userAgentData, vendor } = navigator;
const { _app, target } = this;
let { _user } = this;
let { type } = payload;

payload = {
url,
useragent,
locale,
platform: userAgentData ?? '',
vendor,
...payload,
};

let { appID, target } = this;
delete payload.type;

assertKeyValue('userIdentifier', userIdentifier);
assertKeyValue(APP, _app);
assertKeyValue(USER, _user);

userIdentifier = await sha256(userIdentifier);
_user = await sha256(_user);

return fetch(target, {
method: 'POST',
Expand All @@ -65,16 +72,27 @@ class TelemetryDeck {
},
body: JSON.stringify([
{
appID,
clientUser: userIdentifier,
sessionID: userIdentifier,
appID: _app,
clientUser: _user,
sessionID: _user,
telemetryClientVersion: version,
type: 'pageview',
payload: transformPayload(payload),
type: type ?? 'pageview',
payload: transformPayload({
url,
useragent,
locale,
platform: userAgentData ?? '',
vendor,
...payload,
}),
},
]),
});
}
}

export default TelemetryDeck;
if (window && window.td) {
const td = new TelemetryDeck({});
td.ingest(window.td);
window.td = td;
}
7 changes: 7 additions & 0 deletions src/utils/assert-key-value.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
const assertKeyValue = (key, value) => {
if (!value) {
throw new Error(`TelemetryDeck: "${key}" is not set`);
}
};

export default assertKeyValue;
15 changes: 15 additions & 0 deletions src/utils/sha256.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
// https://stackoverflow.com/a/48161723/54547
export default async function sha256(message) {
// encode as UTF-8
const messageBuffer = new TextEncoder().encode(message);

// hash the message
const hashBuffer = await crypto.subtle.digest('SHA-256', messageBuffer);

// convert ArrayBuffer to Array
const hashArray = [...new Uint8Array(hashBuffer)];

// convert bytes to hex string
const hashHex = hashArray.map((b) => b.toString(16).padStart(2, '0')).join('');
return hashHex;
}
3 changes: 3 additions & 0 deletions src/utils/transform-payload.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
const transformPayload = (payload) => Object.entries(payload).map((entry) => entry.join(':'));

export default transformPayload;
Loading

0 comments on commit e80894f

Please sign in to comment.