move sdk packages to its own folder and rename api & dashboard

This commit is contained in:
Carl-Gerhard Lindesvärd
2024-03-11 13:15:44 +01:00
parent 1ca95442b9
commit 6d4f9010d4
318 changed files with 350 additions and 351 deletions

View File

@@ -0,0 +1,116 @@
import Script from 'next/script';
import type {
MixanEventOptions,
MixanWebOptions,
PostEventPayload,
UpdateProfilePayload,
} from '@mixan/web';
const CDN_URL = 'http://localhost:3002/op.js';
type OpenpanelMethods =
| 'ctor'
| 'event'
| 'setProfile'
| 'setProfileId'
| 'increment'
| 'decrement'
| 'clear';
declare global {
interface Window {
op: {
q?: [string, ...any[]];
(method: OpenpanelMethods, ...args: any[]): void;
};
}
}
type OpenpanelProviderProps = MixanWebOptions & {
profileId?: string;
cdnUrl?: string;
};
export function OpenpanelProvider({
profileId,
cdnUrl,
...options
}: OpenpanelProviderProps) {
const events: { name: OpenpanelMethods; value: unknown }[] = [
{ name: 'ctor', value: options },
];
if (profileId) {
events.push({ name: 'setProfileId', value: profileId });
}
return (
<>
<Script src={cdnUrl ?? CDN_URL} async defer />
<Script
dangerouslySetInnerHTML={{
__html: `window.op = window.op || function(...args) {(window.op.q = window.op.q || []).push(args)};
${events
.map((event) => {
return `window.op('${event.name}', ${JSON.stringify(event.value)});`;
})
.join('\n')}`,
}}
/>
</>
);
}
interface SetProfileIdProps {
value?: string;
}
export function SetProfileId({ value }: SetProfileIdProps) {
return (
<>
<Script
dangerouslySetInnerHTML={{
__html: `window.op('setProfileId', '${value}');`,
}}
/>
</>
);
}
export function trackEvent(
name: string,
data?: PostEventPayload['properties']
) {
window.op('event', name, data);
}
export function trackScreenView(data?: PostEventPayload['properties']) {
trackEvent('screen_view', data);
}
export function setProfile(data?: UpdateProfilePayload) {
window.op('setProfile', data);
}
export function setProfileId(profileId: string) {
window.op('setProfileId', profileId);
}
export function increment(
property: string,
value: number,
options?: MixanEventOptions
) {
window.op('increment', property, value, options);
}
export function decrement(
property: string,
value: number,
options?: MixanEventOptions
) {
window.op('decrement', property, value, options);
}
export function clear() {
window.op('clear');
}

View File

@@ -0,0 +1,35 @@
{
"name": "@mixan/nextjs",
"version": "0.0.1",
"module": "index.ts",
"scripts": {
"build": "rm -rf dist && tsup",
"build-for-openpanel": "pnpm build && cp dist/cdn.global.js ../../apps/public/public/op.js && cp dist/cdn.global.js ../../apps/test/public/op.js",
"lint": "eslint .",
"format": "prettier --check \"**/*.{mjs,ts,md,json}\"",
"typecheck": "tsc --noEmit"
},
"dependencies": {
"@mixan/sdk": "workspace:*",
"@mixan/web": "workspace:*"
},
"peerDependencies": {
"next": "^13.0.0"
},
"devDependencies": {
"@mixan/eslint-config": "workspace:*",
"@mixan/prettier-config": "workspace:*",
"@mixan/tsconfig": "workspace:*",
"eslint": "^8.48.0",
"prettier": "^3.0.3",
"tsup": "^7.2.0",
"typescript": "^5.2.2"
},
"eslintConfig": {
"root": true,
"extends": [
"@mixan/eslint-config/base"
]
},
"prettier": "@mixan/prettier-config"
}

View File

@@ -0,0 +1,6 @@
{
"extends": "@mixan/tsconfig/base.json",
"compilerOptions": {
"outDir": "dist"
}
}

View File

@@ -0,0 +1,9 @@
import { defineConfig } from 'tsup';
import config from '@mixan/tsconfig/tsup.config.json' assert { type: 'json' };
export default defineConfig({
...(config as any),
entry: ['index.ts'],
format: ['cjs', 'esm'],
});

View File

@@ -0,0 +1,45 @@
import { AppState, Platform } from 'react-native';
import * as Application from 'expo-application';
import Constants from 'expo-constants';
import type { MixanOptions, PostEventPayload } from '@mixan/sdk';
import { Mixan } from '@mixan/sdk';
type MixanNativeOptions = MixanOptions;
export class MixanNative extends Mixan<MixanNativeOptions> {
constructor(options: MixanNativeOptions) {
super(options);
this.api.headers['User-Agent'] = Constants.getWebViewUserAgentAsync();
AppState.addEventListener('change', (state) => {
if (state === 'active') {
this.setProperties();
}
});
this.setProperties();
}
private async setProperties() {
this.setGlobalProperties({
__version: Application.nativeApplicationVersion,
__buildNumber: Application.nativeBuildVersion,
__referrer:
Platform.OS === 'android'
? await Application.getInstallReferrerAsync()
: undefined,
});
}
public screenView(
route: string,
properties?: PostEventPayload['properties']
): void {
super.event('screen_view', {
...properties,
__path: route,
});
}
}

View File

@@ -0,0 +1,35 @@
{
"name": "@mixan/react-native",
"version": "0.0.1",
"module": "index.ts",
"scripts": {
"build": "rm -rf dist && tsup",
"lint": "eslint .",
"format": "prettier --check \"**/*.{mjs,ts,md,json}\"",
"typecheck": "tsc --noEmit"
},
"dependencies": {
"@mixan/sdk": "workspace:*"
},
"devDependencies": {
"@mixan/eslint-config": "workspace:*",
"@mixan/prettier-config": "workspace:*",
"@mixan/tsconfig": "workspace:*",
"eslint": "^8.48.0",
"prettier": "^3.0.3",
"tsup": "^7.2.0",
"typescript": "^5.2.2"
},
"peerDependencies": {
"react-native": "^0.72.5",
"expo-application": "~5.3.0",
"expo-constants": "~14.4.2"
},
"eslintConfig": {
"root": true,
"extends": [
"@mixan/eslint-config/base"
]
},
"prettier": "@mixan/prettier-config"
}

View File

@@ -0,0 +1,6 @@
{
"extends": "@mixan/tsconfig/sdk.json",
"compilerOptions": {
"outDir": "dist"
}
}

View File

@@ -0,0 +1,8 @@
import { defineConfig } from 'tsup';
import config from '@mixan/tsconfig/tsup.config.json' assert { type: 'json' };
export default defineConfig({
...(config as any),
minify: false,
});

244
packages/sdks/sdk/index.ts Normal file
View File

@@ -0,0 +1,244 @@
// NEW
export interface MixanEventOptions {
profileId?: string;
}
export interface PostEventPayload {
name: string;
timestamp: string;
deviceId?: string;
profileId?: string;
properties?: Record<string, unknown> & MixanEventOptions;
}
export interface UpdateProfilePayload {
profileId: string;
firstName?: string;
lastName?: string;
email?: string;
avatar?: string;
properties?: Record<string, unknown>;
}
export interface IncrementProfilePayload {
profileId: string;
property: string;
value: number;
}
export interface DecrementProfilePayload {
profileId?: string;
property: string;
value: number;
}
export interface MixanOptions {
url: string;
clientId: string;
clientSecret?: string;
verbose?: boolean;
setDeviceId?: (deviceId: string) => void;
getDeviceId?: () => string | null | undefined;
removeDeviceId?: () => void;
}
export interface MixanState {
deviceId?: string;
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 Mixan<Options extends MixanOptions = MixanOptions> {
public options: Options;
public api: ReturnType<typeof createApi>;
private state: MixanState = {
properties: {},
};
constructor(options: Options) {
this.options = options;
this.api = createApi(options.url);
this.api.headers['mixan-client-id'] = options.clientId;
if (this.options.clientSecret) {
this.api.headers['mixan-client-secret'] = this.options.clientSecret;
}
}
// Public
public setProfileId(profileId: string) {
this.state.profileId = profileId;
}
public setProfile(payload: UpdateProfilePayload) {
this.setProfileId(payload.profileId);
this.api.fetch<UpdateProfilePayload, string>('/profile', {
...payload,
properties: {
...this.state.properties,
...payload.properties,
},
});
}
public increment(
property: string,
value: number,
options?: MixanEventOptions
) {
const profileId = options?.profileId ?? this.state.profileId;
if (!profileId) {
return console.log('No profile id');
}
this.api.fetch<IncrementProfilePayload, string>('/profile/increment', {
profileId,
property,
value,
});
}
public decrement(
property: string,
value: number,
options?: MixanEventOptions
) {
const profileId = options?.profileId ?? this.state.profileId;
if (!profileId) {
return console.log('No profile id');
}
this.api.fetch<DecrementProfilePayload, string>('/profile/decrement', {
profileId,
property,
value,
});
}
public event(name: string, properties?: PostEventPayload['properties']) {
const profileId = properties?.profileId ?? this.state.profileId;
delete properties?.profileId;
this.api
.fetch<PostEventPayload, string>('/event', {
name,
properties: {
...this.state.properties,
...(properties ?? {}),
},
timestamp: this.timestamp(),
deviceId: this.getDeviceId(),
profileId,
})
.then((deviceId) => {
if (this.options.setDeviceId && deviceId) {
this.options.setDeviceId(deviceId);
}
});
}
public setGlobalProperties(properties: Record<string, unknown>) {
this.state.properties = {
...this.state.properties,
...properties,
};
}
public clear() {
this.state.deviceId = undefined;
this.state.profileId = undefined;
if (this.options.removeDeviceId) {
this.options.removeDeviceId();
}
}
// Private
private timestamp() {
return new Date().toISOString();
}
private getDeviceId() {
if (this.state.deviceId) {
return this.state.deviceId;
} else if (this.options.getDeviceId) {
this.state.deviceId = this.options.getDeviceId() || undefined;
}
}
}

View File

@@ -0,0 +1,28 @@
{
"name": "@mixan/sdk",
"version": "0.0.1",
"module": "index.ts",
"scripts": {
"build": "rm -rf dist && tsup",
"lint": "eslint .",
"format": "prettier --check \"**/*.{mjs,ts,md,json}\"",
"typecheck": "tsc --noEmit"
},
"dependencies": {},
"devDependencies": {
"@mixan/eslint-config": "workspace:*",
"@mixan/prettier-config": "workspace:*",
"@mixan/tsconfig": "workspace:*",
"eslint": "^8.48.0",
"prettier": "^3.0.3",
"tsup": "^7.2.0",
"typescript": "^5.2.2"
},
"eslintConfig": {
"root": true,
"extends": [
"@mixan/eslint-config/base"
]
},
"prettier": "@mixan/prettier-config"
}

View File

@@ -0,0 +1 @@
f97a3167-8dc6-4bed-923b-3d118c544006

View File

@@ -0,0 +1,6 @@
{
"extends": "@mixan/tsconfig/sdk.json",
"compilerOptions": {
"outDir": "dist"
}
}

View File

@@ -0,0 +1,7 @@
import { defineConfig } from 'tsup';
import config from '@mixan/tsconfig/tsup.config.json' assert {
type: 'json'
}
export default defineConfig(config as any);

31
packages/sdks/web/cdn.ts Normal file
View File

@@ -0,0 +1,31 @@
import { MixanWeb as Openpanel } from './index';
declare global {
interface Window {
op: {
q?: [string, ...any[]];
(method: string, ...args: any[]): void;
};
}
}
((window) => {
if (window.op && 'q' in window.op) {
const queue = window.op.q || [];
const op = new Openpanel(queue.shift()[1]);
queue.forEach((item) => {
if (item[0] in op) {
// @ts-expect-error
op[item[0]](...item.slice(1));
}
});
window.op = (t, ...args) => {
// @ts-expect-error
const fn = op[t].bind(op);
if (typeof fn === 'function') {
fn(...args);
}
};
}
})(window);

157
packages/sdks/web/index.ts Normal file
View File

@@ -0,0 +1,157 @@
import type { MixanOptions, PostEventPayload } from '@mixan/sdk';
import { Mixan } from '@mixan/sdk';
export * from '@mixan/sdk';
export type MixanWebOptions = MixanOptions & {
trackOutgoingLinks?: boolean;
trackScreenViews?: boolean;
trackAttributes?: boolean;
hash?: boolean;
};
function toCamelCase(str: string) {
return str.replace(/([-_][a-z])/gi, ($1) =>
$1.toUpperCase().replace('-', '').replace('_', '')
);
}
export class MixanWeb extends Mixan<MixanWebOptions> {
private lastPath = '';
constructor(options: MixanWebOptions) {
super(options);
if (!this.isServer()) {
this.setGlobalProperties({
__referrer: document.referrer,
});
if (this.options.trackOutgoingLinks) {
this.trackOutgoingLinks();
}
if (this.options.trackScreenViews) {
this.trackScreenViews();
}
if (this.options.trackAttributes) {
this.trackAttributes();
}
}
}
private isServer() {
return typeof document === 'undefined';
}
public trackOutgoingLinks() {
if (this.isServer()) {
return;
}
document.addEventListener('click', (event) => {
const target = event.target as HTMLElement;
const link = target.closest('a');
if (link && target) {
const href = link.getAttribute('href');
if (href?.startsWith('http')) {
super.event('link_out', {
href,
text:
link.innerText ||
link.getAttribute('title') ||
target.getAttribute('alt') ||
target.getAttribute('title'),
});
}
}
});
}
public trackScreenViews() {
if (this.isServer()) {
return;
}
const oldPushState = history.pushState;
history.pushState = function pushState(...args) {
const ret = oldPushState.apply(this, args);
window.dispatchEvent(new Event('pushstate'));
window.dispatchEvent(new Event('locationchange'));
return ret;
};
const oldReplaceState = history.replaceState;
history.replaceState = function replaceState(...args) {
const ret = oldReplaceState.apply(this, args);
window.dispatchEvent(new Event('replacestate'));
window.dispatchEvent(new Event('locationchange'));
return ret;
};
window.addEventListener('popstate', () =>
window.dispatchEvent(new Event('locationchange'))
);
if (this.options.hash) {
window.addEventListener('hashchange', () => this.screenView());
} else {
window.addEventListener('locationchange', () => this.screenView());
}
// give time for setProfile to be called
setTimeout(() => {
this.screenView();
}, 50);
}
public trackAttributes() {
if (this.isServer()) {
return;
}
document.addEventListener('click', (event) => {
const target = event.target as HTMLElement;
const btn = target.closest('button');
const achor = target.closest('button');
const element = btn?.getAttribute('data-event')
? btn
: achor?.getAttribute('data-event')
? achor
: null;
if (element) {
const properties: Record<string, unknown> = {};
for (const attr of element.attributes) {
if (attr.name.startsWith('data-') && attr.name !== 'data-event') {
properties[toCamelCase(attr.name.replace(/^data-/, ''))] =
attr.value;
}
}
const name = element.getAttribute('data-event');
if (name) {
super.event(name, properties);
}
}
});
}
public screenView(properties?: PostEventPayload['properties']): void {
if (this.isServer()) {
return;
}
const path = window.location.href;
if (this.lastPath === path) {
return;
}
this.lastPath = path;
super.event('screen_view', {
...(properties ?? {}),
__path: path,
__title: document.title,
});
}
}

View File

@@ -0,0 +1,31 @@
{
"name": "@mixan/web",
"version": "0.0.1",
"module": "index.ts",
"scripts": {
"build": "rm -rf dist && tsup",
"build-for-openpanel": "pnpm build && cp dist/cdn.global.js ../../apps/public/public/op.js && cp dist/cdn.global.js ../../apps/test/public/op.js",
"lint": "eslint .",
"format": "prettier --check \"**/*.{mjs,ts,md,json}\"",
"typecheck": "tsc --noEmit"
},
"dependencies": {
"@mixan/sdk": "workspace:*"
},
"devDependencies": {
"@mixan/eslint-config": "workspace:*",
"@mixan/prettier-config": "workspace:*",
"@mixan/tsconfig": "workspace:*",
"eslint": "^8.48.0",
"prettier": "^3.0.3",
"tsup": "^7.2.0",
"typescript": "^5.2.2"
},
"eslintConfig": {
"root": true,
"extends": [
"@mixan/eslint-config/base"
]
},
"prettier": "@mixan/prettier-config"
}

View File

@@ -0,0 +1,6 @@
{
"extends": "@mixan/tsconfig/sdk.json",
"compilerOptions": {
"outDir": "dist"
}
}

View File

@@ -0,0 +1,9 @@
import { defineConfig } from 'tsup';
import config from '@mixan/tsconfig/tsup.config.json' assert { type: 'json' };
export default defineConfig({
...(config as any),
entry: ['index.ts', 'cdn.ts'],
format: ['cjs', 'esm', 'iife'],
});