@vllnt/convex-analytics 0.1.0-canary.332b387

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (83) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +209 -0
  3. package/dist/client/index.d.ts +94 -0
  4. package/dist/client/index.d.ts.map +1 -0
  5. package/dist/client/index.js +132 -0
  6. package/dist/client/index.js.map +1 -0
  7. package/dist/client/types.d.ts +109 -0
  8. package/dist/client/types.d.ts.map +1 -0
  9. package/dist/client/types.js +2 -0
  10. package/dist/client/types.js.map +1 -0
  11. package/dist/component/_generated/api.d.ts +22 -0
  12. package/dist/component/_generated/api.d.ts.map +1 -0
  13. package/dist/component/_generated/api.js +12 -0
  14. package/dist/component/_generated/api.js.map +1 -0
  15. package/dist/component/_generated/dataModel.d.ts +13 -0
  16. package/dist/component/_generated/dataModel.d.ts.map +1 -0
  17. package/dist/component/_generated/dataModel.js +8 -0
  18. package/dist/component/_generated/dataModel.js.map +1 -0
  19. package/dist/component/_generated/server.d.ts +20 -0
  20. package/dist/component/_generated/server.d.ts.map +1 -0
  21. package/dist/component/_generated/server.js +15 -0
  22. package/dist/component/_generated/server.js.map +1 -0
  23. package/dist/component/convex.config.d.ts +3 -0
  24. package/dist/component/convex.config.d.ts.map +1 -0
  25. package/dist/component/convex.config.js +10 -0
  26. package/dist/component/convex.config.js.map +1 -0
  27. package/dist/component/http.d.ts +13 -0
  28. package/dist/component/http.d.ts.map +1 -0
  29. package/dist/component/http.js +180 -0
  30. package/dist/component/http.js.map +1 -0
  31. package/dist/component/internal_mutations.d.ts +26 -0
  32. package/dist/component/internal_mutations.d.ts.map +1 -0
  33. package/dist/component/internal_mutations.js +126 -0
  34. package/dist/component/internal_mutations.js.map +1 -0
  35. package/dist/component/mutations.d.ts +24 -0
  36. package/dist/component/mutations.d.ts.map +1 -0
  37. package/dist/component/mutations.js +209 -0
  38. package/dist/component/mutations.js.map +1 -0
  39. package/dist/component/queries.d.ts +148 -0
  40. package/dist/component/queries.d.ts.map +1 -0
  41. package/dist/component/queries.js +376 -0
  42. package/dist/component/queries.js.map +1 -0
  43. package/dist/component/schema.d.ts +104 -0
  44. package/dist/component/schema.d.ts.map +1 -0
  45. package/dist/component/schema.js +72 -0
  46. package/dist/component/schema.js.map +1 -0
  47. package/dist/component/validators.d.ts +195 -0
  48. package/dist/component/validators.d.ts.map +1 -0
  49. package/dist/component/validators.js +71 -0
  50. package/dist/component/validators.js.map +1 -0
  51. package/dist/react/index.d.ts +89 -0
  52. package/dist/react/index.d.ts.map +1 -0
  53. package/dist/react/index.js +63 -0
  54. package/dist/react/index.js.map +1 -0
  55. package/dist/shared.d.ts +14 -0
  56. package/dist/shared.d.ts.map +1 -0
  57. package/dist/shared.js +18 -0
  58. package/dist/shared.js.map +1 -0
  59. package/dist/test.d.ts +117 -0
  60. package/dist/test.d.ts.map +1 -0
  61. package/dist/test.js +28 -0
  62. package/dist/test.js.map +1 -0
  63. package/dist/web/index.d.ts +121 -0
  64. package/dist/web/index.d.ts.map +1 -0
  65. package/dist/web/index.js +169 -0
  66. package/dist/web/index.js.map +1 -0
  67. package/package.json +116 -0
  68. package/src/client/index.ts +259 -0
  69. package/src/client/types.ts +121 -0
  70. package/src/component/_generated/api.ts +35 -0
  71. package/src/component/_generated/dataModel.ts +24 -0
  72. package/src/component/_generated/server.ts +42 -0
  73. package/src/component/convex.config.ts +12 -0
  74. package/src/component/http.ts +204 -0
  75. package/src/component/internal_mutations.ts +165 -0
  76. package/src/component/mutations.ts +255 -0
  77. package/src/component/queries.ts +436 -0
  78. package/src/component/schema.ts +76 -0
  79. package/src/component/validators.ts +94 -0
  80. package/src/react/index.tsx +127 -0
  81. package/src/shared.ts +30 -0
  82. package/src/test.ts +44 -0
  83. package/src/web/index.ts +232 -0
@@ -0,0 +1 @@
1
+ {"version":3,"file":"test.js","sourceRoot":"","sources":["../src/test.ts"],"names":[],"mappings":"AAGA,OAAO,aAAa,MAAM,4BAA4B,CAAC;AACvD,OAAO,kBAAkB,MAAM,kCAAkC,CAAC;AAClE,OAAO,eAAe,MAAM,+BAA+B,CAAC;AAC5D,OAAO,MAAM,MAAM,uBAAuB,CAAC;AAE3C,MAAM,OAAO,GAAG,MAAM,CAAC,IAAI,CAAC,IAAI,CAAC,qBAAqB,CAAC,CAAC;AAExD;;;;;;;;;;;;;;GAcG;AACH,MAAM,UAAU,QAAQ,CACtB,CAAuD,EACvD,OAAe,WAAW;IAE1B,CAAC,CAAC,iBAAiB,CAAC,IAAI,EAAE,MAAM,EAAE,OAAO,CAAC,CAAC;IAC3C,CAAC,CAAC,iBAAiB,CAAC,GAAG,IAAI,YAAY,EAAE,aAAa,CAAC,MAAM,EAAE,aAAa,CAAC,OAAO,CAAC,CAAC;IACtF,CAAC,CAAC,iBAAiB,CACjB,GAAG,IAAI,iBAAiB,EACxB,kBAAkB,CAAC,MAAM,EACzB,kBAAkB,CAAC,OAAO,CAC3B,CAAC;IACF,CAAC,CAAC,iBAAiB,CACjB,GAAG,IAAI,cAAc,EACrB,eAAe,CAAC,MAAM,EACtB,eAAe,CAAC,OAAO,CACxB,CAAC;AACJ,CAAC;AAED,eAAe,EAAE,QAAQ,EAAE,MAAM,EAAE,OAAO,EAAE,CAAC"}
@@ -0,0 +1,121 @@
1
+ /**
2
+ * Optional web preset for `@vllnt/convex-analytics`.
3
+ *
4
+ * Pure, host-side helpers — NOT part of the sandboxed component. A web host
5
+ * opts in by passing {@link webDimensions} to the `AnalyticsClient` `dimensions`
6
+ * config and using {@link trackPageview} to ingest page views. The generic core
7
+ * stays domain-neutral; nothing here runs inside the component sandbox.
8
+ *
9
+ * @packageDocumentation
10
+ */
11
+ import type { Scalar } from "../shared.js";
12
+ /**
13
+ * Standard web rollup dimensions. Pass to the `AnalyticsClient` `dimensions`
14
+ * config to opt into web breakdowns (path, referrer, device, browser, ...).
15
+ */
16
+ export declare const webDimensions: readonly ["path", "referrer", "device", "browser", "os", "country", "utmSource", "utmMedium", "utmCampaign"];
17
+ /** A key of {@link webDimensions}. */
18
+ export type WebDimension = (typeof webDimensions)[number];
19
+ /** Parsed user-agent facets. */
20
+ export interface UserAgentInfo {
21
+ device: string;
22
+ browser: string;
23
+ os: string;
24
+ }
25
+ /** Geo facets resolved from edge/CDN request headers. */
26
+ export interface GeoInfo {
27
+ country: string;
28
+ region?: string;
29
+ city?: string;
30
+ }
31
+ /** UTM campaign tags. */
32
+ export interface Utm {
33
+ source?: string;
34
+ medium?: string;
35
+ campaign?: string;
36
+ }
37
+ /**
38
+ * Parse a `User-Agent` string into device / browser / os facets.
39
+ *
40
+ * Pure and dependency-free — coarse buckets suitable for rollups, not exact
41
+ * version detection. Unknown agents fall back to `"Other"` / `"desktop"`.
42
+ *
43
+ * @param ua - The raw `User-Agent` header value.
44
+ * @returns Device, browser, and OS buckets.
45
+ * @example
46
+ * ```ts
47
+ * parseUserAgent("Mozilla/5.0 ... Chrome/120 Safari/537");
48
+ * // { device: "desktop", browser: "Chrome", os: "..." }
49
+ * ```
50
+ */
51
+ export declare function parseUserAgent(ua: string): UserAgentInfo;
52
+ /**
53
+ * Resolve geo facets from Cloudflare / Vercel edge request headers.
54
+ *
55
+ * Reads `CF-IPCountry` and the `X-Vercel-IP-*` family. Accepts either a DOM
56
+ * `Headers` instance or a plain object (case-insensitive). Country defaults to
57
+ * `"unknown"` when no header is present.
58
+ *
59
+ * @param headers - Request headers as a `Headers` instance or a plain record.
60
+ * @returns Country (always present) plus optional region / city.
61
+ */
62
+ export declare function geoFromHeaders(headers: Headers | Record<string, string>): GeoInfo;
63
+ /** A subset of the `AnalyticsClient` surface used by {@link trackPageview}. */
64
+ interface PageviewClient {
65
+ track(ctx: unknown, name: string, opts: {
66
+ subjectRef?: string;
67
+ sessionRef?: string;
68
+ props?: Record<string, Scalar>;
69
+ ts?: number;
70
+ scope?: string;
71
+ dedupeKey?: string;
72
+ }): Promise<unknown>;
73
+ }
74
+ /** Options for {@link trackPageview}. */
75
+ export interface TrackPageviewOpts {
76
+ subjectRef?: string;
77
+ sessionRef?: string;
78
+ /** The page path (e.g. `/pricing`). */
79
+ path: string;
80
+ /** The document referrer, if any. */
81
+ referrer?: string;
82
+ /** Raw `User-Agent` header — parsed into device/browser/os when present. */
83
+ ua?: string;
84
+ /** Request headers — parsed for geo (country/region/city) when present. */
85
+ headers?: Headers | Record<string, string>;
86
+ /** UTM campaign tags. */
87
+ utm?: Utm;
88
+ /** Epoch-millis event time. Defaults to the component's clock when omitted. */
89
+ ts?: number;
90
+ /** Override the client's default scope for this event. */
91
+ scope?: string;
92
+ /** Skip if an event with this dedupe key already exists in the scope. */
93
+ dedupeKey?: string;
94
+ }
95
+ /**
96
+ * Build web `props` from a pageview (parsing UA + geo) and ingest a
97
+ * `"page_view"` event through the generic `AnalyticsClient`.
98
+ *
99
+ * Host-side convenience: the component never sees web concepts — this helper
100
+ * just assembles the `{@link webDimensions}`-shaped props and calls
101
+ * `client.track(ctx, "page_view", { props })`. Pair with
102
+ * `dimensions: webDimensions` on the client to get web rollups.
103
+ *
104
+ * @typeParam C - The `AnalyticsClient` (structural) type.
105
+ * @param client - An `AnalyticsClient` (or compatible) instance.
106
+ * @param ctx - The Convex mutation ctx to run `track` against.
107
+ * @param opts - Pageview fields; `path` is required.
108
+ * @returns The `track` result passed through from the client.
109
+ * @example
110
+ * ```ts
111
+ * const analytics = new AnalyticsClient(components.analytics, { dimensions: webDimensions });
112
+ * await trackPageview(analytics, ctx, {
113
+ * path: "/pricing",
114
+ * ua: request.headers.get("user-agent") ?? undefined,
115
+ * headers: request.headers,
116
+ * });
117
+ * ```
118
+ */
119
+ export declare function trackPageview<C extends PageviewClient>(client: C, ctx: unknown, opts: TrackPageviewOpts): Promise<unknown>;
120
+ export {};
121
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/web/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;GASG;AAEH,OAAO,KAAK,EAA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,yCAAyC;AACzC,MAAM,WAAW,iBAAiB;IAChC,UAAU,CAAC,EAAE,MAAM,CAAC;IACpB,UAAU,CAAC,EAAE,MAAM,CAAC;IACpB,uCAAuC;IACvC,IAAI,EAAE,MAAM,CAAC;IACb,qCAAqC;IACrC,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB,4EAA4E;IAC5E,EAAE,CAAC,EAAE,MAAM,CAAC;IACZ,2EAA2E;IAC3E,OAAO,CAAC,EAAE,OAAO,GAAG,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;IAC3C,yBAAyB;IACzB,GAAG,CAAC,EAAE,GAAG,CAAC;IACV,+EAA+E;IAC/E,EAAE,CAAC,EAAE,MAAM,CAAC;IACZ,0DAA0D;IAC1D,KAAK,CAAC,EAAE,MAAM,CAAC;IACf,yEAAyE;IACzE,SAAS,CAAC,EAAE,MAAM,CAAC;CACpB;AAED;;;;;;;;;;;;;;;;;;;;;;;GAuBG;AACH,wBAAsB,aAAa,CAAC,CAAC,SAAS,cAAc,EAC1D,MAAM,EAAE,CAAC,EACT,GAAG,EAAE,OAAO,EACZ,IAAI,EAAE,iBAAiB,GACtB,OAAO,CAAC,OAAO,CAAC,CAmClB"}
@@ -0,0 +1,169 @@
1
+ /**
2
+ * Optional web preset for `@vllnt/convex-analytics`.
3
+ *
4
+ * Pure, host-side helpers — NOT part of the sandboxed component. A web host
5
+ * opts in by passing {@link webDimensions} to the `AnalyticsClient` `dimensions`
6
+ * config and using {@link trackPageview} to ingest page views. The generic core
7
+ * stays domain-neutral; nothing here runs inside the component sandbox.
8
+ *
9
+ * @packageDocumentation
10
+ */
11
+ /**
12
+ * Standard web rollup dimensions. Pass to the `AnalyticsClient` `dimensions`
13
+ * config to opt into web breakdowns (path, referrer, device, browser, ...).
14
+ */
15
+ export const webDimensions = [
16
+ "path",
17
+ "referrer",
18
+ "device",
19
+ "browser",
20
+ "os",
21
+ "country",
22
+ "utmSource",
23
+ "utmMedium",
24
+ "utmCampaign",
25
+ ];
26
+ function browserOf(ua) {
27
+ if (ua.includes("Firefox/"))
28
+ return "Firefox";
29
+ if (ua.includes("Edg/"))
30
+ return "Edge";
31
+ if (ua.includes("Chrome/"))
32
+ return "Chrome";
33
+ if (ua.includes("Safari/") && !ua.includes("Chrome/"))
34
+ return "Safari";
35
+ return "Other";
36
+ }
37
+ function osOf(ua) {
38
+ if (ua.includes("Windows"))
39
+ return "Windows";
40
+ if (ua.includes("iPhone") || ua.includes("iPad"))
41
+ return "iOS";
42
+ if (ua.includes("Android"))
43
+ return "Android";
44
+ if (ua.includes("Mac OS X") || ua.includes("Macintosh"))
45
+ return "macOS";
46
+ if (ua.includes("Linux"))
47
+ return "Linux";
48
+ return "Other";
49
+ }
50
+ function deviceOf(ua) {
51
+ if (/bot|crawler|spider/i.test(ua))
52
+ return "bot";
53
+ if (/iPhone|Android.*Mobile/i.test(ua))
54
+ return "mobile";
55
+ if (/iPad|Android(?!.*Mobile)/i.test(ua))
56
+ return "tablet";
57
+ return "desktop";
58
+ }
59
+ /**
60
+ * Parse a `User-Agent` string into device / browser / os facets.
61
+ *
62
+ * Pure and dependency-free — coarse buckets suitable for rollups, not exact
63
+ * version detection. Unknown agents fall back to `"Other"` / `"desktop"`.
64
+ *
65
+ * @param ua - The raw `User-Agent` header value.
66
+ * @returns Device, browser, and OS buckets.
67
+ * @example
68
+ * ```ts
69
+ * parseUserAgent("Mozilla/5.0 ... Chrome/120 Safari/537");
70
+ * // { device: "desktop", browser: "Chrome", os: "..." }
71
+ * ```
72
+ */
73
+ export function parseUserAgent(ua) {
74
+ return { device: deviceOf(ua), browser: browserOf(ua), os: osOf(ua) };
75
+ }
76
+ function headerGetter(headers) {
77
+ if (typeof headers.get === "function") {
78
+ return (name) => headers.get(name) ?? undefined;
79
+ }
80
+ const lower = {};
81
+ for (const [k, v] of Object.entries(headers)) {
82
+ lower[k.toLowerCase()] = v;
83
+ }
84
+ return (name) => lower[name.toLowerCase()];
85
+ }
86
+ /**
87
+ * Resolve geo facets from Cloudflare / Vercel edge request headers.
88
+ *
89
+ * Reads `CF-IPCountry` and the `X-Vercel-IP-*` family. Accepts either a DOM
90
+ * `Headers` instance or a plain object (case-insensitive). Country defaults to
91
+ * `"unknown"` when no header is present.
92
+ *
93
+ * @param headers - Request headers as a `Headers` instance or a plain record.
94
+ * @returns Country (always present) plus optional region / city.
95
+ */
96
+ export function geoFromHeaders(headers) {
97
+ const get = headerGetter(headers);
98
+ const country = get("CF-IPCountry") ?? get("X-Vercel-IP-Country") ?? "unknown";
99
+ const region = get("X-Vercel-IP-Country-Region");
100
+ const city = get("X-Vercel-IP-City");
101
+ const info = { country };
102
+ if (region !== undefined)
103
+ info.region = region;
104
+ if (city !== undefined)
105
+ info.city = city;
106
+ return info;
107
+ }
108
+ /**
109
+ * Build web `props` from a pageview (parsing UA + geo) and ingest a
110
+ * `"page_view"` event through the generic `AnalyticsClient`.
111
+ *
112
+ * Host-side convenience: the component never sees web concepts — this helper
113
+ * just assembles the `{@link webDimensions}`-shaped props and calls
114
+ * `client.track(ctx, "page_view", { props })`. Pair with
115
+ * `dimensions: webDimensions` on the client to get web rollups.
116
+ *
117
+ * @typeParam C - The `AnalyticsClient` (structural) type.
118
+ * @param client - An `AnalyticsClient` (or compatible) instance.
119
+ * @param ctx - The Convex mutation ctx to run `track` against.
120
+ * @param opts - Pageview fields; `path` is required.
121
+ * @returns The `track` result passed through from the client.
122
+ * @example
123
+ * ```ts
124
+ * const analytics = new AnalyticsClient(components.analytics, { dimensions: webDimensions });
125
+ * await trackPageview(analytics, ctx, {
126
+ * path: "/pricing",
127
+ * ua: request.headers.get("user-agent") ?? undefined,
128
+ * headers: request.headers,
129
+ * });
130
+ * ```
131
+ */
132
+ export async function trackPageview(client, ctx, opts) {
133
+ const ua = opts.ua !== undefined ? parseUserAgent(opts.ua) : undefined;
134
+ const geo = opts.headers !== undefined ? geoFromHeaders(opts.headers) : undefined;
135
+ const props = { path: opts.path };
136
+ if (opts.referrer !== undefined)
137
+ props["referrer"] = opts.referrer;
138
+ if (ua !== undefined) {
139
+ props["device"] = ua.device;
140
+ props["browser"] = ua.browser;
141
+ props["os"] = ua.os;
142
+ }
143
+ if (geo !== undefined) {
144
+ props["country"] = geo.country;
145
+ if (geo.region !== undefined)
146
+ props["region"] = geo.region;
147
+ if (geo.city !== undefined)
148
+ props["city"] = geo.city;
149
+ }
150
+ if (opts.utm?.source !== undefined)
151
+ props["utmSource"] = opts.utm.source;
152
+ if (opts.utm?.medium !== undefined)
153
+ props["utmMedium"] = opts.utm.medium;
154
+ if (opts.utm?.campaign !== undefined)
155
+ props["utmCampaign"] = opts.utm.campaign;
156
+ const trackOpts = { props };
157
+ if (opts.subjectRef !== undefined)
158
+ trackOpts.subjectRef = opts.subjectRef;
159
+ if (opts.sessionRef !== undefined)
160
+ trackOpts.sessionRef = opts.sessionRef;
161
+ if (opts.ts !== undefined)
162
+ trackOpts.ts = opts.ts;
163
+ if (opts.scope !== undefined)
164
+ trackOpts.scope = opts.scope;
165
+ if (opts.dedupeKey !== undefined)
166
+ trackOpts.dedupeKey = opts.dedupeKey;
167
+ return client.track(ctx, "page_view", trackOpts);
168
+ }
169
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/web/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;GASG;AAIH;;;GAGG;AACH,MAAM,CAAC,MAAM,aAAa,GAAG;IAC3B,MAAM;IACN,UAAU;IACV,QAAQ;IACR,SAAS;IACT,IAAI;IACJ,SAAS;IACT,WAAW;IACX,WAAW;IACX,aAAa;CACL,CAAC;AA0BX,SAAS,SAAS,CAAC,EAAU;IAC3B,IAAI,EAAE,CAAC,QAAQ,CAAC,UAAU,CAAC;QAAE,OAAO,SAAS,CAAC;IAC9C,IAAI,EAAE,CAAC,QAAQ,CAAC,MAAM,CAAC;QAAE,OAAO,MAAM,CAAC;IACvC,IAAI,EAAE,CAAC,QAAQ,CAAC,SA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E,IAAI,IAAI,CAAC,GAAG,EAAE,QAAQ,KAAK,SAAS;QAAE,KAAK,CAAC,aAAa,CAAC,GAAG,IAAI,CAAC,GAAG,CAAC,QAAQ,CAAC;IAE/E,MAAM,SAAS,GAOX,EAAE,KAAK,EAAE,CAAC;IACd,IAAI,IAAI,CAAC,UAAU,KAAK,SAAS;QAAE,SAAS,CAAC,UAAU,GAAG,IAAI,CAAC,UAAU,CAAC;IAC1E,IAAI,IAAI,CAAC,UAAU,KAAK,SAAS;QAAE,SAAS,CAAC,UAAU,GAAG,IAAI,CAAC,UAAU,CAAC;IAC1E,IAAI,IAAI,CAAC,EAAE,KAAK,SAAS;QAAE,SAAS,CAAC,EAAE,GAAG,IAAI,CAAC,EAAE,CAAC;IAClD,IAAI,IAAI,CAAC,KAAK,KAAK,SAAS;QAAE,SAAS,CAAC,KAAK,GAAG,IAAI,CAAC,KAAK,CAAC;IAC3D,IAAI,IAAI,CAAC,SAAS,KAAK,SAAS;QAAE,SAAS,CAAC,SAAS,GAAG,IAAI,CAAC,SAAS,CAAC;IAEvE,OAAO,MAAM,CAAC,KAAK,CAAC,GAAG,EAAE,WAAW,EAAE,SAAS,CAAC,CAAC;AACnD,CAAC"}
package/package.json ADDED
@@ -0,0 +1,116 @@
1
+ {
2
+ "name": "@vllnt/convex-analytics",
3
+ "version": "0.1.0-canary.332b387",
4
+ "description": "Generic, configurable analytics component for Convex — any event, any dimension, any domain; rollup-on-write with funnels, retention, uniques",
5
+ "license": "MIT",
6
+ "type": "module",
7
+ "packageManager": "pnpm@9.15.0",
8
+ "main": "./dist/client/index.js",
9
+ "module": "./dist/client/index.js",
10
+ "types": "./dist/client/index.d.ts",
11
+ "sideEffects": false,
12
+ "exports": {
13
+ "./package.json": "./package.json",
14
+ ".": {
15
+ "types": "./dist/client/index.d.ts",
16
+ "default": "./dist/client/index.js"
17
+ },
18
+ "./test": "./src/test.ts",
19
+ "./web": {
20
+ "types": "./dist/web/index.d.ts",
21
+ "default": "./dist/web/index.js"
22
+ },
23
+ "./react": {
24
+ "types": "./dist/react/index.d.ts",
25
+ "default": "./dist/react/index.js"
26
+ },
27
+ "./convex.config": {
28
+ "types": "./dist/component/convex.config.d.ts",
29
+ "default": "./dist/component/convex.config.js"
30
+ },
31
+ "./_generated/component.js": {
32
+ "types": "./dist/component/_generated/component.d.ts"
33
+ }
34
+ },
35
+ "files": [
36
+ "dist",
37
+ "src",
38
+ "README.md",
39
+ "LICENSE"
40
+ ],
41
+ "scripts": {
42
+ "build": "rm -rf dist && tsc && cp ../../README.md ../../LICENSE ./",
43
+ "test": "vitest run",
44
+ "test:watch": "vitest",
45
+ "test:coverage": "vitest run --coverage",
46
+ "typecheck": "tsc --noEmit",
47
+ "typecheck:ci": "tsc --noEmit",
48
+ "lint": "eslint src/",
49
+ "generate:llms": "node scripts/generate-llms.mjs",
50
+ "preversion": "pnpm install --frozen-lockfile && pnpm build && pnpm test:coverage && pnpm typecheck && pnpm generate:llms"
51
+ },
52
+ "dependencies": {
53
+ "@convex-dev/aggregate": "^0.2.1",
54
+ "@convex-dev/rate-limiter": "^0.3.2",
55
+ "@convex-dev/sharded-counter": "^0.2.0",
56
+ "convex": "^1.21.0"
57
+ },
58
+ "devDependencies": {
59
+ "@edge-runtime/vm": "^4.0.0",
60
+ "@testing-library/react": "^16.1.0",
61
+ "@types/react": "^19.0.0",
62
+ "@vitest/coverage-v8": "^3.0.0",
63
+ "convex-test": "^0.0.36",
64
+ "jsdom": "^26.0.0",
65
+ "react": "^19.0.0",
66
+ "react-dom": "^19.0.0",
67
+ "typescript": "~5.7.0",
68
+ "vite": "^6.0.0",
69
+ "vitest": "^3.0.0"
70
+ },
71
+ "peerDependencies": {
72
+ "convex": ">=1.21.0",
73
+ "react": ">=18.0.0"
74
+ },
75
+ "peerDependenciesMeta": {
76
+ "convex": {
77
+ "optional": true
78
+ },
79
+ "react": {
80
+ "optional": true
81
+ }
82
+ },
83
+ "engines": {
84
+ "node": ">=18"
85
+ },
86
+ "publishConfig": {
87
+ "access": "public"
88
+ },
89
+ "author": {
90
+ "name": "bntvllnt",
91
+ "url": "https://bntvllnt.com"
92
+ },
93
+ "funding": {
94
+ "type": "github",
95
+ "url": "https://github.com/sponsors/bntvllnt"
96
+ },
97
+ "homepage": "https://github.com/vllnt/convex-analytics#readme",
98
+ "bugs": {
99
+ "url": "https://github.com/vllnt/convex-analytics/issues"
100
+ },
101
+ "repository": {
102
+ "type": "git",
103
+ "url": "https://github.com/vllnt/convex-analytics.git"
104
+ },
105
+ "keywords": [
106
+ "convex",
107
+ "convex-component",
108
+ "analytics",
109
+ "events",
110
+ "metrics",
111
+ "funnels",
112
+ "retention",
113
+ "rollup",
114
+ "vllnt"
115
+ ]
116
+ }
@@ -0,0 +1,259 @@
1
+ import type {
2
+ GenericMutationCtx,
3
+ GenericQueryCtx,
4
+ GenericDataModel,
5
+ } from "convex/server";
6
+ import type {
7
+ AnalyticsConfig,
8
+ Props,
9
+ Granularity,
10
+ Range,
11
+ Where,
12
+ TrackOpts,
13
+ TrackResult,
14
+ TopRow,
15
+ TimeseriesPoint,
16
+ UniquesView,
17
+ FunnelStep,
18
+ RetentionCohort,
19
+ DistributionView,
20
+ PaginationOpts,
21
+ EventPage,
22
+ } from "./types.js";
23
+
24
+ export type {
25
+ AnalyticsConfig,
26
+ Range,
27
+ Where,
28
+ TrackOpts,
29
+ TrackResult,
30
+ TopRow,
31
+ TimeseriesPoint,
32
+ UniquesView,
33
+ FunnelStep,
34
+ RetentionCohort,
35
+ DistributionBin,
36
+ DistributionView,
37
+ PaginationOpts,
38
+ EventPage,
39
+ EventView,
40
+ } from "./types.js";
41
+ export type { Scalar, Props, Granularity } from "../shared.js";
42
+
43
+ type MutationCtx = {
44
+ runMutation: GenericMutationCtx<GenericDataModel>["runMutation"];
45
+ };
46
+ type QueryCtx = { runQuery: GenericQueryCtx<GenericDataModel>["runQuery"] };
47
+
48
+ interface ComponentApi {
49
+ mutations: {
50
+ track: unknown;
51
+ configure: unknown;
52
+ configSet: unknown;
53
+ };
54
+ queries: {
55
+ metric: unknown;
56
+ top: unknown;
57
+ timeseries: unknown;
58
+ uniques: unknown;
59
+ funnel: unknown;
60
+ retention: unknown;
61
+ distribution: unknown;
62
+ list: unknown;
63
+ configGet: unknown;
64
+ };
65
+ }
66
+
67
+ const DEFAULT_SCOPE = "default";
68
+
69
+ /**
70
+ * AnalyticsClient — typed, configurable wrapper over the analytics component.
71
+ *
72
+ * Generic over the host's props shape `TProps` for compile-time typing of
73
+ * `track`. Config (`scope`, `dimensions`, `granularities`, ...) is stored on
74
+ * the client and applied to every call — not ignored.
75
+ *
76
+ * @example
77
+ * ```ts
78
+ * const analytics = new AnalyticsClient(components.analytics, {
79
+ * dimensions: ["plan", "source"],
80
+ * granularities: ["hour", "day"],
81
+ * });
82
+ * await analytics.track(ctx, "signup", { subjectRef: userId, props: { plan: "pro" } });
83
+ * const total = await analytics.metric(ctx, "signup");
84
+ * ```
85
+ */
86
+ export class AnalyticsClient<TProps extends Props = Props> {
87
+ private readonly component: ComponentApi;
88
+ private readonly scope: string;
89
+ private readonly dimensions: string[];
90
+ private readonly granularities: Granularity[];
91
+ private readonly sampleRate: number;
92
+ private readonly config: AnalyticsConfig;
93
+
94
+ constructor(component: unknown, config: AnalyticsConfig = {}) {
95
+ this.component = component as ComponentApi;
96
+ this.config = config;
97
+ this.scope = config.scope ?? DEFAULT_SCOPE;
98
+ this.dimensions = config.dimensions ?? [];
99
+ this.granularities = config.granularities ?? ["day"];
100
+ this.sampleRate = config.sampleRate ?? 1;
101
+ }
102
+
103
+ /** Ingest an event: rollup-on-write + raw event + counter. Sampling + dedupe applied. */
104
+ async track(
105
+ ctx: MutationCtx,
106
+ name: string,
107
+ opts: TrackOpts<TProps> = {},
108
+ ): Promise<TrackResult> {
109
+ return (await ctx.runMutation(this.component.mutations.track as never, {
110
+ scope: opts.scope ?? this.scope,
111
+ name,
112
+ subjectRef: opts.subjectRef,
113
+ sessionRef: opts.sessionRef,
114
+ props: opts.props,
115
+ ts: opts.ts,
116
+ dedupeKey: opts.dedupeKey,
117
+ dimensions: this.dimensions,
118
+ granularities: this.granularities,
119
+ sampleRate: this.sampleRate,
120
+ } as never)) as TrackResult;
121
+ }
122
+
123
+ /** Total count over a range, optionally filtered by a dimension value. */
124
+ async metric(
125
+ ctx: QueryCtx,
126
+ name: string,
127
+ opts: { range?: Range; where?: Where; scope?: string } = {},
128
+ ): Promise<number> {
129
+ return (await ctx.runQuery(this.component.queries.metric as never, {
130
+ scope: opts.scope ?? this.scope,
131
+ name,
132
+ range: opts.range,
133
+ where: opts.where,
134
+ } as never)) as number;
135
+ }
136
+
137
+ /** Top values of a dimension (breakdown). */
138
+ async top(
139
+ ctx: QueryCtx,
140
+ name: string,
141
+ dimension: string,
142
+ opts: { range?: Range; limit?: number; scope?: string } = {},
143
+ ): Promise<TopRow[]> {
144
+ return (await ctx.runQuery(this.component.queries.top as never, {
145
+ scope: opts.scope ?? this.scope,
146
+ name,
147
+ dimension,
148
+ range: opts.range,
149
+ limit: opts.limit,
150
+ } as never)) as TopRow[];
151
+ }
152
+
153
+ /** Bucketed counts over a range. */
154
+ async timeseries(
155
+ ctx: QueryCtx,
156
+ name: string,
157
+ opts: { granularity: Granularity; range: Range; where?: Where; scope?: string },
158
+ ): Promise<TimeseriesPoint[]> {
159
+ return (await ctx.runQuery(this.component.queries.timeseries as never, {
160
+ scope: opts.scope ?? this.scope,
161
+ name,
162
+ granularity: opts.granularity,
163
+ range: opts.range,
164
+ where: opts.where,
165
+ } as never)) as TimeseriesPoint[];
166
+ }
167
+
168
+ /** DAU/WAU/MAU from subjects. */
169
+ async uniques(
170
+ ctx: QueryCtx,
171
+ opts: { range: Range; granularity: Granularity; scope?: string },
172
+ ): Promise<UniquesView> {
173
+ return (await ctx.runQuery(this.component.queries.uniques as never, {
174
+ scope: opts.scope ?? this.scope,
175
+ range: opts.range,
176
+ granularity: opts.granularity,
177
+ } as never)) as UniquesView;
178
+ }
179
+
180
+ /** Ordered step conversion (generic, keyed by subjectRef). */
181
+ async funnel(
182
+ ctx: QueryCtx,
183
+ steps: string[],
184
+ opts: { range: Range; scope?: string },
185
+ ): Promise<FunnelStep[]> {
186
+ return (await ctx.runQuery(this.component.queries.funnel as never, {
187
+ scope: opts.scope ?? this.scope,
188
+ steps,
189
+ range: opts.range,
190
+ } as never)) as FunnelStep[];
191
+ }
192
+
193
+ /** Cohort return rates by first-seen period. */
194
+ async retention(
195
+ ctx: QueryCtx,
196
+ opts: {
197
+ cohortRange: Range;
198
+ periods: number;
199
+ granularity?: Granularity;
200
+ scope?: string;
201
+ },
202
+ ): Promise<RetentionCohort[]> {
203
+ return (await ctx.runQuery(this.component.queries.retention as never, {
204
+ scope: opts.scope ?? this.scope,
205
+ cohortRange: opts.cohortRange,
206
+ periods: opts.periods,
207
+ granularity: opts.granularity,
208
+ } as never)) as RetentionCohort[];
209
+ }
210
+
211
+ /** Histogram of a numeric measure: ascending upper-bound bins + overflow. */
212
+ async distribution(
213
+ ctx: QueryCtx,
214
+ name: string,
215
+ measure: string,
216
+ opts: { buckets: number[]; range?: Range; where?: Where; scope?: string },
217
+ ): Promise<DistributionView> {
218
+ return (await ctx.runQuery(this.component.queries.distribution as never, {
219
+ scope: opts.scope ?? this.scope,
220
+ name,
221
+ measure,
222
+ buckets: opts.buckets,
223
+ range: opts.range,
224
+ where: opts.where,
225
+ } as never)) as DistributionView;
226
+ }
227
+
228
+ /** Paginated raw events for an event name, newest first. */
229
+ async list(
230
+ ctx: QueryCtx,
231
+ name: string,
232
+ paginationOpts: PaginationOpts,
233
+ opts: { scope?: string } = {},
234
+ ): Promise<EventPage> {
235
+ return (await ctx.runQuery(this.component.queries.list as never, {
236
+ scope: opts.scope ?? this.scope,
237
+ name,
238
+ paginationOpts,
239
+ } as never)) as EventPage;
240
+ }
241
+
242
+ /** Persist cron-relevant config (retention/sampling/idle) for the scope. */
243
+ async configure(
244
+ ctx: MutationCtx,
245
+ opts: {
246
+ retentionDays?: number;
247
+ sampleRate?: number;
248
+ sessionIdleMs?: number;
249
+ scope?: string;
250
+ } = {},
251
+ ): Promise<void> {
252
+ await ctx.runMutation(this.component.mutations.configure as never, {
253
+ scope: opts.scope ?? this.scope,
254
+ retentionDays: opts.retentionDays ?? this.config.retentionDays,
255
+ sampleRate: opts.sampleRate ?? this.config.sampleRate,
256
+ sessionIdleMs: opts.sessionIdleMs ?? this.config.sessionIdleMs,
257
+ } as never);
258
+ }
259
+ }