web & sdk: improved sdk (better failover and batching)

This commit is contained in:
Carl-Gerhard Lindesvärd
2024-01-12 11:31:46 +01:00
parent 8e7558790e
commit 5b5ad23f66
26 changed files with 1266 additions and 377 deletions

1
.gitignore vendored
View File

@@ -1,6 +1,7 @@
# Based on https://raw.githubusercontent.com/github/gitignore/main/Node.gitignore # Based on https://raw.githubusercontent.com/github/gitignore/main/Node.gitignore
packages/sdk/profileId.txt packages/sdk/profileId.txt
packages/sdk/test.ts packages/sdk/test.ts
dump.sql
# Logs # Logs

View File

@@ -3,10 +3,11 @@ import { mixan } from '@/analytics';
import type { AppProps } from 'next/app'; import type { AppProps } from 'next/app';
import { useRouter } from 'next/router'; import { useRouter } from 'next/router';
mixan.init();
export default function MyApp({ Component, pageProps }: AppProps) { export default function MyApp({ Component, pageProps }: AppProps) {
const router = useRouter(); const router = useRouter();
useEffect(() => { useEffect(() => {
mixan.init();
return router.events.on('routeChangeComplete', () => { return router.events.on('routeChangeComplete', () => {
mixan.screenView(); mixan.screenView();
}); });

View File

@@ -1,9 +1,53 @@
import { mixan } from '@/analytics';
import Link from 'next/link'; import Link from 'next/link';
export default function Test() { export default function Test() {
return ( return (
<div> <div>
<Link href="/">Home</Link> <Link href="/">Home</Link>
<button
onClick={() => {
mixan.setUser({
first_name: 'John',
});
mixan.setUser({
last_name: 'Doe',
});
mixan.setUser({
email: 'john.doe@gmail.com',
});
mixan.setUser({
id: '1234',
});
}}
>
Set user
</button>
<button
onClick={() => {
localStorage.clear();
window.location.reload();
}}
>
Clear storage and reload
</button>
<button
onClick={() => {
mixan.event('custom_click', {
custom_string: 'test',
custom_number: 1,
});
}}
>
Trigger event
</button>
<button
onClick={() => {
mixan.clear();
}}
>
Logout
</button>
</div> </div>
); );
} }

View File

@@ -0,0 +1,3 @@
-- AlterTable
ALTER TABLE "clients" ADD COLUMN "cors" TEXT NOT NULL DEFAULT '*',
ALTER COLUMN "secret" DROP NOT NULL;

View File

@@ -0,0 +1,9 @@
-- CreateTable
CREATE TABLE "event_failed" (
"id" UUID NOT NULL DEFAULT gen_random_uuid(),
"data" JSONB NOT NULL,
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
"updatedAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
CONSTRAINT "event_failed_pkey" PRIMARY KEY ("id")
);

View File

@@ -90,14 +90,24 @@ model Profile {
@@map("profiles") @@map("profiles")
} }
model EventFailed {
id String @id @default(dbgenerated("gen_random_uuid()")) @db.Uuid
data Json
createdAt DateTime @default(now())
updatedAt DateTime @default(now()) @updatedAt
@@map("event_failed")
}
model Client { model Client {
id String @id @default(dbgenerated("gen_random_uuid()")) @db.Uuid id String @id @default(dbgenerated("gen_random_uuid()")) @db.Uuid
name String name String
secret String secret String?
project_id String @db.Uuid project_id String @db.Uuid
project Project @relation(fields: [project_id], references: [id]) project Project @relation(fields: [project_id], references: [id])
organization_id String @db.Uuid organization_id String @db.Uuid
organization Organization @relation(fields: [organization_id], references: [id]) organization Organization @relation(fields: [organization_id], references: [id])
cors String @default("*")
createdAt DateTime @default(now()) createdAt DateTime @default(now())
updatedAt DateTime @default(now()) @updatedAt updatedAt DateTime @default(now()) @updatedAt

View File

@@ -9,5 +9,9 @@ interface SyntaxProps {
} }
export default function Syntax({ code }: SyntaxProps) { export default function Syntax({ code }: SyntaxProps) {
return <SyntaxHighlighter style={docco}>{code}</SyntaxHighlighter>; return (
<SyntaxHighlighter wrapLongLines style={docco}>
{code}
</SyntaxHighlighter>
);
} }

View File

@@ -23,17 +23,26 @@ export const columns: ColumnDef<IClientWithProject>[] = [
accessorKey: 'id', accessorKey: 'id',
header: 'Client ID', header: 'Client ID',
}, },
{
accessorKey: 'cors',
header: 'Cors',
},
{ {
accessorKey: 'secret', accessorKey: 'secret',
header: 'Secret', header: 'Secret',
cell: () => <div className="italic text-muted-foreground">Hidden</div>, cell: (info) =>
info.getValue() ? (
<div className="italic text-muted-foreground">Hidden</div>
) : (
'None'
),
}, },
{ {
accessorKey: 'createdAt', accessorKey: 'createdAt',
header: 'Created at', header: 'Created at',
cell({ row }) { cell({ row }) {
const date = row.original.createdAt; const date = row.original.createdAt;
return <div>{formatDate(date)}</div>; return formatDate(date);
}, },
}, },
{ {

View File

@@ -9,9 +9,9 @@ type InputWithLabelProps = InputProps & {
}; };
export const InputWithLabel = forwardRef<HTMLInputElement, InputWithLabelProps>( export const InputWithLabel = forwardRef<HTMLInputElement, InputWithLabelProps>(
({ label, ...props }, ref) => { ({ label, className, ...props }, ref) => {
return ( return (
<div> <div className={className}>
<Label htmlFor={label} className="block mb-2"> <Label htmlFor={label} className="block mb-2">
{label} {label}
</Label> </Label>

View File

@@ -1,8 +1,10 @@
import { ButtonContainer } from '@/components/ButtonContainer'; import { ButtonContainer } from '@/components/ButtonContainer';
import { InputWithLabel } from '@/components/forms/InputWithLabel'; import { InputWithLabel } from '@/components/forms/InputWithLabel';
import { Button } from '@/components/ui/button'; import { Button } from '@/components/ui/button';
import { Checkbox } from '@/components/ui/checkbox';
import { Combobox } from '@/components/ui/combobox'; import { Combobox } from '@/components/ui/combobox';
import { Label } from '@/components/ui/label'; import { Label } from '@/components/ui/label';
import { RadioGroup, RadioGroupItem } from '@/components/ui/radio-group';
import { toast } from '@/components/ui/use-toast'; import { toast } from '@/components/ui/use-toast';
import { useOrganizationParams } from '@/hooks/useOrganizationParams'; import { useOrganizationParams } from '@/hooks/useOrganizationParams';
import { useRefetchActive } from '@/hooks/useRefetchActive'; import { useRefetchActive } from '@/hooks/useRefetchActive';
@@ -11,7 +13,7 @@ import { clipboard } from '@/utils/clipboard';
import { zodResolver } from '@hookform/resolvers/zod'; import { zodResolver } from '@hookform/resolvers/zod';
import { Copy } from 'lucide-react'; import { Copy } from 'lucide-react';
import dynamic from 'next/dynamic'; import dynamic from 'next/dynamic';
import { Controller, useForm } from 'react-hook-form'; import { Controller, useForm, useWatch } from 'react-hook-form';
import { z } from 'zod'; import { z } from 'zod';
import { popModal } from '.'; import { popModal } from '.';
@@ -21,6 +23,8 @@ const Syntax = dynamic(import('@/components/Syntax'));
const validator = z.object({ const validator = z.object({
name: z.string().min(1, 'Required'), name: z.string().min(1, 'Required'),
cors: z.string().min(1, 'Required'),
withCors: z.boolean(),
projectId: z.string().min(1, 'Required'), projectId: z.string().min(1, 'Required'),
}); });
@@ -46,12 +50,29 @@ export default function CreateProject() {
resolver: zodResolver(validator), resolver: zodResolver(validator),
defaultValues: { defaultValues: {
name: '', name: '',
cors: '*',
projectId: '', projectId: '',
withCors: true,
}, },
}); });
const withCors = useWatch({
control,
name: 'withCors',
});
if (mutation.isSuccess && mutation.data) { if (mutation.isSuccess && mutation.data) {
const { clientId, clientSecret } = mutation.data; const { clientId, clientSecret, cors } = mutation.data;
const snippet = clientSecret
? `const mixan = new Mixan({
clientId: "${clientId}",
// Avoid using this on web, rely on cors settings instead
// Mostly for react-native and node/backend
clientSecret: "${clientSecret}",
})`
: `const mixan = new Mixan({
clientId: "${clientId}",
})`;
return ( return (
<ModalContent> <ModalContent>
<ModalHeader title="Client created 🚀" /> <ModalHeader title="Client created 🚀" />
@@ -60,6 +81,13 @@ export default function CreateProject() {
so keep it safe 🫣 so keep it safe 🫣
</p> </p>
<button className="mt-4 text-left" onClick={() => clipboard(cors)}>
<Label>Cors settings</Label>
<div className="flex items-center justify-between rounded bg-gray-100 p-2 px-3">
{cors}
<Copy size={16} />
</div>
</button>
<button className="mt-4 text-left" onClick={() => clipboard(clientId)}> <button className="mt-4 text-left" onClick={() => clipboard(clientId)}>
<Label>Client ID</Label> <Label>Client ID</Label>
<div className="flex items-center justify-between rounded bg-gray-100 p-2 px-3"> <div className="flex items-center justify-between rounded bg-gray-100 p-2 px-3">
@@ -67,25 +95,22 @@ export default function CreateProject() {
<Copy size={16} /> <Copy size={16} />
</div> </div>
</button> </button>
<button {clientSecret && (
className="mt-4 text-left" <button
onClick={() => clipboard(clientSecret)} className="mt-4 text-left"
> onClick={() => clipboard(clientSecret)}
<Label>Client Secret</Label> >
<div className="flex items-center justify-between rounded bg-gray-100 p-2 px-3"> <Label>Client Secret</Label>
{clientSecret} <div className="flex items-center justify-between rounded bg-gray-100 p-2 px-3">
<Copy size={16} /> {clientSecret}
</div> <Copy size={16} />
</button> </div>
</button>
)}
<div className="mt-4"> <div className="mt-4">
<Label>Code snippet</Label> <Label>Code snippet</Label>
<div className="overflow-x-auto [&_pre]:!rounded [&_pre]:!bg-gray-100 [&_pre]:text-sm"> <div className="[&_pre]:!rounded [&_pre]:!bg-gray-100 [&_pre]:text-sm">
<Syntax <Syntax code={snippet} />
code={`const mixan = new Mixan({
clientId: "${clientId}",
clientSecret: "${clientSecret}",
})`}
/>
</div> </div>
</div> </div>
@@ -114,6 +139,36 @@ export default function CreateProject() {
{...register('name')} {...register('name')}
className="mb-4" className="mb-4"
/> />
<Controller
name="withCors"
control={control}
render={({ field }) => (
<label className="flex items-center gap-2 text-sm font-medium leading-none mb-4">
<Checkbox
ref={field.ref}
onBlur={field.onBlur}
defaultChecked={field.value}
onCheckedChange={(checked) => {
field.onChange(checked);
}}
/>
Auth with cors settings
</label>
)}
/>
{withCors && (
<>
<InputWithLabel
label="Cors"
placeholder="Cors"
{...register('cors')}
/>
<div className="text-xs text-muted-foreground mb-4 mt-1">
Restrict access by domain names (include https://)
</div>
</>
)}
<Controller <Controller
control={control} control={control}
name="projectId" name="projectId"

View File

@@ -19,6 +19,7 @@ interface EditClientProps {
const validator = z.object({ const validator = z.object({
id: z.string().min(1), id: z.string().min(1),
name: z.string().min(1), name: z.string().min(1),
cors: z.string().min(1),
}); });
type IForm = z.infer<typeof validator>; type IForm = z.infer<typeof validator>;
@@ -43,6 +44,7 @@ export default function EditClient({ id }: EditClientProps) {
defaultValues: { defaultValues: {
id: '', id: '',
name: '', name: '',
cors: '',
}, },
}); });
@@ -60,7 +62,18 @@ export default function EditClient({ id }: EditClientProps) {
mutation.mutate(values); mutation.mutate(values);
})} })}
> >
<InputWithLabel label="Name" placeholder="Name" {...register('name')} /> <div className="flex flex-col gap-4">
<InputWithLabel
label="Name"
placeholder="Name"
{...register('name')}
/>
<InputWithLabel
label="Cors"
placeholder="Cors"
{...register('cors')}
/>
</div>
<ButtonContainer> <ButtonContainer>
<Button type="button" variant="outline" onClick={() => popModal()}> <Button type="button" variant="outline" onClick={() => popModal()}>
Cancel Cancel

View File

@@ -0,0 +1,238 @@
import { validateSdkRequest } from '@/server/auth';
import { db } from '@/server/db';
import { createError, handleError } from '@/server/exceptions';
import { tickProfileProperty } from '@/server/services/profile.service';
import { Prisma } from '@prisma/client';
import type { NextApiRequest, NextApiResponse } from 'next';
import { mergeDeepRight } from 'ramda';
import type { BatchPayload } from '@mixan/types';
interface Request extends NextApiRequest {
body: BatchPayload[];
}
export const config = {
api: {
responseLimit: false,
},
};
export default async function handler(req: Request, res: NextApiResponse) {
if (req.method == 'OPTIONS') {
await validateSdkRequest(req, res);
return res.status(200).json({});
}
if (req.method !== 'POST') {
return handleError(res, createError(405, 'Method not allowed'));
}
const time = Date.now();
try {
// Check client id & secret
const projectId = await validateSdkRequest(req, res);
const profileIds = new Set<string>(
req.body
.map((item) => item.payload.profileId)
.filter((id): id is string => typeof id === 'string' && id.length > 0)
);
if (profileIds.size === 0) {
return res.status(400).json({ status: 'error' });
}
const profiles = await db.profile.findMany({
where: {
id: {
in: Array.from(profileIds),
},
},
});
// eslint-disable-next-line no-inner-declarations
async function getProfile(profileId: string) {
const profile = profiles.find((profile) => profile.id === profileId);
if (profile) {
return profile;
}
const created = await db.profile.create({
data: {
id: profileId,
properties: {},
project_id: projectId,
},
});
profiles.push(created);
return created;
}
const mergedBody: BatchPayload[] = req.body.reduce((acc, item) => {
const canMerge =
item.type === 'update_profile' || item.type === 'update_session';
if (!canMerge) {
return [...acc, item];
}
const match = acc.findIndex(
(i) =>
i.type === item.type && i.payload.profileId === item.payload.profileId
);
if (acc[match]) {
acc[match]!.payload = mergeDeepRight(acc[match]!.payload, item.payload);
} else {
acc.push(item);
}
return acc;
}, [] as BatchPayload[]);
const failedEvents: BatchPayload[] = [];
for (const item of mergedBody) {
try {
const { type, payload } = item;
const profile = await getProfile(payload.profileId);
switch (type) {
case 'create_profile': {
profile.properties = {
...(typeof profile.properties === 'object'
? profile.properties ?? {}
: {}),
...(payload.properties ?? {}),
};
await db.profile.update({
where: {
id: payload.profileId,
},
data: {
properties: profile.properties,
},
});
break;
}
case 'update_profile': {
profile.properties = {
...(typeof profile.properties === 'object'
? profile.properties ?? {}
: {}),
...(payload.properties ?? {}),
};
await db.profile.update({
where: {
id: payload.profileId,
},
data: {
external_id: payload.id,
email: payload.email,
first_name: payload.first_name,
last_name: payload.last_name,
avatar: payload.avatar,
properties: profile.properties,
},
});
break;
}
case 'set_profile_property': {
if (
typeof (profile.properties as Record<string, unknown>)[
payload.name
] === 'undefined'
) {
(profile.properties as Record<string, unknown>)[payload.name] =
payload.value;
await db.profile.update({
where: {
id: payload.profileId,
},
data: {
// @ts-expect-error
properties: profile.properties,
},
});
}
break;
}
case 'increment': {
await tickProfileProperty({
profileId: payload.profileId,
name: payload.name,
tick: payload.value,
});
break;
}
case 'decrement': {
await tickProfileProperty({
profileId: payload.profileId,
name: payload.name,
tick: -Math.abs(payload.value),
});
break;
}
case 'event': {
await db.event.create({
data: {
name: payload.name,
properties: payload.properties,
createdAt: payload.time,
project_id: projectId,
profile_id: payload.profileId,
},
});
break;
}
case 'update_session': {
const session = await db.event.findFirst({
where: {
profile_id: payload.profileId,
project_id: projectId,
name: 'session_start',
},
orderBy: {
createdAt: 'desc',
},
});
if (session) {
await db.$executeRawUnsafe(
`UPDATE events SET properties = '${JSON.stringify(
payload.properties
)}' || properties WHERE "createdAt" >= '${session.createdAt.toISOString()}' AND profile_id = '${
payload.profileId
}'`
);
}
break;
}
}
} catch (error) {
console.log(`Failed to create "${item.type}"`);
console.log(' > Payload:', item.payload);
console.log(' > Error:', error);
failedEvents.push(item);
}
} // end for
await db.eventFailed.createMany({
data: failedEvents.map((item) => ({
data: item as Record<string, any>,
})),
});
console.log('Batch took', Date.now() - time, 'ms', {
events: req.body.length,
combined: mergedBody.length,
});
res.status(200).json({ status: 'ok' });
} catch (error) {
handleError(res, error);
}
}

View File

@@ -11,7 +11,8 @@ interface Request extends NextApiRequest {
export default async function handler(req: Request, res: NextApiResponse) { export default async function handler(req: Request, res: NextApiResponse) {
if (req.method == 'OPTIONS') { if (req.method == 'OPTIONS') {
return res.status(202).json({}); await validateSdkRequest(req, res);
return res.status(200).json({});
} }
if (req.method !== 'POST') { if (req.method !== 'POST') {
@@ -20,7 +21,7 @@ export default async function handler(req: Request, res: NextApiResponse) {
try { try {
// Check client id & secret // Check client id & secret
const projectId = await validateSdkRequest(req); const projectId = await validateSdkRequest(req, res);
await db.event.createMany({ await db.event.createMany({
data: req.body.map((event) => ({ data: req.body.map((event) => ({

View File

@@ -11,7 +11,8 @@ interface Request extends NextApiRequest {
export default async function handler(req: Request, res: NextApiResponse) { export default async function handler(req: Request, res: NextApiResponse) {
if (req.method == 'OPTIONS') { if (req.method == 'OPTIONS') {
return res.status(202).json({}); await validateSdkRequest(req, res);
return res.status(200).json({});
} }
if (req.method !== 'PUT') { if (req.method !== 'PUT') {
@@ -20,7 +21,7 @@ export default async function handler(req: Request, res: NextApiResponse) {
try { try {
// Check client id & secret // Check client id & secret
await validateSdkRequest(req); await validateSdkRequest(req, res);
const profileId = req.query.profileId as string; const profileId = req.query.profileId as string;

View File

@@ -11,7 +11,8 @@ interface Request extends NextApiRequest {
export default async function handler(req: Request, res: NextApiResponse) { export default async function handler(req: Request, res: NextApiResponse) {
if (req.method == 'OPTIONS') { if (req.method == 'OPTIONS') {
return res.status(202).json({}); await validateSdkRequest(req, res);
return res.status(200).json({});
} }
if (req.method !== 'PUT') { if (req.method !== 'PUT') {
@@ -20,7 +21,7 @@ export default async function handler(req: Request, res: NextApiResponse) {
try { try {
// Check client id & secret // Check client id & secret
await validateSdkRequest(req); await validateSdkRequest(req, res);
const profileId = req.query.profileId as string; const profileId = req.query.profileId as string;

View File

@@ -12,7 +12,8 @@ interface Request extends NextApiRequest {
export default async function handler(req: Request, res: NextApiResponse) { export default async function handler(req: Request, res: NextApiResponse) {
if (req.method == 'OPTIONS') { if (req.method == 'OPTIONS') {
return res.status(202).json({}); await validateSdkRequest(req, res);
return res.status(200).json({});
} }
if (req.method !== 'PUT' && req.method !== 'POST') { if (req.method !== 'PUT' && req.method !== 'POST') {
@@ -21,7 +22,7 @@ export default async function handler(req: Request, res: NextApiResponse) {
try { try {
// Check client id & secret // Check client id & secret
await validateSdkRequest(req); await validateSdkRequest(req, res);
const profileId = req.query.profileId as string; const profileId = req.query.profileId as string;
const profile = await getProfile(profileId); const profile = await getProfile(profileId);

View File

@@ -4,16 +4,20 @@ import { createError, handleError } from '@/server/exceptions';
import type { NextApiRequest, NextApiResponse } from 'next'; import type { NextApiRequest, NextApiResponse } from 'next';
import randomAnimalName from 'random-animal-name'; import randomAnimalName from 'random-animal-name';
import type {
CreateProfilePayload,
CreateProfileResponse,
ProfilePayload,
} from '@mixan/types';
interface Request extends NextApiRequest { interface Request extends NextApiRequest {
body: { body: ProfilePayload | CreateProfilePayload;
id?: string;
properties?: Record<string, any>;
};
} }
export default async function handler(req: Request, res: NextApiResponse) { export default async function handler(req: Request, res: NextApiResponse) {
if (req.method == 'OPTIONS') { if (req.method == 'OPTIONS') {
return res.status(202).json({}); await validateSdkRequest(req, res);
return res.status(200).json({});
} }
if (req.method !== 'POST') { if (req.method !== 'POST') {
@@ -22,12 +26,15 @@ export default async function handler(req: Request, res: NextApiResponse) {
try { try {
// Check client id & secret // Check client id & secret
const projectId = await validateSdkRequest(req); const projectId = await validateSdkRequest(req, res);
// Providing an `ID` is deprecated, should be removed in the future
const profileId = 'id' in req.body ? req.body.id : undefined;
const { properties } = req.body ?? {};
const { id, properties } = req.body ?? {};
const profile = await db.profile.create({ const profile = await db.profile.create({
data: { data: {
id, id: profileId,
external_id: null, external_id: null,
email: null, email: null,
first_name: randomAnimalName(), first_name: randomAnimalName(),
@@ -40,7 +47,8 @@ export default async function handler(req: Request, res: NextApiResponse) {
}, },
}); });
res.status(200).json({ id: profile.id }); const response: CreateProfileResponse = { id: profile.id };
res.status(200).json(response);
} catch (error) { } catch (error) {
handleError(res, error); handleError(res, error);
} }

View File

@@ -59,6 +59,7 @@ export const clientRouter = createTRPCRouter({
name: z.string(), name: z.string(),
projectId: z.string(), projectId: z.string(),
organizationSlug: z.string(), organizationSlug: z.string(),
withCors: z.boolean().default(true),
}) })
) )
.mutation(async ({ input }) => { .mutation(async ({ input }) => {
@@ -69,13 +70,14 @@ export const clientRouter = createTRPCRouter({
organization_id: organization.id, organization_id: organization.id,
project_id: input.projectId, project_id: input.projectId,
name: input.name, name: input.name,
secret: await hashPassword(secret), secret: input.withCors ? null : await hashPassword(secret),
}, },
}); });
return { return {
clientSecret: secret, clientSecret: input.withCors ? null : secret,
clientId: client.id, clientId: client.id,
cors: client.cors,
}; };
}), }),
remove: protectedProcedure remove: protectedProcedure

View File

@@ -1,6 +1,10 @@
import { db } from '@/server/db'; import { db } from '@/server/db';
import { verifyPassword } from '@/server/services/hash.service'; import { verifyPassword } from '@/server/services/hash.service';
import type { GetServerSidePropsContext, NextApiRequest } from 'next'; import type {
GetServerSidePropsContext,
NextApiRequest,
NextApiResponse,
} from 'next';
import { getServerSession } from 'next-auth'; import { getServerSession } from 'next-auth';
import type { DefaultSession, NextAuthOptions } from 'next-auth'; import type { DefaultSession, NextAuthOptions } from 'next-auth';
import Credentials from 'next-auth/providers/credentials'; import Credentials from 'next-auth/providers/credentials';
@@ -98,7 +102,10 @@ export const getServerAuthSession = (ctx: {
return getServerSession(ctx.req, ctx.res, authOptions); return getServerSession(ctx.req, ctx.res, authOptions);
}; };
export async function validateSdkRequest(req: NextApiRequest): Promise<string> { export async function validateSdkRequest(
req: NextApiRequest,
res: NextApiResponse
): Promise<string> {
const clientId = req?.headers['mixan-client-id'] as string | undefined; const clientId = req?.headers['mixan-client-id'] as string | undefined;
const clientSecret = req.headers['mixan-client-secret'] as string | undefined; const clientSecret = req.headers['mixan-client-secret'] as string | undefined;
@@ -106,10 +113,6 @@ export async function validateSdkRequest(req: NextApiRequest): Promise<string> {
throw createError(401, 'Misisng client id'); throw createError(401, 'Misisng client id');
} }
if (!clientSecret) {
throw createError(401, 'Misisng client secret');
}
const client = await db.client.findUnique({ const client = await db.client.findUnique({
where: { where: {
id: clientId, id: clientId,
@@ -120,8 +123,12 @@ export async function validateSdkRequest(req: NextApiRequest): Promise<string> {
throw createError(401, 'Invalid client id'); throw createError(401, 'Invalid client id');
} }
if (!(await verifyPassword(clientSecret, client.secret))) { if (client.secret) {
throw createError(401, 'Invalid client secret'); if (!(await verifyPassword(clientSecret || '', client.secret))) {
throw createError(401, 'Invalid client secret');
}
} else if (client.cors !== '*') {
res.setHeader('Access-Control-Allow-Origin', client.cors);
} }
return client.project_id; return client.project_id;

View File

@@ -6,15 +6,8 @@ export class MixanNative extends Mixan {
super(options); super(options);
} }
async properties() { init(properties?: Record<string, unknown>) {
return {
ip: await super.ip(),
};
}
async init(properties: Record<string, unknown>) {
super.init({ super.init({
...(await this.properties()),
...(properties ?? {}), ...(properties ?? {}),
}); });
} }

View File

@@ -1,45 +1,56 @@
import type { NewMixanOptions } from '@mixan/sdk'; import type { NewMixanOptions } from '@mixan/sdk';
import { Mixan } from '@mixan/sdk'; import { Mixan } from '@mixan/sdk';
import type { PartialBy } from '@mixan/types';
import { parseQuery } from './src/parseQuery'; import { parseQuery } from './src/parseQuery';
import { getDevice, getOS, getTimezone } from './src/utils'; import { getDevice, getOS, getTimezone } from './src/utils';
type Omit<T, K extends keyof T> = Pick<T, Exclude<keyof T, K>>;
type PartialBy<T, K extends keyof T> = Omit<T, K> & Partial<Pick<T, K>>;
export class MixanWeb extends Mixan { export class MixanWeb extends Mixan {
constructor( constructor(
options: PartialBy<NewMixanOptions, 'setItem' | 'removeItem' | 'getItem'> options: PartialBy<NewMixanOptions, 'setItem' | 'removeItem' | 'getItem'>
) { ) {
const hasStorage = typeof localStorage === 'undefined';
super({ super({
batchInterval: options.batchInterval ?? 1000, batchInterval: options.batchInterval ?? 2000,
setItem: setItem: hasStorage ? () => {} : localStorage.setItem.bind(localStorage),
typeof localStorage === 'undefined' removeItem: hasStorage
? () => {} ? () => {}
: localStorage.setItem.bind(localStorage), : localStorage.removeItem.bind(localStorage),
removeItem: getItem: hasStorage
typeof localStorage === 'undefined' ? () => null
? () => {} : localStorage.getItem.bind(localStorage),
: localStorage.removeItem.bind(localStorage),
getItem:
typeof localStorage === 'undefined'
? () => null
: localStorage.getItem.bind(localStorage),
...options, ...options,
}); });
} }
isServer() { private isServer() {
return typeof document === 'undefined'; return typeof document === 'undefined';
} }
async properties() { private parseUrl(url?: string) {
if (!url || url === '') {
return {
direct: true,
};
}
const ref = new URL(url);
return {
host: ref.host,
hostname: ref.hostname,
url: ref.href,
path: ref.pathname,
query: parseQuery(ref.search),
hash: ref.hash,
};
}
private properties() {
return { return {
ip: await super.ip(),
os: getOS(), os: getOS(),
device: getDevice(), device: getDevice(),
ua: navigator.userAgent, ua: navigator.userAgent,
referrer: document.referrer, referrer: this.parseUrl(document.referrer),
language: navigator.language, language: navigator.language,
timezone: getTimezone(), timezone: getTimezone(),
screen: { screen: {
@@ -47,22 +58,28 @@ export class MixanWeb extends Mixan {
height: window.screen.height, height: window.screen.height,
pixelRatio: window.devicePixelRatio, pixelRatio: window.devicePixelRatio,
}, },
title: document.title,
...this.parseUrl(window.location.href),
}; };
} }
async init(properties?: Record<string, unknown>) { public init(properties?: Record<string, unknown>) {
if (this.isServer()) { if (this.isServer()) {
return; return;
} }
super.init({ super.init({
...(await this.properties()), ...this.properties(),
...(properties ?? {}), ...(properties ?? {}),
}); });
this.screenView(); this.screenView();
window.addEventListener('beforeunload', () => {
this.flush();
});
} }
trackOutgoingLinks() { public trackOutgoingLinks() {
if (this.isServer()) { if (this.isServer()) {
return; return;
} }
@@ -82,16 +99,15 @@ export class MixanWeb extends Mixan {
}); });
} }
screenView(properties?: Record<string, unknown>): void { public screenView(properties?: Record<string, unknown>): void {
if (this.isServer()) { if (this.isServer()) {
return; return;
} }
super.event('screen_view', { super.event('screen_view', {
...properties, ...properties,
route: window.location.pathname, ...this.parseUrl(window.location.href),
url: window.location.href, title: document.title,
query: parseQuery(window.location.search ?? ''),
}); });
} }
} }

View File

@@ -1,37 +1,60 @@
import type { import type {
EventPayload, BatchPayload,
BatchUpdateProfilePayload,
BatchUpdateSessionPayload,
MixanErrorResponse, MixanErrorResponse,
ProfilePayload,
} from '@mixan/types'; } from '@mixan/types';
type MixanLogger = (...args: unknown[]) => void;
export interface NewMixanOptions { export interface NewMixanOptions {
url: string; url: string;
clientId: string; clientId: string;
clientSecret: string; clientSecret?: string;
batchInterval?: number; batchInterval?: number;
maxBatchSize?: number; maxBatchSize?: number;
sessionTimeout?: number; sessionTimeout?: number;
session?: boolean; session?: boolean;
verbose?: boolean; verbose?: boolean;
profile?: boolean;
trackIp?: boolean; trackIp?: boolean;
ipUrl?: string;
setItem: (key: string, profileId: string) => void; setItem: (key: string, profileId: string) => void;
getItem: (key: string) => string | null; getItem: (key: string) => string | null;
removeItem: (key: string) => void; removeItem: (key: string) => void;
} }
export type MixanOptions = Required<NewMixanOptions>; export type MixanOptions = Required<NewMixanOptions>;
export interface MixanState {
profileId: string;
lastEventAt: number;
properties: Record<string, unknown>;
}
function createLogger(verbose: boolean): MixanLogger {
return verbose ? (...args) => console.log('[Mixan]', ...args) : () => {};
}
function uuid() {
return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, (c) => {
const r = (Math.random() * 16) | 0;
const v = c === 'x' ? r : (r & 0x3) | 0x8;
return v.toString(16);
});
}
class Fetcher { class Fetcher {
private url: string; private url: string;
private clientId: string; private clientId: string;
private clientSecret: string; private clientSecret: string;
private logger: (...args: any[]) => void;
constructor(options: MixanOptions) { constructor(
options: MixanOptions,
private logger: MixanLogger
) {
this.url = options.url; this.url = options.url;
this.clientId = options.clientId; this.clientId = options.clientId;
this.clientSecret = options.clientSecret; this.clientSecret = options.clientSecret;
this.logger = options.verbose ? console.log : () => {};
} }
post<PostData, PostResponse>( post<PostData, PostResponse>(
@@ -40,91 +63,96 @@ class Fetcher {
options?: RequestInit options?: RequestInit
): Promise<PostResponse | null> { ): Promise<PostResponse | null> {
const url = `${this.url}${path}`; const url = `${this.url}${path}`;
this.logger(`Mixan request: ${url}`, JSON.stringify(data, null, 2)); let timer: ReturnType<typeof setTimeout>;
return fetch(url, { return new Promise((resolve) => {
headers: { const wrappedFetch = (attempt: number) => {
['mixan-client-id']: this.clientId, clearTimeout(timer);
['mixan-client-secret']: this.clientSecret,
'Content-Type': 'application/json',
},
method: 'POST',
body: JSON.stringify(data ?? {}),
keepalive: true,
...(options ?? {}),
})
.then(async (res) => {
const response = (await res.json()) as
| MixanErrorResponse
| PostResponse;
if (!response) {
return null;
}
if (
typeof response === 'object' &&
'status' in response &&
response.status === 'error'
) {
this.logger(
`Mixan request failed: [${options?.method ?? 'POST'}] ${url}`,
JSON.stringify(response, null, 2)
);
return null;
}
return response as PostResponse;
})
.catch(() => {
this.logger( this.logger(
`Mixan request failed: [${options?.method ?? 'POST'}] ${url}` `Request attempt ${attempt + 1}: ${url}`,
JSON.stringify(data, null, 2)
); );
return null;
}); fetch(url, {
headers: {
['mixan-client-id']: this.clientId,
['mixan-client-secret']: this.clientSecret,
'Content-Type': 'application/json',
},
method: 'POST',
body: JSON.stringify(data ?? {}),
keepalive: true,
...(options ?? {}),
})
.then(async (res) => {
if (res.status !== 200) {
return retry(attempt, resolve);
}
const response = (await res.json()) as
| MixanErrorResponse
| PostResponse;
if (!response) {
return resolve(null);
}
resolve(response as PostResponse);
})
.catch(() => {
return retry(attempt, resolve);
});
};
function retry(
attempt: number,
resolve: (value: PostResponse | null) => void
) {
if (attempt > 3) {
return resolve(null);
}
timer = setTimeout(
() => {
wrappedFetch(attempt + 1);
},
Math.pow(2, attempt) * 500
);
}
wrappedFetch(0);
});
} }
} }
class Batcher<T> { class Batcher {
queue: T[] = []; queue: BatchPayload[] = [];
timer?: ReturnType<typeof setTimeout>; timer?: ReturnType<typeof setTimeout>;
callback: (queue: T[]) => void;
maxBatchSize: number;
batchInterval: number;
constructor(options: MixanOptions, callback: (queue: T[]) => void) { constructor(
this.callback = callback; private options: MixanOptions,
this.maxBatchSize = options.maxBatchSize; private callback: (payload: BatchPayload[]) => void,
this.batchInterval = options.batchInterval; private logger: MixanLogger
} ) {}
add(payload: T) { add(action: BatchPayload) {
this.queue.push(payload);
this.flush();
}
flush() {
if (this.timer) { if (this.timer) {
clearTimeout(this.timer); clearTimeout(this.timer);
} }
if (this.queue.length === 0) { this.logger(`Add to queue ${action.type}`);
return; this.queue.push(action);
}
if (this.queue.length >= this.maxBatchSize) { if (this.queue.length >= this.options.maxBatchSize) {
this.send(); this.send();
return; } else {
this.timer = setTimeout(this.send.bind(this), this.options.batchInterval);
} }
this.timer = setTimeout(this.send.bind(this), this.batchInterval);
} }
send() { send() {
if (this.timer) { this.logger('Send queue', this.queue.length > 0);
clearTimeout(this.timer);
}
if (this.queue.length > 0) { if (this.queue.length > 0) {
this.callback(this.queue); this.callback(this.queue);
this.queue = []; this.queue = [];
@@ -133,17 +161,18 @@ class Batcher<T> {
} }
export class Mixan { export class Mixan {
private fetch: Fetcher;
private eventBatcher: Batcher<EventPayload>;
private profileId?: string;
private options: MixanOptions; private options: MixanOptions;
private fetch: Fetcher;
private batcher: Batcher;
private logger: (...args: any[]) => void; private logger: (...args: any[]) => void;
private globalProperties: Record<string, unknown> = {}; private state: MixanState = {
private lastEventAt: string; profileId: '',
private promiseIp: Promise<string | null>; lastEventAt: 0,
properties: {},
};
constructor(options: NewMixanOptions) { constructor(options: NewMixanOptions) {
this.logger = options.verbose ? console.log : () => {}; this.logger = createLogger(options.verbose ?? false);
this.options = { this.options = {
sessionTimeout: 1000 * 60 * 30, sessionTimeout: 1000 * 60 * 30,
session: true, session: true,
@@ -151,210 +180,234 @@ export class Mixan {
batchInterval: 10000, batchInterval: 10000,
maxBatchSize: 10, maxBatchSize: 10,
trackIp: false, trackIp: false,
profile: true, clientSecret: '',
ipUrl: 'https://api.ipify.org',
...options, ...options,
}; };
this.fetch = new Fetcher(this.options, this.logger);
this.lastEventAt = this.batcher = new Batcher(
this.options.getItem('@mixan:lastEventAt') ?? '1970-01-01'; this.options,
this.fetch = new Fetcher(this.options); (queue) => {
this.eventBatcher = new Batcher(this.options, (queue) => { this.fetch.post('/batch', queue);
this.fetch.post( },
'/events', this.logger
queue.map((item) => ({ );
...item,
properties: {
...this.globalProperties,
...item.properties,
},
profileId: item.profileId ?? this.profileId ?? null,
}))
);
});
this.promiseIp = this.options.trackIp
? fetch('https://api.ipify.org')
.then((res) => res.text())
.catch(() => null)
: Promise.resolve(null);
} }
async ip() { // Public
return this.promiseIp;
public init(properties?: Record<string, unknown>) {
this.logger('Init');
this.state.properties = properties ?? {};
this.createProfile();
this.createSession();
this.ipLookup();
} }
timestamp(modify = 0) { public setUser(payload: Omit<BatchUpdateProfilePayload, 'profileId'>) {
return new Date(Date.now() + modify).toISOString(); this.createSession();
}
init(properties?: Record<string, unknown>) { this.batcher.add({
if (properties) { type: 'update_profile',
this.setGlobalProperties(properties); payload: {
} ...payload,
this.logger('Mixan: Init'); properties: payload.properties ?? {},
this.setAnonymousUser(); profileId: this.state.profileId,
}
event(name: string, properties: Record<string, unknown> = {}) {
const now = new Date();
const isSessionStart =
this.options.session &&
now.getTime() - new Date(this.lastEventAt).getTime() >
this.options.sessionTimeout;
if (isSessionStart) {
this.logger('Mixan: Session start');
this.eventBatcher.add({
name: 'session_start',
time: this.timestamp(-10),
properties: {},
profileId: this.profileId ?? null,
});
}
this.logger('Mixan: Queue event', name);
this.eventBatcher.add({
name,
properties,
time: this.timestamp(),
profileId: this.profileId ?? null,
});
this.lastEventAt = this.timestamp();
this.options.setItem('@mixan:lastEventAt', this.lastEventAt);
}
private async setAnonymousUser(retryCount = 0) {
if (!this.options.profile) {
return;
}
const profileId = this.options.getItem('@mixan:profileId');
if (profileId) {
this.profileId = profileId;
await this.setUser({
properties: this.globalProperties,
});
this.logger('Mixan: Use existing profile', this.profileId);
} else {
const res = await this.fetch.post<ProfilePayload, { id: string }>(
'/profiles',
{
properties: this.globalProperties,
}
);
if (res) {
this.profileId = res.id;
this.options.setItem('@mixan:profileId', res.id);
this.logger('Mixan: Create new profile', this.profileId);
} else if (retryCount < 2) {
setTimeout(() => {
this.setAnonymousUser(retryCount + 1);
}, 500);
} else {
this.logger('Mixan: Failed to create new profile');
}
}
}
async setUser(profile: ProfilePayload) {
if (!this.options.profile) {
return;
}
if (!this.profileId) {
return this.logger('Mixan: Set user failed, no profileId');
}
this.logger('Mixan: Set user', profile);
await this.fetch.post(`/profiles/${this.profileId}`, profile, {
method: 'PUT',
});
}
async setUserProperty(
name: string,
value: string | number | boolean | Record<string, unknown> | unknown[]
) {
if (!this.options.profile) {
return;
}
if (!this.profileId) {
return this.logger('Mixan: Set user property, no profileId');
}
this.logger('Mixan: Set user property', name, value);
await this.fetch.post(`/profiles/${this.profileId}`, {
properties: {
[name]: value,
}, },
}); });
} }
setGlobalProperties(properties: Record<string, unknown>) { public setSession(properties: BatchUpdateSessionPayload['properties']) {
this.createSession();
this.batcher.add({
type: 'update_session',
payload: {
properties,
profileId: this.state.profileId,
},
});
}
public increment(name: string, value: number) {
this.createSession();
this.batcher.add({
type: 'increment',
payload: {
name,
value,
profileId: this.state.profileId,
},
});
}
public decrement(name: string, value: number) {
this.createSession();
this.batcher.add({
type: 'decrement',
payload: {
name,
value,
profileId: this.state.profileId,
},
});
}
public event(name: string, properties?: Record<string, unknown>) {
this.createSession();
this.batcher.add({
type: 'event',
payload: {
name,
properties: {
...this.state.properties,
...(properties ?? {}),
},
time: this.timestamp(),
profileId: this.state.profileId,
},
});
}
public setGlobalProperties(properties: Record<string, unknown>) {
if (typeof properties !== 'object') { if (typeof properties !== 'object') {
return this.logger( return this.logger(
'Mixan: Set global properties failed, properties must be an object' 'Set global properties failed, properties must be an object'
); );
} }
this.logger('Mixan: Set global properties', properties);
this.globalProperties = { this.logger('Set global properties', properties);
...this.globalProperties, this.state.properties = {
...this.state.properties,
...properties, ...properties,
}; };
} }
async increment(name: string, value = 1) { public flush() {
if (!this.options.profile) { this.batcher.send();
return;
}
if (!this.profileId) {
this.logger('Mixan: Increment failed, no profileId');
return;
}
this.logger('Mixan: Increment user property', name, value);
await this.fetch.post(
`/profiles/${this.profileId}/increment`,
{
name,
value,
},
{
method: 'PUT',
}
);
} }
async decrement(name: string, value = 1) { public clear() {
if (!this.options.profile) { this.logger('Clear / Logout');
return; this.flush();
} this.options.removeItem('@mixan:ip');
if (!this.profileId) {
this.logger('Mixan: Decrement failed, no profileId');
return;
}
this.logger('Mixan: Decrement user property', name, value);
await this.fetch.post(
`/profiles/${this.profileId}/decrement`,
{
name,
value,
},
{
method: 'PUT',
}
);
}
flush() {
this.logger('Mixan: Flushing events queue');
this.eventBatcher.send();
}
clear() {
this.logger('Mixan: Clear, send remaining events and remove profileId');
this.eventBatcher.send();
this.options.removeItem('@mixan:profileId'); this.options.removeItem('@mixan:profileId');
this.options.removeItem('@mixan:lastEventAt'); this.options.removeItem('@mixan:lastEventAt');
this.profileId = undefined; this.state.profileId = '';
this.setAnonymousUser(); this.state.lastEventAt = 0;
this.createProfile();
}
public setUserProperty(name: string, value: unknown, update = true) {
this.batcher.add({
type: 'set_profile_property',
payload: {
name,
value,
update,
profileId: this.state.profileId,
},
});
}
// Private
private timestamp(modify = 0) {
this.setLastEventAt();
return new Date(Date.now() + modify).toISOString();
}
private createProfile() {
const profileId = this.options.getItem('@mixan:profileId');
if (profileId) {
this.logger('Reusing existing profile');
this.state.profileId = profileId;
} else {
this.logger('Creating profile');
this.state.profileId = uuid();
this.options.setItem('@mixan:profileId', this.state.profileId);
this.batcher.add({
type: 'create_profile',
payload: {
profileId: this.state.profileId,
properties: this.state.properties,
},
});
}
}
private checkSession() {
if (!this.options.session) {
return false;
}
if (this.state.lastEventAt === 0) {
const str = this.options.getItem('@mixan:lastEventAt') ?? '0';
const value = parseInt(str, 10);
this.state.lastEventAt = isNaN(value) ? 0 : value;
}
return Date.now() - this.state.lastEventAt > this.options.sessionTimeout;
}
private createSession() {
if (!this.checkSession()) {
return;
}
const time = this.timestamp(-10);
this.batcher.add({
type: 'event',
payload: {
name: 'session_start',
properties: this.state.properties,
profileId: this.state.profileId,
time,
},
});
}
private setLastEventAt() {
this.state.lastEventAt = Date.now();
this.options.setItem(
'@mixan:lastEventAt',
this.state.lastEventAt.toString()
);
}
private async ipLookup() {
if (!this.options.trackIp) {
return null;
}
let ip: string | null;
const cachedIp = this.options.getItem('@mixan:ip');
if (cachedIp) {
ip = cachedIp;
} else {
const controller = new AbortController();
const timeout = setTimeout(() => controller.abort(), 1000);
ip = await fetch(this.options.ipUrl, {
signal: controller.signal,
})
.then((res) => res.text())
.catch(() => null)
.finally(() => clearTimeout(timeout));
}
if (ip) {
this.options.setItem('@mixan:ip', ip);
this.setGlobalProperties({ ip });
if (!cachedIp) {
this.setUserProperty('ip', ip, false);
this.setSession({ ip });
}
}
} }
} }

360
packages/sdk/index_old.ts Normal file
View File

@@ -0,0 +1,360 @@
import type {
EventPayload,
MixanErrorResponse,
ProfilePayload,
} from '@mixan/types';
export interface NewMixanOptions {
url: string;
clientId: string;
clientSecret: string;
batchInterval?: number;
maxBatchSize?: number;
sessionTimeout?: number;
session?: boolean;
verbose?: boolean;
profile?: boolean;
trackIp?: boolean;
setItem: (key: string, profileId: string) => void;
getItem: (key: string) => string | null;
removeItem: (key: string) => void;
}
export type MixanOptions = Required<NewMixanOptions>;
class Fetcher {
private url: string;
private clientId: string;
private clientSecret: string;
private logger: (...args: any[]) => void;
constructor(options: MixanOptions) {
this.url = options.url;
this.clientId = options.clientId;
this.clientSecret = options.clientSecret;
this.logger = options.verbose ? console.log : () => {};
}
post<PostData, PostResponse>(
path: string,
data?: PostData,
options?: RequestInit
): Promise<PostResponse | null> {
const url = `${this.url}${path}`;
this.logger(`Mixan request: ${url}`, JSON.stringify(data, null, 2));
return fetch(url, {
headers: {
['mixan-client-id']: this.clientId,
['mixan-client-secret']: this.clientSecret,
'Content-Type': 'application/json',
},
method: 'POST',
body: JSON.stringify(data ?? {}),
keepalive: true,
...(options ?? {}),
})
.then(async (res) => {
const response = (await res.json()) as
| MixanErrorResponse
| PostResponse;
if (!response) {
return null;
}
if (
typeof response === 'object' &&
'status' in response &&
response.status === 'error'
) {
this.logger(
`Mixan request failed: [${options?.method ?? 'POST'}] ${url}`,
JSON.stringify(response, null, 2)
);
return null;
}
return response as PostResponse;
})
.catch(() => {
this.logger(
`Mixan request failed: [${options?.method ?? 'POST'}] ${url}`
);
return null;
});
}
}
class Batcher<T> {
queue: T[] = [];
timer?: ReturnType<typeof setTimeout>;
callback: (queue: T[]) => void;
maxBatchSize: number;
batchInterval: number;
constructor(options: MixanOptions, callback: (queue: T[]) => void) {
this.callback = callback;
this.maxBatchSize = options.maxBatchSize;
this.batchInterval = options.batchInterval;
}
add(payload: T) {
this.queue.push(payload);
this.flush();
}
flush() {
if (this.timer) {
clearTimeout(this.timer);
}
if (this.queue.length === 0) {
return;
}
if (this.queue.length >= this.maxBatchSize) {
this.send();
return;
}
this.timer = setTimeout(this.send.bind(this), this.batchInterval);
}
send() {
if (this.timer) {
clearTimeout(this.timer);
}
if (this.queue.length > 0) {
this.callback(this.queue);
this.queue = [];
}
}
}
export class Mixan {
private fetch: Fetcher;
private eventBatcher: Batcher<EventPayload>;
private profileId?: string;
private options: MixanOptions;
private logger: (...args: any[]) => void;
private globalProperties: Record<string, unknown> = {};
private lastEventAt: string;
private promiseIp: Promise<string | null>;
constructor(options: NewMixanOptions) {
this.logger = options.verbose ? console.log : () => {};
this.options = {
sessionTimeout: 1000 * 60 * 30,
session: true,
verbose: false,
batchInterval: 10000,
maxBatchSize: 10,
trackIp: false,
profile: true,
...options,
};
this.lastEventAt =
this.options.getItem('@mixan:lastEventAt') ?? '1970-01-01';
this.fetch = new Fetcher(this.options);
this.eventBatcher = new Batcher(this.options, (queue) => {
this.fetch.post(
'/events',
queue.map((item) => ({
...item,
properties: {
...this.globalProperties,
...item.properties,
},
profileId: item.profileId ?? this.profileId ?? null,
}))
);
});
this.promiseIp = this.options.trackIp
? fetch('https://api.ipify.org')
.then((res) => res.text())
.catch(() => null)
: Promise.resolve(null);
}
async ip() {
return this.promiseIp;
}
timestamp(modify = 0) {
return new Date(Date.now() + modify).toISOString();
}
init(properties?: Record<string, unknown>) {
if (properties) {
this.setGlobalProperties(properties);
}
this.logger('Mixan: Init');
this.setAnonymousUser();
}
event(name: string, properties: Record<string, unknown> = {}) {
const now = new Date();
const isSessionStart =
this.options.session &&
now.getTime() - new Date(this.lastEventAt).getTime() >
this.options.sessionTimeout;
if (isSessionStart) {
this.logger('Mixan: Session start');
this.eventBatcher.add({
name: 'session_start',
time: this.timestamp(-10),
properties: {},
profileId: this.profileId ?? null,
});
}
this.logger('Mixan: Queue event', name);
this.eventBatcher.add({
name,
properties,
time: this.timestamp(),
profileId: this.profileId ?? null,
});
this.lastEventAt = this.timestamp();
this.options.setItem('@mixan:lastEventAt', this.lastEventAt);
}
private async setAnonymousUser(retryCount = 0) {
if (!this.options.profile) {
return;
}
const profileId = this.options.getItem('@mixan:profileId');
if (profileId) {
this.profileId = profileId;
await this.setUser({
properties: this.globalProperties,
});
this.logger('Mixan: Use existing profile', this.profileId);
} else {
const res = await this.fetch.post<ProfilePayload, { id: string }>(
'/profiles',
{
properties: this.globalProperties,
}
);
if (res) {
this.profileId = res.id;
this.options.setItem('@mixan:profileId', res.id);
this.logger('Mixan: Create new profile', this.profileId);
} else if (retryCount < 2) {
setTimeout(() => {
this.setAnonymousUser(retryCount + 1);
}, 500);
} else {
this.logger('Mixan: Failed to create new profile');
}
}
}
async setUser(profile: ProfilePayload) {
if (!this.options.profile) {
return;
}
if (!this.profileId) {
return this.logger('Mixan: Set user failed, no profileId');
}
this.logger('Mixan: Set user', profile);
await this.fetch.post(`/profiles/${this.profileId}`, profile, {
method: 'PUT',
});
}
async setUserProperty(
name: string,
value: string | number | boolean | Record<string, unknown> | unknown[]
) {
if (!this.options.profile) {
return;
}
if (!this.profileId) {
return this.logger('Mixan: Set user property, no profileId');
}
this.logger('Mixan: Set user property', name, value);
await this.fetch.post(`/profiles/${this.profileId}`, {
properties: {
[name]: value,
},
});
}
setGlobalProperties(properties: Record<string, unknown>) {
if (typeof properties !== 'object') {
return this.logger(
'Mixan: Set global properties failed, properties must be an object'
);
}
this.logger('Mixan: Set global properties', properties);
this.globalProperties = {
...this.globalProperties,
...properties,
};
}
async increment(name: string, value = 1) {
if (!this.options.profile) {
return;
}
if (!this.profileId) {
this.logger('Mixan: Increment failed, no profileId');
return;
}
this.logger('Mixan: Increment user property', name, value);
await this.fetch.post(
`/profiles/${this.profileId}/increment`,
{
name,
value,
},
{
method: 'PUT',
}
);
}
async decrement(name: string, value = 1) {
if (!this.options.profile) {
return;
}
if (!this.profileId) {
this.logger('Mixan: Decrement failed, no profileId');
return;
}
this.logger('Mixan: Decrement user property', name, value);
await this.fetch.post(
`/profiles/${this.profileId}/decrement`,
{
name,
value,
},
{
method: 'PUT',
}
);
}
flush() {
this.logger('Mixan: Flushing events queue');
this.eventBatcher.send();
}
clear() {
this.logger('Mixan: Clear, send remaining events and remove profileId');
this.eventBatcher.send();
this.options.removeItem('@mixan:profileId');
this.options.removeItem('@mixan:lastEventAt');
this.profileId = undefined;
this.setAnonymousUser();
}
}

View File

@@ -1,5 +1,9 @@
export type Omit<T, K extends keyof T> = Pick<T, Exclude<keyof T, K>>;
export type PartialBy<T, K extends keyof T> = Omit<T, K> & Partial<Pick<T, K>>;
export type MixanJson = Record<string, any>; export type MixanJson = Record<string, any>;
// Deprecated
export interface EventPayload { export interface EventPayload {
name: string; name: string;
time: string; time: string;
@@ -7,6 +11,7 @@ export interface EventPayload {
properties: MixanJson; properties: MixanJson;
} }
// Deprecated
export interface ProfilePayload { export interface ProfilePayload {
first_name?: string; first_name?: string;
last_name?: string; last_name?: string;
@@ -16,46 +21,98 @@ export interface ProfilePayload {
properties?: MixanJson; properties?: MixanJson;
} }
export type BatchPayload =
| {
type: 'increment';
payload: BatchProfileIncrementPayload;
}
| {
type: 'decrement';
payload: BatchProfileDecrementPayload;
}
| {
type: 'event';
payload: BatchEventPayload;
}
| {
type: 'create_profile';
payload: BatchCreateProfilePayload;
}
| {
type: 'update_profile';
payload: BatchUpdateProfilePayload;
}
| {
type: 'update_session';
payload: BatchUpdateSessionPayload;
}
| {
type: 'set_profile_property';
payload: BatchSetProfilePropertyPayload;
};
export interface BatchSetProfilePropertyPayload {
profileId: string;
name: string;
value: any;
update: boolean;
}
export interface CreateProfileResponse {
id: string;
}
export interface BatchCreateProfilePayload {
profileId: string;
properties?: MixanJson;
}
export interface BatchUpdateSessionPayload {
profileId: string;
properties?: MixanJson;
}
export interface BatchEventPayload {
name: string;
time: string;
profileId: string;
properties: MixanJson;
}
export interface BatchUpdateProfilePayload {
first_name?: string;
last_name?: string;
email?: string;
avatar?: string;
id?: string;
properties?: MixanJson;
profileId: string;
}
export interface ProfileIncrementPayload { export interface ProfileIncrementPayload {
name: string; name: string;
value: number; value: number;
id: string; profileId: string;
} }
export interface ProfileDecrementPayload { export interface ProfileDecrementPayload {
name: string; name: string;
value: number; value: number;
id: string; profileId: string;
} }
// Batching export interface BatchProfileIncrementPayload {
export interface BatchEvent { name: string;
type: 'event'; value: number;
payload: EventPayload; profileId: string;
} }
export interface BatchProfile { export interface BatchProfileDecrementPayload {
type: 'profile'; name: string;
payload: ProfilePayload; value: number;
profileId: string;
} }
export interface BatchProfileIncrement {
type: 'profile_increment';
payload: ProfileIncrementPayload;
}
export interface BatchProfileDecrement {
type: 'profile_decrement';
payload: ProfileDecrementPayload;
}
export type BatchItem =
| BatchEvent
| BatchProfile
| BatchProfileIncrement
| BatchProfileDecrement;
export type BatchPayload = BatchItem[];
export interface MixanIssue { export interface MixanIssue {
field: string; field: string;
message: string; message: string;

View File

@@ -1,3 +1,4 @@
/* eslint-disable @typescript-eslint/no-var-requires */
import { execSync } from 'node:child_process'; import { execSync } from 'node:child_process';
import fs from 'node:fs'; import fs from 'node:fs';
import path from 'node:path'; import path from 'node:path';

View File

@@ -4,5 +4,6 @@
"dts": true, "dts": true,
"splitting": false, "splitting": false,
"sourcemap": true, "sourcemap": true,
"clean": true "clean": true,
"minify": true
} }