add @aptabase/browser
This commit is contained in:
parent
9900d6ea6d
commit
348898fc82
14 changed files with 295 additions and 1 deletions
3
packages/browser/CHANGELOG.md
Normal file
3
packages/browser/CHANGELOG.md
Normal file
|
@ -0,0 +1,3 @@
|
|||
## 0.1.0
|
||||
|
||||
- Initial version of the Aptabase SDK for Browser Extensions
|
21
packages/browser/LICENSE
Normal file
21
packages/browser/LICENSE
Normal file
|
@ -0,0 +1,21 @@
|
|||
MIT License
|
||||
|
||||
Copyright (c) 2023 Sumbit Labs Ltd.
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
44
packages/browser/README.md
Normal file
44
packages/browser/README.md
Normal file
|
@ -0,0 +1,44 @@
|
|||

|
||||
|
||||
# Aptabase SDK for Browser Extensions
|
||||
|
||||
A tiny SDK (1 kB) to instrument your Browser/Chrome extensions with Aptabase, an Open Source, Privacy-First and Simple Analytics for Mobile, Desktop and Web Apps.
|
||||
|
||||
## Install
|
||||
|
||||
Install the SDK using npm or your preferred JavaScript package manager
|
||||
|
||||
```bash
|
||||
npm add @aptabase/browser
|
||||
```
|
||||
|
||||
## Usage
|
||||
|
||||
First you need to get your `App Key` from Aptabase, you can find it in the `Instructions` menu on the left side menu.
|
||||
|
||||
Initialize the SDK in your `Background Script` using your `App Key`:
|
||||
|
||||
```js
|
||||
import { init } from '@aptabase/browser';
|
||||
|
||||
init('<YOUR_APP_KEY>'); // 👈 this is where you enter your App Key
|
||||
```
|
||||
|
||||
The init function also supports an optional second parameter, which is an object with the `isDebug` property. Your data is seggregated between development and production environments, so it's important to set this value correctly. By default the SDK will use the `NODE_ENV` environment variable to determine if it's in development or production mode, which is only available in bundlers like Webpack, Rollup, etc. If you're not using a bundler, you can pass in the `isDebug` property manually.
|
||||
|
||||
Afterwards you can start tracking events with `trackEvent` from anywhere in your extension:
|
||||
|
||||
```js
|
||||
import { trackEvent } from '@aptabase/browser';
|
||||
|
||||
trackEvent('connect_click'); // An event with no properties
|
||||
trackEvent('play_music', { name: 'Here comes the sun' }); // An event with a custom property
|
||||
```
|
||||
|
||||
A few important notes:
|
||||
|
||||
1. The SDK will automatically enhance the event with some useful information, like the OS, the app version, and other things.
|
||||
2. You're in control of what gets sent to Aptabase. This SDK does not automatically track any events, you need to call `trackEvent` manually.
|
||||
- Because of this, it's generally recommended to at least track an event at startup
|
||||
3. You do not need to await the `trackEvent` function, it'll run in the background.
|
||||
4. Only strings and numeric values are allowed on custom properties
|
36
packages/browser/package.json
Normal file
36
packages/browser/package.json
Normal file
|
@ -0,0 +1,36 @@
|
|||
{
|
||||
"name": "@aptabase/browser",
|
||||
"version": "0.1.0",
|
||||
"type": "module",
|
||||
"description": "Browser Extension SDK for Aptabase: Open Source, Privacy-First and Simple Analytics for Mobile, Desktop and Web Apps",
|
||||
"main": "./dist/index.cjs",
|
||||
"module": "./dist/index.js",
|
||||
"types": "./dist/index.d.ts",
|
||||
"exports": {
|
||||
".": {
|
||||
"require": "./dist/index.cjs",
|
||||
"import": "./dist/index.js",
|
||||
"types": "./dist/index.d.ts"
|
||||
}
|
||||
},
|
||||
"repository": {
|
||||
"type": "git",
|
||||
"url": "git+https://github.com/aptabase/aptabase-js.git",
|
||||
"directory": "packages/browser"
|
||||
},
|
||||
"bugs": {
|
||||
"url": "https://github.com/aptabase/aptabase-js/issues"
|
||||
},
|
||||
"homepage": "https://github.com/aptabase/aptabase-js",
|
||||
"license": "MIT",
|
||||
"scripts": {
|
||||
"build": "tsup",
|
||||
"prepublishOnly": "npm run build"
|
||||
},
|
||||
"files": [
|
||||
"README.md",
|
||||
"LICENSE",
|
||||
"dist",
|
||||
"package.json"
|
||||
]
|
||||
}
|
4
packages/browser/src/global.d.ts
vendored
Normal file
4
packages/browser/src/global.d.ts
vendored
Normal file
|
@ -0,0 +1,4 @@
|
|||
declare var aptabase: {
|
||||
init: Function;
|
||||
trackEvent: Function;
|
||||
};
|
82
packages/browser/src/index.ts
Normal file
82
packages/browser/src/index.ts
Normal file
|
@ -0,0 +1,82 @@
|
|||
import { newSessionId, sendEvent, validateAppKey, type AptabaseOptions } from '../../shared';
|
||||
|
||||
// Session expires after 1 hour of inactivity
|
||||
const SESSION_TIMEOUT = 1 * 60 * 60;
|
||||
const sdkVersion = `aptabase-browser@${process.env.PKG_VERSION}`;
|
||||
const isWebContext = 'document' in globalThis;
|
||||
|
||||
let _appKey = '';
|
||||
let _options: AptabaseOptions | undefined;
|
||||
|
||||
globalThis.aptabase = {
|
||||
init,
|
||||
trackEvent,
|
||||
};
|
||||
|
||||
export function init(appKey: string, options?: AptabaseOptions) {
|
||||
if (isWebContext) {
|
||||
console.error('@aptabase/browser can only be initialized in your background script.');
|
||||
return;
|
||||
}
|
||||
|
||||
if (!validateAppKey(appKey)) return;
|
||||
|
||||
_appKey = appKey;
|
||||
_options = { ...options, appVersion: options?.appVersion ?? chrome.runtime.getManifest().version };
|
||||
|
||||
chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
|
||||
if (message && message.type === '__aptabase__trackEvent') {
|
||||
trackEvent(message.eventName, message.props);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
export async function trackEvent(eventName: string, props?: Record<string, string | number | boolean>): Promise<void> {
|
||||
if (isWebContext) {
|
||||
return chrome.runtime.sendMessage({ type: '__aptabase__trackEvent', eventName, props });
|
||||
}
|
||||
|
||||
const sessionId = await getSessionId();
|
||||
|
||||
return sendEvent({
|
||||
sessionId,
|
||||
appKey: _appKey,
|
||||
isDebug: _options?.isDebug,
|
||||
appVersion: _options?.appVersion,
|
||||
sdkVersion,
|
||||
eventName,
|
||||
props,
|
||||
});
|
||||
}
|
||||
|
||||
type CachedItem = {
|
||||
id: string;
|
||||
lastTouched: number;
|
||||
};
|
||||
|
||||
let _sessionId = newSessionId();
|
||||
|
||||
async function getSessionId(): Promise<string> {
|
||||
const now = Date.now();
|
||||
|
||||
// If storage is not available, return the in memory session id
|
||||
// This id will be recreated if the extension is reloaded or the service worker becomes inactive
|
||||
if (!chrome?.storage?.local) return _sessionId;
|
||||
|
||||
return new Promise((resolve) => {
|
||||
chrome.storage.local.get('_ab_session_id', (result) => {
|
||||
let item = (result['_ab_session_id'] as CachedItem) ?? { id: _sessionId, lastTouched: Date.now() };
|
||||
|
||||
const diffInMs = now - item.lastTouched;
|
||||
const diffInSec = Math.floor(diffInMs / 1000);
|
||||
if (diffInSec > SESSION_TIMEOUT) {
|
||||
item.id = newSessionId();
|
||||
}
|
||||
item.lastTouched = now;
|
||||
|
||||
chrome.storage.local.set({ _ab_session_id: item }, () => {
|
||||
resolve(item.id);
|
||||
});
|
||||
});
|
||||
});
|
||||
}
|
15
packages/browser/tsconfig.json
Normal file
15
packages/browser/tsconfig.json
Normal file
|
@ -0,0 +1,15 @@
|
|||
{
|
||||
"compilerOptions": {
|
||||
"target": "es6",
|
||||
"strict": true,
|
||||
"moduleResolution": "node",
|
||||
"esModuleInterop": true,
|
||||
"jsx": "react-jsx",
|
||||
"baseUrl": ".",
|
||||
"paths": {
|
||||
"types": ["@types"]
|
||||
},
|
||||
"declaration": true,
|
||||
"declarationDir": "./dist"
|
||||
}
|
||||
}
|
15
packages/browser/tsup.config.ts
Normal file
15
packages/browser/tsup.config.ts
Normal file
|
@ -0,0 +1,15 @@
|
|||
import { defineConfig } from 'tsup';
|
||||
const { version } = require('./package.json');
|
||||
|
||||
export default defineConfig({
|
||||
entry: ['src/index.ts'],
|
||||
format: ['cjs', 'esm'],
|
||||
dts: true,
|
||||
splitting: false,
|
||||
minify: true,
|
||||
sourcemap: true,
|
||||
clean: true,
|
||||
env: {
|
||||
PKG_VERSION: version,
|
||||
},
|
||||
});
|
Loading…
Add table
Add a link
Reference in a new issue