Skip to content

Commit ed3c638

Browse files
authored
Documentation Updates (#284)
* Added comments * Add CONTRIBUTING.md * Update README.md
1 parent be81c6d commit ed3c638

File tree

11 files changed

+84
-19
lines changed

11 files changed

+84
-19
lines changed

CONTRIBUTING.md

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
# Contributing to the Amplitude SDK for JavaScript
2+
🎉 Thanks for your interest in contributing! 🎉
3+
4+
## Ramping Up
5+
### Intro
6+
- There are three ways for SDK to be loaded
7+
- Standard NPM package
8+
- Snippet in `<script>` tag
9+
- RequireJS (may be dropped in future)
10+
- Workflow is facilitated with both `make` and `yarn` (legacy, may possibly be updated to full `yarn`)
11+
- Chek out the [Amplitude Instrumentation Explorer]((https://chrome.google.com/webstore/detail/amplitude-instrumentation/acehfjhnmhbmgkedjmjlobpgdicnhkbp)) to help logging events during development
12+
13+
### Architecture
14+
- `index.js` is the main entrypoint of SDK
15+
- Stubbed methods are used when client imports via `<script>` snippet
16+
- Allows app to not be blocked while real JS SDK is loaded in
17+
- Sent events and identifys are tracked with queues
18+
- Metadata storage (new) vs cookie (old) storage
19+
- more of issue with anonymous id, because it uses device id instead of user id
20+
- UA Parser: Helps identify browsers
21+
- might be able to use upstream library and convert results, rather than our fork
22+
- sameSiteCookie: Sets how public the cookie reading is
23+
- `amplitude.getInstance() is necessary even during reuse because of snippet stubbed
24+
- only applicable to snippet import
25+
26+
### Setting Up Development
27+
- Cloning, installing, and building
28+
```
29+
git clone [email protected]:amplitude/Amplitude-JavaScript.git
30+
cd Amplitude-JavaScript
31+
make # Runs tests and generate builds
32+
yarn dev # Start development utility. Open localhost:9000 in your browser to access
33+
```

Makefile

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -66,14 +66,14 @@ README.md: $(SNIPPET_OUT) version
6666

6767
$(OUT): node_modules $(SRC) package.json rollup.config.js rollup.min.js rollup.native.js rollup.esm.js rollup.umd.js rollup.umd.min.js
6868
@$(JSHINT) --verbose $(SRC)
69-
@NODE_ENV=production $(ROLLUP) --config rollup.config.js
70-
@NODE_ENV=production $(ROLLUP) --config rollup.esm.js
71-
@NODE_ENV=production $(ROLLUP) --config rollup.umd.js
72-
@NODE_ENV=production $(ROLLUP) --config rollup.native.js
73-
@NODE_ENV=production $(ROLLUP) --config rollup.nocompat.js
69+
@NODE_ENV=production $(ROLLUP) --config rollup.config.js # is the snippet build config
70+
@NODE_ENV=production $(ROLLUP) --config rollup.esm.js # does not concat dependencies, only has module and dependencies
71+
@NODE_ENV=production $(ROLLUP) --config rollup.umd.js # generates npm version, also usable in require js app
72+
@NODE_ENV=production $(ROLLUP) --config rollup.native.js # generates react native build
73+
@NODE_ENV=production $(ROLLUP) --config rollup.nocompat.js # may be able to remove
7474
@NODE_ENV=production $(ROLLUP) --config rollup.umd.min.js
7575
@NODE_ENV=production $(ROLLUP) --config rollup.min.js
76-
@NODE_ENV=production $(ROLLUP) --config rollup.nocompat.min.js
76+
@NODE_ENV=production $(ROLLUP) --config rollup.nocompat.min.js # may be able to remove
7777

7878
#
7979
# Target for minified `amplitude-snippet.js` file.

README.md

Lines changed: 8 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -13,22 +13,27 @@
1313
A JavaScript SDK for tracking events and revenue to [Amplitude](https://www.amplitude.com).
1414

1515
## Installation and Quick Start
16-
Please visit our :100:[Developer Center](https://developers.amplitude.com/docs/javascript) for instructions on installing and using our the SDK.
16+
* For using the SDK, please visit our :100:[Developer Center](https://developers.amplitude.com/docs/javascript) for instructions on installing and using our the SDK.
17+
* For developing the SDK, please visit our [CONTRIBUTING.md](https://github.com/amplitude/Amplitude-JavaScript/blob/master/CONTRIBUTING.md) to get started.
1718

1819
## Demo Pages
1920
* A [demo page](https://github.com/amplitude/Amplitude-JavaScript/blob/master/test/browser/amplitudejs.html) showing a simple integration on a web page.
2021
* A [demo page](https://github.com/amplitude/Amplitude-JavaScript/blob/master/test/browser/amplitudejs-requirejs.html) showing an integration using RequireJS.
2122
* A [demo page](https://github.com/amplitude/GTM-Web-Demo) demonstrating a potential integration with Google Tag Manager.
2223

23-
## Changelog
24-
Click [here](https://github.com/amplitude/Amplitude-JavaScript/blob/master/CHANGELOG.md) to view the JavaScript SDK Changelog.
2524

2625
## React Native
2726
This library now supports react-native. It has two dependencies on react-native modules you will have to install yourself:
2827

2928
* [react-native-device-info](https://www.npmjs.com/package/react-native-device-info) Tested with version 3.1.4
3029
* [@react-native-community/async-storage](https://www.npmjs.com/package/@react-native-community/async-storage) Tested with version 1.6.2
3130

31+
## Node.js
32+
Please visit [Amplitude-Node](https://github.com/amplitude/Amplitude-Node) for our Node SDK.
33+
34+
## Changelog
35+
Click [here](https://github.com/amplitude/Amplitude-JavaScript/blob/master/CHANGELOG.md) to view the JavaScript SDK Changelog.
36+
3237
## Upgrading Major Versions and Breaking Changes #
3338

3439
### 6.0

scripts/version.js

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -30,6 +30,7 @@ replaceTextInFile(
3030
);
3131

3232
// Update integrity hash in snippet
33+
// Provides extra layer of security. If script changes, it will fail to load
3334
const sdkText = fs.readFileSync(path.join('.', `amplitude.min.js`), 'utf-8');
3435
const hash = crypto.createHash('sha384').update(sdkText).digest('base64');
3536
replaceTextInFile(

src/amplitude-client.js

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,14 +1,15 @@
1+
// Core of SDK code
12
import Constants from './constants';
23
import cookieStorage from './cookiestorage';
34
import MetadataStorage from '../src/metadata-storage';
4-
import getUtmData from './utm';
5+
import getUtmData from './utm'; // Urchin Tracking Module
56
import Identify from './identify';
67
import localStorage from './localstorage'; // jshint ignore:line
78
import md5 from 'blueimp-md5';
89
import Request from './xhr';
910
import Revenue from './revenue';
1011
import type from './type';
11-
import UAParser from '@amplitude/ua-parser-js';
12+
import UAParser from '@amplitude/ua-parser-js'; // Identifying device and browser info (maybe move to backend?)
1213
import utils from './utils';
1314
import UUID from './uuid';
1415
import base64Id from './base64Id';
@@ -51,6 +52,7 @@ var AmplitudeClient = function AmplitudeClient(instanceName) {
5152
this._identifyId = 0;
5253
this._lastEventTime = null;
5354
this._newSession = false;
55+
// sequence used for by frontend for prioritizing event send retries
5456
this._sequenceNumber = 0;
5557
this._sessionId = null;
5658
this._isInitialized = false;
@@ -1567,6 +1569,7 @@ AmplitudeClient.prototype.sendEvents = function sendEvents() {
15671569

15681570
/**
15691571
* Merge unsent events and identifys together in sequential order based on their sequence number, for uploading.
1572+
* Identifys given higher priority than Events. Also earlier sequence given priority
15701573
* @private
15711574
*/
15721575
AmplitudeClient.prototype._mergeEventsAndIdentifys = function _mergeEventsAndIdentifys(numEvents) {

src/amplitude-snippet.js

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,9 @@
1+
/**
2+
* Imported in client browser via <script> tag
3+
* Async capabilities: Interally creates stubbed window.amplitude object until real SDK loaded
4+
* Stubbed functions keep track of funciton calls and their arguments
5+
* These are sent once real SDK loaded through another <script> tag
6+
*/
17
(function(window, document) {
28
var amplitude = window.amplitude || {'_q':[],'_iq':{}};
39
var as = document.createElement('script');

src/amplitude.js

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,7 @@ import { version } from '../package.json';
88
import DEFAULT_OPTIONS from './options';
99

1010
/**
11-
* Amplitude SDK API - instance manager.
11+
* Legacy API of Amplitude SDK - instance manager. Wraps around the current amplitude-client.js which provides more features
1212
* Function calls directly on amplitude have been deprecated. Please call methods on the default shared instance: amplitude.getInstance() instead.
1313
* See [Readme]{@link https://github.com/amplitude/Amplitude-Javascript#300-update-and-logging-events-to-multiple-amplitude-apps} for more information about this change.
1414
* @constructor Amplitude

src/index.js

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,15 +1,22 @@
11
/* jshint expr:true */
2+
// Entry point
23
import Amplitude from './amplitude';
34

45
const old = window.amplitude || {};
56
const newInstance = new Amplitude();
67
newInstance._q = old._q || [];
8+
9+
/**
10+
* Instantiates Amplitude object and runs all queued function logged by stubbed methods provided by snippets
11+
* Event queue allows async loading of SDK to not blocking client's app
12+
*/
713
for (let instance in old._iq) { // migrate each instance's queue
814
if (old._iq.hasOwnProperty(instance)) {
915
newInstance.getInstance(instance)._q = old._iq[instance]._q || [];
1016
}
1117
}
1218

19+
// If SDK is enabled as snippet, process the events queued by stubbed function
1320
if (BUILD_COMPAT_SNIPPET) {
1421
newInstance.runQueuedFunctions();
1522
}

src/metadata-storage.js

Lines changed: 15 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,13 @@ import getLocation from './get-location';
99
import localStorage from './localstorage'; // jshint ignore:line
1010
import topDomain from './top-domain';
1111

12-
class MetadataStorage {
12+
/**
13+
* MetadataStorage involves SDK data persistance
14+
* storage priority: cookies -> localStorage -> in memory
15+
* if in localStorage, unable track users between subdomains
16+
* if in memory, then memory can't be shared between different tabs
17+
*/
18+
class MetadataStorage {
1319
constructor({storageKey, disableCookies, domain, secure, sameSite, expirationDays}) {
1420
this.storageKey = storageKey;
1521
this.disableCookieStorage = !baseCookie.areCookiesEnabled() || disableCookies;
@@ -35,18 +41,21 @@ class MetadataStorage {
3541
return `${this.storageKey}${suffix ? `_${suffix}` : ''}`;
3642
}
3743

44+
/*
45+
* Data is saved as delimited values rather than JSO to minimize cookie space
46+
* Should not change order of the items
47+
*/
3848
save({ deviceId, userId, optOut, sessionId, lastEventTime, eventId, identifyId, sequenceNumber }) {
39-
// do not change the order of these items
4049
const value = [
4150
deviceId,
42-
Base64.encode(userId || ''),
51+
Base64.encode(userId || ''), // used to convert not unicode to alphanumeric since cookies only use alphanumeric
4352
optOut ? '1' : '',
44-
sessionId ? sessionId.toString(32) : '0',
45-
lastEventTime ? lastEventTime.toString(32) : '0',
53+
sessionId ? sessionId.toString(32) : '0', // generated when instantiated, timestamp (but re-uses session id in cookie if not expired) @TODO clients may want custom session id
54+
lastEventTime ? lastEventTime.toString(32) : '0', // last time an event was set
4655
eventId ? eventId.toString(32) : '0',
4756
identifyId ? identifyId.toString(32) : '0',
4857
sequenceNumber ? sequenceNumber.toString(32) : '0'
49-
].join('.');
58+
].join('.');
5059

5160
if (this.disableCookieStorage) {
5261
localStorage.setItem(this.storageKey, value);

src/options.js

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,7 @@ export default {
1616
batchEvents: false,
1717
cookieExpiration: 365 * 10,
1818
cookieName: 'amplitude_id', // this is a deprecated option
19-
sameSiteCookie: 'Lax',
19+
sameSiteCookie: 'Lax', // cookie privacy policy
2020
cookieForceUpgrade: false,
2121
deferInitialization: false,
2222
disableCookies: false,

0 commit comments

Comments
 (0)