@aman-sagar06077/zappa-analytics 0.1.2 → 0.1.3

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.
package/README.md CHANGED
@@ -15,12 +15,12 @@ export default function RootLayout({ children }: { children: React.ReactNode })
15
15
  return <html><body>{children}<Analytics
16
16
  projectId={process.env.NEXT_PUBLIC_ZAPPA_PROJECT_ID!}
17
17
  writeKey={process.env.NEXT_PUBLIC_ZAPPA_WRITE_KEY!}
18
- endpoint={process.env.NEXT_PUBLIC_ZAPPA_ORIGIN + '/api/events'}
18
+ endpoint={process.env.NEXT_PUBLIC_ZAPPA_ENDPOINT}
19
19
  /></body></html>;
20
20
  }
21
21
  ```
22
22
 
23
- Copy the project-specific `NEXT_PUBLIC_ZAPPA_PROJECT_ID`, `NEXT_PUBLIC_ZAPPA_WRITE_KEY`, and `NEXT_PUBLIC_ZAPPA_ORIGIN` values from Zappa's Installation setup into `.env.local` and your production hosting environment. These values are public browser configuration; the write key scopes events to one project and is not a secret.
23
+ Copy `NEXT_PUBLIC_ZAPPA_PROJECT_ID`, `NEXT_PUBLIC_ZAPPA_WRITE_KEY`, and `NEXT_PUBLIC_ZAPPA_ENDPOINT` from Zappa's Installation setup into `.env.local` and your production hosting environment. `NEXT_PUBLIC_ZAPPA_ENDPOINT` must point to the collector that should receive events; for Cloudflare geolocation, use the geo-ingest Worker URL. `NEXT_PUBLIC_ZAPPA_ORIGIN` is for loading Zappa's hosted script in script-tag installs and does not select the NPM collector. Next.js embeds `NEXT_PUBLIC_*` values at build time, so redeploy after changing them. These values are public browser configuration; the write key scopes events to one project and is not a secret.
24
24
 
25
25
  ## Any JavaScript site
26
26
 
@@ -33,3 +33,22 @@ analytics.track('signup_completed', { plan: 1 });
33
33
  The SDK defaults to Zappa's hosted collector at `https://www.zappa.in/api/events`. Override `endpoint` only when using a different collector.
34
34
 
35
35
  Only initialize analytics when your consent policy permits it. Pass `enabled={false}` to the Next.js component until consent is granted, then render it with `enabled` set to `true`. `init` fails closed without a valid write key. The package tracks initial navigation, History API push/replace, query-only changes and browser back/forward, suppressing duplicate pageviews. It shares a persistent first-party visitor and session hint across tabs; the collector assigns the authoritative session after 30 minutes of inactivity or at a UTC day boundary. Use `analytics.reset()` to start a fresh anonymous identity and `analytics.optOut()` to stop collection and clear identifiers. Events are sent in batches of up to 20 and retried on transient network failures.
36
+
37
+ ## Server-side AI crawler observations (Node.js 18+)
38
+
39
+ Browser tracking cannot see crawlers that do not execute JavaScript. For Node/Express-style sites, install the optional server middleware from the separate `./crawler` export:
40
+
41
+ ```js
42
+ import express from 'express';
43
+ import { createCrawlerMiddleware } from '@aman-sagar06077/zappa-analytics/crawler';
44
+
45
+ const app = express();
46
+ app.use(createCrawlerMiddleware({
47
+ projectId: process.env.ZAPPA_PROJECT_ID,
48
+ crawlerKey: process.env.ZAPPA_CRAWLER_KEY,
49
+ // Optional when using a self-hosted collector:
50
+ // endpoint: process.env.ZAPPA_CRAWLER_ENDPOINT,
51
+ }));
52
+ ```
53
+
54
+ Generate or rotate the private crawler key in the Zappa dashboard under **Overview → AI Traffic → AI crawlers**. Set `ZAPPA_PROJECT_ID` and `ZAPPA_CRAWLER_KEY` on the website's server only; never expose the crawler key to browser code. The middleware logs recognized crawler-like requests asynchronously after the response completes. It records the hostname, query-free path, method, status, timestamp, bounded User-Agent and a deduplication ID; it does not send request bodies or IP addresses. Requests are identified by User-Agent patterns only and are explicitly marked **unverified**—this does not prove that a request came from the crawler operator. Apply your site's usual consent/privacy policy and deploy middleware only on the Node server that receives the requests.
package/crawler.d.ts ADDED
@@ -0,0 +1,40 @@
1
+ export type CrawlerCategory =
2
+ | 'ai_search_crawler'
3
+ | 'ai_training_crawler'
4
+ | 'ai_assistant_fetcher'
5
+ | 'general_search_crawler'
6
+ | 'unknown_bot';
7
+
8
+ export type CrawlerMatch = {
9
+ crawler: string;
10
+ organization: string;
11
+ category: CrawlerCategory;
12
+ detectionMethod: 'known_user_agent_match' | 'generic_user_agent_match';
13
+ verificationStatus: 'unverified';
14
+ };
15
+
16
+ export type CrawlerRequest = {
17
+ headers?: Record<string, string | undefined>;
18
+ hostname?: string;
19
+ originalUrl?: string;
20
+ url?: string;
21
+ method?: string;
22
+ };
23
+
24
+ export type CrawlerResponse = {
25
+ statusCode: number;
26
+ once(event: 'finish', listener: () => void): unknown;
27
+ };
28
+
29
+ export type CrawlerMiddlewareOptions = {
30
+ projectId: string;
31
+ crawlerKey: string;
32
+ endpoint?: string;
33
+ fetchImpl?: (input: URL, init: Record<string, unknown>) => Promise<unknown>;
34
+ timeoutMs?: number;
35
+ };
36
+
37
+ export function classifyCrawler(userAgent: string | null | undefined): CrawlerMatch | null;
38
+ export function createCrawlerMiddleware(
39
+ options: CrawlerMiddlewareOptions,
40
+ ): (request: CrawlerRequest, response: CrawlerResponse, next: () => unknown) => unknown;
package/crawler.js ADDED
@@ -0,0 +1,95 @@
1
+ import { randomUUID } from 'node:crypto';
2
+
3
+ const DEFAULT_ENDPOINT = 'https://www.zappa.in/api/ai-crawlers';
4
+ const REGISTRY = [
5
+ [/\bOAI-SearchBot\b/i, 'OAI-SearchBot', 'OpenAI', 'ai_search_crawler'],
6
+ [/\bChatGPT-User\b/i, 'ChatGPT-User', 'OpenAI', 'ai_assistant_fetcher'],
7
+ [/\bGPTBot\b/i, 'GPTBot', 'OpenAI', 'ai_training_crawler'],
8
+ [/\bClaude-SearchBot\b/i, 'Claude-SearchBot', 'Anthropic', 'ai_search_crawler'],
9
+ [/\bClaude-User\b/i, 'Claude-User', 'Anthropic', 'ai_assistant_fetcher'],
10
+ [/\bClaudeBot\b/i, 'ClaudeBot', 'Anthropic', 'ai_training_crawler'],
11
+ [/\bPerplexityBot\b/i, 'PerplexityBot', 'Perplexity', 'ai_search_crawler'],
12
+ [/\bDuckAssistBot\b/i, 'DuckAssistBot', 'DuckDuckGo', 'ai_search_crawler'],
13
+ [/\bGoogle-Extended\b/i, 'Google-Extended', 'Google', 'ai_training_crawler'],
14
+ [/\bGoogleOther\b/i, 'GoogleOther', 'Google', 'unknown_bot'],
15
+ [/\bGooglebot\b/i, 'Googlebot', 'Google', 'general_search_crawler'],
16
+ [/\bBingbot\b/i, 'Bingbot', 'Microsoft', 'general_search_crawler'],
17
+ [/\bApplebot\b/i, 'Applebot', 'Apple', 'general_search_crawler'],
18
+ [/\bAmazonbot\b/i, 'Amazonbot', 'Amazon', 'unknown_bot'],
19
+ [/\bMeta-ExternalAgent\b/i, 'Meta-ExternalAgent', 'Meta', 'unknown_bot'],
20
+ [/\bBytespider\b/i, 'Bytespider', 'ByteDance', 'ai_training_crawler'],
21
+ [/\bCCBot\b/i, 'CCBot', 'Common Crawl', 'unknown_bot'],
22
+ ];
23
+ const GENERIC_BOT = /(?:\bbot\b|crawler|spider|crawl|slurp|scrapy|archiver|headlesschrome|phantomjs|puppeteer|playwright|selenium|lighthouse|pagespeed|pingdom|uptime|statuscake|gtmetrix|facebookexternalhit|slackbot|discordbot)/i;
24
+ const HOST_LABELS = /^(?=.{1,253}$)(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.)*[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/i;
25
+
26
+ /** Return a known UA match, explicitly unverified, or null for an ordinary UA. */
27
+ export function classifyCrawler(userAgent) {
28
+ if (typeof userAgent !== 'string' || !userAgent.trim()) return null;
29
+ const value = userAgent.slice(0, 1024);
30
+ for (const [pattern, crawler, organization, category] of REGISTRY) {
31
+ if (pattern.test(value)) {
32
+ return { crawler, organization, category, detectionMethod: 'known_user_agent_match', verificationStatus: 'unverified' };
33
+ }
34
+ }
35
+ if (GENERIC_BOT.test(value)) {
36
+ return { crawler: 'Unknown bot', organization: 'Unknown', category: 'unknown_bot', detectionMethod: 'generic_user_agent_match', verificationStatus: 'unverified' };
37
+ }
38
+ return null;
39
+ }
40
+
41
+ /**
42
+ * Install on the site's own Node HTTP/Express-style server. It records only
43
+ * crawler-like requests, never blocks the response, and strips the query string.
44
+ */
45
+ export function createCrawlerMiddleware({ projectId, crawlerKey, endpoint = DEFAULT_ENDPOINT, fetchImpl = globalThis.fetch, timeoutMs = 800 } = {}) {
46
+ if (typeof projectId !== 'string' || !projectId.trim()) throw new TypeError('projectId is required');
47
+ if (typeof crawlerKey !== 'string' || !/^ZappaCrawler_[A-Za-z0-9_-]{32,}$/.test(crawlerKey)) throw new TypeError('A private Zappa crawler key is required');
48
+ if (typeof fetchImpl !== 'function') throw new TypeError('Node.js fetch is required');
49
+ const target = new URL(endpoint);
50
+ if (target.protocol !== 'https:' && target.hostname !== 'localhost') throw new TypeError('The crawler endpoint must use HTTPS');
51
+ const safeTimeout = Math.max(100, Math.min(Number(timeoutMs) || 800, 3000));
52
+
53
+ return function zappaCrawlerMiddleware(request, response, next) {
54
+ const rawUserAgent = request?.headers?.['user-agent'];
55
+ const userAgent = typeof rawUserAgent === 'string' ? rawUserAgent.slice(0, 1024) : '';
56
+ if (!classifyCrawler(userAgent)) return next();
57
+
58
+ response.once('finish', () => {
59
+ try {
60
+ const rawHost = request.hostname || request.headers?.host || '';
61
+ const hostname = String(rawHost).toLowerCase().replace(/:\d+$/, '').replace(/\.$/, '');
62
+ const rawUrl = request.originalUrl || request.url || '/';
63
+ const path = new URL(String(rawUrl), 'https://zappa.invalid').pathname;
64
+ const method = String(request.method || 'GET').toUpperCase();
65
+ const statusCode = Number(response.statusCode);
66
+ if (!HOST_LABELS.test(hostname) || !path.startsWith('/') || path.length > 512 || /[\u0000-\u001f\u007f]/.test(path) || !/^[A-Z]{1,10}$/.test(method) || statusCode < 100 || statusCode > 599) return;
67
+
68
+ const controller = new AbortController();
69
+ const timeout = setTimeout(() => controller.abort(), safeTimeout);
70
+ timeout.unref?.();
71
+ const payload = {
72
+ projectId,
73
+ requests: [{
74
+ requestId: randomUUID(),
75
+ timestamp: new Date().toISOString(),
76
+ hostname,
77
+ path,
78
+ method,
79
+ statusCode,
80
+ userAgent,
81
+ }],
82
+ };
83
+ Promise.resolve(fetchImpl(target, {
84
+ method: 'POST',
85
+ headers: { 'Content-Type': 'application/json', 'X-Zappa-Crawler-Key': crawlerKey },
86
+ body: JSON.stringify(payload),
87
+ signal: controller.signal,
88
+ })).catch(() => {}).finally(() => clearTimeout(timeout));
89
+ } catch {
90
+ // Telemetry must not affect the website request.
91
+ }
92
+ });
93
+ return next();
94
+ };
95
+ }
package/next.js CHANGED
@@ -5,7 +5,11 @@ import { init } from './index.js';
5
5
  export function Analytics({ projectId, writeKey, endpoint, enabled = true }) {
6
6
  useEffect(() => {
7
7
  if (!enabled) return;
8
- const analytics = init({ projectId, writeKey, endpoint });
8
+ const analytics = init({
9
+ projectId,
10
+ writeKey,
11
+ endpoint: endpoint || process.env.NEXT_PUBLIC_ZAPPA_ENDPOINT,
12
+ });
9
13
  return () => analytics.destroy();
10
14
  }, [projectId, writeKey, endpoint, enabled]);
11
15
  return null;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@aman-sagar06077/zappa-analytics",
3
- "version": "0.1.2",
3
+ "version": "0.1.3",
4
4
  "description": "Privacy-aware website analytics for Zappa projects.",
5
5
  "license": "MIT",
6
6
  "type": "module",
@@ -13,6 +13,10 @@
13
13
  "./next": {
14
14
  "types": "./next.d.ts",
15
15
  "default": "./next.js"
16
+ },
17
+ "./crawler": {
18
+ "types": "./crawler.d.ts",
19
+ "default": "./crawler.js"
16
20
  }
17
21
  },
18
22
  "files": [
@@ -20,6 +24,8 @@
20
24
  "index.d.ts",
21
25
  "next.js",
22
26
  "next.d.ts",
27
+ "crawler.js",
28
+ "crawler.d.ts",
23
29
  "README.md"
24
30
  ],
25
31
  "peerDependencies": {