Skip to content

OpenPanel is an open-source web and product analytics platform, an open-source alternative to Mixpanel with optional self-hosting.

initial for v1

Carl-Gerhard Lindesvärd15e997129a8e
diff --git a/apps/api/src/controllers/track.controller.ts b/apps/api/src/controllers/track.controller.ts
new file mode 100644
index 000000000..634fd054e
--- /dev/null
+++ b/apps/api/src/controllers/track.controller.ts
@@ -0,0 +1,262 @@
+import type { GeoLocation } from '@/utils/parseIp';
+import { getClientIp, parseIp } from '@/utils/parseIp';
+import { parseUserAgent } from '@/utils/parseUserAgent';
+import type { FastifyReply, FastifyRequest } from 'fastify';
+import { assocPath, pathOr } from 'ramda';
+
+import { generateDeviceId } from '@openpanel/common';
+import {
+ ch,
+ getProfileById,
+ getSalts,
+ TABLE_NAMES,
+ upsertProfile,
+} from '@openpanel/db';
+import { eventsQueue } from '@openpanel/queue';
+import { getRedisCache } from '@openpanel/redis';
+import type {
+ AliasPayload,
+ DecrementPayload,
+ IdentifyPayload,
+ IncrementPayload,
+ TrackHandlerPayload,
+} from '@openpanel/sdk';
+
+export async function handler(
+ request: FastifyRequest<{
+ Body: TrackHandlerPayload;
+ }>,
+ reply: FastifyReply
+) {
+ const ip = getClientIp(request)!;
+ const ua = request.headers['user-agent']!;
+ const projectId = request.client?.projectId;
+
+ if (!projectId) {
+ reply.status(400).send('missing origin');
+ return;
+ }
+
+ switch (request.body.type) {
+ case 'track': {
+ const [salts, geo] = await Promise.all([getSalts(), parseIp(ip)]);
+ const currentDeviceId = generateDeviceId({
+ salt: salts.current,
+ origin: projectId,
+ ip,
+ ua,
+ });
+ const previousDeviceId = generateDeviceId({
+ salt: salts.previous,
+ origin: projectId,
+ ip,
+ ua,
+ });
+ await track({
+ payload: request.body.payload,
+ currentDeviceId,
+ previousDeviceId,
+ projectId,
+ geo,
+ ua,
+ });
+ break;
+ }
+ case 'identify': {
+ const geo = await parseIp(ip);
+ await identify({
+ payload: request.body.payload,
+ projectId,
+ geo,
+ ua,
+ });
+ break;
+ }
+ case 'alias': {
+ await alias({
+ payload: request.body.payload,
+ projectId,
+ });
+ break;
+ }
+ case 'increment': {
+ await increment({
+ payload: request.body.payload,
+ projectId,
+ });
+ break;
+ }
+ case 'decrement': {
+ await decrement({
+ payload: request.body.payload,
+ projectId,
+ });
+ break;
+ }
+ }
+}
+
+type TrackPayload = {
+ name: string;
+ properties?: Record<string, any>;
+};
+
+async function track({
+ payload,
+ currentDeviceId,
+ previousDeviceId,
+ projectId,
+ geo,
+ ua,
+}: {
+ payload: TrackPayload;
+ currentDeviceId: string;
+ previousDeviceId: string;
+ projectId: string;
+ geo: GeoLocation;
+ ua: string;
+}) {
+ // this will ensure that we don't have multiple events creating sessions
+ const locked = await getRedisCache().set(
+ `request:priority:${currentDeviceId}-${previousDeviceId}`,
+ 'locked',
+ 'EX',
+ 10,
+ 'NX'
+ );
+
+ eventsQueue.add('event', {
+ type: 'incomingEvent',
+ payload: {
+ projectId,
+ headers: {
+ ua,
+ },
+ event: {
+ ...payload,
+ // Dont rely on the client for the timestamp
+ timestamp: new Date().toISOString(),
+ },
+ geo,
+ currentDeviceId,
+ previousDeviceId,
+ priority: locked === 'OK',
+ },
+ });
+}
+
+async function identify({
+ payload,
+ projectId,
+ geo,
+ ua,
+}: {
+ payload: IdentifyPayload;
+ projectId: string;
+ geo: GeoLocation;
+ ua: string;
+}) {
+ const uaInfo = parseUserAgent(ua);
+ await upsertProfile({
+ id: payload.profileId,
+ isExternal: true,
+ projectId,
+ properties: {
+ ...(payload.properties ?? {}),
+ ...(geo ?? {}),
+ ...uaInfo,
+ },
+ ...payload,
+ });
+}
+
+async function alias({
+ payload,
+ projectId,
+}: {
+ payload: AliasPayload;
+ projectId: string;
+}) {
+ await ch.insert({
+ table: TABLE_NAMES.alias,
+ values: [
+ {
+ projectId,
+ profile_id: payload.profileId,
+ alias: payload.alias,
+ },
+ ],
+ });
+}
+
+async function increment({
+ payload,
+ projectId,
+}: {
+ payload: IncrementPayload;
+ projectId: string;
+}) {
+ const { profileId, property, value } = payload;
+ const profile = await getProfileById(profileId, projectId);
+ if (!profile) {
+ throw new Error('Not found');
+ }
+
+ const parsed = parseInt(
+ pathOr<string>('0', property.split('.'), profile.properties),
+ 10
+ );
+
+ if (isNaN(parsed)) {
+ throw new Error('Not number');
+ }
+
+ profile.properties = assocPath(
+ property.split('.'),
+ parsed + (value || 1),
+ profile.properties
+ );
+
+ await upsertProfile({
+ id: profile.id,
+ projectId,
+ properties: profile.properties,
+ isExternal: true,
+ });
+}
+
+async function decrement({
+ payload,
+ projectId,
+}: {
+ payload: DecrementPayload;
+ projectId: string;
+}) {
+ const { profileId, property, value } = payload;
+ const profile = await getProfileById(profileId, projectId);
+ if (!profile) {
+ throw new Error('Not found');
+ }
+
+ const parsed = parseInt(
+ pathOr<string>('0', property.split('.'), profile.properties),
+ 10
+ );
+
+ if (isNaN(parsed)) {
+ throw new Error('Not number');
+ }
+
+ profile.properties = assocPath(
+ property.split('.'),
+ parsed - (value || 1),
+ profile.properties
+ );
+
+ await upsertProfile({
+ id: profile.id,
+ projectId,
+ properties: profile.properties,
+ isExternal: true,
+ });
+}
diff --git a/apps/api/src/routes/track.router.ts b/apps/api/src/routes/track.router.ts
new file mode 100644
index 000000000..8829829f6
--- /dev/null
+++ b/apps/api/src/routes/track.router.ts
@@ -0,0 +1,69 @@
+import { isBot } from '@/bots';
+import type { TrackHandlerPayload } from '@/controllers/track.controller';
+import { handler } from '@/controllers/track.controller';
+import { SdkAuthError, validateSdkRequest } from '@/utils/auth';
+import { logger } from '@/utils/logger';
+import type { FastifyPluginCallback, FastifyRequest } from 'fastify';
+
+import { createBotEvent } from '@openpanel/db';
+
+const eventRouter: FastifyPluginCallback = (fastify, opts, done) => {
+ fastify.addHook(
+ 'preHandler',
+ async (
+ req: FastifyRequest<{
+ Body: TrackHandlerPayload;
+ }>,
+ reply
+ ) => {
+ try {
+ const client = await validateSdkRequest(req.headers).catch((error) => {
+ if (!(error instanceof SdkAuthError)) {
+ logger.error(error, 'Failed to validate sdk request');
+ }
+ return null;
+ });
+
+ if (!client?.projectId) {
+ return reply.status(401).send();
+ }
+
+ req.projectId = client.projectId;
+ req.client = client;
+
+ const bot = req.headers['user-agent']
+ ? isBot(req.headers['user-agent'])
+ : null;
+
+ if (bot) {
+ if (req.body.type === 'track') {
+ const path = (req.body.payload.properties?.__path ||
+ req.body.payload.properties?.path) as string | undefined;
+ await createBotEvent({
+ ...bot,
+ projectId: client.projectId,
+ path: path ?? '',
+ createdAt: new Date(),
+ });
+ }
+
+ reply.status(202).send('OK');
+ }
+ } catch (e) {
+ logger.error(e, 'Failed to create bot event');
+ reply.status(401).send();
+ return;
+ }
+ }
+ );
+
+ fastify.route({
+ method: 'POST',
+ url: '/',
+ handler: handler,
+ });
+
+ done();
+};
+
+export default eventRouter;
diff --git a/apps/api/src/utils/parseIp.ts b/apps/api/src/utils/parseIp.ts
index dc7437e6d..c75cc226c 100644
--- a/apps/api/src/utils/parseIp.ts
+++ b/apps/api/src/utils/parseIp.ts
@@ -11,7 +11,7 @@ interface RemoteIpLookupResponse {
latitude: number | undefined;
}
-interface GeoLocation {
+export interface GeoLocation {
country: string | undefined;
city: string | undefined;
region: string | undefined;
diff --git a/apps/worker/src/jobs/events.incoming-event.ts b/apps/worker/src/jobs/events.incoming-event.ts
index 1ee4a99d5..100db59f3 100644
--- a/apps/worker/src/jobs/events.incoming-event.ts
+++ b/apps/worker/src/jobs/events.incoming-event.ts
@@ -11,7 +11,7 @@ import {
toISOString,
} from '@openpanel/common';
import type { IServiceCreateEventPayload, IServiceEvent } from '@openpanel/db';
-import { createEvent } from '@openpanel/db';
+import { chQuery, createEvent, TABLE_NAMES } from '@openpanel/db';
import { getLastScreenViewFromProfileId } from '@openpanel/db/src/services/event.service';
import { eventsQueue, findJobByPrefix, sessionsQueue } from '@openpanel/queue';
import type {
@@ -20,14 +20,6 @@ import type {
} from '@openpanel/queue';
import { getRedisQueue } from '@openpanel/redis';
-function noDateInFuture(eventDate: Date): Date {
- if (eventDate > new Date()) {
- return new Date();
- } else {
- return eventDate;
- }
-}
-
const GLOBAL_PROPERTIES = ['__path', '__referrer'];
const SESSION_TIMEOUT = 1000 * 60 * 30;
const SESSION_END_TIMEOUT = SESSION_TIMEOUT + 1000;
@@ -54,8 +46,12 @@ export async function incomingEvent(job: Job<EventsQueuePayloadIncomingEvent>) {
);
};
- const profileId = body.profileId ? String(body.profileId) : '';
- const createdAt = noDateInFuture(new Date(body.timestamp));
+ // this will get the profileId from the alias table if it exists
+ const profileId = await getProfileId({
+ projectId,
+ profileId: body.profileId,
+ });
+ const createdAt = new Date(body.timestamp);
const url = getProperty('__path');
const { path, hash, query, origin } = parsePath(url);
const referrer = isSameDomain(getProperty('__referrer'), url)
@@ -263,3 +259,29 @@ async function getSessionEnd({
// Create session
return null;
}
+
+async function getProfileId({
+ profileId,
+ projectId,
+}: {
+ profileId: string | undefined;
+ projectId: string;
+}) {
+ if (!profileId) {
+ return '';
+ }
+
+ const res = await chQuery<{
+ alias: string;
+ profile_id: string;
+ project_id: string;
+ }>(
+ `SELECT * FROM ${TABLE_NAMES.alias} WHERE project_id = '${projectId}' AND (alias = '${profileId}' OR profile_id = '${profileId}')`
+ );
+
+ if (res[0]) {
+ return res[0].profile_id;
+ }
+
+ return profileId;
+}
diff --git a/packages/db/src/clickhouse-client.ts b/packages/db/src/clickhouse-client.ts
index 210bea52a..828c2da9d 100644
--- a/packages/db/src/clickhouse-client.ts
+++ b/packages/db/src/clickhouse-client.ts
@@ -4,6 +4,7 @@ import { createClient } from '@clickhouse/client';
export const TABLE_NAMES = {
events: 'events_v2',
profiles: 'profiles',
+ alias: 'profile_aliases',
};
export const originalCh = createClient({
diff --git a/packages/queue/src/queues.ts b/packages/queue/src/queues.ts
index 2cb4cbf5e..911531aaa 100644
--- a/packages/queue/src/queues.ts
+++ b/packages/queue/src/queues.ts
@@ -2,13 +2,15 @@ import { Queue } from 'bullmq';
import type { IServiceEvent } from '@openpanel/db';
import { getRedisQueue } from '@openpanel/redis';
-import type { PostEventPayload } from '@openpanel/sdk';
+import type { TrackPayload } from '@openpanel/sdk';
export interface EventsQueuePayloadIncomingEvent {
type: 'incomingEvent';
payload: {
projectId: string;
- event: PostEventPayload;
+ event: TrackPayload & {
+ timestamp: string;
+ };
geo: {
country: string | undefined;
city: string | undefined;
diff --git a/packages/sdks/express/index.ts b/packages/sdks/express/index.ts
index bd55c22a7..fa0d1e4c3 100644
--- a/packages/sdks/express/index.ts
+++ b/packages/sdks/express/index.ts
@@ -1,8 +1,8 @@
import type { NextFunction, Request, Response } from 'express';
import { getClientIp } from 'request-ip';
-import type { OpenpanelSdkOptions } from '@openpanel/sdk';
-import { OpenpanelSdk } from '@openpanel/sdk';
+import type { OpenPanelOptions } from '@openpanel/sdk';
+import { OpenPanel } from '@openpanel/sdk';
export * from '@openpanel/sdk';
@@ -10,33 +10,35 @@ declare global {
// eslint-disable-next-line @typescript-eslint/no-namespace
namespace Express {
export interface Request {
- op: OpenpanelSdk;
+ op: OpenPanel;
}
}
}
-export type OpenpanelOptions = OpenpanelSdkOptions & {
+export type OpenpanelOptions = OpenPanelOptions & {
trackRequest?: (url: string) => boolean;
getProfileId?: (req: Request) => string;
};
export default function createMiddleware(options: OpenpanelOptions) {
return function middleware(req: Request, res: Response, next: NextFunction) {
- const sdk = new OpenpanelSdk(options);
+ const sdk = new OpenPanel(options);
const ip = getClientIp(req);
if (ip) {
- sdk.api.headers['x-client-ip'] = ip;
+ sdk.api.addHeader('x-client-ip', ip);
}
if (options.getProfileId) {
const profileId = options.getProfileId(req);
if (profileId) {
- sdk.setProfileId(profileId);
+ sdk.identify({
+ profileId,
+ });
}
}
if (options.trackRequest?.(req.url)) {
- sdk.event('request', {
+ sdk.track('request', {
url: req.url,
method: req.method,
query: req.query,
diff --git a/packages/sdks/nextjs/index.tsx b/packages/sdks/nextjs/index.tsx
index 921c14440..7c83df301 100644
--- a/packages/sdks/nextjs/index.tsx
+++ b/packages/sdks/nextjs/index.tsx
@@ -2,10 +2,12 @@ import React from 'react';
import Script from 'next/script';
import type {
- OpenpanelEventOptions,
- OpenpanelOptions,
- PostEventPayload,
- UpdateProfilePayload,
+ DecrementPayload,
+ IdentifyPayload,
+ IncrementPayload,
+ OpenPanelMethodNames,
+ OpenPanelOptions,
+ TrackProperties,
} from '@openpanel/web';
export * from '@openpanel/web';
@@ -13,48 +15,33 @@ export { createNextRouteHandler } from './createNextRouteHandler';
const CDN_URL = 'https://openpanel.dev/op.js';
-declare global {
- interface Window {
- op: {
- q?: [string, ...any[]];
- (method: OpenpanelMethods, ...args: any[]): void;
- };
- }
-}
-
-type OpenpanelMethods =
- | 'ctor'
- | 'event'
- | 'setProfile'
- | 'setProfileId'
- | 'increment'
- | 'decrement'
- | 'clear';
-
-declare global {
- interface window {
- op: {
- q?: [string, ...any[]];
- (method: OpenpanelMethods, ...args: any[]): void;
- };
- }
-}
-
-type OpenpanelProviderProps = OpenpanelOptions & {
+type OpenPanelComponentProps = OpenPanelOptions & {
profileId?: string;
cdnUrl?: string;
};
-export function OpenpanelProvider({
+export function OpenPanelComponent({
profileId,
cdnUrl,
...options
-}: OpenpanelProviderProps) {
- const methods: { name: OpenpanelMethods; value: unknown }[] = [
- { name: 'ctor', value: options },
+}: OpenPanelComponentProps) {
+ const methods: { name: OpenPanelMethodNames; value: unknown }[] = [
+ {
+ name: 'init',
+ value: {
+ ...options,
+ sdk: 'nextjs',
+ sdkVersion: process.env.NEXTJS_VERSION!,
+ },
+ },
];
if (profileId) {
- methods.push({ name: 'setProfileId', value: profileId });
+ methods.push({
+ name: 'identify',
+ value: {
+ profileId,
+ },
+ });
}
return (
<>
@@ -73,25 +60,9 @@ export function OpenpanelProvider({
);
}
-interface SetProfileIdProps {
- value?: string;
-}
-
-export function SetProfileId({ value }: SetProfileIdProps) {
- return (
- <>
- <Script
- dangerouslySetInnerHTML={{
- __html: `window.op('setProfileId', '${value}');`,
- }}
- />
- </>
- );
-}
-
-type SetProfileProps = UpdateProfilePayload;
+type IdentifyComponentProps = IdentifyPayload;
-export function SetProfile(props: SetProfileProps) {
+export function IdentifyComponent(props: IdentifyComponentProps) {
return (
<>
<Script
@@ -103,41 +74,37 @@ export function SetProfile(props: SetProfileProps) {
);
}
-export function trackEvent(
- name: string,
- data?: PostEventPayload['properties']
-) {
- window.op('event', name, data);
+export function useOpenPanel() {
+ return {
+ track,
+ screenView,
+ identify,
+ increment,
+ decrement,
+ clear,
+ };
}
-export function trackScreenView(data?: PostEventPayload['properties']) {
- trackEvent('screen_view', data);
+function track(name: string, properties?: TrackProperties) {
+ window.op('track', name, properties);
}
-export function setProfile(data?: UpdateProfilePayload) {
- window.op('setProfile', data);
+function screenView(properties: TrackProperties) {
+ track('screen_view', properties);
}
-export function setProfileId(profileId: string) {
- window.op('setProfileId', profileId);
+function identify(payload: IdentifyPayload) {
+ window.op('identify', payload);
}
-export function increment(
- property: string,
- value: number,
- options?: OpenpanelEventOptions
-) {
- window.op('increment', property, value, options);
+function increment(payload: IncrementPayload) {
+ window.op('increment', payload);
}
-export function decrement(
- property: string,
- value: number,
- options?: OpenpanelEventOptions
-) {
- window.op('decrement', property, value, options);
+function decrement(payload: DecrementPayload) {
+ window.op('decrement', payload);
}
-export function clear() {
+function clear() {
window.op('clear');
}
diff --git a/packages/sdks/react-native/index.ts b/packages/sdks/react-native/index.ts
index 604a48730..e45d51d5d 100644
--- a/packages/sdks/react-native/index.ts
+++ b/packages/sdks/react-native/index.ts
@@ -2,28 +2,31 @@ import { AppState, Platform } from 'react-native';
import * as Application from 'expo-application';
import Constants from 'expo-constants';
-import type { OpenpanelSdkOptions, PostEventPayload } from '@openpanel/sdk';
-import { OpenpanelSdk } from '@openpanel/sdk';
+import type { OpenPanelOptions, TrackProperties } from '@openpanel/sdk';
+import { OpenPanel as OpenPanelBase } from '@openpanel/sdk';
export * from '@openpanel/sdk';
-export type OpenpanelOptions = OpenpanelSdkOptions;
-export class Openpanel extends OpenpanelSdk<OpenpanelOptions> {
- constructor(options: OpenpanelOptions) {
- super(options);
+export class OpenPanel extends OpenPanelBase {
+ constructor(public options: OpenPanelOptions) {
+ super({
+ ...options,
+ sdk: 'react-native',
+ sdkVersion: process.env.REACT_NATIVE_VERSION!,
+ });
- this.api.headers['User-Agent'] = Constants.getWebViewUserAgentAsync();
+ this.api.addHeader('User-Agent', Constants.getWebViewUserAgentAsync());
AppState.addEventListener('change', (state) => {
if (state === 'active') {
- this.setProperties();
+ this.setDefaultProperties();
}
});
- this.setProperties();
+ this.setDefaultProperties();
}
- private async setProperties() {
+ private async setDefaultProperties() {
this.setGlobalProperties({
__version: Application.nativeApplicationVersion,
__buildNumber: Application.nativeBuildVersion,
@@ -34,11 +37,8 @@ export class Openpanel extends OpenpanelSdk<OpenpanelOptions> {
});
}
- public screenView(
- route: string,
- properties?: PostEventPayload['properties']
- ): void {
- super.event('screen_view', {
+ public screenView(route: string, properties?: TrackProperties): void {
+ super.track('screen_view', {
...properties,
__path: route,
});
diff --git a/packages/sdks/react-native/package.json b/packages/sdks/react-native/package.json
index 751ee057e..00985f6ff 100644
--- a/packages/sdks/react-native/package.json
+++ b/packages/sdks/react-native/package.json
@@ -15,15 +15,16 @@
"@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",
"typescript": "^5.2.2"
},
"peerDependencies": {
- "react-native": "0.73 - 0.74",
"expo-application": "^5",
- "expo-constants": "14 - 16"
+ "expo-constants": "14 - 16",
+ "react-native": "0.73 - 0.74"
},
"eslintConfig": {
"root": true,
diff --git a/packages/sdks/react-native/tsup.config.ts b/packages/sdks/react-native/tsup.config.ts
index 76b96e47b..16a91b68d 100644
--- a/packages/sdks/react-native/tsup.config.ts
+++ b/packages/sdks/react-native/tsup.config.ts
@@ -2,4 +2,6 @@ import { defineConfig } from 'tsup';
import config from '@openpanel/tsconfig/tsup.config.json' assert { type: 'json' };
-export default defineConfig(config as any);
+export default defineConfig({
+ ...(config as any),
+});
diff --git a/packages/sdks/sdk/index.ts b/packages/sdks/sdk/index.ts
index 77a7b3413..7e5b7f5b7 100644
--- a/packages/sdks/sdk/index.ts
+++ b/packages/sdks/sdk/index.ts
@@ -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();
- }
-}
diff --git a/packages/sdks/sdk/package.json b/packages/sdks/sdk/package.json
index 694443e27..37a175c57 100644
--- a/packages/sdks/sdk/package.json
+++ b/packages/sdks/sdk/package.json
@@ -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",
diff --git a/packages/sdks/sdk/src/api.ts b/packages/sdks/sdk/src/api.ts
new file mode 100644
index 000000000..53e936d69
--- /dev/null
+++ b/packages/sdks/sdk/src/api.ts
@@ -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);
+ }
+}
diff --git a/packages/sdks/sdk/src/index.ts b/packages/sdks/sdk/src/index.ts
new file mode 100644
index 000000000..4aa07eb85
--- /dev/null
+++ b/packages/sdks/sdk/src/index.ts
@@ -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 = [];
+ }
+}
diff --git a/packages/sdks/web/index.ts b/packages/sdks/web/index.ts
index 07feeb9a0..4e0f49a6b 100644
--- a/packages/sdks/web/index.ts
+++ b/packages/sdks/web/index.ts
@@ -1,165 +1,2 @@
-/* eslint-disable @typescript-eslint/unbound-method */
-
-import type { OpenpanelSdkOptions, PostEventPayload } from '@openpanel/sdk';
-import { OpenpanelSdk } from '@openpanel/sdk';
-
-export * from '@openpanel/sdk';
-
-export type OpenpanelOptions = OpenpanelSdkOptions & {
- 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 Openpanel extends OpenpanelSdk<OpenpanelOptions> {
- private lastPath = '';
- private debounceTimer: any;
-
- constructor(options: OpenpanelOptions) {
- 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 debounce(func: () => void, delay: number) {
- clearTimeout(this.debounceTimer);
- this.debounceTimer = setTimeout(func, delay);
- }
-
- 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', function () {
- window.dispatchEvent(new Event('locationchange'));
- });
-
- const eventHandler = () => this.debounce(() => this.screenView(), 50);
-
- if (this.options.hash) {
- window.addEventListener('hashchange', eventHandler);
- } else {
- window.addEventListener('locationchange', eventHandler);
- }
-
- // give time for setProfile to be called
- setTimeout(() => eventHandler(), 50);
- }
-
- public trackAttributes() {
- if (this.isServer()) {
- return;
- }
-
- document.addEventListener('click', (event) => {
- const target = event.target as HTMLElement;
- const btn = target.closest('button');
- const anchor = target.closest('a');
- const element = btn?.getAttribute('data-event')
- ? btn
- : anchor?.getAttribute('data-event')
- ? anchor
- : 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,
- });
- }
-}
+export * from './src/index';
+export * from './src/types.d';
diff --git a/packages/sdks/web/package.json b/packages/sdks/web/package.json
index ac166f930..57eb8d64f 100644
--- a/packages/sdks/web/package.json
+++ b/packages/sdks/web/package.json
@@ -4,7 +4,7 @@
"module": "index.ts",
"scripts": {
"build": "rm -rf dist && tsup",
- "build-for-openpanel": "pnpm build && cp dist/cdn.global.js ../../../apps/public/public/op.js",
+ "build-for-openpanel": "pnpm build && cp dist/src/tracker.global.js ../../../apps/public/public/tracker.js",
"lint": "eslint .",
"format": "prettier --check \"**/*.{mjs,ts,md,json}\"",
"typecheck": "tsc --noEmit"
@@ -16,6 +16,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",
diff --git a/packages/sdks/web/src/index.ts b/packages/sdks/web/src/index.ts
new file mode 100644
index 000000000..7bec688d9
--- /dev/null
+++ b/packages/sdks/web/src/index.ts
@@ -0,0 +1,185 @@
+/* eslint-disable @typescript-eslint/unbound-method */
+
+import type {
+ OpenPanelOptions as OpenPanelBaseOptions,
+ TrackProperties,
+} from '@openpanel/sdk';
+import { OpenPanel as OpenPanelBase } from '@openpanel/sdk';
+
+export * from '@openpanel/sdk';
+
+export type OpenPanelOptions = OpenPanelBaseOptions & {
+ trackOutgoingLinks?: boolean;
+ trackScreenViews?: boolean;
+ trackAttributes?: boolean;
+ trackHashChanges?: boolean;
+};
+
+function toCamelCase(str: string) {
+ return str.replace(/([-_][a-z])/gi, ($1) =>
+ $1.toUpperCase().replace('-', '').replace('_', '')
+ );
+}
+
+export class OpenPanel extends OpenPanelBase {
+ private lastPath = '';
+ private debounceTimer: any;
+
+ constructor(public options: OpenPanelOptions) {
+ super({
+ ...options,
+ sdk: 'web',
+ sdkVersion: process.env.WEB_VERSION!,
+ });
+
+ if (!this.isServer()) {
+ this.setGlobalProperties({
+ __referrer: document.referrer,
+ });
+
+ if (this.options.trackScreenViews) {
+ this.trackScreenViews();
+ }
+
+ if (this.options.trackOutgoingLinks) {
+ this.trackOutgoingLinks();
+ }
+
+ if (this.options.trackAttributes) {
+ this.trackAttributes();
+ }
+ }
+ }
+
+ private debounce(func: () => void, delay: number) {
+ clearTimeout(this.debounceTimer);
+ this.debounceTimer = setTimeout(func, delay);
+ }
+
+ 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.track('link_out', {
+ href,
+ text:
+ link.innerText ||
+ link.getAttribute('title') ||
+ target.getAttribute('alt') ||
+ target.getAttribute('title'),
+ });
+ }
+ }
+ });
+ }
+
+ public trackScreenViews() {
+ if (this.isServer()) {
+ return;
+ }
+
+ this.screenView();
+
+ 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', function () {
+ window.dispatchEvent(new Event('locationchange'));
+ });
+
+ const eventHandler = () => this.debounce(() => this.screenView(), 50);
+
+ if (this.options.trackHashChanges) {
+ window.addEventListener('hashchange', eventHandler);
+ } else {
+ window.addEventListener('locationchange', eventHandler);
+ }
+ }
+
+ public trackAttributes() {
+ if (this.isServer()) {
+ return;
+ }
+
+ document.addEventListener('click', (event) => {
+ const target = event.target as HTMLElement;
+ const btn = target.closest('button');
+ const anchor = target.closest('a');
+ const element = btn?.getAttribute('data-event')
+ ? btn
+ : anchor?.getAttribute('data-event')
+ ? anchor
+ : 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.track(name, properties);
+ }
+ }
+ });
+ }
+
+ screenView(properties?: TrackProperties): void;
+ screenView(path: string, properties?: TrackProperties): void;
+ screenView(
+ pathOrProperties?: string | TrackProperties,
+ propertiesOrUndefined?: TrackProperties
+ ): void {
+ if (this.isServer()) {
+ return;
+ }
+
+ let path: string;
+ let properties: TrackProperties | undefined;
+
+ if (typeof pathOrProperties === 'string') {
+ path = pathOrProperties;
+ properties = propertiesOrUndefined;
+ } else {
+ path = window.location.href;
+ properties = pathOrProperties;
+ }
+
+ if (this.lastPath === path) {
+ return;
+ }
+
+ this.lastPath = path;
+ super.track('screen_view', {
+ ...(properties ?? {}),
+ __path: path,
+ __title: document.title,
+ });
+ }
+}
diff --git a/packages/sdks/web/cdn.ts b/packages/sdks/web/src/tracker.ts
similarity index 61%
rename from packages/sdks/web/cdn.ts
rename to packages/sdks/web/src/tracker.ts
index 9e606004d..27d7df0a7 100644
--- a/packages/sdks/web/cdn.ts
+++ b/packages/sdks/web/src/tracker.ts
@@ -1,20 +1,10 @@
-/* eslint-disable @typescript-eslint/no-unsafe-call */
-
-import { Openpanel } from './index';
-
-declare global {
- interface Window {
- op: {
- q?: [string, ...any[]];
- (method: string, ...args: any[]): void;
- };
- }
-}
+import { OpenPanel } from './index';
((window) => {
if (window.op && 'q' in window.op) {
const queue = window.op.q || [];
- const op = new Openpanel(queue.shift()[1]);
+ // @ts-expect-error
+ const op = new OpenPanel(queue.shift()[1]);
queue.forEach((item) => {
if (item[0] in op) {
// @ts-expect-error
@@ -23,13 +13,15 @@ declare global {
});
window.op = (t, ...args) => {
- // @ts-expect-error
const fn = op[t] ? op[t].bind(op) : undefined;
if (typeof fn === 'function') {
+ // @ts-expect-error
fn(...args);
} else {
console.warn(`op.js: ${t} is not a function`);
}
};
+
+ window.openpanel = op;
}
})(window);
diff --git a/packages/sdks/web/src/types.d.ts b/packages/sdks/web/src/types.d.ts
new file mode 100644
index 000000000..68b003aaf
--- /dev/null
+++ b/packages/sdks/web/src/types.d.ts
@@ -0,0 +1,29 @@
+import type { OpenPanel, OpenPanelOptions } from './';
+
+type ExposedMethodsNames =
+ | 'screenView'
+ | 'track'
+ | 'identify'
+ | 'alias'
+ | 'increment'
+ | 'decrement'
+ | 'clear';
+
+export type ExposedMethods = {
+ [K in ExposedMethodsNames]: OpenPanel[K] extends (...args: any[]) => any
+ ? [K, ...Parameters<OpenPanel[K]>]
+ : never;
+}[ExposedMethodsNames];
+
+export type OpenPanelMethodNames = ExposedMethodsNames | 'init';
+export type OpenPanelMethods = ExposedMethods | ['init', OpenPanelOptions];
+
+declare global {
+ interface Window {
+ openpanel?: OpenPanel;
+ op: {
+ q?: OpenPanelMethods[];
+ (...args: OpenPanelMethods): void;
+ };
+ }
+}
diff --git a/packages/sdks/web/tsup.config.ts b/packages/sdks/web/tsup.config.ts
index f27e56176..dc618f175 100644
--- a/packages/sdks/web/tsup.config.ts
+++ b/packages/sdks/web/tsup.config.ts
@@ -4,6 +4,6 @@ import config from '@openpanel/tsconfig/tsup.config.json' assert { type: 'json'
export default defineConfig({
...(config as any),
- entry: ['index.ts', 'cdn.ts'],
+ entry: ['index.ts', 'src/tracker.ts'],
format: ['cjs', 'esm', 'iife'],
});
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index 26a1871f8..f2dd5a67e 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -1269,6 +1269,9 @@ importers:
'@openpanel/tsconfig':
specifier: workspace:*
version: link:../../../tooling/typescript
+ '@types/node':
+ specifier: ^20.14.12
+ version: 20.14.12
eslint:
specifier: ^8.48.0
version: 8.56.0
@@ -1293,6 +1296,9 @@ importers:
'@openpanel/tsconfig':
specifier: workspace:*
version: link:../../../tooling/typescript
+ '@types/node':
+ specifier: ^20.14.12
+ version: 20.14.12
eslint:
specifier: ^8.48.0
version: 8.56.0
@@ -1321,6 +1327,9 @@ importers:
'@openpanel/tsconfig':
specifier: workspace:*
version: link:../../../tooling/typescript
+ '@types/node':
+ specifier: ^20.14.12
+ version: 20.14.12
eslint:
specifier: ^8.48.0
version: 8.56.0
@@ -4372,7 +4381,7 @@ packages:
dependencies:
'@jest/fake-timers': 29.7.0
'@jest/types': 29.6.3
- '@types/node': 18.19.17
+ '@types/node': 20.14.12
jest-mock: 29.7.0
dev: false
@@ -4382,7 +4391,7 @@ packages:
dependencies:
'@jest/types': 29.6.3
'@sinonjs/fake-timers': 10.3.0
- '@types/node': 18.19.17
+ '@types/node': 20.14.12
jest-message-util: 29.7.0
jest-mock: 29.7.0
jest-util: 29.7.0
@@ -4401,7 +4410,7 @@ packages:
dependencies:
'@types/istanbul-lib-coverage': 2.0.6
'@types/istanbul-reports': 3.0.4
- '@types/node': 18.19.17
+ '@types/node': 20.14.12
'@types/yargs': 15.0.19
chalk: 4.1.2
dev: false
@@ -4413,7 +4422,7 @@ packages:
'@jest/schemas': 29.6.3
'@types/istanbul-lib-coverage': 2.0.6
'@types/istanbul-reports': 3.0.4
- '@types/node': 18.19.17
+ '@types/node': 20.14.12
'@types/yargs': 17.0.32
chalk: 4.1.2
dev: false
@@ -7282,20 +7291,20 @@ packages:
resolution: {integrity: sha512-6atioO8Y75fNcbmj0G7UjI9lXN2pQ/IGJ2FWT4a/btd0Lk9lQalHLKhkgKVZ3r+spnmWUKfbMi1GEe9wyHQfNQ==}
dependencies:
- '@types/node': 18.19.17
+ '@types/node': 20.14.12
dev: true
resolution: {integrity: sha512-fB3Zu92ucau0iQ0JMCFQE7b/dv8Ot07NI3KaZIkIUNXq82k4eBAqUaneXfleGY9JWskeS9y+u0nXMyspcuQrCg==}
dependencies:
'@types/connect': 3.4.38
- '@types/node': 18.19.17
+ '@types/node': 20.14.12
dev: true
resolution: {integrity: sha512-K6uROf1LD88uDQqJCktA4yzL1YYAK6NgfsI0v/mTgyPKWsX1CnJ0XPSDhViejru1GcRkLWb8RlzFYJRqGUbaug==}
dependencies:
- '@types/node': 18.19.17
+ '@types/node': 20.14.12
dev: true
@@ -7528,7 +7537,7 @@ packages:
resolution: {integrity: sha512-oaYtiBirUOPQGSWNGPWnzyAFJ0BP3cwvN4oWZQY+zUBwpVIGsKUkpBpSztp74drYcjavs7SKFZ4DX1V2QeN8rg==}
dependencies:
- '@types/node': 18.19.17
+ '@types/node': 20.14.12
'@types/qs': 6.9.11
'@types/range-parser': 1.2.7
'@types/send': 0.17.4
@@ -7599,7 +7608,7 @@ packages:
resolution: {integrity: sha512-/5hndP5dCjloafCXns6SZyESp3Ldq7YjH3zwzwczYnjxIT0Fqzk5ROSYVGfFyczIue7IUEj8hkvLbPoLQ18vQw==}
dependencies:
- '@types/node': 18.19.17
+ '@types/node': 20.14.12
dev: true
@@ -7654,6 +7663,7 @@ packages:
resolution: {integrity: sha512-SzyGKgwPzuWp2SHhlpXKzCX0pIOfcI4V2eF37nNBJOhwlegQ83omtVQ1XxZpDE06V/d6AQvfQdPfnw0tRC//Ng==}
dependencies:
undici-types: 5.26.5
+ dev: true
resolution: {integrity: sha512-kprQpL8MMeszbz6ojB5/tU8PLN4kesnN8Gjzw349rDlNgsSzg90lAVj3llK99Dh7JON+t9AuscPPFW6mPbTnSA==}
@@ -7661,6 +7671,11 @@ packages:
undici-types: 5.26.5
dev: true
+ resolution: {integrity: sha512-r7wNXakLeSsGT0H1AU863vS2wa5wBOK4bWMjZz2wj+8nBx+m5PeIn0k8AloSLpRuiwdRQZwarZqHE4FNArPuJQ==}
+ dependencies:
+ undici-types: 5.26.5
+
resolution: {integrity: sha512-k7kRA033QNtC+gLc4VPlfnue58CM1iQLgn1IMAU8VPHGOj7oIHPp9UlhedEnD/Gl8evoCjwkZjlBORtZ3JByUA==}
dev: false
@@ -7668,7 +7683,7 @@ packages:
resolution: {integrity: sha512-iadjw02vte8qWx7U0YM++EybBha2CQLPGu9iJ97whVgJUT5Zq9MjAPYUnbfRI2Kpehimf1QjFJYxD0t8nqzu5w==}
dependencies:
- '@types/node': 18.19.17
+ '@types/node': 20.14.12
dev: true
@@ -7724,7 +7739,7 @@ packages:
resolution: {integrity: sha512-Qzz0PM2nSZej4lsLzzNfADIORZhhxO7PED0fXpg4FjXiHuJ/lMyUg+YFF5q8x9HPZH3Gl6N+NOM8QZjItNgGKg==}
dependencies:
- '@types/node': 18.19.17
+ '@types/node': 20.14.12
dev: true
@@ -7737,7 +7752,7 @@ packages:
resolution: {integrity: sha512-x2EM6TJOybec7c52BX0ZspPodMsQUd5L6PRwOunVyVUhXiBSKf3AezDL8Dgvgt5o0UfKNfuA0eMLr2wLT4AiBA==}
dependencies:
'@types/mime': 1.3.5
- '@types/node': 18.19.17
+ '@types/node': 20.14.12
dev: true
@@ -7745,7 +7760,7 @@ packages:
dependencies:
'@types/http-errors': 2.0.4
'@types/mime': 3.0.4
- '@types/node': 18.19.17
+ '@types/node': 20.14.12
dev: true
@@ -7783,7 +7798,7 @@ packages:
resolution: {integrity: sha512-vmQSUcfalpIq0R9q7uTo2lXs6eGIpt9wtnLdMv9LVpIjCA/+ufZRozlVoVelIYixx1ugCBKDhn89vnsEGOCx9A==}
dependencies:
- '@types/node': 18.19.17
+ '@types/node': 20.14.12
dev: true
@@ -8996,7 +9011,7 @@ packages:
engines: {node: '>=12.13.0'}
hasBin: true
dependencies:
- '@types/node': 18.19.17
+ '@types/node': 20.14.12
escape-string-regexp: 4.0.0
is-wsl: 2.2.0
lighthouse-logger: 1.4.2
@@ -9007,7 +9022,7 @@ packages:
resolution: {integrity: sha512-pgtgjNKZ7i5U++1g1PWv75umkHvhVTDOQIZ+sjeUX9483S7Y6MUvO0lrd7ShGlQlFHMN4SwKTCq/X8hWrbv2KA==}
dependencies:
- '@types/node': 18.19.17
+ '@types/node': 20.14.12
escape-string-regexp: 4.0.0
is-wsl: 2.2.0
lighthouse-logger: 1.4.2
@@ -12824,7 +12839,7 @@ packages:
'@jest/environment': 29.7.0
'@jest/fake-timers': 29.7.0
'@jest/types': 29.6.3
- '@types/node': 18.19.17
+ '@types/node': 20.14.12
jest-mock: 29.7.0
jest-util: 29.7.0
dev: false
@@ -12854,7 +12869,7 @@ packages:
engines: {node: ^14.15.0 || ^16.10.0 || >=18.0.0}
dependencies:
'@jest/types': 29.6.3
- '@types/node': 18.19.17
+ '@types/node': 20.14.12
jest-util: 29.7.0
dev: false
@@ -12863,7 +12878,7 @@ packages:
engines: {node: ^14.15.0 || ^16.10.0 || >=18.0.0}
dependencies:
'@jest/types': 29.6.3
- '@types/node': 18.19.17
+ '@types/node': 20.14.12
chalk: 4.1.2
ci-info: 3.9.0
graceful-fs: 4.2.11
@@ -12886,7 +12901,7 @@ packages:
resolution: {integrity: sha512-eIz2msL/EzL9UFTFFx7jBTkeZfku0yUAyZZZmJ93H2TYEiroIx2PQjEXcwYtYl8zXCxb+PAmA2hLIt/6ZEkPHw==}
engines: {node: ^14.15.0 || ^16.10.0 || >=18.0.0}
dependencies:
- '@types/node': 18.19.17
+ '@types/node': 20.14.12
jest-util: 29.7.0
merge-stream: 2.0.0
supports-color: 8.1.1
@@ -15903,7 +15918,7 @@ packages:
'@protobufjs/path': 1.1.2
'@protobufjs/pool': 1.1.0
'@protobufjs/utf8': 1.1.0
- '@types/node': 18.19.17
+ '@types/node': 20.14.12
long: 5.2.3
dev: false
diff --git a/tooling/publish/publish.ts b/tooling/publish/publish.ts
index 6e7c4c2eb..977e8f5f0 100644
--- a/tooling/publish/publish.ts
+++ b/tooling/publish/publish.ts
@@ -153,7 +153,7 @@ function main() {
require: './dist/index.cjs',
},
version: nextVersion,
- dependencies: Object.entries(restPkgJson.dependencies).reduce(
+ dependencies: Object.entries(restPkgJson.dependencies || {}).reduce(
(acc, [depName, depVersion]) => {
const dep = packages[depName];
if (!dep) {
@@ -187,9 +187,21 @@ function main() {
updatePackageJsonForRelease(dependent);
});
+ const versionEnvs = dependents.map((dependent) => {
+ const { nextVersion } = packages[dependent]!;
+ const env = dependent
+ .replace(/@openpanel\//g, '')
+ .toUpperCase()
+ .replace(/\//g, '_')
+ .replace('-', '_');
+ return `--env.${env}_VERSION=${nextVersion}`;
+ });
+
+ console.log('versionEnvs', versionEnvs);
+
dependents.forEach((dependent) => {
console.log(`🔨 Building ${dependent}`);
- execSync('pnpm build', {
+ execSync(`pnpm build ${versionEnvs.join(' ')}`, {
cwd: workspacePath(packages[dependent]!.localPath),
});
});
@@ -202,14 +214,14 @@ function main() {
cwd: workspacePath(packages[dependent]!.localPath),
});
});
- }
- // Restoring package.json
- const filesToRestore = dependents
- .map((dependent) => workspacePath(packages[dependent]!.localPath))
- .join(' ');
+ // Restoring package.json
+ const filesToRestore = dependents
+ .map((dependent) => workspacePath(packages[dependent]!.localPath))
+ .join(' ');
- execSync(`git checkout ${filesToRestore}`);
+ execSync(`git checkout ${filesToRestore}`);
+ }
// // Save new versions only 😈
dependents.forEach((dependent) => {