Skip to content

Commit bfe8492

Browse files
[HELPS-3198] document and publish to npm (#6)
* Documentation * Github workflows * Fix broken code example
1 parent d23a552 commit bfe8492

File tree

10 files changed

+296
-42
lines changed

10 files changed

+296
-42
lines changed

.github/workflows/javascript.yml

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
# This workflow will do a clean install of node dependencies, build the source code,
2+
# and run linting/tests across different versions of node.
3+
# For more information see:
4+
# https://help.github.com/actions/language-and-framework-guides/using-nodejs-with-github-actions
5+
6+
name: Javascript CI
7+
8+
on:
9+
push:
10+
pull_request:
11+
12+
jobs:
13+
build:
14+
runs-on: ubuntu-latest
15+
16+
strategy:
17+
matrix:
18+
node-version: [12.x, 14.x]
19+
20+
steps:
21+
- uses: actions/checkout@v2
22+
- name: Use Node.js ${{ matrix.node-version }}
23+
uses: actions/setup-node@v1
24+
with:
25+
node-version: ${{ matrix.node-version }}
26+
- run: npm set audit false
27+
- run: npm ci
28+
- run: npm audit --production --audit-level=low
29+
- run: npm run build --if-present
30+
- run: npm run lint
31+
- run: npm run test --if-present

.github/workflows/npm.yml

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
# This workflow will do a clean install of node dependencies, build the source code,
2+
# and publish to NPM.
3+
# For more information, see:
4+
# https://docs.github.com/en/actions/language-and-framework-guides/publishing-nodejs-packages#publishing-packages-to-the-npm-registry
5+
6+
name: NPM Publish
7+
8+
on:
9+
release:
10+
types: [ published ]
11+
12+
jobs:
13+
build:
14+
15+
runs-on: ubuntu-latest
16+
17+
steps:
18+
- uses: actions/checkout@v2
19+
- name: Use Node.js 14
20+
uses: actions/setup-node@v1
21+
with:
22+
node-version: 14.x
23+
- run: npm set audit false
24+
- run: npm ci
25+
- run: npm run test --if-present
26+
- run: npm run build --if-present
27+
- run: printf '\n//registry.npmjs.org/:_authToken=${NPM_TOKEN}' >> .npmrc
28+
- run: npm publish --access public
29+
env:
30+
# `secrets.NPM_TOKEN` references a GitHub Secret configured for this repo or organization,
31+
# and is used to authenticate for the NPM publish command.
32+
NPM_TOKEN: ${{ secrets.NPM_TOKEN }}

README.md

Lines changed: 154 additions & 35 deletions
Original file line numberDiff line numberDiff line change
@@ -1,49 +1,168 @@
1-
# Segment LDK
1+
# Loop Analytics Library
22

3-
This wrapper library makes use of [Segment](https://segment.com/docs/) to send loop data to analytics services like GA and Mixpanel. Its intent is to make it easier for developers to add analytics to loops, reduce code bloat and most importantly to be consistent with event trigger names/labels. Feel free to change the types to match event trigger names specific for your use case.
3+
This library makes use of the LDK's Network aptitude to support analytics within loops through builtin analytics services or can be extended to support custom services
44

5-
## How to use
5+
Currently supported out of the box:
66

7-
In the root file that starts the loop, add the following ahead of prior code.
7+
- [Google Analytics (Universal)](https://developers.google.com/analytics/devguides/collection/protocol/v1)
8+
- [Segment](https://segment.com/docs/connections/sources/catalog/libraries/server/http-api/)
89

9-
```js
10-
import User from '../user';
11-
import Segment from 'loop-segment';
10+
## How to Use
1211

13-
/*
14-
* We are using userId from user.jwt() aptitude (part of @oliveai/ldk) which has been
15-
* abstracted to a separate class User. But the Segment userId can be populated from other
16-
* id sources to fit your use case.
17-
*/
18-
const { userId } = await User.getUser();
19-
Segment.init({
20-
loopName: 'KnowledgeReference Loop',
21-
userId,
22-
writeKey: 'this is found in segment sources settings',
23-
});
24-
```
12+
### 1. Add the necessary aptitude permissions to your loop's `package.json`
2513

26-
You should receive a Segment tracking event in your account, that says "Loop Started"
14+
The only required aptitude is `network` to make requests to the analytics service you choose. Some other aptitudes that can be helpful are `user` for getting the user's information and `system` for getting the user's operating system.
2715

28-
To use the rest of the methods, add them in where necessary in the code (e.g. `Segment.whisperDisplayed(Markdown, true)`). Be sure to update the `types` when creating new event names to be triggered in the loops.
16+
> Note: Use the information from `user` and `system` aptitudes at your own risk. PII and PHI should **NEVER** be sent to an analytics service, only the minimum required info that is helpful for metrics should be used. If you are unsure whether your information would be considered PII or PHI or you don't need this info for your metrics, err on the side of caution and omit these aptitudes altogether.
2917
30-
## Important Notes
18+
#### Network Aptitude URLs for the provided Transports
3119

32-
- Be sure to add the network and user permissions in your loop like so,
20+
| Transport | URL |
21+
| :-------: | :------------------: |
22+
| Google | google-analytics.com |
23+
| Segment | api.segment.io |
3324

3425
```json
35-
"network": {
36-
"urlDomains": [
37-
{
38-
"value": "api.segment.io"
39-
}
40-
]
41-
},
26+
{
27+
...
28+
"ldk": {
29+
"permissions": {
30+
"whisper": {},
31+
"system": {},
4232
"user": {
43-
"optionalClaims": [
44-
{
45-
"value": "email"
46-
}
47-
]
33+
"optionalClaims": [{ "value": "email" }]
34+
},
35+
"network": {
36+
"urlDomains": [{ "value": "google-analytics.com" }]
4837
}
38+
}
39+
}
40+
}
41+
```
42+
43+
### 2. Set up the Analytics Client with your desired Transport
44+
45+
In this example we setup and export the Google Analytics client in a separate file to make it accessible across the loop
46+
47+
```ts
48+
// analytics.ts
49+
import { user, system } from '@oliveai/ldk';
50+
import { AnalyticsClient, Transports } from '@oliveai/loop-analytics';
51+
import jwtDecode from 'jwt-decode';
52+
53+
import { LOOP_NAME } from './index';
54+
55+
const createAnalyticsClient = async () => {
56+
// Helper function to fetch the user's JWT and decode the payload
57+
const getUserInfo = async () =>
58+
jwtDecode<{ email: string; org: string; sub: string }>(
59+
await user.jwt({ includeEmail: true })
60+
);
61+
62+
// Get the info we need from LDK
63+
const { sub: userId, email, org } = await getUserInfo();
64+
const os = await system.operatingSystem();
65+
66+
// Define required and custom category/action pairings
67+
// Export outside of this function to use across the loop for custom events if you'd like
68+
const categoryActionMap: Transports.GoogleTransportTypes.CategoryActionMap = {
69+
// === Required ===
70+
whisperDisplayed: {
71+
category: 'Whispers',
72+
action: 'Whisper Displayed',
73+
},
74+
whisperClosed: {
75+
category: 'Whispers',
76+
action: 'Whisper Closed',
77+
},
78+
componentClicked: {
79+
category: 'Click Events',
80+
action: 'Component Clicked',
81+
},
82+
componentCopied: {
83+
category: 'Click Events',
84+
action: 'Component Copied',
85+
},
86+
// === Custom (Optional) ===
87+
customEvent: {
88+
category: 'Custom',
89+
action: 'Custom Event',
90+
},
91+
};
92+
93+
// An example of how to set custom dimensions, use whatever is appropriate
94+
const customDimensions: Transports.GoogleTransportTypes.CustomDimensionOrMetric[] =
95+
[
96+
{
97+
index: 1,
98+
name: 'Loop Name',
99+
value: LOOP_NAME,
100+
},
101+
{
102+
index: 2,
103+
name: 'User ID',
104+
value: userId, // The user's generated ID in Loop Library, not considered PII
105+
},
106+
{
107+
index: 3,
108+
name: 'Email Domain',
109+
value: email.split('@')[1], // ONLY send the email domain, full email would be PII
110+
},
111+
{
112+
index: 4,
113+
name: 'Organization',
114+
value: org,
115+
},
116+
{
117+
index: 5,
118+
name: 'Operating System',
119+
value: os,
120+
},
121+
];
122+
123+
const transportConfig: Transports.GoogleTransportTypes.GoogleTransportConfig =
124+
{
125+
trackingId: 'UA-12345678-90',
126+
// Can be whatever you want but is required for Google's request headers
127+
userAgent: LOOP_NAME,
128+
categoryActionMap,
129+
customDimensions,
130+
};
131+
132+
const userConfig: Transports.UserConfig = {
133+
id: userId,
134+
};
135+
const loopConfig: Transports.LoopConfig = {
136+
name: LOOP_NAME,
137+
};
138+
139+
return new AnalyticsClient(
140+
new Transports.GoogleTransport(transportConfig, userConfig, loopConfig)
141+
);
142+
};
143+
144+
// One example of how to export the client in a way that is accessible across the loop
145+
export default await createAnalyticsClient();
146+
```
147+
148+
### 3. Use the new Analytics Client wherever it's needed
149+
150+
```ts
151+
// index.ts
152+
import { whisper } from '@oliveai/ldk';
153+
import GA from './analytics';
154+
155+
export const LOOP_NAME = 'My Awesome Loop';
156+
157+
(async () => {
158+
const label = 'Hello World!';
159+
160+
whisper.create({
161+
label,
162+
components: [],
163+
onClose: () => GA.trackWhisperClosed(label),
164+
});
165+
166+
GA.trackWhisperDisplayed(label, false);
167+
})();
49168
```

src/index.ts

Lines changed: 32 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,34 +4,65 @@ import { Component, WhisperComponentType } from '@oliveai/ldk/dist/whisper';
44

55
import * as Transports from './transports';
66

7+
/**
8+
* Main class for interacting with different analytics providers
9+
* Must be provided a Transport at construction or before calling any track methods
10+
*/
711
class AnalyticsClient {
812
constructor(public transport?: Transports.BaseTransport) {}
913

14+
/** Provided for setting the transport after instancing */
1015
setTransport(transport: Transports.BaseTransport) {
1116
this.transport = transport;
1217
}
1318

19+
/**
20+
* Default method for what to do when a whisper is displayed
21+
*
22+
* @param whisperName Either the label or a distinct name for the whisper
23+
* @param isUpdated Whether the whisper was displayed through create or update
24+
*/
1425
async trackWhisperDisplayed(whisperName: string, isUpdated: boolean) {
1526
if (!this.transport) return;
1627
await this.transport.trackWhisperDisplayed(whisperName, isUpdated);
1728
}
1829

30+
/**
31+
* Default method for what to do when a whisper is closed
32+
*
33+
* @param whisperName Either the label or a distinct name for the whisper
34+
*/
1935
async trackWhisperClosed(whisperName: string) {
2036
if (!this.transport) return;
2137
await this.transport.trackWhisperClosed(whisperName);
2238
}
2339

40+
/**
41+
* Default method for what to do when a component's onClick handler is triggered
42+
*
43+
* @param componentType The LDK provided identifier for the type of component
44+
*/
2445
async trackComponentClicked(componentType: WhisperComponentType) {
2546
if (!this.transport) return;
2647
await this.transport.trackComponentClicked(componentType);
2748
}
2849

50+
/**
51+
* Default method for what to do when a component's onCopy handler is triggered
52+
*
53+
* @param componentType The LDK provided identifier for the type of component
54+
*/
2955
async trackComponentCopied(componentType: WhisperComponentType) {
3056
if (!this.transport) return;
3157
await this.transport.trackComponentCopied(componentType);
3258
}
3359

34-
async trackEvent(props: any) {
60+
/**
61+
* Generic tracking method, up to the Transport to define what the props should be
62+
*
63+
* @param props Some kind of object passed through to the Transport for handling events
64+
*/
65+
async trackEvent(props: Record<string, unknown>) {
3566
if (!this.transport) return;
3667
await this.transport.trackEvent(props);
3768
}

src/transports/base/index.ts

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,33 +4,52 @@ import { LoopConfig, TransportConfig, UserConfig } from './types';
44

55
export * from './types';
66

7+
/**
8+
* Abstract for all Transports to extend
9+
*
10+
* @param TransportConfig Defines properties for the Transport's client itself, such as auth keys, custom parameters, etc
11+
* @param UserConfig Defines properties for the user, such as their id, etc
12+
* @param LoopConfig Defines properties for the loop, such as the name, etc
13+
*/
714
export abstract class BaseTransport<
815
T extends TransportConfig = TransportConfig,
916
U extends UserConfig = UserConfig,
1017
L extends LoopConfig = LoopConfig
1118
> {
19+
// Keep track of which whisper we're on so events can tie to it as a page if needed
1220
currentWhisperName?: string;
1321

22+
// All Transports need a baseUrl for the HTTP Requests
1423
abstract baseUrl: string;
1524

25+
// Set up the Transport with default or extended configs
1626
constructor(readonly transportConfig: T, readonly userConfig: U, readonly loopConfig: L) {}
1727

28+
// All Transports will be using LDK's network call, this helper method reduces redundancy
1829
protected static async send(request: network.HTTPRequest) {
1930
const { statusCode } = await network.httpRequest(request);
2031
if (statusCode < 200 || statusCode >= 300) {
2132
console.error(`Request failed with status code ${statusCode}: ${request.url}`);
2233
}
2334
}
2435

36+
// === Abstracts for every Transport to implement ===
37+
38+
/** @see {@link AnalyticsClient.trackWhisperDisplayed} */
2539
abstract trackWhisperDisplayed(name: string, isUpdated: boolean): Promise<void>;
2640

41+
/** @see {@link AnalyticsClient.trackWhisperClosed} */
2742
abstract trackWhisperClosed(name: string): Promise<void>;
2843

44+
/** @see {@link AnalyticsClient.trackComponentClicked} */
2945
abstract trackComponentClicked(type: whisper.WhisperComponentType): Promise<void>;
3046

47+
/** @see {@link AnalyticsClient.trackComponentCopied} */
3148
abstract trackComponentCopied(type: whisper.WhisperComponentType): Promise<void>;
3249

50+
/** @see {@link AnalyticsClient.trackEvent} */
3351
abstract trackEvent(props: any): Promise<void>;
3452

53+
/** All Transports should have a method for building the request used in Transport.send */
3554
protected abstract buildRequest(...args: any[]): network.HTTPRequest;
3655
}

0 commit comments

Comments
 (0)