Open source Loom alternative. Beautiful, shareable screen recordings.
Rust appcapcossloommacnextjsnextjs15open-sourceossreactrecordrustscreen-capturescreen-recorderscreenshotsolidjstauritauri-apptypescriptvite
Integrate Tinybird analytics and update dashboard
Richie McIlroyacda2fcdfd34
diff --git a/.gitignore b/.gitignoreindex b88fcb3f4..40ea0b279 100644--- a/.gitignore+++ b/.gitignore@@ -35,6 +35,9 @@ pnpm-lock.yaml.vinxinative-deps*apps/storybook/storybook-static+.tinyb++**/.tinyb*.tsbuildinfo.cargo/config.tomldiff --git a/README.md b/README.mdindex f4f413018..314deee61 100644--- a/README.md+++ b/README.md@@ -60,3 +60,12 @@ Portions of this software are licensed as follows:# ContributingSee [CONTRIBUTING.md](CONTRIBUTING.md) for more information. This guide is a work in progress, and is updated regularly as the app matures.++## Analytics (Tinybird)++Cap uses [Tinybird](https://www.tinybird.co) to ingest viewer telemetry for dashboards. The Tinybird admin token (`TINYBIRD_ADMIN_TOKEN` or `TINYBIRD_TOKEN`) must be available in your environment. Once the token is present you can:++- Provision the required data sources and materialized views via `pnpm analytics:setup`. This command installs the Tinybird CLI (if needed), runs `tb login` when a `.tinyb` credential file is missing, copies that credential into `scripts/analytics/tinybird`, and finally executes `tb deploy --allow-destructive-operations --wait` from that directory. **It synchronizes the Tinybird workspace to the resources defined in `scripts/analytics/tinybird`, removing any other datasources/pipes in that workspace.**+- Validate that the schema and materialized views match what the app expects via `pnpm analytics:check`.++Both commands target the workspace pointed to by `TINYBIRD_HOST` (defaults to `https://api.tinybird.co`). Make sure you are comfortable with the destructive nature of the deploy step before running `analytics:setup`.diff --git a/apps/web/actions/videos/get-analytics.ts b/apps/web/actions/videos/get-analytics.tsindex 7792c16d4..c4518cc36 100644--- a/apps/web/actions/videos/get-analytics.ts+++ b/apps/web/actions/videos/get-analytics.ts@@ -1,28 +1,99 @@"use server";-import { dub } from "@cap/utils";--export async function getVideoAnalytics(videoId: string) {- if (!videoId) {- throw new Error("Video ID is required");- }-- try {- const response = await dub().analytics.retrieve({- domain: "cap.link",- key: videoId,- });- const { clicks } = response as { clicks: number };-- if (typeof clicks !== "number" || clicks === null) {- return { count: 0 };- }-- return { count: clicks };- } catch (error: any) {- if (error.code === "not_found") {- return { count: 0 };- }- return { count: 0 };- }+import { Tinybird } from "@cap/web-backend";+import { Effect } from "effect";++import { runPromise } from "@/lib/server";++import { db } from "@cap/database";+import { videos } from "@cap/database/schema";+import { Video } from "@cap/web-domain";+import { eq } from "drizzle-orm";++const DAY_IN_MS = 24 * 60 * 60 * 1000;+const MIN_RANGE_DAYS = 1;+const MAX_RANGE_DAYS = 90;+const DEFAULT_RANGE_DAYS = MAX_RANGE_DAYS;++const escapeLiteral = (value: string) => value.replace(/'/g, "''");+const formatDate = (date: Date) => date.toISOString().slice(0, 10);+const formatDateTime = (date: Date) => date.toISOString().slice(0, 19).replace("T", " ");+const buildConditions = (clauses: Array<string | undefined>) =>+ clauses+ .filter((clause): clause is string => Boolean(clause))+ .join(" AND ");++const normalizeRangeDays = (rangeDays?: number) => {+ if (!Number.isFinite(rangeDays)) return DEFAULT_RANGE_DAYS;+ const normalized = Math.floor(rangeDays as number);+ if (normalized <= 0) return DEFAULT_RANGE_DAYS;+ return Math.max(MIN_RANGE_DAYS, Math.min(normalized, MAX_RANGE_DAYS));+};++interface GetVideoAnalyticsOptions {+ rangeDays?: number;+}++export async function getVideoAnalytics(+ videoId: string,+ options?: GetVideoAnalyticsOptions,+) {+ if (!videoId) throw new Error("Video ID is required");++ const [{ orgId } = { orgId: null }] = await db()+ .select({ orgId: videos.orgId })+ .from(videos)+ .where(eq(videos.id, Video.VideoId.make(videoId)))+ .limit(1);++ return runPromise(+ Effect.gen(function* () {+ const tinybird = yield* Tinybird;++ const rangeDays = normalizeRangeDays(options?.rangeDays);+ const now = new Date();+ const from = new Date(now.getTime() - rangeDays * DAY_IN_MS);+ const pathname = `/s/${videoId}`;+ const aggregateConditions = [+ orgId ? `tenant_id = '${escapeLiteral(orgId)}'` : undefined,+ `pathname = '${escapeLiteral(pathname)}'`,+ `date BETWEEN toDate('${formatDate(from)}') AND toDate('${formatDate(now)}')`,+ ];+ const aggregateSql = `SELECT coalesce(uniqMerge(visits), 0) AS views FROM analytics_pages_mv WHERE ${buildConditions(aggregateConditions)}`;++ const rawConditions = [+ "action = 'page_hit'",+ orgId ? `tenant_id = '${escapeLiteral(orgId)}'` : undefined,+ `pathname = '${escapeLiteral(pathname)}'`,+ `timestamp BETWEEN toDateTime('${formatDateTime(from)}') AND toDateTime('${formatDateTime(now)}')`,+ ];+ const rawSql = `SELECT coalesce(uniq(session_id), 0) AS views FROM analytics_events WHERE ${buildConditions(rawConditions)}`;++ const querySql = (sql: string) =>+ tinybird+ .querySql<{ views: number }>(sql)+ .pipe(+ Effect.catchAll((e) => {+ console.error("tinybird sql error", e);+ return Effect.succeed({ data: [] });+ }),+ );++ const aggregateResult = yield* querySql(aggregateSql);++ const fallbackResult =+ aggregateResult.data?.length+ ? aggregateResult+ : yield* querySql(rawSql);++ const data = fallbackResult?.data ?? [];+ const firstItem = data[0];+ const count = typeof firstItem === "number"+ ? firstItem+ : typeof firstItem === "object" && firstItem !== null && "views" in firstItem+ ? Number(firstItem.views ?? 0)+ : 0;+ return { count: Number.isFinite(count) ? count : 0 };+ }),+ );}diff --git a/apps/web/app/(org)/dashboard/analytics/components/AnalyticsDashboard.tsx b/apps/web/app/(org)/dashboard/analytics/components/AnalyticsDashboard.tsxnew file mode 100644index 000000000..b88910e24--- /dev/null+++ b/apps/web/app/(org)/dashboard/analytics/components/AnalyticsDashboard.tsx@@ -0,0 +1,91 @@+"use client";++import { useState } from "react";+import { useQuery } from "@tanstack/react-query";++import { useDashboardContext } from "../../Contexts";+import type { AnalyticsRange, OrgAnalyticsResponse } from "../types";+import Header from "./Header";+import OtherStats from "./OtherStats";+import StatsChart from "./StatsChart";++const RANGE_OPTIONS: { value: AnalyticsRange; label: string }[] = [+ { value: "24h", label: "Last 24 hours" },+ { value: "7d", label: "Last 7 days" },+ { value: "30d", label: "Last 30 days" },+];++const formatNumber = (value: number) =>+ new Intl.NumberFormat("en-US", { maximumFractionDigits: 0 }).format(value);++export function AnalyticsDashboard() {+ const { activeOrganization } = useDashboardContext();+ const [range, setRange] = useState<AnalyticsRange>("7d");+ const orgId = activeOrganization?.organization.id;++ const query = useQuery<{ data: OrgAnalyticsResponse } | null>({+ queryKey: ["dashboard-analytics", orgId, range],+ queryFn: async () => {+ if (!orgId) return null;+ const response = await fetch(+ `/api/dashboard/analytics?orgId=${orgId}&range=${range}`,+ { cache: "no-store" }+ );+ console.log("response", response);+ if (!response.ok) throw new Error("Failed to load analytics");+ return (await response.json()) as { data: OrgAnalyticsResponse };+ },+ enabled: Boolean(orgId),+ staleTime: 60 * 1000,+ });++ const analytics = query.data?.data;++ if (!orgId) {+ return (+ <div className="rounded-xl border border-gray-5 bg-white p-6 text-gray-11">+ Select or join an organization to view analytics.+ </div>+ );+ }++ const otherStats = analytics+ ? {+ countries: analytics.breakdowns.countries,+ cities: analytics.breakdowns.cities,+ browsers: analytics.breakdowns.browsers,+ operatingSystems: analytics.breakdowns.operatingSystems,+ deviceTypes: analytics.breakdowns.devices,+ topCaps: analytics.breakdowns.topCaps,+ }+ : {+ countries: [],+ cities: [],+ browsers: [],+ operatingSystems: [],+ deviceTypes: [],+ topCaps: [],+ };++ return (+ <div className="space-y-8">+ <Header+ options={RANGE_OPTIONS}+ value={range}+ onChange={setRange}+ isLoading={query.isFetching}+ />+ <StatsChart+ counts={{+ caps: analytics?.counts.caps ?? 0,+ views: analytics?.counts.views ?? 0,+ comments: analytics?.counts.comments ?? 0,+ reactions: analytics?.counts.reactions ?? 0,+ }}+ data={analytics?.chart ?? []}+ isLoading={query.isLoading}+ />+ <OtherStats data={otherStats} isLoading={query.isLoading} />+ </div>+ );+}diff --git a/apps/web/app/(org)/dashboard/analytics/components/ChartArea.tsx b/apps/web/app/(org)/dashboard/analytics/components/ChartArea.tsxindex 732f481e5..6abc77ddd 100644--- a/apps/web/app/(org)/dashboard/analytics/components/ChartArea.tsx+++ b/apps/web/app/(org)/dashboard/analytics/components/ChartArea.tsx@@ -1,6 +1,6 @@"use client";-import { useId } from "react";+import { useId, useMemo } from "react";import { Area, AreaChart, CartesianGrid, XAxis, YAxis } from "recharts";import {type ChartConfig,@@ -11,14 +11,6 @@ import {export const description = "An area chart with gradient fill";-const chartData = Array.from({ length: 24 }, (_, i) => ({- hour: i + 1,- views: Math.floor(Math.random() * 100),- comments: Math.floor(Math.random() * 100),- reactions: Math.floor(Math.random() * 100),- caps: Math.floor(Math.random() * 100),-}));-const chartConfig = {views: {label: "Views",@@ -40,15 +32,50 @@ const chartConfig = {interface ChartAreaProps {selectedMetric: "caps" | "views" | "comments" | "reactions";+ data: Array<{+ bucket: string;+ caps: number;+ views: number;+ comments: number;+ reactions: number;+ }>;+ isLoading?: boolean;}-function ChartArea({ selectedMetric }: ChartAreaProps) {+function ChartArea({ selectedMetric, data, isLoading }: ChartAreaProps) {const viewsGradientId = useId();const commentsGradientId = useId();const reactionsGradientId = useId();const capsGradientId = useId();const glowFilterId = useId();+ const chartData = useMemo(() => {+ if (!data || data.length === 0) return [];+ const bucketDuration =+ data.length > 1+ ? new Date(data[1]!.bucket).getTime() - new Date(data[0]!.bucket).getTime()+ : 0;+ const hourly = bucketDuration > 0 && bucketDuration <= 60 * 60 * 1000;+ return data.map((point) => ({+ ...point,+ label: formatBucketLabel(point.bucket, hourly),+ }));+ }, [data]);++ if (isLoading && chartData.length === 0) {+ return (+ <div className="h-[300px] w-full animate-pulse rounded-xl bg-gray-3" />+ );+ }++ if (chartData.length === 0) {+ return (+ <div className="flex h-[300px] w-full flex-col items-center justify-center rounded-xl border border-dashed border-gray-5 text-sm text-gray-9">+ No analytics data yet.+ </div>+ );+ }+return (<ChartContainer className="h-[500px]" config={chartConfig}><AreaChart@@ -67,8 +94,8 @@ function ChartArea({ selectedMetric }: ChartAreaProps) {stroke="var(--gray-8)"opacity={0.3}/>- <XAxis- dataKey="hour"+ <XAxis+ dataKey="label"axisLine={false}tickMargin={10}interval={0}@@ -172,3 +199,14 @@ function ChartArea({ selectedMetric }: ChartAreaProps) {}export default ChartArea;++const formatBucketLabel = (bucket: string, hourly: boolean) => {+ const date = new Date(bucket);+ if (Number.isNaN(date.getTime())) return bucket;+ if (hourly)+ return date.toLocaleTimeString([], {+ hour: "numeric",+ minute: undefined,+ });+ return date.toLocaleDateString([], { month: "short", day: "numeric" });+};diff --git a/apps/web/app/(org)/dashboard/analytics/components/CompareDataDialog.tsx b/apps/web/app/(org)/dashboard/analytics/components/CompareDataDialog.tsxdeleted file mode 100644index ffa1ba73f..000000000--- a/apps/web/app/(org)/dashboard/analytics/components/CompareDataDialog.tsx+++ /dev/null@@ -1,260 +0,0 @@-import {- Button,- Dialog,- DialogContent,- DialogHeader,- DialogTitle,-} from "@cap/ui";-import { faChartSimple } from "@fortawesome/free-solid-svg-icons";-import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";-import { LayoutGroup } from "motion/react";-import { useRef, useState } from "react";-import { CompareDataDroppable, type FilterValue } from "./CompareFilters";-import { FiltersList } from "./FiltersList";-import CompareVideos from "./VideoFilters";-import VideosPicker from "./VideosPicker";--export const CompareDataDialog = ({- open,- onOpenChange,-}: {- open: boolean;- onOpenChange: (open: boolean) => void;-}) => {- const [droppedItems, setDroppedItems] = useState<{- compare: string | null;- compareTwo: string | null;- }>({- compare: null,- compareTwo: null,- });- const [droppedVideos, setDroppedVideos] = useState<{- video1: string | null;- video2: string | null;- }>({- video1: null,- video2: null,- });- const [isDragging, setIsDragging] = useState(false);- const [isVideoDragging, setIsVideoDragging] = useState(false);- const [currentDragValue, setCurrentDragValue] = useState<FilterValue | null>(- null,- );- const [currentDragVideo, setCurrentDragVideo] = useState<string | null>(null);-- const FILTERS: readonly FilterValue[] = [- "views",- "comments",- "reactions",- "shares",- "downloads",- "uploads",- "deletions",- "creations",- "edits",- ] as const;-- const VIDEOS: readonly string[] = [- "Video A",- "Video B",- "Video C",- "Video D",- ] as const;-- const [dragPosition, setDragPosition] = useState({ x: 0, y: 0 });- const [videoDragPosition, setVideoDragPosition] = useState({ x: 0, y: 0 });-- const compareRef = useRef<HTMLDivElement>(null);- const compareTwoRef = useRef<HTMLDivElement>(null);- const video1Ref = useRef<HTMLDivElement>(null);- const video2Ref = useRef<HTMLDivElement>(null);-- const handleDrop = (dropZoneId: "compare" | "compareTwo") => {- if (currentDragValue) {- setDroppedItems((prev) => ({- ...prev,- [dropZoneId]: currentDragValue,- }));- }- };-- const handleRemoveItem = (dropZoneId: "compare" | "compareTwo") => {- setDroppedItems((prev) => ({- ...prev,- [dropZoneId]: null,- }));- };-- const isFilterInUse = (value: string) => {- return droppedItems.compare === value || droppedItems.compareTwo === value;- };-- const checkDropZone = (x: number, y: number): string | null => {- const zones = [- { id: "compare", ref: compareRef },- { id: "compareTwo", ref: compareTwoRef },- ];-- for (const zone of zones) {- if (zone.ref.current) {- const rect = zone.ref.current.getBoundingClientRect();- if (- x >= rect.left &&- x <= rect.right &&- y >= rect.top &&- y <= rect.bottom- ) {- return zone.id;- }- }- }- return null;- };-- const handleVideoDrop = (dropZoneId: "video1" | "video2") => {- if (currentDragVideo) {- setDroppedVideos((prev) => ({- ...prev,- [dropZoneId]: currentDragVideo,- }));- }- };-- const handleRemoveVideo = (dropZoneId: "video1" | "video2") => {- setDroppedVideos((prev) => ({- ...prev,- [dropZoneId]: null,- }));- };-- const isVideoInUse = (videoId: string) => {- return droppedVideos.video1 === videoId || droppedVideos.video2 === videoId;- };-- const checkVideoDropZone = (x: number, y: number): string | null => {- const zones = [- { id: "video1", ref: video1Ref },- { id: "video2", ref: video2Ref },- ];-- for (const zone of zones) {- if (zone.ref.current) {- const rect = zone.ref.current.getBoundingClientRect();- if (- x >= rect.left &&- x <= rect.right &&- y >= rect.top &&- y <= rect.bottom- ) {- return zone.id;- }- }- }- return null;- };-- return (- <Dialog open={open} onOpenChange={onOpenChange}>- <DialogContent className="max-w-[766px]">- <DialogHeader- description="Visualize data comparisons between each other"- icon={<FontAwesomeIcon icon={faChartSimple} />}- >- <DialogTitle>Compare data</DialogTitle>- </DialogHeader>- <LayoutGroup>- <div className="flex flex-1 w-full h-full">- <FiltersList- filters={FILTERS}- isFilterInUse={isFilterInUse}- onFilterDragStart={(value) => {- setIsDragging(true);- setCurrentDragValue(value);- }}- onFilterDragEnd={(x, y) => {- setIsDragging(false);- const dropZone = checkDropZone(x, y);- if (dropZone) {- handleDrop(dropZone as "compare" | "compareTwo");- }- setCurrentDragValue(null);- }}- onFilterDrag={(x, y) => setDragPosition({ x, y })}- />- {/*Main side*/}- <div className="flex flex-col flex-1 h-full">- <div className="border-b border-gray-4 bg-gray-3">- <p className="px-4 py-2 text-xs font-medium text-gray-12 will-change-auto">- Analysis- </p>- </div>- <div className="flex flex-col flex-1 gap-5 justify-between p-4">- <div className="space-y-5">- <div className="flex justify-evenly items-end px-4 py-3 w-full rounded-full border bg-gray-3 border-gray-5">- <div className="flex flex-1 gap-2 items-center border-r border-gray-6">- <p className="text-[13px] font-medium text-gray-11 will-change-auto">- Compare- </p>- {/* biome-ignore lint: Static ID for drop zone identification */}- <CompareDataDroppable- id="compare"- ref={compareRef}- droppedValue={droppedItems.compare}- onRemove={() => handleRemoveItem("compare")}- isDragging={isDragging}- dragPosition={dragPosition}- />- </div>- <div className="flex flex-1 gap-2 justify-end items-center">- <p className="text-[13px] font-medium text-gray-11 will-change-auto">- with- </p>- {/* biome-ignore lint: Static ID for drop zone identification */}- <CompareDataDroppable- id="compareTwo"- ref={compareTwoRef}- droppedValue={droppedItems.compareTwo}- onRemove={() => handleRemoveItem("compareTwo")}- isDragging={isDragging}- dragPosition={dragPosition}- />- </div>- </div>- <VideosPicker- droppedVideos={droppedVideos}- onRemoveVideo={handleRemoveVideo}- isDragging={isVideoDragging}- dragPosition={videoDragPosition}- video1Ref={video1Ref}- video2Ref={video2Ref}- />- </div>- <Button className="w-full" size="sm" variant="dark">- Compare- </Button>- </div>- </div>- {/*Videos Picker*/}- <CompareVideos- videos={VIDEOS}- isVideoInUse={isVideoInUse}- onVideoDragStart={(videoId) => {- setIsVideoDragging(true);- setCurrentDragVideo(videoId);- }}- onVideoDragEnd={(x, y) => {- setIsVideoDragging(false);- const dropZone = checkVideoDropZone(x, y);- if (dropZone) {- handleVideoDrop(dropZone as "video1" | "video2");- }- setCurrentDragVideo(null);- }}- onVideoDrag={(x, y) => setVideoDragPosition({ x, y })}- />- </div>- </LayoutGroup>- </DialogContent>- </Dialog>- );-};diff --git a/apps/web/app/(org)/dashboard/analytics/components/Header.tsx b/apps/web/app/(org)/dashboard/analytics/components/Header.tsxindex a20397662..d486f767f 100644--- a/apps/web/app/(org)/dashboard/analytics/components/Header.tsx+++ b/apps/web/app/(org)/dashboard/analytics/components/Header.tsx@@ -1,40 +1,37 @@"use client";-import { Button, Select } from "@cap/ui";-import { useState } from "react";-import { CompareDataDialog } from "./CompareDataDialog";+import { Select } from "@cap/ui";+import type { AnalyticsRange } from "../types";import { faCalendar } from "@fortawesome/free-solid-svg-icons";import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";-export default function Header() {- const [openCompareDataDialog, setOpenCompareDataDialog] = useState(false);- return (- <>- <CompareDataDialog- open={openCompareDataDialog}- onOpenChange={setOpenCompareDataDialog}- />- <div className="flex gap-2 items-center">- <Select- variant="light"- icon={<FontAwesomeIcon icon={faCalendar} />}- size="md"- options={[- { value: "24_hours", label: "24 hours" },- { value: "7_days", label: "7 days" },- { value: "30_days", label: "30 days" },- ]}- onValueChange={() => {}}- placeholder="Time range"- />- <Button- size="sm"- variant="white"- onClick={() => setOpenCompareDataDialog(true)}- >- Compare data- </Button>- </div>- </>- );+interface HeaderProps {+ options: { value: AnalyticsRange; label: string }[];+ value: AnalyticsRange;+ onChange: (value: AnalyticsRange) => void;+ isLoading?: boolean;+}++export default function Header({+ options,+ value,+ onChange,+ isLoading,+}: HeaderProps) {+ return (+ <>+ <div className="flex gap-2 items-center">+ <Select+ placeholder="Select a range"+ variant="light"+ icon={<FontAwesomeIcon icon={faCalendar} />}+ size="md"+ options={options}+ value={value}+ onValueChange={(val) => onChange(val as AnalyticsRange)}+ disabled={isLoading}+ />+ </div>+ </>+ );}diff --git a/apps/web/app/(org)/dashboard/analytics/components/OtherStats.tsx b/apps/web/app/(org)/dashboard/analytics/components/OtherStats.tsxindex aff9033a7..31b0fa568 100644--- a/apps/web/app/(org)/dashboard/analytics/components/OtherStats.tsx+++ b/apps/web/app/(org)/dashboard/analytics/components/OtherStats.tsx@@ -7,7 +7,8 @@ import {faRecordVinyl,} from "@fortawesome/free-solid-svg-icons";import OtherStatBox from "./OtherStatBox";-import type {+import type { BreakdownRow } from "../types";+import TableCard, {BrowserRowData,CapRowData,CityRowData,@@ -15,22 +16,108 @@ import type {DeviceRowData,OSRowData,} from "./TableCard";-import TableCard from "./TableCard";export interface OtherStatsData {- countries: CountryRowData[];- cities: CityRowData[];- browsers: BrowserRowData[];- operatingSystems: OSRowData[];- deviceTypes: DeviceRowData[];- topCaps?: CapRowData[] | null;+ countries: BreakdownRow[];+ cities: BreakdownRow[];+ browsers: BreakdownRow[];+ operatingSystems: BreakdownRow[];+ deviceTypes: BreakdownRow[];+ topCaps?: Array<BreakdownRow & { id?: string }> | null;}interface OtherStatsProps {data: OtherStatsData;+ isLoading?: boolean;}-export default function OtherStats({ data }: OtherStatsProps) {+const deviceMap: Record<string, DeviceRowData["device"]> = {+ desktop: "desktop",+ mobile: "mobile",+ tablet: "tablet",+};++const toCountryRow = (row: BreakdownRow): CountryRowData => ({+ countryCode: row.name,+ name: row.name,+ views: row.views,+ comments: null,+ reactions: null,+ percentage: row.percentage,+});++const toCityRow = (row: BreakdownRow): CityRowData => ({+ countryCode: row.subtitle || "",+ name: row.subtitle ? `${row.name}, ${row.subtitle}` : row.name,+ views: row.views,+ comments: null,+ reactions: null,+ percentage: row.percentage,+});++const toBrowserRow = (row: BreakdownRow): BrowserRowData => ({+ browser: browserNameToSlug(row.name),+ name: row.name,+ views: row.views,+ comments: null,+ reactions: null,+ percentage: row.percentage,+});++const toOSRow = (row: BreakdownRow): OSRowData => ({+ os: osNameToKey(row.name),+ name: row.name,+ views: row.views,+ comments: null,+ reactions: null,+ percentage: row.percentage,+});++const toCapRow = (row: BreakdownRow & { id?: string }): CapRowData => ({+ name: row.name,+ views: row.views,+ comments: null,+ reactions: null,+ percentage: row.percentage,+});++const browserNameToSlug = (name: string): BrowserRowData["browser"] => {+ switch (name.toLowerCase()) {+ case "chrome":+ return "google-chrome";+ case "firefox":+ return "firefox";+ case "safari":+ return "safari";+ case "edge":+ case "internet explorer":+ return "explorer";+ case "opera":+ return "opera";+ case "brave":+ return "brave";+ default:+ return "google-chrome";+ }+};++const osNameToKey = (name: string): OSRowData["os"] => {+ switch (name.toLowerCase()) {+ case "macos":+ case "ios":+ return "ios";+ case "linux":+ return "linux";+ case "ubuntu":+ return "ubuntu";+ case "fedora":+ return "fedora";+ default:+ return "windows";+ }+};++export default function OtherStats({ data, isLoading }: OtherStatsProps) {return (<div className="grid grid-cols-1 gap-8 w-full xl:grid-cols-4"><OtherStatBox className="col-span-2" title="Geography" icon={faGlobe}>@@ -44,14 +131,16 @@ export default function OtherStats({ data }: OtherStatsProps) {"Reactions","Percentage",]}- rows={data.countries}+ rows={data.countries.map(toCountryRow)}type="country"+ isLoading={isLoading}/><TableCardtitle="Cities"columns={["City", "Views", "Comments", "Reactions", "Percentage"]}- rows={data.cities}+ rows={data.cities.map(toCityRow)}type="city"+ isLoading={isLoading}/></div></OtherStatBox>@@ -66,8 +155,9 @@ export default function OtherStats({ data }: OtherStatsProps) {"Reactions","Percentage",]}- rows={data.browsers}+ rows={data.browsers.map(toBrowserRow)}type="browser"+ isLoading={isLoading}/><TableCardtitle="Operating Systems"@@ -78,8 +168,9 @@ export default function OtherStats({ data }: OtherStatsProps) {"Reactions","Percentage",]}- rows={data.operatingSystems}+ rows={data.operatingSystems.map(toOSRow)}type="os"+ isLoading={isLoading}/></div></OtherStatBox>@@ -92,12 +183,20 @@ export default function OtherStats({ data }: OtherStatsProps) {<TableCardtitle="Device Type"columns={["Device", "Views", "Comments", "Reactions", "Percentage"]}- rows={data.deviceTypes}+ rows={data.deviceTypes.map((device) => ({+ device: deviceMap[device.name.toLowerCase()] ?? "desktop",+ name: device.name,+ views: device.views,+ comments: null,+ reactions: null,+ percentage: device.percentage,+ }))}type="device"+ isLoading={isLoading}/></div></OtherStatBox>- {data.topCaps && (+ {data.topCaps && data.topCaps.length > 0 && (<OtherStatBoxclassName="col-span-2"title="Top Caps"@@ -107,12 +206,13 @@ export default function OtherStats({ data }: OtherStatsProps) {<TableCardtitle="Caps"columns={["Cap", "Views", "Comments", "Reactions", "Percentage"]}- rows={data.topCaps}+ rows={data.topCaps.map(toCapRow)}type="cap"+ isLoading={isLoading}/></div></OtherStatBox>)}</div>);-}+}diff --git a/apps/web/app/(org)/dashboard/analytics/components/StatsChart.tsx b/apps/web/app/(org)/dashboard/analytics/components/StatsChart.tsxindex 974d494ca..0a6c010d4 100644--- a/apps/web/app/(org)/dashboard/analytics/components/StatsChart.tsx+++ b/apps/web/app/(org)/dashboard/analytics/components/StatsChart.tsx@@ -1,141 +1,161 @@"use client";import {- cloneElement,- type HTMLAttributes,- type SVGProps,- useRef,- useState,+ cloneElement,+ type HTMLAttributes,+ type SVGProps,+ useMemo,+ useRef,+ useState,} from "react";import {- CapIcon,- ChatIcon,- ClapIcon,- ReactionIcon,+ CapIcon,+ ChatIcon,+ ClapIcon,+ ReactionIcon,} from "@/app/(org)/dashboard/_components/AnimatedIcons";import { classNames } from "@/utils/helpers";import type { CapIconHandle } from "../../_components/AnimatedIcons/Cap";import ChartArea from "./ChartArea";type boxes = "caps" | "views" | "comments" | "reactions";+type ChartPoint = {+ bucket: string;+ caps: number;+ views: number;+ comments: number;+ reactions: number;+};++const formatCount = (value: number) => {+ if (value >= 1_000_000) return `${(value / 1_000_000).toFixed(1)}M`;+ if (value >= 1_000) return `${(value / 1_000).toFixed(1)}k`;+ return value.toLocaleString();+};+interface StatsChartProps {- counts: {- caps?: string;- views?: string;- chats?: string;- reactions?: string;- };- defaultSelectedBox?: boxes;+ counts: Record<boxes, number>;+ data: ChartPoint[];+ defaultSelectedBox?: boxes;+ isLoading?: boolean;}export default function StatsBox({- counts,- defaultSelectedBox = "caps",+ counts,+ data,+ defaultSelectedBox = "caps",+ isLoading,}: StatsChartProps) {- const [selectedBox, setSelectedBox] = useState<boxes>(defaultSelectedBox);+ const [selectedBox, setSelectedBox] = useState<boxes>(defaultSelectedBox);++ const capsBoxRef = useRef<CapIconHandle | null>(null);+ const viewsBoxRef = useRef<CapIconHandle | null>(null);+ const chatsBoxRef = useRef<CapIconHandle | null>(null);+ const reactionsBoxRef = useRef<CapIconHandle | null>(null);- const capsBoxRef = useRef<CapIconHandle | null>(null);- const viewsBoxRef = useRef<CapIconHandle | null>(null);- const chatsBoxRef = useRef<CapIconHandle | null>(null);- const reactionsBoxRef = useRef<CapIconHandle | null>(null);+ const selectHandler = (box: boxes) => {+ setSelectedBox(box);+ };- const selectHandler = (box: boxes) => {- setSelectedBox(box);- };+ const formattedCounts = useMemo(+ () => ({+ caps: formatCount(counts.caps),+ views: formatCount(counts.views),+ comments: formatCount(counts.comments),+ reactions: formatCount(counts.reactions),+ }),+ [counts]+ );- return (- <div className="flex flex-col gap-4 px-8 pt-8 w-full rounded-xl border bg-gray-1 border-gray-3">- <div className="flex flex-wrap gap-4">- {counts.caps && (- <StatBox- onClick={() => selectHandler("caps")}- isSelected={selectedBox === "caps"}- title="Caps"- value={counts.caps}- onMouseEnter={() => capsBoxRef.current?.startAnimation()}- onMouseLeave={() => capsBoxRef.current?.stopAnimation()}- icon={<CapIcon ref={capsBoxRef} size={20} />}- />- )}- {counts.views && (- <StatBox- onClick={() => selectHandler("views")}- isSelected={selectedBox === "views"}- title="Views"- value={counts.views}- onMouseEnter={() => viewsBoxRef.current?.startAnimation()}- onMouseLeave={() => viewsBoxRef.current?.stopAnimation()}- icon={<ClapIcon ref={viewsBoxRef} size={20} />}- />- )}- {counts.chats && (- <StatBox- onClick={() => selectHandler("comments")}- isSelected={selectedBox === "comments"}- title="Comments"- value={counts.chats}- onMouseEnter={() => chatsBoxRef.current?.startAnimation()}- onMouseLeave={() => chatsBoxRef.current?.stopAnimation()}- icon={<ChatIcon ref={chatsBoxRef} size={20} />}- />- )}- {counts.reactions && (- <StatBox- onClick={() => selectHandler("reactions")}- isSelected={selectedBox === "reactions"}- title="Reactions"- value={counts.reactions}- onMouseEnter={() => reactionsBoxRef.current?.startAnimation()}- onMouseLeave={() => reactionsBoxRef.current?.stopAnimation()}- icon={<ReactionIcon ref={reactionsBoxRef} size={20} />}- />- )}- </div>- <ChartArea selectedMetric={selectedBox} />- </div>- );+ return (+ <div className="flex flex-col gap-4 px-8 pt-8 w-full rounded-xl border bg-gray-1 border-gray-3">+ <div className="flex flex-wrap gap-4">+ <StatBox+ onClick={() => selectHandler("caps")}+ isSelected={selectedBox === "caps"}+ title="Caps"+ value={formattedCounts.caps}+ onMouseEnter={() => capsBoxRef.current?.startAnimation()}+ onMouseLeave={() => capsBoxRef.current?.stopAnimation()}+ icon={<CapIcon ref={capsBoxRef} size={20} />}+ />+ <StatBox+ onClick={() => selectHandler("views")}+ isSelected={selectedBox === "views"}+ title="Views"+ value={formattedCounts.views}+ onMouseEnter={() => viewsBoxRef.current?.startAnimation()}+ onMouseLeave={() => viewsBoxRef.current?.stopAnimation()}+ icon={<ClapIcon ref={viewsBoxRef} size={20} />}+ />+ <StatBox+ onClick={() => selectHandler("comments")}+ isSelected={selectedBox === "comments"}+ title="Comments"+ value={formattedCounts.comments}+ onMouseEnter={() => chatsBoxRef.current?.startAnimation()}+ onMouseLeave={() => chatsBoxRef.current?.stopAnimation()}+ icon={<ChatIcon ref={chatsBoxRef} size={20} />}+ />+ <StatBox+ onClick={() => selectHandler("reactions")}+ isSelected={selectedBox === "reactions"}+ title="Reactions"+ value={formattedCounts.reactions}+ onMouseEnter={() => reactionsBoxRef.current?.startAnimation()}+ onMouseLeave={() => reactionsBoxRef.current?.stopAnimation()}+ icon={<ReactionIcon ref={reactionsBoxRef} size={20} />}+ />+ </div>+ <ChartArea+ selectedMetric={selectedBox}+ data={data}+ isLoading={isLoading}+ />+ </div>+ );}interface StatBoxProps extends HTMLAttributes<HTMLDivElement> {- title: string;- value: string;- icon: React.ReactElement<SVGProps<SVGSVGElement>>;- isSelected?: boolean;+ title: string;+ value: string;+ icon: React.ReactElement<SVGProps<SVGSVGElement>>;+ isSelected?: boolean;}function StatBox({- title,- value,- icon,- isSelected = false,- ...props+ title,+ value,+ icon,+ isSelected = false,+ ...props}: StatBoxProps) {- return (- <div- {...props}- className={classNames(- "flex flex-col flex-1 min-w-[150px] gap-2 px-8 py-6 bg-transparent rounded-xl border transition-all duration-200 cursor-pointer group h-fit hover:bg-gray-3 border-gray-5",- isSelected && "bg-gray-3 border-gray-8",- )}- >- <div className="flex gap-2 items-center h-fit">- {cloneElement(icon, {- className: classNames(- "group-hover:text-gray-12 transition-colors duration-200",- isSelected ? "text-gray-12" : "text-gray-10",- ),- })}- <p- className={classNames(- "text-base font-medium transition-colors duration-200 group-hover:text-gray-12 text-gray-10",- isSelected && "text-gray-12",- )}- >- {title}- </p>- </div>- <p className="text-2xl font-medium transition-colors duration-200 text-gray-12">- {value}- </p>- </div>- );+ return (+ <div+ {...props}+ className={classNames(+ "flex flex-col flex-1 min-w-[150px] gap-2 px-8 py-6 bg-transparent rounded-xl border transition-all duration-200 cursor-pointer group h-fit hover:bg-gray-3 border-gray-5",+ isSelected && "bg-gray-3 border-gray-8"+ )}+ >+ <div className="flex gap-2 items-center h-fit">+ {cloneElement(icon, {+ className: classNames(+ "group-hover:text-gray-12 transition-colors duration-200",+ isSelected ? "text-gray-12" : "text-gray-10"+ ),+ })}+ <p+ className={classNames(+ "text-base font-medium transition-colors duration-200 group-hover:text-gray-12 text-gray-10",+ isSelected && "text-gray-12"+ )}+ >+ {title}+ </p>+ </div>+ <p className="text-2xl font-medium transition-colors duration-200 text-gray-12">+ {value}+ </p>+ </div>+ );}diff --git a/apps/web/app/(org)/dashboard/analytics/components/TableCard.tsx b/apps/web/app/(org)/dashboard/analytics/components/TableCard.tsxindex f9e50cbb6..72b27aa37 100644--- a/apps/web/app/(org)/dashboard/analytics/components/TableCard.tsx+++ b/apps/web/app/(org)/dashboard/analytics/components/TableCard.tsx@@ -1,20 +1,20 @@import {- LogoBadge,- Select,- Table,- TableBody,- TableCell,- TableHead,- TableHeader,- TableRow,+ LogoBadge,+ Select,+ Table,+ TableBody,+ TableCell,+ TableHead,+ TableHeader,+ TableRow,} from "@cap/ui";import {- faAppleWhole,- faDesktop,- faMobileScreen,- faFilter,- faTablet,- faDownLong,+ faAppleWhole,+ faDesktop,+ faDownLong,+ faFilter,+ faMobileScreen,+ faTablet,} from "@fortawesome/free-solid-svg-icons";import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";import clsx from "clsx";@@ -22,271 +22,276 @@ import getUnicodeFlagIcon from "country-flag-icons/unicode";import Image from "next/image";const countryCodeToIcon = (countryCode: string) => {- return getUnicodeFlagIcon(countryCode.toUpperCase());+ return getUnicodeFlagIcon(countryCode.toUpperCase());};+const formatNumber = (value?: number | null) =>+ value == null ? "—" : value.toLocaleString();+const formatPercentage = (value?: number | null) =>+ value == null ? "—" : `${Math.round(value * 100)}%`;+const skeletonBar = (width = 48) => (+ <div className="h-2 rounded-full bg-gray-5 animate-pulse" style={{ width }} />+);+type BrowserType =- | "google-chrome"- | "firefox"- | "safari"- | "explorer"- | "opera"- | "brave"- | "vivaldi"- | "yandex"- | "duckduckgo"- | "internet-explorer"- | "samsung-internet"- | "uc-browser"- | "qq-browser"- | "maxthon"- | "arora"- | "lunascape";+ | "google-chrome"+ | "firefox"+ | "safari"+ | "explorer"+ | "opera"+ | "brave"+ | "vivaldi"+ | "yandex"+ | "duckduckgo"+ | "internet-explorer"+ | "samsung-internet"+ | "uc-browser"+ | "qq-browser"+ | "maxthon"+ | "arora"+ | "lunascape";type OperatingSystemType = "windows" | "ios" | "linux" | "fedora" | "ubuntu";type DeviceType = "desktop" | "tablet" | "mobile";export interface CountryRowData {- countryCode: string;- name: string;- views: string;- comments: string;- reactions: string;- percentage: string;+ countryCode: string;+ name: string;+ views: number;+ comments?: number | null;+ reactions?: number | null;+ percentage: number;}export interface CityRowData {- countryCode: string;- name: string;- views: string;- comments: string;- reactions: string;- percentage: string;+ countryCode: string;+ name: string;+ views: number;+ comments?: number | null;+ reactions?: number | null;+ percentage: number;}export interface BrowserRowData {- browser: BrowserType;- name: string;- views: string;- comments: string;- reactions: string;- percentage: string;+ browser: BrowserType;+ name: string;+ views: number;+ comments?: number | null;+ reactions?: number | null;+ percentage: number;}export interface OSRowData {- os: OperatingSystemType;- name: string;- views: string;- comments: string;- reactions: string;- percentage: string;+ os: OperatingSystemType;+ name: string;+ views: number;+ comments?: number | null;+ reactions?: number | null;+ percentage: number;}export interface DeviceRowData {- device: DeviceType;- name: string;- views: string;- comments: string;- reactions: string;- percentage: string;+ device: DeviceType;+ name: string;+ views: number;+ comments?: number | null;+ reactions?: number | null;+ percentage: number;}export interface CapRowData {- name: string;- views: string;- comments: string;- reactions: string;- percentage: string;+ name: string;+ views: number;+ comments?: number | null;+ reactions?: number | null;+ percentage: number;}export interface TableCardProps {- title: string;- columns: string[];- tableClassname?: string;- type: "country" | "city" | "browser" | "os" | "device" | "cap";- rows:- | CountryRowData[]- | CityRowData[]- | BrowserRowData[]- | OSRowData[]- | DeviceRowData[]- | CapRowData[];+ title: string;+ columns: string[];+ tableClassname?: string;+ type: "country" | "city" | "browser" | "os" | "device" | "cap";+ rows:+ | CountryRowData[]+ | CityRowData[]+ | BrowserRowData[]+ | OSRowData[]+ | DeviceRowData[]+ | CapRowData[];+ isLoading?: boolean;}const TableCard = ({- title,- columns,- rows,- type,- tableClassname,+ title,+ columns,+ rows,+ type,+ tableClassname,+ isLoading,}: TableCardProps) => {- return (- <div className="p-5 w-full rounded-xl border bg-gray-2 border-gray-4">- <div className="flex flex-1 gap-2 justify-between items-center h-[48px]">- <p className="text-lg font-medium text-gray-12">{title}</p>- <Select- variant="light"- icon={<FontAwesomeIcon icon={faFilter} />}- size="md"- options={[- { label: "Views", value: "views_desc" },- { label: "Comments", value: "comments_desc" },- { label: "Reactions", value: "reactions_desc" },- { label: "Percentage", value: "percentage_desc" },- ]}- onValueChange={() => {}}- placeholder="Sort by"- />- </div>- <div className="w-full">- <Table- className={clsx(- "w-full border-separate table-fixed border-spacing-y-0",- tableClassname,- )}- >- <TableHeader>- <TableRow className="w-full">- {columns.map((column) => (- <TableHead- key={column}- className="border-b px-[6px] text-nowrap border-gray-4 bg-gray-2 text-gray-10"- >- {column}- </TableHead>- ))}- </TableRow>- </TableHeader>- </Table>- <div className="h-[400px] overflow-auto custom-scroll pr-2">- <Table- className={clsx(- "w-full border-separate table-fixed border-spacing-y-2",- tableClassname,- )}- >- <TableBody className="before:content-[''] before:block w-full">- {rows.map((row) => (- <TableRow className="w-full" key={row.name}>- <TableCell className="p-2.5 text-sm rounded-l-lg border-l border-y text-gray-11 bg-gray-3 border-gray-5">- <div className="flex gap-2 items-center min-w-0">- <span className="flex-shrink-0 fill-[var(--gray-12)]">- {getIconForRow(row, type)}- </span>- <span className="truncate">{row.name}</span>- </div>- </TableCell>- <TableCell className="py-2.5 px-3 text-sm text-nowrap text-gray-11 bg-gray-3 border-y border-gray-5 whitespace-nowrap">- {row.views}- </TableCell>- <TableCell className="p-2.5 px-3 text-sm text-nowrap text-gray-11 bg-gray-3 border-y border-gray-5 whitespace-nowrap">- {row.comments}- </TableCell>- <TableCell className="p-2.5 px-3 text-sm text-nowrap text-gray-11 bg-gray-3 border-y border-gray-5 whitespace-nowrap">- {row.reactions}- </TableCell>- <TableCell className="p-2.5 px-3 text-sm text-nowrap rounded-r-lg border-r text-gray-11 bg-gray-3 border-y border-gray-5 whitespace-nowrap">- {row.percentage}- </TableCell>- </TableRow>- ))}- </TableBody>- </Table>- </div>- </div>- </div>- );+ const hasRows = rows.length > 0;+ const placeholders = Array.from({ length: 4 }, (_, index) => ({+ name: `placeholder-${index}`,+ views: 0,+ comments: null,+ reactions: null,+ percentage: 0,+ })) as TableCardProps["rows"];++ const displayRows = hasRows ? rows : placeholders;++ return (+ <div className="p-5 w-full rounded-xl border bg-gray-2 border-gray-4">+ <div className="flex flex-1 gap-2 justify-between items-center h-[48px]">+ <p className="text-lg font-medium text-gray-12">{title}</p>+ <Select+ variant="light"+ placeholder="Views"+ icon={<FontAwesomeIcon icon={faFilter} className="text-gray-11" />}+ options={[+ { value: "views", label: "Views" },+ { value: "comments", label: "Comments" },+ { value: "reactions", label: "Reactions" },+ ]}+ value="views"+ onValueChange={() => {}}+ size="sm"+ />+ </div>+ <div className="flex flex-1 flex-col gap-4 justify-center">+ <div className="relative w-full">+ <Table className="w-full border-separate table-fixed border-spacing-y-2">+ <TableHeader className="text-xs uppercase text-gray-11 opacity-70">+ <TableRow>+ {columns.map((column) => (+ <TableHead className="px-3 text-left" key={column}>+ {column}+ </TableHead>+ ))}+ </TableRow>+ </TableHeader>+ <TableBody+ className={clsx(+ "before:content-[''] before:block w-full",+ tableClassname+ )}+ >+ {displayRows.map((row, index) => {+ const typedRow = row as {+ comments?: number | null;+ reactions?: number | null;+ };+ return (+ <TableRow className="w-full" key={row.name ?? index}>+ <TableCell className="p-2.5 text-sm rounded-l-lg border-l border-y text-gray-11 bg-gray-3 border-gray-5">+ <div className="flex gap-2 items-center min-w-0">+ <span className="flex-shrink-0 fill-[var(--gray-12)]">+ {hasRows ? getIconForRow(row, type) : skeletonBar(16)}+ </span>+ <span className="truncate">+ {hasRows ? row.name : ""}+ </span>+ </div>+ </TableCell>+ <TableCell className="py-2.5 px-3 text-sm text-nowrap text-gray-11 bg-gray-3 border-y border-gray-5 whitespace-nowrap">+ {hasRows ? formatNumber(row.views) : skeletonBar()}+ </TableCell>+ <TableCell className="p-2.5 px-3 text-sm text-nowrap text-gray-11 bg-gray-3 border-y border-gray-5 whitespace-nowrap">+ {hasRows+ ? formatNumber(typedRow.comments)+ : skeletonBar()}+ </TableCell>+ <TableCell className="p-2.5 px-3 text-sm text-nowrap text-gray-11 bg-gray-3 border-y border-gray-5 whitespace-nowrap">+ {hasRows+ ? formatNumber(typedRow.reactions)+ : skeletonBar()}+ </TableCell>+ <TableCell className="p-2.5 px-3 text-sm text-nowrap rounded-r-lg border-r text-gray-11 bg-gray-3 border-y border-gray-5 whitespace-nowrap">+ {hasRows+ ? formatPercentage(row.percentage)+ : skeletonBar(32)}+ </TableCell>+ </TableRow>+ );+ })}+ </TableBody>+ </Table>+ </div>+ </div>+ </div>+ );};const getIconForRow = (- row:- | CountryRowData- | CityRowData- | BrowserRowData- | OSRowData- | DeviceRowData- | CapRowData,- type: TableCardProps["type"],+ row:+ | CountryRowData+ | CityRowData+ | BrowserRowData+ | OSRowData+ | DeviceRowData+ | CapRowData,+ type: TableCardProps["type"]) => {- switch (type) {- case "country":- return countryCodeToIcon((row as CountryRowData).countryCode);- case "city":- return countryCodeToIcon((row as CityRowData).countryCode);- case "browser":- return <BrowserIcon browser={(row as BrowserRowData).browser} />;- case "os":- return <OperatingSystemIcon operatingSystem={(row as OSRowData).os} />;- case "device": {- const device = (row as DeviceRowData).device;- const iconMap = {- desktop: faDesktop,- tablet: faTablet,- mobile: faMobileScreen,- };- return (- <FontAwesomeIcon icon={iconMap[device]} className="text-gray-12" />- );- }- case "cap":- return <LogoBadge className="size-4" />;- default:- return null;- }+ switch (type) {+ case "country":+ return countryCodeToIcon((row as CountryRowData).countryCode);+ case "city":+ return countryCodeToIcon((row as CityRowData).countryCode);+ case "browser":+ return <BrowserIcon browser={(row as BrowserRowData).browser} />;+ case "os":+ return <OperatingSystemIcon operatingSystem={(row as OSRowData).os} />;+ case "device": {+ const device = (row as DeviceRowData).device;+ const iconMap = {+ desktop: faDesktop,+ tablet: faTablet,+ mobile: faMobileScreen,+ };+ return (+ <FontAwesomeIcon icon={iconMap[device]} className="text-gray-12" />+ );+ }+ case "cap":+ return <LogoBadge className="size-4" />;+ default:+ return null;+ }};type OperatingSystemIconProps = {- operatingSystem: "windows" | "ios" | "linux" | "fedora" | "ubuntu";+ operatingSystem: OperatingSystemType;};const OperatingSystemIcon = ({ operatingSystem }: OperatingSystemIconProps) => {- if (operatingSystem === "ios") {- return <FontAwesomeIcon className="text-gray-12" icon={faAppleWhole} />;- } else {- return (- <Image- src={`/logos/os/${operatingSystem}.svg`}- alt={operatingSystem}- width={16}- height={16}- className="size-4"- />- );- }+ if (operatingSystem === "ios") {+ return <FontAwesomeIcon className="text-gray-12" icon={faAppleWhole} />;+ }+ return (+ <Image+ src={`/logos/os/${operatingSystem}.svg`}+ alt={operatingSystem}+ width={16}+ height={16}+ className="size-4"+ />+ );};type BrowserIconProps = {- browser:- | "google-chrome"- | "firefox"- | "safari"- | "explorer"- | "opera"- | "brave"- | "vivaldi"- | "yandex"- | "duckduckgo"- | "internet-explorer"- | "samsung-internet"- | "uc-browser"- | "qq-browser"- | "maxthon"- | "arora"- | "lunascape"- | "lunascape";+ browser: BrowserType;};-const BrowserIcon = ({ browser }: BrowserIconProps) => {- return (- <Image- src={`/logos/browsers/${browser}.svg`}- alt={browser}- width={16}- height={16}- className="size-4"- />- );-};+const BrowserIcon = ({ browser }: BrowserIconProps) => (+ <Image+ src={`/logos/browsers/${browser}.svg`}+ alt={browser}+ width={16}+ height={16}+ className="size-4"+ />+);export default TableCard;diff --git a/apps/web/app/(org)/dashboard/analytics/data.ts b/apps/web/app/(org)/dashboard/analytics/data.tsnew file mode 100644index 000000000..63f0d4000--- /dev/null+++ b/apps/web/app/(org)/dashboard/analytics/data.ts@@ -0,0 +1,640 @@+import { db } from "@cap/database";+import { comments, videos } from "@cap/database/schema";+import { Tinybird } from "@cap/web-backend";+import { and, between, eq, inArray, sql } from "drizzle-orm";+import { Effect } from "effect";++import { runPromise } from "@/lib/server";++import type {+ AnalyticsRange,+ BreakdownRow,+ OrgAnalyticsResponse,+} from "./types";++type VideoRow = typeof videos.$inferSelect;+type OrgId = VideoRow["orgId"];+type VideoId = VideoRow["id"];++type CountSeriesRow = { bucket: string; count: number };+type ViewSeriesRow = { bucket: string; views: number };+type BreakdownSourceRow = { name: string; views: number; subtitle?: string };+type TopCapRow = { videoId: string; views: number };++type TinybirdAnalyticsData = {+ viewSeries: ViewSeriesRow[];+ countries: BreakdownSourceRow[];+ cities: BreakdownSourceRow[];+ browsers: BreakdownSourceRow[];+ devices: BreakdownSourceRow[];+ operatingSystems: BreakdownSourceRow[];+ topCapsRaw: TopCapRow[];+};++const RANGE_CONFIG: Record<AnalyticsRange, { hours: number; bucket: "hour" | "day" }> = {+ "24h": { hours: 24, bucket: "hour" },+ "7d": { hours: 7 * 24, bucket: "day" },+ "30d": { hours: 30 * 24, bucket: "day" },+};++const escapeLiteral = (value: string) => value.replace(/'/g, "''");+const toDateString = (date: Date) => date.toISOString().slice(0, 10);+const toDateTimeString = (date: Date) => date.toISOString().slice(0, 19).replace("T", " ");++const normalizeBucket = (input: string | null | undefined, bucket: "hour" | "day") => {+ if (!input) return undefined;+ if (input.endsWith("Z")) return input;+ if (bucket === "day" && input.length === 10) return `${input}T00:00:00Z`;+ return `${input.replace(" ", "T")}Z`;+};++const formatBucketTimestamp = (value: Date) =>+ // Strip milliseconds so we can string-compare with MySQL/Tinybird buckets+ `${value.toISOString().slice(0, 19)}Z`;++const buildBuckets = (from: Date, to: Date, bucket: "hour" | "day") => {+ const size = bucket === "hour" ? 60 * 60 * 1000 : 24 * 60 * 60 * 1000;+ const buckets: string[] = [];+ const start = Math.floor(from.getTime() / size) * size;+ const end = Math.floor(to.getTime() / size) * size;+ for (let ts = start; ts <= end; ts += size) {+ buckets.push(formatBucketTimestamp(new Date(ts)));+ }+ return buckets;+};++const fallbackIfEmpty = <Row>(+ primary: Effect.Effect<Row[], never, never>,+ fallback?: Effect.Effect<Row[], never, never>,+) =>+ fallback+ ? primary.pipe(+ Effect.flatMap((rows) =>+ rows.length > 0 ? Effect.succeed(rows) : fallback,+ ),+ )+ : primary;++const withTinybirdFallback = <Row>(+ effect: Effect.Effect<unknown, unknown, never>,+) =>+ effect.pipe(+ Effect.catchAll((e) => {+ console.error("tinybird query error", e);+ return Effect.succeed<{ data: Row[] }>({ data: [] as Row[] });+ }),+ Effect.map((res) => {+ console.log("tinybird raw response", JSON.stringify(res, null, 2));+ const response = res as { data: unknown[] };+ const data = response.data ?? [];+ console.log("tinybird data array", JSON.stringify(data, null, 2));+ const filtered = data.filter((item): item is Row => {+ const isObject = typeof item === "object" && item !== null;+ if (!isObject) {+ console.log("filtered out non-object item", typeof item, item);+ }+ return isObject;+ }) as Row[];+ console.log("tinybird filtered rows", JSON.stringify(filtered, null, 2));+ return filtered;+ }),+ );++export const getOrgAnalyticsData = async (+ orgId: string,+ range: AnalyticsRange,+): Promise<OrgAnalyticsResponse> => {+ const rangeConfig = RANGE_CONFIG[range];+ const to = new Date();+ const from = new Date(to.getTime() - rangeConfig.hours * 60 * 60 * 1000);+ const buckets = buildBuckets(from, to, rangeConfig.bucket);+ const typedOrgId = orgId as OrgId;++ const [capsSeries, commentSeries, reactionSeries] = await Promise.all([+ queryVideoSeries(typedOrgId, from, to, rangeConfig.bucket),+ queryCommentsSeries(typedOrgId, from, to, "text", rangeConfig.bucket),+ queryCommentsSeries(typedOrgId, from, to, "emoji", rangeConfig.bucket),+ ]);++ const tinybirdData = await runPromise(+ Effect.gen(function* () {+ const tinybird = yield* Tinybird;+ console.log("getOrgAnalyticsData - orgId:", orgId, "range:", range);+ console.log("getOrgAnalyticsData - from:", from.toISOString(), "to:", to.toISOString());++ const viewSeries = yield* queryViewSeries(+ tinybird,+ typedOrgId,+ from,+ to,+ rangeConfig.bucket,+ );+ console.log("getOrgAnalyticsData - viewSeries:", JSON.stringify(viewSeries, null, 2));++ const countries = yield* queryCountries(tinybird, typedOrgId, from, to);+ console.log("getOrgAnalyticsData - countries:", JSON.stringify(countries, null, 2));++ const cities = yield* queryCities(tinybird, typedOrgId, from, to);+ console.log("getOrgAnalyticsData - cities:", JSON.stringify(cities, null, 2));++ const browsers = yield* queryBrowsers(tinybird, typedOrgId, from, to);+ console.log("getOrgAnalyticsData - browsers:", JSON.stringify(browsers, null, 2));++ const devices = yield* queryDevices(tinybird, typedOrgId, from, to);+ console.log("getOrgAnalyticsData - devices:", JSON.stringify(devices, null, 2));++ const operatingSystems = yield* queryOperatingSystems(+ tinybird,+ typedOrgId,+ from,+ to,+ );+ console.log("getOrgAnalyticsData - operatingSystems:", JSON.stringify(operatingSystems, null, 2));++ const topCapsRaw = yield* queryTopCaps(tinybird, typedOrgId, from, to);+ console.log("getOrgAnalyticsData - topCapsRaw:", JSON.stringify(topCapsRaw, null, 2));++ return {+ viewSeries,+ countries,+ cities,+ browsers,+ devices,+ operatingSystems,+ topCapsRaw,+ } satisfies TinybirdAnalyticsData;+ }),+ );++ const totalViews = tinybirdData.viewSeries.reduce((sum, row) => sum + row.views, 0);+ const totalCaps = capsSeries.reduce((sum, row) => sum + row.count, 0);+ const totalComments = commentSeries.reduce((sum, row) => sum + row.count, 0);+ const totalReactions = reactionSeries.reduce((sum, row) => sum + row.count, 0);++ const chartData = buckets.map((bucket) => ({+ bucket,+ caps: capsSeries.find((row) => row.bucket === bucket)?.count ?? 0,+ views: tinybirdData.viewSeries.find((row) => row.bucket === bucket)?.views ?? 0,+ comments: commentSeries.find((row) => row.bucket === bucket)?.count ?? 0,+ reactions: reactionSeries.find((row) => row.bucket === bucket)?.count ?? 0,+ }));++ const videoNames = await loadVideoNames(+ tinybirdData.topCapsRaw.map((cap) => cap.videoId).filter(Boolean),+ );++ return {+ counts: {+ caps: totalCaps,+ views: totalViews,+ comments: totalComments,+ reactions: totalReactions,+ },+ chart: chartData,+ breakdowns: {+ countries: formatBreakdown(+ tinybirdData.countries,+ totalViews,+ (row) => row.name,+ ),+ cities: formatBreakdown(+ tinybirdData.cities,+ totalViews,+ (row) => row.name,+ ),+ browsers: formatBreakdown(+ tinybirdData.browsers,+ totalViews,+ (row) => row.name,+ ),+ operatingSystems: formatBreakdown(+ tinybirdData.operatingSystems,+ totalViews,+ (row) => row.name,+ ),+ devices: formatBreakdown(+ tinybirdData.devices,+ totalViews,+ (row) => row.name,+ ),+ topCaps: tinybirdData.topCapsRaw.map((row) => ({+ id: row.videoId,+ name: videoNames.get(row.videoId) ?? row.videoId,+ views: row.views,+ percentage: totalViews > 0 ? row.views / totalViews : 0,+ })),+ },+ };+};++const formatBreakdown = <T extends { name: string; views: number }>(+ rows: T[],+ totalViews: number,+ getName: (row: T) => string,+): BreakdownRow[] =>+ rows.map((row) => ({+ name: getName(row),+ views: row.views,+ percentage: totalViews > 0 ? row.views / totalViews : 0,+ }));++const loadVideoNames = async (videoIds: ReadonlyArray<string>) => {+ if (videoIds.length === 0) return new Map<string, string>();+ const typedVideoIds = videoIds.map((id) => id as VideoId);+ const records = await db()+ .select({ id: videos.id, name: videos.name })+ .from(videos)+ .where(inArray(videos.id, typedVideoIds));+ return new Map(records.map((record) => [record.id, record.name]));+};++const queryVideoSeries = async (+ orgId: OrgId,+ from: Date,+ to: Date,+ bucket: "hour" | "day",+): Promise<CountSeriesRow[]> => {+ const bucketExpr =+ bucket === "hour"+ ? sql<string>`DATE_FORMAT(${videos.createdAt}, '%Y-%m-%dT%H:00:00Z')`+ : sql<string>`DATE_FORMAT(${videos.createdAt}, '%Y-%m-%dT00:00:00Z')`;++ const rows = await db()+ .select({ bucket: bucketExpr, count: sql<number>`COUNT(*)` })+ .from(videos)+ .where(and(eq(videos.orgId, orgId), between(videos.createdAt, from, to)))+ .groupBy(bucketExpr);++ return rows+ .map((row) => ({+ bucket: normalizeBucket(row.bucket, bucket),+ count: Number(row.count) || 0,+ }))+ .filter((row): row is CountSeriesRow => Boolean(row.bucket));+};++const queryCommentsSeries = async (+ orgId: OrgId,+ from: Date,+ to: Date,+ type: "text" | "emoji",+ bucket: "hour" | "day",+): Promise<CountSeriesRow[]> => {+ const column = comments.createdAt;+ const bucketExpr =+ bucket === "hour"+ ? sql<string>`DATE_FORMAT(${column}, '%Y-%m-%dT%H:00:00Z')`+ : sql<string>`DATE_FORMAT(${column}, '%Y-%m-%dT00:00:00Z')`;++ const rows = await db()+ .select({ bucket: bucketExpr, count: sql<number>`COUNT(*)` })+ .from(comments)+ .innerJoin(videos, eq(comments.videoId, videos.id))+ .where(+ and(+ eq(videos.orgId, orgId),+ eq(comments.type, type),+ between(comments.createdAt, from, to),+ ),+ )+ .groupBy(bucketExpr);++ return rows+ .map((row) => ({+ bucket: normalizeBucket(row.bucket, bucket),+ count: Number(row.count) || 0,+ }))+ .filter((row): row is CountSeriesRow => Boolean(row.bucket));+};++const queryViewSeries = (+ tinybird: Tinybird,+ orgId: OrgId,+ from: Date,+ to: Date,+ bucket: "hour" | "day",+) => {+ const bucketFormatter = bucket === "hour" ? "%Y-%m-%dT%H:00:00Z" : "%Y-%m-%dT00:00:00Z";+ const rawSql = `+ SELECT+ formatDateTime(${bucket === "hour" ? "toStartOfHour" : "toStartOfDay"}(timestamp), '${bucketFormatter}') as bucket,+ uniq(session_id) as views+ FROM analytics_events+ WHERE action = 'page_hit'+ AND tenant_id = '${escapeLiteral(orgId)}'+ AND timestamp BETWEEN toDateTime('${toDateTimeString(from)}') AND toDateTime('${toDateTimeString(to)}')+ GROUP BY bucket+ ORDER BY bucket+ `;++ const aggregatedSql = `+ SELECT+ formatDateTime(date, '${bucketFormatter}') as bucket,+ uniqMerge(visits) as views+ FROM analytics_pages_mv+ WHERE tenant_id = '${escapeLiteral(orgId)}'+ AND date BETWEEN toDate('${toDateString(from)}') AND toDate('${toDateString(to)}')+ GROUP BY bucket+ ORDER BY bucket+ `;++ type Row = { bucket: string; views: number };+ const rawEffect = withTinybirdFallback<Row>(tinybird.querySql<Row>(rawSql));+ const effect =+ bucket === "hour"+ ? rawEffect+ : fallbackIfEmpty(+ withTinybirdFallback<Row>(tinybird.querySql<Row>(aggregatedSql)),+ rawEffect,+ );++ return effect.pipe(+ Effect.map((rows) =>+ rows.map((row) => ({+ bucket: row.bucket,+ views: Number(row.views) || 0,+ })),+ ),+ );+};++const queryCountries = (+ tinybird: Tinybird,+ orgId: OrgId,+ from: Date,+ to: Date,+) => {+ const aggregatedSql = `+ SELECT+ country as name,+ uniqMerge(visits) as views+ FROM analytics_pages_mv+ WHERE tenant_id = '${escapeLiteral(orgId)}'+ AND date BETWEEN toDate('${toDateString(from)}') AND toDate('${toDateString(to)}')+ AND country != ''+ GROUP BY name+ ORDER BY views DESC+ LIMIT 10+ `;++ const rawSql = `+ SELECT+ coalesce(nullIf(country, ''), '') as name,+ uniq(session_id) as views+ FROM analytics_events+ WHERE action = 'page_hit'+ AND tenant_id = '${escapeLiteral(orgId)}'+ AND timestamp BETWEEN toDateTime('${toDateTimeString(from)}') AND toDateTime('${toDateTimeString(to)}')+ AND country != ''+ GROUP BY name+ ORDER BY views DESC+ LIMIT 10+ `;++ type Row = { name: string; views: number };+ return fallbackIfEmpty(+ withTinybirdFallback<Row>(tinybird.querySql<Row>(aggregatedSql)),+ withTinybirdFallback<Row>(tinybird.querySql<Row>(rawSql)),+ ).pipe(+ Effect.map((rows) =>+ rows.map((row) => ({+ name: row.name,+ views: Number(row.views) || 0,+ })),+ ),+ );+};++const queryCities = (+ tinybird: Tinybird,+ orgId: OrgId,+ from: Date,+ to: Date,+) => {+ const aggregatedSql = `+ SELECT+ country as country,+ city as city,+ uniqMerge(visits) as views+ FROM analytics_pages_mv+ WHERE tenant_id = '${escapeLiteral(orgId)}'+ AND date BETWEEN toDate('${toDateString(from)}') AND toDate('${toDateString(to)}')+ AND city != ''+ GROUP BY country, city+ ORDER BY views DESC+ LIMIT 10+ `;++ const rawSql = `+ SELECT+ coalesce(nullIf(country, ''), '') as country,+ coalesce(nullIf(city, ''), '') as city,+ uniq(session_id) as views+ FROM analytics_events+ WHERE action = 'page_hit'+ AND tenant_id = '${escapeLiteral(orgId)}'+ AND timestamp BETWEEN toDateTime('${toDateTimeString(from)}') AND toDateTime('${toDateTimeString(to)}')+ AND city != ''+ GROUP BY country, city+ ORDER BY views DESC+ LIMIT 10+ `;++ type Row = { country: string; city: string; views: number };+ return fallbackIfEmpty(+ withTinybirdFallback<Row>(tinybird.querySql<Row>(aggregatedSql)),+ withTinybirdFallback<Row>(tinybird.querySql<Row>(rawSql)),+ ).pipe(+ Effect.map((rows) =>+ rows.map((row) => ({+ name: row.city,+ subtitle: row.country,+ views: Number(row.views) || 0,+ })),+ ),+ );+};++const queryBrowsers = (+ tinybird: Tinybird,+ orgId: OrgId,+ from: Date,+ to: Date,+) => {+ const aggregatedSql = `+ SELECT+ browser as name,+ uniq(session_id) as views+ FROM analytics_sessions_mv+ WHERE tenant_id = '${escapeLiteral(orgId)}'+ AND date BETWEEN toDate('${toDateString(from)}') AND toDate('${toDateString(to)}')+ GROUP BY name+ ORDER BY views DESC+ LIMIT 10+ `;++ const rawSql = `+ SELECT+ coalesce(nullIf(browser, ''), 'unknown') as name,+ uniq(session_id) as views+ FROM analytics_events+ WHERE action = 'page_hit'+ AND tenant_id = '${escapeLiteral(orgId)}'+ AND timestamp BETWEEN toDateTime('${toDateTimeString(from)}') AND toDateTime('${toDateTimeString(to)}')+ GROUP BY name+ ORDER BY views DESC+ LIMIT 10+ `;++ type Row = { name: string; views: number };+ return fallbackIfEmpty(+ withTinybirdFallback<Row>(tinybird.querySql<Row>(aggregatedSql)),+ withTinybirdFallback<Row>(tinybird.querySql<Row>(rawSql)),+ ).pipe(+ Effect.map((rows) =>+ rows.map((row) => ({+ name: row.name,+ views: Number(row.views) || 0,+ })),+ ),+ );+};++const queryDevices = (+ tinybird: Tinybird,+ orgId: OrgId,+ from: Date,+ to: Date,+) => {+ const aggregatedSql = `+ SELECT+ device as name,+ uniq(session_id) as views+ FROM analytics_sessions_mv+ WHERE tenant_id = '${escapeLiteral(orgId)}'+ AND date BETWEEN toDate('${toDateString(from)}') AND toDate('${toDateString(to)}')+ GROUP BY name+ ORDER BY views DESC+ LIMIT 10+ `;++ const rawSql = `+ SELECT+ coalesce(nullIf(device, ''), 'desktop') as name,+ uniq(session_id) as views+ FROM analytics_events+ WHERE action = 'page_hit'+ AND tenant_id = '${escapeLiteral(orgId)}'+ AND timestamp BETWEEN toDateTime('${toDateTimeString(from)}') AND toDateTime('${toDateTimeString(to)}')+ GROUP BY name+ ORDER BY views DESC+ LIMIT 10+ `;++ type Row = { name: string; views: number };+ return fallbackIfEmpty(+ withTinybirdFallback<Row>(tinybird.querySql<Row>(aggregatedSql)),+ withTinybirdFallback<Row>(tinybird.querySql<Row>(rawSql)),+ ).pipe(+ Effect.map((rows) =>+ rows.map((row) => ({+ name: row.name,+ views: Number(row.views) || 0,+ })),+ ),+ );+};++const queryOperatingSystems = (+ tinybird: Tinybird,+ orgId: OrgId,+ from: Date,+ to: Date,+) => {+ const aggregatedSql = `+ SELECT+ os as name,+ uniq(session_id) as views+ FROM analytics_sessions_mv+ WHERE tenant_id = '${escapeLiteral(orgId)}'+ AND date BETWEEN toDate('${toDateString(from)}') AND toDate('${toDateString(to)}')+ GROUP BY name+ ORDER BY views DESC+ LIMIT 10+ `;++ const rawSql = `+ SELECT+ coalesce(nullIf(os, ''), 'unknown') as name,+ uniq(session_id) as views+ FROM analytics_events+ WHERE action = 'page_hit'+ AND tenant_id = '${escapeLiteral(orgId)}'+ AND timestamp BETWEEN toDateTime('${toDateTimeString(from)}') AND toDateTime('${toDateTimeString(to)}')+ GROUP BY name+ ORDER BY views DESC+ LIMIT 10+ `;++ type Row = { name: string; views: number };+ return fallbackIfEmpty(+ withTinybirdFallback<Row>(tinybird.querySql<Row>(aggregatedSql)),+ withTinybirdFallback<Row>(tinybird.querySql<Row>(rawSql)),+ ).pipe(+ Effect.map((rows) =>+ rows.map((row) => ({+ name: row.name,+ views: Number(row.views) || 0,+ })),+ ),+ );+};++const queryTopCaps = (+ tinybird: Tinybird,+ orgId: OrgId,+ from: Date,+ to: Date,+) => {+ const aggregatedSql = `+ SELECT+ pathname,+ uniqMerge(visits) as views+ FROM analytics_pages_mv+ WHERE tenant_id = '${escapeLiteral(orgId)}'+ AND date BETWEEN toDate('${toDateString(from)}') AND toDate('${toDateString(to)}')+ AND startsWith(pathname, '/s/')+ GROUP BY pathname+ ORDER BY views DESC+ LIMIT 10+ `;++ const rawSql = `+ SELECT+ coalesce(pathname, '') as pathname,+ uniq(session_id) as views+ FROM analytics_events+ WHERE action = 'page_hit'+ AND tenant_id = '${escapeLiteral(orgId)}'+ AND timestamp BETWEEN toDateTime('${toDateTimeString(from)}') AND toDateTime('${toDateTimeString(to)}')+ GROUP BY pathname+ HAVING startsWith(pathname, '/s/')+ ORDER BY views DESC+ LIMIT 10+ `;++ type Row = { pathname: string; views: number };+ return fallbackIfEmpty(+ withTinybirdFallback<Row>(tinybird.querySql<Row>(aggregatedSql)),+ withTinybirdFallback<Row>(tinybird.querySql<Row>(rawSql)),+ ).pipe(+ Effect.map((rows) =>+ rows+ .map((row) => ({+ videoId: row.pathname?.split("/s/")[1] ?? row.pathname,+ views: Number(row.views) || 0,+ }))+ .filter((row): row is TopCapRow => Boolean(row.videoId)),+ ),+ );+};diff --git a/apps/web/app/(org)/dashboard/analytics/page.tsx b/apps/web/app/(org)/dashboard/analytics/page.tsxindex bdadbaf0d..a52cf3ae7 100644--- a/apps/web/app/(org)/dashboard/analytics/page.tsx+++ b/apps/web/app/(org)/dashboard/analytics/page.tsx@@ -1,386 +1,5 @@-import Header from "./components/Header";-import OtherStats, { type OtherStatsData } from "./components/OtherStats";-import StatsChart from "./components/StatsChart";+import { AnalyticsDashboard } from "./components/AnalyticsDashboard";export default function AnalyticsPage() {- return (- <div className="space-y-8">- <Header />- <StatsChart- counts={{- caps: "524",- views: "2,768",- chats: "100",- reactions: "170",- }}- />- <OtherStats data={mockData} />- </div>- );+ return <AnalyticsDashboard />;}--const mockData: OtherStatsData = {- countries: [- {- countryCode: "US",- name: "United States",- views: "8,452",- comments: "100",- reactions: "100",- percentage: "34.2%",- },- {- countryCode: "GB",- name: "United Kingdom",- views: "3,891",- comments: "100",- reactions: "100",- percentage: "15.7%",- },- {- countryCode: "CA",- name: "Canada",- views: "2,764",- comments: "100",- reactions: "100",- percentage: "11.2%",- },- {- countryCode: "DE",- name: "Germany",- views: "2,143",- comments: "100",- reactions: "100",- percentage: "8.7%",- },- {- countryCode: "FR",- name: "France",- views: "1,876",- comments: "100",- reactions: "100",- percentage: "7.6%",- },- {- countryCode: "AU",- name: "Australia",- views: "1,542",- comments: "100",- reactions: "100",- percentage: "6.2%",- },- {- countryCode: "JP",- name: "Japan",- views: "1,298",- comments: "100",- reactions: "100",- percentage: "5.2%",- },- {- countryCode: "BR",- name: "Brazil",- views: "987",- comments: "100",- reactions: "100",- percentage: "4.0%",- },- ],- cities: [- {- countryCode: "US",- name: "New York",- views: "3,421",- comments: "100",- reactions: "100",- percentage: "18.7%",- },- {- countryCode: "US",- name: "Los Angeles",- views: "2,876",- comments: "100",- reactions: "100",- percentage: "15.7%",- },- {- countryCode: "GB",- name: "London",- views: "2,145",- comments: "100",- reactions: "100",- percentage: "11.7%",- },- {- countryCode: "CA",- name: "Toronto",- views: "1,892",- comments: "100",- reactions: "100",- percentage: "10.3%",- },- {- countryCode: "US",- name: "San Francisco",- views: "1,654",- comments: "100",- reactions: "100",- percentage: "9.0%",- },- {- countryCode: "US",- name: "Chicago",- views: "1,432",- comments: "100",- reactions: "100",- percentage: "7.8%",- },- {- countryCode: "DE",- name: "Berlin",- views: "1,198",- comments: "100",- reactions: "100",- percentage: "6.5%",- },- {- countryCode: "US",- name: "Seattle",- views: "987",- comments: "100",- reactions: "100",- percentage: "5.4%",- },- {- countryCode: "AU",- name: "Sydney",- views: "876",- comments: "100",- reactions: "100",- percentage: "4.8%",- },- {- countryCode: "FR",- name: "Paris",- views: "743",- comments: "100",- reactions: "100",- percentage: "4.1%",- },- {- countryCode: "US",- name: "Boston",- views: "621",- comments: "100",- reactions: "100",- percentage: "3.4%",- },- ],- browsers: [- {- browser: "google-chrome",- name: "Chrome",- views: "12,456",- comments: "100",- reactions: "100",- percentage: "42.3%",- },- {- browser: "safari",- name: "Safari",- views: "6,234",- comments: "100",- reactions: "100",- percentage: "21.2%",- },- {- browser: "firefox",- name: "Firefox",- views: "4,187",- comments: "100",- reactions: "100",- percentage: "14.2%",- },- {- browser: "explorer",- name: "Edge",- views: "3,542",- comments: "100",- reactions: "100",- percentage: "12.0%",- },- {- browser: "brave",- name: "Brave",- views: "1,876",- comments: "100",- reactions: "100",- percentage: "6.4%",- },- {- browser: "opera",- name: "Opera",- views: "654",- comments: "100",- reactions: "100",- percentage: "2.2%",- },- {- browser: "vivaldi",- name: "Vivaldi",- views: "298",- comments: "100",- reactions: "100",- percentage: "1.0%",- },- {- browser: "yandex",- name: "Yandex",- views: "143",- comments: "100",- reactions: "100",- percentage: "0.5%",- },- {- browser: "duckduckgo",- name: "DuckDuckGo",- views: "67",- comments: "100",- reactions: "100",- percentage: "0.2%",- },- ],- operatingSystems: [- {- os: "windows",- name: "Windows",- views: "9,876",- comments: "100",- reactions: "100",- percentage: "38.7%",- },- {- os: "ios",- name: "macOS",- views: "7,432",- comments: "100",- reactions: "100",- percentage: "29.1%",- },- {- os: "linux",- name: "Linux",- views: "3,654",- comments: "100",- reactions: "100",- percentage: "14.3%",- },- {- os: "ubuntu",- name: "Ubuntu",- views: "2,187",- comments: "100",- reactions: "100",- percentage: "8.6%",- },- {- os: "fedora",- name: "Fedora",- views: "1,243",- comments: "100",- reactions: "100",- percentage: "4.9%",- },- ],- deviceTypes: [- {- device: "desktop",- name: "Desktop",- views: "2,456",- comments: "100",- reactions: "100",- percentage: "45.6%",- },- {- device: "tablet",- name: "Tablet",- views: "1,234",- comments: "100",- reactions: "100",- percentage: "23.4%",- },- {- device: "mobile",- name: "Mobile",- views: "1,789",- comments: "100",- reactions: "100",- percentage: "30.9%",- },- ],- topCaps: [- {- name: "Product Demo - Q4 2024",- views: "5,842",- comments: "100",- reactions: "100",- percentage: "28.3%",- },- {- name: "Tutorial: Getting Started",- views: "4,156",- comments: "100",- reactions: "100",- percentage: "20.1%",- },- {- name: "Team Meeting Highlights",- views: "3,421",- comments: "100",- reactions: "100",- percentage: "16.6%",- },- {- name: "Bug Fix Walkthrough",- views: "2,789",- comments: "100",- reactions: "100",- percentage: "13.5%",- },- {- name: "Feature Announcement",- views: "1,923",- comments: "100",- reactions: "100",- percentage: "9.3%",- },- {- name: "Customer Feedback Review",- views: "1,245",- comments: "100",- reactions: "100",- percentage: "6.0%",- },- {- name: "Sprint Retrospective",- views: "876",- comments: "100",- reactions: "100",- percentage: "4.2%",- },- {- name: "Design System Update",- views: "543",- comments: "100",- reactions: "100",- percentage: "2.6%",- },- {- name: "API Documentation Demo",- views: "289",- comments: "100",- reactions: "100",- percentage: "1.4%",- },- ],-};diff --git a/apps/web/app/(org)/dashboard/analytics/types.ts b/apps/web/app/(org)/dashboard/analytics/types.tsnew file mode 100644index 000000000..272b1a9a9--- /dev/null+++ b/apps/web/app/(org)/dashboard/analytics/types.ts@@ -0,0 +1,32 @@+export type AnalyticsRange = "24h" | "7d" | "30d";++export interface BreakdownRow {+ name: string;+ subtitle?: string | null;+ views: number;+ percentage: number;+}++export interface OrgAnalyticsResponse {+ counts: {+ caps: number;+ views: number;+ comments: number;+ reactions: number;+ };+ chart: Array<{+ bucket: string;+ caps: number;+ views: number;+ comments: number;+ reactions: number;+ }>;+ breakdowns: {+ countries: BreakdownRow[];+ cities: BreakdownRow[];+ browsers: BreakdownRow[];+ operatingSystems: BreakdownRow[];+ devices: BreakdownRow[];+ topCaps: Array<BreakdownRow & { id: string }>;+ };+}diff --git a/apps/web/app/api/analytics/route.ts b/apps/web/app/api/analytics/route.tsindex 7a3fd4a06..949edfb8f 100644--- a/apps/web/app/api/analytics/route.ts+++ b/apps/web/app/api/analytics/route.ts@@ -1,16 +1,34 @@import type { NextRequest } from "next/server";import { getVideoAnalytics } from "@/actions/videos/get-analytics";+const parseRangeParam = (value: string | null) => {+ if (!value) return undefined;+ const trimmed = value.trim();+ if (!trimmed) return undefined;+ const normalized = trimmed.endsWith("d") || trimmed.endsWith("D")+ ? trimmed.slice(0, -1)+ : trimmed;+ const parsed = Number.parseInt(normalized, 10);+ if (!Number.isFinite(parsed) || parsed <= 0) return undefined;+ return parsed;+};++export const dynamic = 'force-dynamic';+export async function GET(request: NextRequest) {const url = new URL(request.url);const videoId = url.searchParams.get("videoId");+ const rangeParam = url.searchParams.get("range");+ const rangeDays = parseRangeParam(rangeParam);if (!videoId) {return Response.json({ error: "Video ID is required" }, { status: 400 });}try {- const result = await getVideoAnalytics(videoId);+ console.log("videoId", videoId);+ const result = await getVideoAnalytics(videoId, { rangeDays });+ console.log("result", result);return Response.json({ count: result.count }, { status: 200 });} catch (error) {console.error("Error fetching video analytics:", error);diff --git a/apps/web/app/api/analytics/track/route.ts b/apps/web/app/api/analytics/track/route.tsnew file mode 100644index 000000000..160254f55--- /dev/null+++ b/apps/web/app/api/analytics/track/route.ts@@ -0,0 +1,104 @@+import { provideOptionalAuth, Tinybird } from "@cap/web-backend";+import { CurrentUser } from "@cap/web-domain";+import { Effect, Option } from "effect";+import type { NextRequest } from "next/server";+import UAParser from "ua-parser-js";++import { runPromise } from "@/lib/server";++interface TrackPayload {+ videoId: string;+ orgId?: string | null;+ ownerId?: string | null;+ sessionId?: string;+ pathname?: string;+ hostname?: string | null;+ userAgent?: string;+ occurredAt?: string;+}++const sanitizeString = (value?: string | null) =>+ value?.trim() && value.trim() !== "unknown"+ ? value.trim().slice(0, 256)+ : undefined;++export async function POST(request: NextRequest) {+ let body: TrackPayload;+ try {+ body = (await request.json()) as TrackPayload;+ } catch (_error) {+ return Response.json({ error: "Invalid JSON payload" }, { status: 400 });+ }++ if (!body?.videoId) {+ return Response.json({ error: "videoId is required" }, { status: 400 });+ }++ const sessionId = body.sessionId?.slice(0, 128) ?? "anon";+ const userAgent =+ sanitizeString(request.headers.get("user-agent")) ||+ sanitizeString(body.userAgent) ||+ "unknown";+ const parser = new UAParser(userAgent);+ const browserName = parser.getBrowser().name ?? "unknown";+ const osName = parser.getOS().name ?? "unknown";+ const deviceType = parser.getDevice().type ?? "desktop";++ const timestamp = body.occurredAt+ ? new Date(body.occurredAt)+ : new Date();++ const country =+ sanitizeString(request.headers.get("x-vercel-ip-country")) ||+ "";+ const region =+ sanitizeString(request.headers.get("x-vercel-ip-country-region")) ||+ "";+ const city = sanitizeString(request.headers.get("x-vercel-ip-city")) || "";++ const hostname =+ sanitizeString(body.hostname) ||+ sanitizeString(request.nextUrl.hostname) ||+ "";++ const tenantId =+ body.orgId ||+ body.ownerId ||+ (hostname ? `domain:${hostname}` : "public");++ const pathname = body.pathname ?? `/s/${body.videoId}`;++ await runPromise(+ Effect.gen(function* () {+ const maybeUser = yield* Effect.serviceOption(CurrentUser);+ const userId = Option.isSome(maybeUser)+ ? maybeUser.value.id+ : null;+ if (userId && body.ownerId && userId === body.ownerId) {+ return;+ }++ const tinybird = yield* Tinybird;+ yield* tinybird.appendEvents([+ {+ timestamp: timestamp.toISOString(),+ session_id: sessionId,+ action: "page_hit",+ version: "1.0",+ tenant_id: tenantId,+ video_id: body.videoId,+ pathname,+ country,+ region,+ city,+ browser: browserName,+ device: deviceType,+ os: osName,+ user_id: userId,+ },+ ]);+ }).pipe(provideOptionalAuth),+ );++ return Response.json({ success: true });+}diff --git a/apps/web/app/api/dashboard/analytics/route.ts b/apps/web/app/api/dashboard/analytics/route.tsnew file mode 100644index 000000000..3894df02b--- /dev/null+++ b/apps/web/app/api/dashboard/analytics/route.ts@@ -0,0 +1,39 @@+import { getCurrentUser } from "@cap/database/auth/session";+import type { NextRequest } from "next/server";++import { getOrgAnalyticsData } from "@/app/(org)/dashboard/analytics/data";+import type { AnalyticsRange } from "@/app/(org)/dashboard/analytics/types";++const RANGE_VALUES: AnalyticsRange[] = ["24h", "7d", "30d"];++export const dynamic = "force-dynamic";++export async function GET(request: NextRequest) {+ const user = await getCurrentUser();+ if (!user)+ return Response.json({ error: "Unauthorized" }, { status: 401 });++ const { searchParams } = new URL(request.url);+ const requestedOrgId = searchParams.get("orgId");+ const orgId = requestedOrgId ?? user.activeOrganizationId;++ if (!orgId)+ return Response.json({ error: "No active organization" }, { status: 400 });++ if (requestedOrgId && requestedOrgId !== user.activeOrganizationId) {+ return Response.json({ error: "Forbidden" }, { status: 403 });+ }++ const rangeParam = (searchParams.get("range") ?? "7d") as AnalyticsRange;+ const range: AnalyticsRange = RANGE_VALUES.includes(rangeParam)+ ? rangeParam+ : "7d";++ try {+ const data = await getOrgAnalyticsData(orgId, range);+ return Response.json({ data });+ } catch (error) {+ console.error("Failed to load analytics", error);+ return Response.json({ error: "Failed to load analytics" }, { status: 500 });+ }+}diff --git a/apps/web/app/layout.tsx b/apps/web/app/layout.tsxindex 7130597f6..bf9d86a20 100644--- a/apps/web/app/layout.tsx+++ b/apps/web/app/layout.tsx@@ -4,7 +4,6 @@ import { buildEnv, serverEnv } from "@cap/env";import { STRIPE_PLAN_IDS, userIsPro } from "@cap/utils";import { ImageUploads } from "@cap/web-backend";import type { ImageUpload } from "@cap/web-domain";-import { Analytics as DubAnalytics } from "@dub/analytics/react";import * as TooltipPrimitive from "@radix-ui/react-tooltip";import { Effect } from "effect";import type { Metadata } from "next";@@ -147,13 +146,6 @@ export default ({ children }: PropsWithChildren) =></AuthContextProvider></PostHogProvider></TooltipPrimitive.Provider>- {buildEnv.NEXT_PUBLIC_IS_CAP && (- <DubAnalytics- domainsConfig={{- refer: "go.cap.so",- }}- />- )}</body></html>);diff --git a/apps/web/app/s/[videoId]/Share.tsx b/apps/web/app/s/[videoId]/Share.tsxindex 347c5bd5a..d830277c1 100644--- a/apps/web/app/s/[videoId]/Share.tsx+++ b/apps/web/app/s/[videoId]/Share.tsx@@ -7,6 +7,7 @@ import {startTransition,use,useCallback,+ useEffect,useMemo,useOptimistic,useRef,@@ -34,6 +35,107 @@ export type CommentType = typeof commentsSchema.$inferSelect & {sending?: boolean;};+const SESSION_STORAGE_KEY = "cap_tb_session_id";+const SESSION_TTL_MS = 30 * 60 * 1000; // 30 minutes++const ensureAnalyticsSessionId = () => {+ if (typeof window === "undefined") return "anonymous";+ try {+ const raw = window.localStorage.getItem(SESSION_STORAGE_KEY);+ const now = Date.now();+ if (raw) {+ const parsed = JSON.parse(raw) as { value: string; expiry: number };+ if (parsed?.value && parsed.expiry > now) return parsed.value;+ }+ const newId =+ typeof crypto !== "undefined" && "randomUUID" in crypto+ ? crypto.randomUUID()+ : Math.random().toString(36).slice(2);+ window.localStorage.setItem(+ SESSION_STORAGE_KEY,+ JSON.stringify({ value: newId, expiry: now + SESSION_TTL_MS }),+ );+ return newId;+ } catch (error) {+ console.warn("Failed to persist analytics session id", error);+ return "anonymous";+ }+};++const trackVideoView = (payload: {+ videoId: string;+ orgId?: string | null;+ ownerId?: string | null;+}) => {+ if (typeof window === "undefined") return;+ const sessionId = ensureAnalyticsSessionId();+ const screen = window.screen;+ const body = {+ videoId: payload.videoId,+ orgId: payload.orgId,+ ownerId: payload.ownerId,+ sessionId,+ pathname: window.location.pathname,+ href: window.location.href,+ referrer: document.referrer,+ hostname: window.location.hostname,+ timezone: Intl.DateTimeFormat().resolvedOptions().timeZone,+ language:+ typeof navigator !== "undefined" ? navigator.language : undefined,+ locale:+ typeof navigator !== "undefined" && navigator.languages?.length+ ? navigator.languages[0]+ : undefined,+ screen: screen+ ? {+ width: screen.width,+ height: screen.height,+ colorDepth: screen.colorDepth,+ }+ : undefined,+ userAgent: typeof navigator !== "undefined" ? navigator.userAgent : undefined,+ occurredAt: new Date().toISOString(),+ };++ const serializedBody = JSON.stringify(body);++ if (+ typeof navigator !== "undefined" &&+ typeof navigator.sendBeacon === "function"+ ) {+ try {+ const beaconPayload = new Blob([serializedBody], {+ type: "application/json",+ });+ const queued = navigator.sendBeacon(+ "/api/analytics/track",+ beaconPayload,+ );+ if (queued) {+ return;+ }+ } catch (error) {+ console.warn("Falling back to fetch for analytics tracking", error);+ }+ }++ const controller = new AbortController();++ void fetch("/api/analytics/track", {+ method: "POST",+ headers: { "Content-Type": "application/json" },+ body: serializedBody,+ signal: controller.signal,+ keepalive: true,+ }).catch((error) => {+ if (error?.name !== "AbortError") {+ console.warn("Failed to track analytics event", error);+ }+ });++ return () => controller.abort();+};+interface ShareProps {data: VideoData;comments: MaybePromise<CommentWithAuthor[]>;@@ -42,6 +144,7 @@ interface ShareProps {domainVerified: boolean;videoSettings?: OrganizationSettings | null;userOrganizations?: { id: string; name: string }[];+ viewerId?: string | null;initialAiData?: {title?: string | null;summary?: string | null;@@ -134,6 +237,7 @@ export const Share = ({initialAiData,aiGenerationEnabled,videoSettings,+ viewerId,}: ShareProps) => {const effectiveDate: Date = data.metadata?.customCreatedAt? new Date(data.metadata.customCreatedAt)@@ -171,6 +275,21 @@ export const Share = ({[videoStatus],);+ useEffect(() => {+ if (viewerId && viewerId === data.owner.id) {+ return;+ }++ const dispose = trackVideoView({+ videoId: data.id,+ orgId: data.orgId,+ ownerId: data.owner.id,+ });+ return () => {+ dispose?.();+ };+ }, [data.id, data.orgId, data.owner.id, viewerId]);+const shouldShowLoading = () => {if (!aiGenerationEnabled) {return false;diff --git a/apps/web/app/s/[videoId]/page.tsx b/apps/web/app/s/[videoId]/page.tsxindex 38329a3c4..12de03c20 100644--- a/apps/web/app/s/[videoId]/page.tsx+++ b/apps/web/app/s/[videoId]/page.tsx@@ -748,6 +748,7 @@ async function AuthorizedContent({customDomain={customDomain}domainVerified={domainVerified}userOrganizations={userOrganizations}+ viewerId={user?.id ?? null}initialAiData={initialAiData}aiGenerationEnabled={aiGenerationEnabled}/>diff --git a/apps/web/lib/server.ts b/apps/web/lib/server.tsindex 3c93c45b7..c9105e336 100644--- a/apps/web/lib/server.ts+++ b/apps/web/lib/server.ts@@ -17,6 +17,7 @@ import {Videos,VideosPolicy,VideosRepo,+ Tinybird,Workflows,} from "@cap/web-backend";import { type HttpAuthMiddleware, Video } from "@cap/web-domain";@@ -113,6 +114,7 @@ export const Dependencies = Layer.mergeAll(Videos.Default,VideosPolicy.Default,VideosRepo.Default,+ Tinybird.Default,Folders.Default,SpacesPolicy.Default,OrganisationsPolicy.Default,diff --git a/apps/web/package.json b/apps/web/package.jsonindex d17fa1ed0..3e0281a1e 100644--- a/apps/web/package.json+++ b/apps/web/package.json@@ -28,7 +28,6 @@"@deepgram/sdk": "^3.3.4","@dnd-kit/core": "^6.3.1","@dnd-kit/utilities": "^3.2.2",- "@dub/analytics": "^0.0.27","@effect/cluster": "^0.50.4","@effect/experimental": "^0.56.0","@effect/opentelemetry": "^0.58.0",@@ -132,6 +131,7 @@"tailwindcss-animate": "^1.0.7","tldts": "^7.0.11","uuid": "^9.0.1",+ "ua-parser-js": "^1.0.38","zod": "^3.25.76"},"devDependencies": {@@ -147,6 +147,7 @@"@types/react": "19.1.13","@types/react-dom": "19.1.9","@types/react-responsive-masonry": "^2.6.0",+ "@types/ua-parser-js": "^0.7.39","@types/uuid": "^9.0.8","autoprefixer": "^10.4.14","babel-loader": "^10.0.0",diff --git a/package.json b/package.jsonindex 0f7c91b6b..decc3128e 100644--- a/package.json+++ b/package.json@@ -5,6 +5,9 @@"build:web": "turbo run build:web","build:web:docker": "pnpm run --filter=@cap/web build:docker","cap-setup": "dotenv -e .env -- node scripts/setup.js",+ "analytics:setup": "dotenv -e .env -- node scripts/analytics/setup-analytics.js",+ "analytics:check": "dotenv -e .env -- node scripts/analytics/check-analytics.js",+ "analytics:delete-all": "dotenv -e .env -- node scripts/analytics/delete-all-data.js","db:generate": "dotenv -e .env -- pnpm --filter @cap/database db:generate","db:push": "dotenv -e .env -- pnpm --filter @cap/database db:push","db:studio": "dotenv -e .env -- pnpm --filter @cap/database db:studio",diff --git a/packages/env/server.ts b/packages/env/server.tsindex 8adcc3492..f32a6f09e 100644--- a/packages/env/server.ts+++ b/packages/env/server.ts@@ -92,6 +92,10 @@ function createServerEnv() {STRIPE_WEBHOOK_SECRET: z.string().optional(),DISCORD_FEEDBACK_WEBHOOK_URL: z.string().optional(),DISCORD_LOGS_WEBHOOK_URL: z.string().optional(),++ /// Tinybird analytics+ TINYBIRD_HOST: z.string().optional(),+ TINYBIRD_TOKEN: z.string().optional(),VERCEL_ENV: z.union([z.literal("production"),diff --git a/packages/web-backend/src/Tinybird/index.ts b/packages/web-backend/src/Tinybird/index.tsnew file mode 100644index 000000000..d80ccc401--- /dev/null+++ b/packages/web-backend/src/Tinybird/index.ts@@ -0,0 +1,274 @@+import { serverEnv } from "@cap/env";+import { Effect } from "effect";++const DEFAULT_DATASOURCE = "analytics_events";++interface TinybirdResponse<T> {+ data: T[];+ error?: string;+}++export interface TinybirdEventRow {+ timestamp: string;+ session_id?: string | null;+ user_id?: string | null;+ tenant_id?: string | null;+ action: string;+ version?: string;+ pathname?: string | null;+ video_id?: string | null;+ country?: string | null;+ region?: string | null;+ city?: string | null;+ browser?: string | null;+ device?: string | null;+ os?: string | null;+}++export class Tinybird extends Effect.Service<Tinybird>()("Tinybird", {+ effect: Effect.gen(function* () {+ const env = serverEnv();+ const token = env.TINYBIRD_TOKEN;+ const host = env.TINYBIRD_HOST;++ if (!host) {+ yield* Effect.die(+ new Error("TINYBIRD_HOST must be set"),+ );+ }++ yield* Effect.logDebug("Initializing Tinybird service", {+ hasToken: Boolean(token),+ host,+ });++ const enabled = Boolean(token);++ if (!enabled) {+ yield* Effect.logWarning(+ "Tinybird is disabled: TINYBIRD_TOKEN is not set",+ );+ }++ const request = <T>(path: string, init?: RequestInit) => {+ if (!enabled) return Effect.succeed<TinybirdResponse<T>>({ data: [] });++ return Effect.tryPromise({+ try: async () => {+ const url = `${host}/v0${path}`;+ const response = await fetch(url, {+ ...init,+ headers: {+ Authorization: `Bearer ${token}`,+ Accept: "application/json",+ "Content-Type": "application/json",+ ...(init?.headers ?? {}),+ },+ });++ const textBody = await response.text();++ if (!response.ok) {+ const errorMessage = textBody || `Tinybird request failed (${response.status})`;+ console.error("Tinybird request failed", {+ path,+ status: response.status,+ statusText: response.statusText,+ body: textBody,+ });+ throw new Error(errorMessage);+ }++ if (!textBody) {+ console.log("Tinybird empty response", { path });+ return { data: [] } as TinybirdResponse<T>;+ }++ let parsed: unknown;+ try {+ parsed = JSON.parse(textBody);+ } catch (parseError) {+ console.error("Tinybird JSON parse error", {+ path,+ responseBody: textBody,+ bodyLength: textBody.length,+ bodyPreview: textBody.slice(0, 500),+ parseError,+ });+ throw new Error(`Tinybird returned invalid JSON for ${path}`);+ }++ const normalized: TinybirdResponse<T> = Array.isArray(parsed)+ ? ({ data: parsed } as TinybirdResponse<T>)+ : parsed && typeof parsed === "object" && "data" in parsed+ ? (parsed as TinybirdResponse<T>)+ : ({ data: [parsed as T] } as TinybirdResponse<T>);++ if (normalized.error) {+ throw new Error(normalized.error);+ }++ return normalized;+ },+ catch: (cause) => cause as Error,+ });+ };++ const splitSelectColumns = (selectClause: string) => {+ const columns: string[] = [];+ let current = "";+ let depth = 0;+ let inSingle = false;+ let inDouble = false;+ for (let i = 0; i < selectClause.length; i++) {+ const ch = selectClause.charAt(i);+ if (ch === "'" && !inDouble) {+ inSingle = !inSingle;+ } else if (ch === '"' && !inSingle) {+ inDouble = !inDouble;+ }+ if (!inSingle && !inDouble) {+ if (ch === "(") depth++;+ else if (ch === ")") depth--;+ else if (ch === "," && depth === 0) {+ columns.push(current.trim());+ current = "";+ continue;+ }+ }+ current += ch;+ }+ if (current.trim()) columns.push(current.trim());+ return columns;+ };++ const extractAliases = (sql: string) => {+ const upper = sql.toUpperCase();+ const selectIdx = upper.indexOf("SELECT ");+ const fromIdx = upper.indexOf(" FROM ");+ if (selectIdx === -1 || fromIdx === -1 || fromIdx <= selectIdx) return [];+ const clause = sql.slice(selectIdx + 7, fromIdx);+ const parts = splitSelectColumns(clause);+ return parts.map((part, idx) => {+ const mAs = part.match(/\bas\s+([a-zA-Z_][a-zA-Z0-9_]*)\s*$/i);+ if (mAs) return String(mAs[1]);+ const mSimple = part.match(/([a-zA-Z_][a-zA-Z0-9_]*)\s*$/);+ return mSimple ? String(mSimple[1]) : `col_${idx}`;+ });+ };++ const parseTsvToObjects = <T>(text: string, aliases: string[]) => {+ const lines = text.trim().split(/\r?\n/).filter(Boolean);+ const rows = lines.map((line) => line.split("\t"));+ const objects = rows.map((values) => {+ const obj: Record<string, unknown> = {};+ for (let i = 0; i < values.length; i++) {+ const key = aliases[i] ?? `col_${i}`;+ const raw = values[i] ?? "";+ obj[key] = key === "views" ? Number(raw) : raw;+ }+ return obj as T;+ });+ return objects;+ };++ const appendEvents = (rows: TinybirdEventRow[]) => {+ if (!enabled || rows.length === 0) return Effect.void;+ const body = rows+ .map((row) =>+ JSON.stringify({+ ...row,+ session_id: row.session_id ?? "",+ user_id: row.user_id ?? "",+ tenant_id: row.tenant_id ?? "",+ pathname: row.pathname ?? "",+ video_id: row.video_id ?? "",+ country: row.country ?? "",+ region: row.region ?? "",+ city: row.city ?? "",+ browser: row.browser ?? "unknown",+ device: row.device ?? "desktop",+ os: row.os ?? "unknown",+ }),+ )+ .join("\n");+ const search = new URLSearchParams({+ name: DEFAULT_DATASOURCE,+ format: "ndjson",+ });+ return request(`/events?${search.toString()}`, {+ method: "POST",+ body,+ headers: {+ "Content-Type": "application/x-ndjson",+ },+ }).pipe(Effect.asVoid);+ };++ const queryPipe = <T>(+ name: string,+ params?: Record<string, string | number | boolean | undefined>,+ ) => {+ if (!enabled) return Effect.succeed<TinybirdResponse<T>>({ data: [] });+ const search = new URLSearchParams();+ Object.entries(params ?? {}).forEach(([key, value]) => {+ if (value === undefined || value === null) return;+ search.set(key, String(value));+ });+ const query = search.toString();+ return request<T>(`/pipes/${name}.json${query ? `?${query}` : ""}`);+ };++ const querySql = <T>(sql: string) => {+ if (!enabled) return Effect.succeed<TinybirdResponse<T>>({ data: [] });+ const normalized = sql.replace(/\s+/g, " ").trim();+ const encoded = encodeURIComponent(normalized);+ const path = `/sql?q=${encoded}&format=JSON`;+ return Effect.tryPromise({+ try: async () => {+ const url = `${host}/v0${path}`;+ const response = await fetch(url, {+ headers: {+ Authorization: `Bearer ${token}`,+ Accept: "application/json",+ },+ });+ const textBody = await response.text();+ if (!response.ok) {+ const errorMessage = textBody || `Tinybird request failed (${response.status})`;+ console.error("Tinybird request failed", {+ path,+ status: response.status,+ statusText: response.statusText,+ body: textBody,+ });+ throw new Error(errorMessage);+ }+ if (!textBody) {+ console.log("Tinybird empty response", { path });+ return { data: [] } as TinybirdResponse<T>;+ }+ try {+ const parsed = JSON.parse(textBody);+ const normalizedRes: TinybirdResponse<T> = Array.isArray(parsed)+ ? ({ data: parsed } as TinybirdResponse<T>)+ : parsed && typeof parsed === "object" && "data" in parsed+ ? (parsed as TinybirdResponse<T>)+ : ({ data: [parsed as T] } as TinybirdResponse<T>);+ if ((normalizedRes as TinybirdResponse<T>).error) {+ throw new Error((normalizedRes as TinybirdResponse<T>).error as string);+ }+ return normalizedRes;+ } catch {+ const aliases = extractAliases(normalized);+ const objects = parseTsvToObjects<T>(textBody, aliases);+ return { data: objects } as TinybirdResponse<T>;+ }+ },+ catch: (cause) => cause as Error,+ });+ };++ return { enabled, appendEvents, queryPipe, querySql } as const;+ }),+}) {}diff --git a/packages/web-backend/src/Videos/index.ts b/packages/web-backend/src/Videos/index.tsindex 49f758770..9825f2017 100644--- a/packages/web-backend/src/Videos/index.ts+++ b/packages/web-backend/src/Videos/index.ts@@ -8,10 +8,15 @@ import type { Schema } from "effect/Schema";import { Database } from "../Database.ts";import { S3Buckets } from "../S3Buckets/index.ts";+import { Tinybird } from "../Tinybird/index.ts";import { VideosPolicy } from "./VideosPolicy.ts";import type { CreateVideoInput as RepoCreateVideoInput } from "./VideosRepo.ts";import { VideosRepo } from "./VideosRepo.ts";+const DEFAULT_ANALYTICS_RANGE_DAYS = 30;+const escapeSqlLiteral = (value: string) => value.replace(/'/g, "''");+const formatDate = (date: Date) => date.toISOString().slice(0, 10);+type UploadProgressUpdateInput = Schema.Type<typeof Video.UploadProgressUpdateInput>;@@ -30,6 +35,7 @@ export class Videos extends Effect.Service<Videos>()("Videos", {const repo = yield* VideosRepo;const policy = yield* VideosPolicy;const s3Buckets = yield* S3Buckets;+ const tinybird = yield* Tinybird;const getByIdForViewing = (id: Video.VideoId) =>repo@@ -359,17 +365,23 @@ export class Videos extends Effect.Service<Videos>()("Videos", {return yield* Effect.fail(new Video.NotFoundError());const [video] = maybeVideo.value;- const response = yield* Effect.tryPromise(() =>- dub().analytics.retrieve({- domain: "cap.link",- key: video.id,- }),+ const now = new Date();+ const from = new Date(+ now.getTime() - DEFAULT_ANALYTICS_RANGE_DAYS * 24 * 60 * 60 * 1000,);- const { clicks } = response as { clicks: unknown };-- if (typeof clicks !== "number" || clicks === null) return { count: 0 };-- return { count: clicks };+ const pathname = `/s/${video.id}`;+ const sql = `+ SELECT coalesce(uniqMerge(visits), 0) AS views+ FROM analytics_pages_mv+ WHERE pathname = '${escapeSqlLiteral(pathname)}'+ AND date >= toDate('${formatDate(from)}')+ AND date <= toDate('${formatDate(now)}')+ `;+ const response = yield* tinybird+ .querySql<{ views: number }>(sql)+ .pipe(Effect.catchAll(() => Effect.succeed({ data: [] })));+ const views = response.data[0]?.views ?? 0;+ return { count: Number.isFinite(views) ? Number(views) : 0 };}),};}),@@ -378,5 +390,6 @@ export class Videos extends Effect.Service<Videos>()("Videos", {VideosRepo.Default,Database.Default,S3Buckets.Default,+ Tinybird.Default,],}) {}diff --git a/packages/web-backend/src/index.ts b/packages/web-backend/src/index.tsindex b3b4382dc..f1715d2a3 100644--- a/packages/web-backend/src/index.ts+++ b/packages/web-backend/src/index.ts@@ -15,4 +15,5 @@ export { Users } from "./Users/index.ts";export { Videos } from "./Videos/index.ts";export { VideosPolicy } from "./Videos/VideosPolicy.ts";export { VideosRepo } from "./Videos/VideosRepo.ts";+export { Tinybird } from "./Tinybird/index.ts";export * as Workflows from "./Workflows.ts";diff --git a/pnpm-lock.yaml b/pnpm-lock.yamlindex a74db17ba..f9ab4ab13 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -395,9 +395,6 @@ importers:'@dnd-kit/utilities':specifier: ^3.2.2version: 3.2.2([email protected])- '@dub/analytics':- specifier: ^0.0.27- version: 0.0.27'@effect/cluster':specifier: ^0.50.4version: 0.50.4(@effect/[email protected]([email protected]))(@effect/[email protected](@effect/[email protected]([email protected]))([email protected]))(@effect/[email protected](@effect/[email protected](@effect/[email protected]([email protected]))([email protected])([email protected]))(@effect/[email protected]([email protected]))([email protected]))(@effect/[email protected](@effect/[email protected]([email protected]))(@effect/[email protected](@effect/[email protected]([email protected]))([email protected]))([email protected]))([email protected])@@ -704,6 +701,9 @@ importers:tldts:specifier: ^7.0.11version: 7.0.11+ ua-parser-js:+ specifier: ^1.0.38+ version: 1.0.41uuid:specifier: ^9.0.1version: 9.0.1@@ -747,6 +747,9 @@ importers:'@types/react-responsive-masonry':specifier: ^2.6.0version: 2.6.0+ '@types/ua-parser-js':+ specifier: ^0.7.39+ version: 0.7.39'@types/uuid':specifier: ^9.0.8version: 9.0.8@@ -2100,9 +2103,6 @@ packages:'@drizzle-team/[email protected]':resolution: {integrity: sha512-z33Il7l5dKjUgGULTqBsQBQwckHh5AbIuxhdsIxDDiZAzBOrZO6q9ogcWC65kU382AfynTfgNumVcNIjuIua6w==}- '@dub/[email protected]':- resolution: {integrity: sha512-TbLr+sKWiBsMw1GOLpduZI7skXmrLwZlEoVoHyxq66RvMk/5Fl84QoenlhjdxaX1rlHAkWCcjcbAYcCN7skoKw==}-'@effect-ts/[email protected]':resolution: {integrity: sha512-qi1WrtJA90XLMnj2hnUszW9Sx4dXP03ZJtCc5DiUBIOhF4Vw7plfb65/bdBySPoC9s7zy995TdUX1XBSxUkl5w==}@@ -4316,8 +4316,8 @@ packages:'@oxc-project/[email protected]':resolution: {integrity: sha512-+UgQT/4o59cZfH6Cp7G0hwmqEQ0wE+AdIwhikdwnhWI9Dp8CgSY081+Q3O67/wq3VJu8mgUEB93J9EHHn70fOw==}- '@oxc-project/[email protected]':- resolution: {integrity: sha512-r/xkmoXA0xEpU6UGtn18CNVjXH6erU3KCpCDbpLmbVxBFor1U9MqN5Z2uMmCHJuXjJzlnDR+hWY+yPoLo8oHDw==}+ '@oxc-project/[email protected]':+ resolution: {integrity: sha512-lxmZK4xFrdvU0yZiDwgVQTCvh2gHWBJCBk5ALsrtsBWhs0uDIi+FTOnXRQeQfs304imdvTdaakT/lqwQ8hkOXQ==}'@panva/[email protected]':resolution: {integrity: sha512-6oclG6Y3PiDFcoyk8srjLfVKyMfVCKJ27JwNPViuXziFpmdz+MZnZN/aKY0JGXgYuO/VghU0jcOAZgWXZ1Dmrw==}@@ -5258,8 +5258,8 @@ packages:cpu: [arm64]os: [android]- '@rolldown/[email protected]':- resolution: {integrity: sha512-xKQEOmqOet0vFHt/aqcoQGWvoDJhfSO8EBhuST0CDnxQRmnVzbI8keeeX62vi53ZyICKZxczyfx4A8dUY3dqKw==}+ '@rolldown/[email protected]':+ resolution: {integrity: sha512-XlEkrOIHLyGT3avOgzfTFSjG+f+dZMw+/qd+Y3HLN86wlndrB/gSimrJCk4gOhr1XtRtEKfszpadI3Md4Z4/Ag==}engines: {node: ^20.19.0 || >=22.12.0}cpu: [arm64]os: [android]@@ -5270,8 +5270,8 @@ packages:cpu: [arm64]os: [darwin]- '@rolldown/[email protected]':- resolution: {integrity: sha512-kN0N/8m8HUYO13PqlIwxcXD7fu2E6GKu0J4iH7wUJw3T3QK+nvrc20rxtTZ0J6sA1sGCE8UYvvvnurDwMUp0dg==}+ '@rolldown/[email protected]':+ resolution: {integrity: sha512-+JRqKJhoFlt5r9q+DecAGPLZ5PxeLva+wCMtAuoFMWPoZzgcYrr599KQ+Ix0jwll4B4HGP43avu9My8KtSOR+w==}engines: {node: ^20.19.0 || >=22.12.0}cpu: [arm64]os: [darwin]@@ -5282,8 +5282,8 @@ packages:cpu: [x64]os: [darwin]- '@rolldown/[email protected]':- resolution: {integrity: sha512-29qmvsgY2A4ymfy8sQkFFOFc13m04SLUcYn1iil41gpkYrAspBLkvsOQMHPCs3rQCOImgweT4tFotqTAonwphQ==}+ '@rolldown/[email protected]':+ resolution: {integrity: sha512-fFXDjXnuX7/gQZQm/1FoivVtRcyAzdjSik7Eo+9iwPQ9EgtA5/nB2+jmbzaKtMGG3q+BnZbdKHCtOacmNrkIDA==}engines: {node: ^20.19.0 || >=22.12.0}cpu: [x64]os: [darwin]@@ -5294,8 +5294,8 @@ packages:cpu: [x64]os: [freebsd]- '@rolldown/[email protected]':- resolution: {integrity: sha512-fY+esrHjgt6+RAnDPuUk39RvFNmYhJekGyC6wr0HWXGTBed07Feap9BrYINSh6x5xFlNpOPs6tImKnV0zVDuWQ==}+ '@rolldown/[email protected]':+ resolution: {integrity: sha512-F1b6vARy49tjmT/hbloplzgJS7GIvwWZqt+tAHEstCh0JIh9sa8FAMVqEmYxDviqKBaAI8iVvUREm/Kh/PD26Q==}engines: {node: ^20.19.0 || >=22.12.0}cpu: [x64]os: [freebsd]@@ -5306,8 +5306,8 @@ packages:cpu: [arm]os: [linux]- '@rolldown/[email protected]':- resolution: {integrity: sha512-oQNAqB+XrRM2AZaSPyudQETsPhzCZqgPICQu80fJuNyBFYoz6nonNNZtm3BJ9uP+HZfUk9NfOn9vPoCNuk6gAw==}+ '@rolldown/[email protected]':+ resolution: {integrity: sha512-U6cR76N8T8M6lHj7EZrQ3xunLPxSvYYxA8vJsBKZiFZkT8YV4kjgCO3KwMJL0NOjQCPGKyiXO07U+KmJzdPGRw==}engines: {node: ^20.19.0 || >=22.12.0}cpu: [arm]os: [linux]@@ -5318,8 +5318,8 @@ packages:cpu: [arm64]os: [linux]- '@rolldown/[email protected]':- resolution: {integrity: sha512-bJinAiuWUJvlBxPa8ZmRnWkmmAoUlSWtZT4pRkWi/QX3HlgHfUUbhF+d7aZLciai+iFfbiPqOwCL2tqNXXrUsA==}+ '@rolldown/[email protected]':+ resolution: {integrity: sha512-ONgyjofCrrE3bnh5GZb8EINSFyR/hmwTzZ7oVuyUB170lboza1VMCnb8jgE6MsyyRgHYmN8Lb59i3NKGrxrYjw==}engines: {node: ^20.19.0 || >=22.12.0}cpu: [arm64]os: [linux]@@ -5330,8 +5330,8 @@ packages:cpu: [arm64]os: [linux]- '@rolldown/[email protected]':- resolution: {integrity: sha512-gwueY8EJU7afq5tNwKSjYy5JqTR/0MNzZfv6s5dX+rMgeUpTNhwIToLO1F41TPYEa+6LRTXUWG23DO/ONPzUJA==}+ '@rolldown/[email protected]':+ resolution: {integrity: sha512-L0zRdH2oDPkmB+wvuTl+dJbXCsx62SkqcEqdM+79LOcB+PxbAxxjzHU14BuZIQdXcAVDzfpMfaHWzZuwhhBTcw==}engines: {node: ^20.19.0 || >=22.12.0}cpu: [arm64]os: [linux]@@ -5342,8 +5342,8 @@ packages:cpu: [x64]os: [linux]- '@rolldown/[email protected]':- resolution: {integrity: sha512-VXYkjzzEZh5N5Ue1IEcBgL8RuJu5jWrIKmg8WY6hhCbnNJ1IOsObT4HFW+rE8ZaKNjoIXzImoiYi1UAkKiQRYA==}+ '@rolldown/[email protected]':+ resolution: {integrity: sha512-gyoI8o/TGpQd3OzkJnh1M2kxy1Bisg8qJ5Gci0sXm9yLFzEXIFdtc4EAzepxGvrT2ri99ar5rdsmNG0zP0SbIg==}engines: {node: ^20.19.0 || >=22.12.0}cpu: [x64]os: [linux]@@ -5354,8 +5354,8 @@ packages:cpu: [x64]os: [linux]- '@rolldown/[email protected]':- resolution: {integrity: sha512-S5Yw6g/ftiW7MpNpnOM5vSIlDzGuohDY8y7VOI47+92HhO6WqsNfcMkDZXm3G5l6YIfUNStGBV86NWrzasp+sw==}+ '@rolldown/[email protected]':+ resolution: {integrity: sha512-zti8A7M+xFDpKlghpcCAzyOi+e5nfUl3QhU023ce5NCgUxRG5zGP2GR9LTydQ1rnIPwZUVBWd4o7NjZDaQxaXA==}engines: {node: ^20.19.0 || >=22.12.0}cpu: [x64]os: [linux]@@ -5366,8 +5366,8 @@ packages:cpu: [arm64]os: [openharmony]- '@rolldown/[email protected]':- resolution: {integrity: sha512-bhRoMO2oP46W1UDd/PTrSdoIYfvLS2jiFAned0SOzOO0tcait9u+b9i8h4ZugbT2IK4qUXNezovbHJs7hKJOEQ==}+ '@rolldown/[email protected]':+ resolution: {integrity: sha512-eZUssog7qljrrRU9Mi0eqYEPm3Ch0UwB+qlWPMKSUXHNqhm3TvDZarJQdTevGEfu3EHAXJvBIe0YFYr0TPVaMA==}engines: {node: ^20.19.0 || >=22.12.0}cpu: [arm64]os: [openharmony]@@ -5377,8 +5377,8 @@ packages:engines: {node: '>=14.0.0'}cpu: [wasm32]- '@rolldown/[email protected]':- resolution: {integrity: sha512-Owp6Y1RQ84UMOV8hrg5e1Fmu8Po1IUXWytAHUtPcc00+ty6Gr9g5GgLLw0oblu7QovBr4848ozvkMcEj3vDKgA==}+ '@rolldown/[email protected]':+ resolution: {integrity: sha512-nmCN0nIdeUnmgeDXiQ+2HU6FT162o+rxnF7WMkBm4M5Ds8qTU7Dzv2Wrf22bo4ftnlrb2hKK6FSwAJSAe2FWLg==}engines: {node: '>=14.0.0'}cpu: [wasm32]@@ -5388,8 +5388,8 @@ packages:cpu: [arm64]os: [win32]- '@rolldown/[email protected]':- resolution: {integrity: sha512-dnheX8aXsN9P12uwPOW3TVvqSnQ1cfjKQlYgU2dTkrRpnco0kTGvqE1nEWybGukTyuPdzVvrGElgSGEJ7crcSQ==}+ '@rolldown/[email protected]':+ resolution: {integrity: sha512-7kcNLi7Ua59JTTLvbe1dYb028QEPaJPJQHqkmSZ5q3tJueUeb6yjRtx8mw4uIqgWZcnQHAR3PrLN4XRJxvgIkA==}engines: {node: ^20.19.0 || >=22.12.0}cpu: [arm64]os: [win32]@@ -5400,8 +5400,8 @@ packages:cpu: [ia32]os: [win32]- '@rolldown/[email protected]':- resolution: {integrity: sha512-Blt1aODXiAuEdZBqHYXGJwVFlonXKkVEJy5hhxOgnAVi/0mzFNWDxc8qVlxl7dpQjQdboW/wXdgMHpTDfomicg==}+ '@rolldown/[email protected]':+ resolution: {integrity: sha512-lL70VTNvSCdSZkDPPVMwWn/M2yQiYvSoXw9hTLgdIWdUfC3g72UaruezusR6ceRuwHCY1Ayu2LtKqXkBO5LIwg==}engines: {node: ^20.19.0 || >=22.12.0}cpu: [ia32]os: [win32]@@ -5412,8 +5412,8 @@ packages:cpu: [x64]os: [win32]- '@rolldown/[email protected]':- resolution: {integrity: sha512-sSu4qUlL/62QJrR3P+Bd+EblD8tUpnovUz65qow3PA7YxH+f5NFDbCJMR1m5b8zBuVZwZIHfzbuawz+Vl34/xg==}+ '@rolldown/[email protected]':+ resolution: {integrity: sha512-4qU4x5DXWB4JPjyTne/wBNPqkbQU8J45bl21geERBKtEittleonioACBL1R0PsBu0Aq21SwMK5a9zdBkWSlQtQ==}engines: {node: ^20.19.0 || >=22.12.0}cpu: [x64]os: [win32]@@ -5421,8 +5421,8 @@ packages:'@rolldown/[email protected]':resolution: {integrity: sha512-N7pQzk9CyE7q0bBN/q0J8s6Db279r5kUZc6d7/wWRe9/zXqC52HQovVyu6iXPIDY4BEzzgbVLhVFXrOuGJ22ZQ==}- '@rolldown/[email protected]':- resolution: {integrity: sha512-HLlu3Qn3ePmNCbfehwKWXQMzX/2rzcL6Jmpo+Dl3xnq46TGMyJAgO+IsS8ka7IDLeD3wcoOhjJwxTdIdbrFhGw==}+ '@rolldown/[email protected]':+ resolution: {integrity: sha512-5e76wQiQVeL1ICOZVUg4LSOVYg9jyhGCin+icYozhsUzM+fHE7kddi1bdiE0jwVqTfkjba3jUFbEkoC9WkdvyA==}'@rollup/[email protected]':resolution: {integrity: sha512-PR9zDb+rOzkRb2VD+EuKB7UC41vU5DIwZ5qqCpk0KJudcWAyi8rvYOhS7+L5aZCspw1stTViLgN5v6FF1p5cgQ==}@@ -7035,6 +7035,9 @@ packages:'@types/[email protected]':resolution: {integrity: sha512-ScaPdn1dQczgbl0QFTeTOmVHFULt394XJgOQNoyVhZ6r2vLnMLJfBPd53SB52T/3G36VI1/g2MZaX0cwDuXsfw==}+ '@types/[email protected]':+ resolution: {integrity: sha512-P/oDfpofrdtF5xw433SPALpdSchtJmY7nsJItf8h3KXqOslkbySh8zq4dSWXH2oTjRvJ5PczVEoCZPow6GicLg==}+'@types/[email protected]':resolution: {integrity: sha512-CmBKiL6NNo/OqgmMn95Fk9Whlp2mtvIv+KNpQKN2F4SjvrEesubTRWGYSg+BnWZOnlCaSTU1sMpsBOzgbYhnsA==}@@ -12389,8 +12392,8 @@ packages:engines: {node: ^20.19.0 || >=22.12.0}hasBin: true- resolution: {integrity: sha512-Bfmdn3ZqyCwi1LxG39KBrSlil9a/xnrOrAj+jqqN2YTR/WJIEOOfwNKgDALQvr0xlO9bG/i1C883KGd4nd7SrA==}+ resolution: {integrity: sha512-JFULvCNl/anKn99eKjOSEubi0lLmNqQDAjyEMME2T4CwezUDL0i6t1O9xZsu2OMehPnV2caNefWpGF+8TnzB6A==}engines: {node: ^20.19.0 || >=22.12.0}hasBin: true@@ -13436,6 +13439,10 @@ packages:engines: {node: '>=14.17'}hasBin: true+ resolution: {integrity: sha512-LbBDqdIC5s8iROCUjMbW1f5dJQTEFB1+KO9ogbvlb3nm9n4YHa5p4KTvFPWvh2Hs8gZMBuiB1/8+pdfe/tDPug==}+ hasBin: true+resolution: {integrity: sha512-9a4/uxlTWJ4+a5i0ooc1rU7C7YOw3wT+UGqdeNNHWnOF9qcMBgLRS+4IYUqbczewFx4mLEig6gawh7X6mFlEkA==}@@ -15904,10 +15911,6 @@ snapshots:'@drizzle-team/[email protected]': {}- '@dub/[email protected]':- dependencies:- server-only: 0.0.1-'@effect-ts/[email protected]':dependencies:'@effect-ts/system': 0.57.5@@ -17966,7 +17969,7 @@ snapshots:'@oxc-project/[email protected]': {}- '@oxc-project/[email protected]': {}+ '@oxc-project/[email protected]': {}'@panva/[email protected]': {}@@ -18939,61 +18942,61 @@ snapshots:'@rolldown/[email protected]':optional: true- '@rolldown/[email protected]':+ '@rolldown/[email protected]':optional: true'@rolldown/[email protected]':optional: true- '@rolldown/[email protected]':+ '@rolldown/[email protected]':optional: true'@rolldown/[email protected]':optional: true- '@rolldown/[email protected]':+ '@rolldown/[email protected]':optional: true'@rolldown/[email protected]':optional: true- '@rolldown/[email protected]':+ '@rolldown/[email protected]':optional: true'@rolldown/[email protected]':optional: true- '@rolldown/[email protected]':+ '@rolldown/[email protected]':optional: true'@rolldown/[email protected]':optional: true- '@rolldown/[email protected]':+ '@rolldown/[email protected]':optional: true'@rolldown/[email protected]':optional: true- '@rolldown/[email protected]':+ '@rolldown/[email protected]':optional: true'@rolldown/[email protected]':optional: true- '@rolldown/[email protected]':+ '@rolldown/[email protected]':optional: true'@rolldown/[email protected]':optional: true- '@rolldown/[email protected]':+ '@rolldown/[email protected]':optional: true'@rolldown/[email protected]':optional: true- '@rolldown/[email protected]':+ '@rolldown/[email protected]':optional: true'@rolldown/[email protected]':@@ -19001,7 +19004,7 @@ snapshots:'@napi-rs/wasm-runtime': 1.0.6optional: true- '@rolldown/[email protected]':+ '@rolldown/[email protected]':dependencies:'@napi-rs/wasm-runtime': 1.0.7optional: true@@ -19009,24 +19012,24 @@ snapshots:'@rolldown/[email protected]':optional: true- '@rolldown/[email protected]':+ '@rolldown/[email protected]':optional: true'@rolldown/[email protected]':optional: true- '@rolldown/[email protected]':+ '@rolldown/[email protected]':optional: true'@rolldown/[email protected]':optional: true- '@rolldown/[email protected]':+ '@rolldown/[email protected]':optional: true'@rolldown/[email protected]': {}- '@rolldown/[email protected]': {}+ '@rolldown/[email protected]': {}'@rollup/[email protected]([email protected])':optionalDependencies:@@ -20967,6 +20970,8 @@ snapshots:'@types/[email protected]':optional: true+ '@types/[email protected]': {}+'@types/[email protected]': {}'@types/[email protected]': {}@@ -27352,7 +27357,7 @@ snapshots:dependencies:glob: 7.2.3dependencies:'@babel/generator': 7.28.3'@babel/parser': 7.28.4@@ -27363,7 +27368,7 @@ snapshots:dts-resolver: 2.1.2get-tsconfig: 4.11.0magic-string: 0.30.19- rolldown: 1.0.0-beta.49+ rolldown: 1.0.0-beta.50optionalDependencies:typescript: 5.8.3transitivePeerDependencies:@@ -27391,25 +27396,25 @@ snapshots:'@rolldown/binding-win32-ia32-msvc': 1.0.0-beta.42'@rolldown/binding-win32-x64-msvc': 1.0.0-beta.42dependencies:- '@oxc-project/types': 0.96.0- '@rolldown/pluginutils': 1.0.0-beta.49+ '@oxc-project/types': 0.97.0+ '@rolldown/pluginutils': 1.0.0-beta.50optionalDependencies:- '@rolldown/binding-android-arm64': 1.0.0-beta.49- '@rolldown/binding-darwin-arm64': 1.0.0-beta.49- '@rolldown/binding-darwin-x64': 1.0.0-beta.49- '@rolldown/binding-freebsd-x64': 1.0.0-beta.49- '@rolldown/binding-linux-arm-gnueabihf': 1.0.0-beta.49- '@rolldown/binding-linux-arm64-gnu': 1.0.0-beta.49- '@rolldown/binding-linux-arm64-musl': 1.0.0-beta.49- '@rolldown/binding-linux-x64-gnu': 1.0.0-beta.49- '@rolldown/binding-linux-x64-musl': 1.0.0-beta.49- '@rolldown/binding-openharmony-arm64': 1.0.0-beta.49- '@rolldown/binding-wasm32-wasi': 1.0.0-beta.49- '@rolldown/binding-win32-arm64-msvc': 1.0.0-beta.49- '@rolldown/binding-win32-ia32-msvc': 1.0.0-beta.49- '@rolldown/binding-win32-x64-msvc': 1.0.0-beta.49+ '@rolldown/binding-android-arm64': 1.0.0-beta.50+ '@rolldown/binding-darwin-arm64': 1.0.0-beta.50+ '@rolldown/binding-darwin-x64': 1.0.0-beta.50+ '@rolldown/binding-freebsd-x64': 1.0.0-beta.50+ '@rolldown/binding-linux-arm-gnueabihf': 1.0.0-beta.50+ '@rolldown/binding-linux-arm64-gnu': 1.0.0-beta.50+ '@rolldown/binding-linux-arm64-musl': 1.0.0-beta.50+ '@rolldown/binding-linux-x64-gnu': 1.0.0-beta.50+ '@rolldown/binding-linux-x64-musl': 1.0.0-beta.50+ '@rolldown/binding-openharmony-arm64': 1.0.0-beta.50+ '@rolldown/binding-wasm32-wasi': 1.0.0-beta.50+ '@rolldown/binding-win32-arm64-msvc': 1.0.0-beta.50+ '@rolldown/binding-win32-ia32-msvc': 1.0.0-beta.50+ '@rolldown/binding-win32-x64-msvc': 1.0.0-beta.50dependencies:@@ -28556,8 +28561,8 @@ snapshots:diff: 8.0.2empathic: 2.0.0hookable: 5.5.3- rolldown: 1.0.0-beta.49- rolldown-plugin-dts: 0.16.11([email protected])([email protected])+ rolldown: 1.0.0-beta.50+ rolldown-plugin-dts: 0.16.11([email protected])([email protected])semver: 7.7.2tinyexec: 1.0.1tinyglobby: 0.2.15@@ -28701,6 +28706,8 @@ snapshots:+ [email protected]: {}+diff --git a/scripts/analytics/check-analytics.js b/scripts/analytics/check-analytics.jsnew file mode 100755index 000000000..ec425250d--- /dev/null+++ b/scripts/analytics/check-analytics.js@@ -0,0 +1,174 @@+#!/usr/bin/env node++import process from "node:process";++import {+ PIPE_DEFINITIONS,+ TABLE_DEFINITIONS,+ buildSchemaLines,+ createTinybirdClient,+ normalizeWhitespace,+} from "./shared.js";++const normalizeColumnDef = (definition) =>+ normalizeWhitespace(+ definition+ .replace(/`/g, "")+ .replace(/\bjson:\$[^\s,\)]+/gi, "")+ .replace(/\bdefault\s+(?:'[^']*'|"[^"]*"|[^\s,\)]+)/gi, ""),+ ).toLowerCase();++const buildExpectedSchema = (table) =>+ buildSchemaLines(table).map((column) => normalizeColumnDef(column));++const splitSchema = (schema) => {+ const parts = [];+ let depth = 0;+ let current = "";+ for (const char of schema) {+ if (char === "(") depth += 1;+ if (char === ")" && depth > 0) depth -= 1;+ if (char === "," && depth === 0) {+ if (current.trim()) parts.push(current.trim());+ current = "";+ continue;+ }+ current += char;+ }+ if (current.trim()) parts.push(current.trim());+ return parts;+};++async function validateTables(client) {+ const issues = [];+ for (const table of TABLE_DEFINITIONS) {+ try {+ const datasource = await client.getDatasource(table.name);+ if (!datasource) {+ issues.push(`Missing data source ${table.name}`);+ continue;+ }++ const remoteSchema = datasource?.schema?.sql_schema;+ if (!remoteSchema) {+ issues.push(`Data source ${table.name} does not expose schema metadata`);+ continue;+ }++ const remoteColumns = splitSchema(remoteSchema).map(normalizeColumnDef);+ const expectedColumns = buildExpectedSchema(table);++ let hasIssue = false;++ if (remoteColumns.length !== expectedColumns.length) {+ issues.push(+ `Schema mismatch for ${table.name}. Expected ${expectedColumns.length} columns, got ${remoteColumns.length}.`,+ );+ hasIssue = true;+ }++ const missingColumns = expectedColumns.filter((column, index) => remoteColumns[index] !== column);+ if (missingColumns.length > 0) {+ issues.push(+ `Schema mismatch for ${table.name}. Expected columns (${expectedColumns.join(", ")}), got (${remoteColumns.join(", ")}).`,+ );+ hasIssue = true;+ }++ if (table.engine) {+ const actualEngine = typeof datasource.engine === "string"+ ? datasource.engine+ : datasource.engine?.engine;+ if (actualEngine && actualEngine !== table.engine) {+ issues.push(+ `Data source ${table.name} has engine ${actualEngine}, expected ${table.engine}.`,+ );+ hasIssue = true;+ }+ }++ if (!hasIssue) {+ console.log(`✔ Data source ${table.name} schema matches`);+ }+ } catch (error) {+ issues.push(+ `Failed to inspect ${table.name}: ${error instanceof Error ? error.message : String(error)}`,+ );+ }+ }+ return issues;+}++async function validatePipes(client) {+ const issues = [];+ for (const pipeDef of PIPE_DEFINITIONS) {+ try {+ const pipe = await client.getPipe(pipeDef.name);+ if (!pipe) {+ issues.push(`Missing pipe ${pipeDef.name}`);+ continue;+ }++ if ((pipe.type || "").toLowerCase() !== "materialized") {+ issues.push(`Pipe ${pipeDef.name} is not materialized (type=${pipe.type ?? "unknown"}).`);+ continue;+ }++ const materializedNode = pipe.nodes?.find((node) =>+ (node.type || "").toLowerCase() === "materialized" ||+ (node.node_type || "").toLowerCase() === "materialized" ||+ node.materialized,+ );++ const targetDatasource =+ materializedNode?.tags?.materializing_target_datasource ||+ materializedNode?.materialized?.datasource ||+ materializedNode?.datasource ||+ materializedNode?.params?.datasource;++ if (targetDatasource !== pipeDef.targetDatasource) {+ issues.push(+ `Pipe ${pipeDef.name} does not target ${pipeDef.targetDatasource} (found ${targetDatasource ?? "unknown"}).`,+ );+ continue;+ }++ console.log(`✔ Pipe ${pipeDef.name} feeds ${pipeDef.targetDatasource}`);+ } catch (error) {+ const errorMessage = error instanceof Error+ ? error.message+ : String(error);+ const errorDetails = error instanceof Error && error.cause+ ? ` (cause: ${error.cause})`+ : "";+ issues.push(+ `Failed to inspect pipe ${pipeDef.name}: ${errorMessage}${errorDetails}`,+ );+ }+ }+ return issues;+}++async function main() {+ try {+ const client = createTinybirdClient();+ const tableIssues = await validateTables(client);+ const pipeIssues = await validatePipes(client);+ const issues = [...tableIssues, ...pipeIssues];++ if (issues.length > 0) {+ console.error("❌ Tinybird analytics validation failed:");+ for (const issue of issues) {+ console.error(` - ${issue}`);+ }+ process.exit(1);+ }++ console.log("✅ Tinybird analytics setup is valid.");+ } catch (error) {+ console.error("❌ Tinybird analytics validation crashed:", error instanceof Error ? error.message : error);+ process.exit(1);+ }+}++main();diff --git a/scripts/analytics/delete-all-data.js b/scripts/analytics/delete-all-data.jsnew file mode 100644index 000000000..27160f7bc--- /dev/null+++ b/scripts/analytics/delete-all-data.js@@ -0,0 +1,135 @@+#!/usr/bin/env node++import { createTinybirdClient, resolveTinybirdAuth } from "./shared.js";+import { intro, outro, text, isCancel, log } from "@clack/prompts";++async function getAllDatasources(client) {+ try {+ const payload = await client.request(`/v0/datasources`);+ const list = Array.isArray(payload?.datasources)+ ? payload.datasources+ : Array.isArray(payload?.data)+ ? payload.data+ : Array.isArray(payload)+ ? payload+ : [];+ const names = list+ .map((ds) => (typeof ds === "string" ? ds : ds?.name))+ .filter(Boolean);+ const unique = Array.from(new Set(names));+ if (unique.length > 0) return unique;+ } catch {+ // fall through to fallback list+ }+ return ["analytics_events", "analytics_pages_mv", "analytics_sessions_mv"];+}++async function doubleConfirm({ workspaceName, workspaceId, host, datasources }) {+ const workspaceLabel =+ workspaceName || workspaceId || new URL(host).host || "unknown-workspace";++ intro("Delete ALL analytics data from Tinybird");+ log.warn(+ `This will TRUNCATE all datasources in the Tinybird workspace:\n` ++ `- Workspace: ${workspaceLabel}\n` ++ `- Host: ${host}\n` ++ `- Datasources (${datasources.length}): ${datasources.join(", ")}`+ );++ const first = await text({+ message: `Type the workspace name or ID to confirm (${workspaceLabel})`,+ placeholder: workspaceLabel,+ defaultValue: "",+ validate: (value) => {+ if (!value) return "Required";+ if (value !== workspaceName && value !== workspaceId && value !== workspaceLabel) {+ return "Value does not match the workspace name or ID";+ }+ },+ });+ if (isCancel(first)) {+ outro("Cancelled.");+ process.exit(0);+ }++ const second = await text({+ message: 'Final confirmation: type "DELETE ALL" to proceed',+ placeholder: "DELETE ALL",+ defaultValue: "",+ validate: (value) => (value === "DELETE ALL" ? undefined : 'You must type "DELETE ALL"'),+ });+ if (isCancel(second)) {+ outro("Cancelled.");+ process.exit(0);+ }+}++async function deleteAllData() {+ const auth = resolveTinybirdAuth();+ const client = createTinybirdClient(auth);++ const datasources = await getAllDatasources(client);++ await doubleConfirm({+ workspaceName: client.workspaceName,+ workspaceId: client.workspaceId,+ host: client.host,+ datasources,+ });++ console.log("\nDeleting all data from Tinybird datasources...\n");++ const successes = [];+ const failures = [];+ for (const datasource of datasources) {+ try {+ console.log(`Deleting data from ${datasource}...`);+ let ok = false;+ try {+ await client.request(`/v0/datasources/${encodeURIComponent(datasource)}/truncate`, {+ method: "POST",+ });+ ok = true;+ } catch (e1) {+ try {+ await client.request(`/v0/datasources/${encodeURIComponent(datasource)}/data`, {+ method: "DELETE",+ });+ ok = true;+ } catch (e2) {+ await client.request(`/v0/datasources/${encodeURIComponent(datasource)}`, {+ method: "DELETE",+ });+ ok = true;+ }+ }+ if (ok) {+ console.log(`✅ Deleted data from ${datasource}`);+ successes.push(datasource);+ } else {+ failures.push(datasource);+ }+ } catch (error) {+ console.error(`❌ Failed to delete data from ${datasource}:`, error.message);+ if (error.payload) {+ console.error(" Details:", JSON.stringify(error.payload, null, 2));+ }+ failures.push(datasource);+ }+ }++ if (failures.length === 0) {+ console.log("\n✅ Finished deleting all data");+ } else {+ console.log(+ `\n⚠️ Finished with errors. Deleted: ${successes.length}. Failed: ${failures.length} -> ${failures.join(", ")}`,+ );+ process.exitCode = 1;+ }+}++deleteAllData().catch((error) => {+ console.error("❌ Failed to delete data:", error.message);+ process.exit(1);+});+diff --git a/scripts/analytics/setup-analytics.js b/scripts/analytics/setup-analytics.jsnew file mode 100755index 000000000..43531360e--- /dev/null+++ b/scripts/analytics/setup-analytics.js@@ -0,0 +1,90 @@+#!/usr/bin/env node++import { spawnSync } from "node:child_process";+import fs from "node:fs";+import path from "node:path";+import process from "node:process";+import { fileURLToPath } from "node:url";++import { PROJECT_ROOT, resolveTinybirdAuth } from "./shared.js";++const DEFAULT_PYTHON = process.env.PYTHON || "python3";+const TB_BINARY = process.env.TB_BIN || "tb";+const __dirname = path.dirname(fileURLToPath(import.meta.url));+const tinybirdProjectDir = path.join(__dirname, "tinybird");+const projectTinybPath = path.join(tinybirdProjectDir, ".tinyb");+const rootTinybPath = path.join(PROJECT_ROOT, ".tinyb");++const run = (command, args, options = {}) => {+ const result = spawnSync(command, args, {+ stdio: "inherit",+ ...options,+ });+ if (result.error || result.status !== 0) {+ const message = result.error?.message || `Command ${command} ${args.join(" ")} failed.`;+ throw new Error(message);+ }+};++const ensureTinybirdCli = () => {+ try {+ run(TB_BINARY, ["--version"], { stdio: "ignore" });+ } catch {+ console.log("Tinybird CLI not found. Installing via pip...");+ run(DEFAULT_PYTHON, ["-m", "pip", "install", "--user", "tinybird-cli"], { stdio: "inherit" });+ console.log("Tinybird CLI installed. Re-running version check...");+ run(TB_BINARY, ["--version"], { stdio: "inherit" });+ }+};++const ensureTinybirdLogin = () => {+ if (fs.existsSync(rootTinybPath)) {+ return;+ }+ console.log("Tinybird credentials not found. Launching `tb login`...");+ run(TB_BINARY, ["login"], { cwd: PROJECT_ROOT, stdio: "inherit" });+ if (!fs.existsSync(rootTinybPath)) {+ throw new Error("Tinybird login did not create a .tinyb file. Please rerun `tb login` and try again.");+ }+};++const syncProjectTinyb = () => {+ if (!fs.existsSync(rootTinybPath)) return;+ fs.copyFileSync(rootTinybPath, projectTinybPath);+};++const deployTinybirdProject = (auth) => {+ console.log(+ "⚠️ Running `tb --cloud deploy --allow-destructive-operations --wait` inside scripts/analytics/tinybird. This will synchronize the Tinybird workspace to the resources defined in that folder and remove any other datasources/pipes in the workspace."+ );+ run(+ TB_BINARY,+ ["--cloud", "deploy", "--allow-destructive-operations", "--wait"],+ {+ cwd: tinybirdProjectDir,+ env: {+ ...process.env,+ TB_HOST: auth.host,+ TB_TOKEN: auth.token,+ TB_LOCAL: "0",+ ...(auth.userToken ? { TB_USER_TOKEN: auth.userToken } : {}),+ },+ },+ );+};++function main() {+ try {+ ensureTinybirdCli();+ ensureTinybirdLogin();+ const auth = resolveTinybirdAuth();+ syncProjectTinyb();+ deployTinybirdProject(auth);+ console.log("✅ Tinybird analytics resources are ready.");+ } catch (error) {+ console.error("❌ Failed to set up Tinybird analytics:", error instanceof Error ? error.message : error);+ process.exit(1);+ }+}++main();diff --git a/scripts/analytics/shared.js b/scripts/analytics/shared.jsnew file mode 100644index 000000000..9f61dfd13--- /dev/null+++ b/scripts/analytics/shared.js@@ -0,0 +1,197 @@+import fs from "node:fs";+import os from "node:os";+import path from "node:path";+import process from "node:process";+import { fileURLToPath } from "node:url";++const DEFAULT_TINYBIRD_HOST = "https://api.tinybird.co";+const MODULE_DIR = path.dirname(fileURLToPath(import.meta.url));+const PROJECT_ROOT = path.resolve(MODULE_DIR, "..", "..");+const TINYB_FILE_CANDIDATES = [+ path.join(PROJECT_ROOT, ".tinyb"),+ path.join(process.cwd(), ".tinyb"),+ path.join(os.homedir(), ".tinyb"),+];++const TABLE_DEFINITIONS = [+ {+ name: "analytics_events",+ description: "Raw analytics events generated by Cap clients.",+ engine: "MergeTree",+ partitionKey: "toYYYYMM(timestamp)",+ sortingKey: "(tenant_id, timestamp)",+ ttl: "timestamp + INTERVAL 90 DAY",+ settings: "index_granularity = 8192",+ columns: [+ { name: "timestamp", type: "DateTime" },+ { name: "session_id", type: "String" },+ { name: "action", type: "LowCardinality(String)" },+ { name: "version", type: "LowCardinality(String)" },+ { name: "payload", type: "String" },+ { name: "tenant_id", type: "LowCardinality(String)" },+ { name: "domain", type: "LowCardinality(String)" },+ ],+ },+ {+ name: "analytics_pages_mv",+ description: "Aggregated page views per tenant/path/day.",+ engine: "AggregatingMergeTree",+ partitionKey: "toYYYYMM(date)",+ sortingKey: "(tenant_id, date, pathname)",+ ttl: "date + INTERVAL 90 DAY",+ settings: "index_granularity = 256",+ columns: [+ { name: "tenant_id", type: "LowCardinality(String)" },+ { name: "date", type: "Date" },+ { name: "pathname", type: "String" },+ { name: "location", type: "String" },+ { name: "visits", type: "AggregateFunction(uniq, String)" },+ ],+ },+ {+ name: "analytics_sessions_mv",+ description: "Session level metadata derived from analytics events.",+ engine: "ReplacingMergeTree",+ partitionKey: "toYYYYMM(date)",+ sortingKey: "(tenant_id, date, session_id)",+ ttl: "date + INTERVAL 90 DAY",+ settings: "index_granularity = 256",+ columns: [+ { name: "tenant_id", type: "LowCardinality(String)" },+ { name: "date", type: "Date" },+ { name: "session_id", type: "String" },+ { name: "browser", type: "LowCardinality(String)" },+ { name: "device", type: "LowCardinality(String)" },+ ],+ },+];++const PIPE_DEFINITIONS = [+ { name: "analytics_pages_mv_pipe", targetDatasource: "analytics_pages_mv" },+ { name: "analytics_sessions_mv_pipe", targetDatasource: "analytics_sessions_mv" },+];++const normalizeWhitespace = (value) => value.replace(/\s+/g, " ").trim();++const buildSchemaLines = (table) => table.columns.map((column) => `${column.name} ${column.type}`);++function formatHost(host) {+ if (!host) return DEFAULT_TINYBIRD_HOST;+ if (host.startsWith("http://") || host.startsWith("https://")) return host;+ return `https://${host}`;+}++function loadTinybFile() {+ for (const candidate of TINYB_FILE_CANDIDATES) {+ try {+ if (fs.existsSync(candidate)) {+ const raw = fs.readFileSync(candidate, "utf8");+ const data = JSON.parse(raw);+ return { path: candidate, data };+ }+ } catch {+ // ignore malformed files and continue+ }+ }+ return null;+}++function resolveTinybirdAuth() {+ const envHost = process.env.TINYBIRD_HOST?.trim();+ const envToken = process.env.TINYBIRD_ADMIN_TOKEN?.trim() || process.env.TINYBIRD_TOKEN?.trim();+ if (envHost && envToken) {+ return {+ host: formatHost(envHost),+ token: envToken,+ source: "env",+ };+ }++ const tinyb = loadTinybFile();+ if (tinyb) {+ if (!tinyb.data?.token) {+ throw new Error(`Tinybird auth file at ${tinyb.path} is missing a token.`);+ }+ return {+ host: formatHost(tinyb.data.host ?? DEFAULT_TINYBIRD_HOST),+ token: tinyb.data.token,+ workspaceId: tinyb.data.id,+ workspaceName: tinyb.data.name,+ userToken: tinyb.data.user_token,+ tinybPath: tinyb.path,+ source: "tinyb",+ };+ }++ throw new Error(+ "Tinybird credentials not found. Set TINYBIRD_TOKEN/TINYBIRD_HOST or run `tb login` to create a .tinyb file.",+ );+}++function createTinybirdClient(authOverride) {+ const auth = authOverride ?? resolveTinybirdAuth();++ const request = async (path, init = {}) => {+ const url = new URL(path, formatHost(auth.host));+ const headers = {+ Authorization: `Bearer ${auth.token}`,+ ...(init.headers ?? {}),+ };+ let response;+ try {+ response = await fetch(url, { ...init, headers });+ } catch (error) {+ const err = new Error(`Tinybird request failed: ${error instanceof Error ? error.message : String(error)}`);+ err.cause = error;+ throw err;+ }+ const text = await response.text();+ let payload = text;+ try {+ payload = text ? JSON.parse(text) : {};+ } catch {+ // keep raw text when JSON parsing fails+ }++ if (!response.ok) {+ const message = payload?.error || payload?.message || response.statusText;+ const err = new Error(`Tinybird request failed (${response.status}): ${message}`);+ err.status = response.status;+ err.payload = payload;+ throw err;+ }++ return payload;+ };++ const getResource = async (resourcePath, { allowNotFound = false } = {}) => {+ try {+ return await request(resourcePath);+ } catch (error) {+ if (allowNotFound && error.status === 404) return null;+ throw error;+ }+ };++ return {+ host: formatHost(auth.host),+ token: auth.token,+ userToken: auth.userToken,+ workspaceId: auth.workspaceId,+ workspaceName: auth.workspaceName,+ tinybPath: auth.tinybPath,+ request,+ getDatasource: (name, options) => getResource(`/v0/datasources/${encodeURIComponent(name)}`, options),+ getPipe: (name, options) => getResource(`/v0/pipes/${encodeURIComponent(name)}`, options),+ };+}++export {+ PIPE_DEFINITIONS,+ PROJECT_ROOT,+ TABLE_DEFINITIONS,+ buildSchemaLines,+ createTinybirdClient,+ normalizeWhitespace,+ resolveTinybirdAuth,+};diff --git a/scripts/analytics/tinybird/datasources/analytics_events.datasource b/scripts/analytics/tinybird/datasources/analytics_events.datasourcenew file mode 100644index 000000000..9c33cb1b0--- /dev/null+++ b/scripts/analytics/tinybird/datasources/analytics_events.datasource@@ -0,0 +1,27 @@+DESCRIPTION >+ Raw analytics events generated by Cap clients.++SCHEMA >+ timestamp DateTime `json:$.timestamp`,+ session_id String `json:$.session_id` DEFAULT '',+ user_id LowCardinality(String) `json:$.user_id` DEFAULT '',+ tenant_id LowCardinality(String) `json:$.tenant_id` DEFAULT '',+ action LowCardinality(String) `json:$.action`,+ version LowCardinality(String) `json:$.version`,+ pathname String `json:$.pathname` DEFAULT '',+ video_id LowCardinality(String) `json:$.video_id` DEFAULT '',+ country LowCardinality(String) `json:$.country` DEFAULT '',+ region LowCardinality(String) `json:$.region` DEFAULT '',+ city LowCardinality(String) `json:$.city` DEFAULT '',+ browser LowCardinality(String) `json:$.browser` DEFAULT 'unknown',+ device LowCardinality(String) `json:$.device` DEFAULT 'desktop',+ os LowCardinality(String) `json:$.os` DEFAULT 'unknown'++ENGINE MergeTree+ENGINE_PARTITION_KEY toYYYYMM(timestamp)+ENGINE_SORTING_KEY (tenant_id, timestamp)+ENGINE_TTL timestamp + INTERVAL 90 DAY+ENGINE_SETTINGS index_granularity = 8192++FORWARD_QUERY >+ SELECT timestamp, session_id, defaultValueOfTypeName('LowCardinality(String)') AS user_id, tenant_id, action, version, defaultValueOfTypeName('String') AS pathname, defaultValueOfTypeName('LowCardinality(String)') AS video_id, defaultValueOfTypeName('LowCardinality(String)') AS country, defaultValueOfTypeName('LowCardinality(String)') AS region, defaultValueOfTypeName('LowCardinality(String)') AS city, defaultValueOfTypeName('LowCardinality(String)') AS browser, defaultValueOfTypeName('LowCardinality(String)') AS device, defaultValueOfTypeName('LowCardinality(String)') AS osdiff --git a/scripts/analytics/tinybird/datasources/analytics_pages_mv.datasource b/scripts/analytics/tinybird/datasources/analytics_pages_mv.datasourcenew file mode 100644index 000000000..016fe18e8--- /dev/null+++ b/scripts/analytics/tinybird/datasources/analytics_pages_mv.datasource@@ -0,0 +1,17 @@+DESCRIPTION >+ Aggregated page views per tenant/path.++SCHEMA >+ tenant_id LowCardinality(String),+ date Date,+ pathname String,+ country LowCardinality(String),+ region LowCardinality(String),+ city LowCardinality(String),+ visits AggregateFunction(uniq, String)++ENGINE AggregatingMergeTree+ENGINE_PARTITION_KEY toYYYYMM(date)+ENGINE_SORTING_KEY (tenant_id, date, country, city, pathname)+ENGINE_TTL date + INTERVAL 90 DAY+ENGINE_SETTINGS index_granularity = 256diff --git a/scripts/analytics/tinybird/datasources/analytics_sessions_mv.datasource b/scripts/analytics/tinybird/datasources/analytics_sessions_mv.datasourcenew file mode 100644index 000000000..4cd0fdb35--- /dev/null+++ b/scripts/analytics/tinybird/datasources/analytics_sessions_mv.datasource@@ -0,0 +1,16 @@+DESCRIPTION >+ Session level facts derived from analytics events.++SCHEMA >+ tenant_id LowCardinality(String),+ date Date,+ session_id String,+ browser LowCardinality(String),+ device LowCardinality(String),+ os LowCardinality(String)++ENGINE ReplacingMergeTree+ENGINE_PARTITION_KEY toYYYYMM(date)+ENGINE_SORTING_KEY (tenant_id, date, session_id)+ENGINE_TTL date + INTERVAL 90 DAY+ENGINE_SETTINGS index_granularity = 256diff --git a/scripts/analytics/tinybird/pipes/analytics_pages_mv_pipe.pipe b/scripts/analytics/tinybird/pipes/analytics_pages_mv_pipe.pipenew file mode 100644index 000000000..f27960532--- /dev/null+++ b/scripts/analytics/tinybird/pipes/analytics_pages_mv_pipe.pipe@@ -0,0 +1,18 @@+NODE "analytics_pages_mv_node"+DESCRIPTION >+ Materialized view that aggregates uniq sessions per tenant, path and day.+SQL >+ SELECT+ tenant_id,+ toDate(timestamp) AS date,+ coalesce(nullIf(pathname, ''), '/') AS pathname,+ coalesce(country, '') AS country,+ coalesce(region, '') AS region,+ coalesce(city, '') AS city,+ uniqState(session_id) AS visits+ FROM analytics_events+ WHERE action = 'page_hit'+ GROUP BY tenant_id, date, pathname, country, region, city++TYPE MATERIALIZED+DATASOURCE analytics_pages_mvdiff --git a/scripts/analytics/tinybird/pipes/analytics_sessions_mv_pipe.pipe b/scripts/analytics/tinybird/pipes/analytics_sessions_mv_pipe.pipenew file mode 100644index 000000000..bde6ae5e0--- /dev/null+++ b/scripts/analytics/tinybird/pipes/analytics_sessions_mv_pipe.pipe@@ -0,0 +1,16 @@+NODE "analytics_sessions_mv_node"+DESCRIPTION >+ Materialized view that denormalizes browser/device metadata per session.+SQL >+ SELECT+ tenant_id,+ toDate(timestamp) AS date,+ session_id,+ coalesce(nullIf(browser, ''), 'unknown') AS browser,+ coalesce(nullIf(device, ''), 'desktop') AS device,+ coalesce(nullIf(os, ''), 'unknown') AS os+ FROM analytics_events+ WHERE action = 'page_hit'++TYPE MATERIALIZED+DATASOURCE analytics_sessions_mv