initial for v1

This commit is contained in:
Carl-Gerhard Lindesvärd
2024-07-28 00:05:32 +02:00
committed by Carl-Gerhard Lindesvärd
parent c770634e73
commit 15e997129a
23 changed files with 1019 additions and 528 deletions

View File

@@ -1,3 +1,8 @@
export * from './src/index';
// Deprecated types for beta version of the SDKs
// Still used in api/event.controller.ts and api/profile.controller.ts
export interface OpenpanelEventOptions {
profileId?: string;
}
@@ -29,201 +34,3 @@ export interface DecrementProfilePayload {
property: string;
value: number;
}
export interface OpenpanelSdkOptions {
url?: string;
clientId: string;
clientSecret?: string;
verbose?: boolean;
}
export interface OpenpanelState {
profileId?: string;
properties: Record<string, unknown>;
}
function awaitProperties(
properties: Record<string, string | Promise<string | null>>
): Promise<Record<string, string>> {
return Promise.all(
Object.entries(properties).map(async ([key, value]) => {
return [key, (await value) ?? ''];
})
).then((entries) => Object.fromEntries(entries));
}
function createApi(_url: string) {
const headers: Record<string, string | Promise<string | null>> = {
'Content-Type': 'application/json',
};
return {
headers,
async fetch<ReqBody, ResBody>(
path: string,
data: ReqBody,
options?: RequestInit
): Promise<ResBody | null> {
const url = `${_url}${path}`;
let timer: ReturnType<typeof setTimeout>;
const h = await awaitProperties(headers);
return new Promise((resolve) => {
const wrappedFetch = (attempt: number) => {
clearTimeout(timer);
fetch(url, {
headers: h,
method: 'POST',
body: JSON.stringify(data ?? {}),
keepalive: true,
...(options ?? {}),
})
.then(async (res) => {
if (res.status === 401) {
return null;
}
if (res.status !== 200 && res.status !== 202) {
return retry(attempt, resolve);
}
const response = await res.text();
if (!response) {
return resolve(null);
}
resolve(response as ResBody);
})
.catch(() => {
return retry(attempt, resolve);
});
};
function retry(
attempt: number,
resolve: (value: ResBody | null) => void
) {
if (attempt > 1) {
return resolve(null);
}
timer = setTimeout(
() => {
wrappedFetch(attempt + 1);
},
Math.pow(2, attempt) * 500
);
}
wrappedFetch(0);
});
},
};
}
export class OpenpanelSdk<
Options extends OpenpanelSdkOptions = OpenpanelSdkOptions,
> {
public options: Options;
public api: ReturnType<typeof createApi>;
private state: OpenpanelState = {
properties: {},
};
constructor(options: Options) {
this.options = options;
this.api = createApi(options.url ?? 'https://api.openpanel.dev');
this.api.headers['openpanel-client-id'] = options.clientId;
if (this.options.clientSecret) {
this.api.headers['openpanel-client-secret'] = this.options.clientSecret;
}
}
// Public
public setProfileId(profileId: string) {
this.state.profileId = profileId;
}
public async setProfile(payload: UpdateProfilePayload) {
this.setProfileId(payload.profileId);
return this.api.fetch<UpdateProfilePayload, string>('/profile', {
...payload,
properties: {
...this.state.properties,
...payload.properties,
},
});
}
public async increment(
property: string,
value: number,
options?: OpenpanelEventOptions
) {
const profileId = options?.profileId ?? this.state.profileId;
if (!profileId) {
return console.log('No profile id');
}
return this.api.fetch<IncrementProfilePayload, string>(
'/profile/increment',
{
profileId,
property,
value,
}
);
}
public async decrement(
property: string,
value: number,
options?: OpenpanelEventOptions
) {
const profileId = options?.profileId ?? this.state.profileId;
if (!profileId) {
return console.log('No profile id');
}
return this.api.fetch<DecrementProfilePayload, string>(
'/profile/decrement',
{
profileId,
property,
value,
}
);
}
public async event(
name: string,
properties?: PostEventPayload['properties']
) {
const profileId = properties?.profileId ?? this.state.profileId;
delete properties?.profileId;
return this.api.fetch<PostEventPayload, string>('/event', {
name,
properties: {
...this.state.properties,
...(properties ?? {}),
},
timestamp: this.timestamp(),
profileId,
});
}
public setGlobalProperties(properties: Record<string, unknown>) {
this.state.properties = {
...this.state.properties,
...properties,
};
}
public clear() {
this.state.profileId = undefined;
}
// Private
private timestamp() {
return new Date().toISOString();
}
}

View File

@@ -13,6 +13,7 @@
"@openpanel/eslint-config": "workspace:*",
"@openpanel/prettier-config": "workspace:*",
"@openpanel/tsconfig": "workspace:*",
"@types/node": "^20.14.12",
"eslint": "^8.48.0",
"prettier": "^3.0.3",
"tsup": "^7.2.0",

View File

@@ -0,0 +1,85 @@
interface ApiConfig {
baseUrl: string;
defaultHeaders?: Record<string, string | Promise<string | null>>;
maxRetries?: number;
initialRetryDelay?: number;
}
interface FetchOptions extends RequestInit {
retries?: number;
}
export class Api {
private baseUrl: string;
private headers: Record<string, string | Promise<string | null>>;
private maxRetries: number;
private initialRetryDelay: number;
constructor(config: ApiConfig) {
this.baseUrl = config.baseUrl;
this.headers = {
'Content-Type': 'application/json',
...config.defaultHeaders,
};
this.maxRetries = config.maxRetries ?? 3;
this.initialRetryDelay = config.initialRetryDelay ?? 500;
}
private async resolveHeaders(): Promise<Record<string, string>> {
const resolvedHeaders: Record<string, string> = {};
for (const [key, value] of Object.entries(this.headers)) {
const resolvedValue = await value;
if (resolvedValue !== null) {
resolvedHeaders[key] = resolvedValue;
}
}
return resolvedHeaders;
}
public addHeader(key: string, value: string | Promise<string | null>) {
this.headers[key] = value;
}
private async post<ReqBody, ResBody>(
url: string,
data: ReqBody,
options: FetchOptions,
attempt: number
): Promise<ResBody | null> {
try {
const response = await fetch(url, {
method: 'POST',
headers: await this.resolveHeaders(),
body: JSON.stringify(data ?? {}),
keepalive: true,
...options,
});
if (response.status === 401) return null;
if (response.status !== 200 && response.status !== 202) {
throw new Error(`HTTP error! status: ${response.status}`);
}
const responseText = await response.text();
return responseText ? JSON.parse(responseText) : null;
} catch (error) {
if (attempt < this.maxRetries) {
const delay = this.initialRetryDelay * Math.pow(2, attempt);
await new Promise((resolve) => setTimeout(resolve, delay));
return this.post<ReqBody, ResBody>(url, data, options, attempt + 1);
}
console.error('Max retries reached:', error);
return null;
}
}
async fetch<ReqBody, ResBody>(
path: string,
data: ReqBody,
options: FetchOptions = {}
): Promise<ResBody | null> {
const url = `${this.baseUrl}${path}`;
return this.post<ReqBody, ResBody>(url, data, options, 0);
}
}

View File

@@ -0,0 +1,199 @@
import { Api } from './api';
export type TrackHandlerPayload =
| {
type: 'track';
payload: TrackPayload;
}
| {
type: 'increment';
payload: IncrementPayload;
}
| {
type: 'decrement';
payload: DecrementPayload;
}
| {
type: 'alias';
payload: AliasPayload;
}
| {
type: 'identify';
payload: IdentifyPayload;
};
export type TrackPayload = {
name: string;
properties?: Record<string, unknown>;
profileId?: string;
};
export type TrackProperties = {
[key: string]: unknown;
profileId?: string;
};
export type IdentifyPayload = {
profileId: string;
firstName?: string;
lastName?: string;
email?: string;
avatar?: string;
properties?: Record<string, unknown>;
};
export type AliasPayload = {
profileId: string;
alias: string;
};
export type IncrementPayload = {
profileId: string;
property: string;
value?: number;
};
export type DecrementPayload = {
profileId: string;
property: string;
value?: number;
};
export type OpenPanelOptions = {
clientId: string;
clientSecret?: string;
apiUrl?: string;
sdk?: string;
sdkVersion?: string;
waitForProfile?: boolean;
filter?: (payload: TrackHandlerPayload) => boolean;
};
export class OpenPanel {
api: Api;
profileId?: string;
global?: Record<string, any>;
queue: TrackHandlerPayload[] = [];
constructor(public options: OpenPanelOptions) {
const defaultHeaders: Record<string, string> = {
'openpanel-client-id': options.clientId,
};
if (options.clientSecret) {
defaultHeaders['openpanel-client-secret'] = options.clientSecret;
}
defaultHeaders['openpanel-sdk'] = options.sdk || 'node';
defaultHeaders['openpanel-sdk-version'] =
options.sdkVersion || process.env.SDK_VERSION!;
this.api = new Api({
baseUrl: options.apiUrl || 'https://api.openpanel.dev',
defaultHeaders,
});
}
init() {
// empty
}
ready() {
this.options.waitForProfile = false;
this.flush();
}
async send(payload: TrackHandlerPayload) {
if (this.options.filter && !this.options.filter(payload)) {
return Promise.resolve();
}
if (this.options.waitForProfile && !this.profileId) {
this.queue.push(payload);
return Promise.resolve();
}
return this.api.fetch('/track', payload);
}
setGlobalProperties(properties: Record<string, any>) {
this.global = {
...this.global,
...properties,
};
}
async track(name: string, properties?: TrackProperties) {
return this.send({
type: 'track',
payload: {
name,
profileId: properties?.profileId ?? this.profileId,
properties: {
...(this.global ?? {}),
...(properties ?? {}),
},
},
});
}
async identify(payload: IdentifyPayload) {
if (payload.profileId) {
this.profileId = payload.profileId;
this.flush();
}
if (Object.keys(payload).length > 1) {
return this.send({
type: 'identify',
payload: {
...payload,
properties: {
...this.global,
...payload.properties,
},
},
});
}
}
async alias(payload: AliasPayload) {
return this.send({
type: 'alias',
payload,
});
}
async increment(payload: IncrementPayload) {
return this.send({
type: 'increment',
payload,
});
}
async decrement(payload: DecrementPayload) {
return this.send({
type: 'decrement',
payload,
});
}
clear() {
this.profileId = undefined;
// session end?
}
flush() {
this.queue.forEach((item) => {
this.send({
...item,
// Not user why ts-expect-error is needed here
// @ts-expect-error
payload: {
...item.payload,
profileId: this.profileId,
},
});
});
this.queue = [];
}
}