apptvty 0.1.2

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.
@@ -0,0 +1,170 @@
1
+ import { A as ApptvtyConfig, R as RequestLogEntry, Q as QueryRequest, B as BackendQueryResponse, P as PageAdsResponse, I as ImpressionLog, S as SiteOverviewStats, D as DailyStat, C as CrawlerBreakdown, a as RecentActivityItem, b as RecentQueryItem, c as SiteWalletInfo, d as CrawlerInfo, e as AgentQueryResponse, f as QueryEndpointDiscovery, g as AgentErrorResponse } from './types-C1oUTCsT.js';
2
+ export { h as PageAd, i as QuerySource, j as SponsoredAd } from './types-C1oUTCsT.js';
3
+ export { createNextjsQueryHandler, withApptvty } from './middleware/nextjs.js';
4
+ export { createExpressMiddleware, createExpressQueryHandler } from './middleware/express.js';
5
+ import 'next/server';
6
+ import 'node:http';
7
+
8
+ /**
9
+ * HTTP client for the Apptvty API.
10
+ *
11
+ * Handles:
12
+ * - Batch log ingestion (/v1/logs/batch)
13
+ * - Query processing (/v1/query) — returns answer + optional ad
14
+ * - Impression logging (/v1/impressions) — triggers billing for ads
15
+ */
16
+
17
+ declare class ApptvtyClient {
18
+ private readonly baseUrl;
19
+ private readonly apiKey;
20
+ private readonly siteId;
21
+ private readonly debug;
22
+ constructor(config: ApptvtyConfig);
23
+ /**
24
+ * Send a batch of request log entries to the Apptvty ingestion API.
25
+ * Called by the logger's auto-flush — not called directly by user code.
26
+ */
27
+ sendLogs(logs: RequestLogEntry[]): Promise<void>;
28
+ /**
29
+ * Send a query to the Apptvty backend.
30
+ * The backend runs RAG against the site's indexed content and,
31
+ * if ads are enabled for the site, attaches a relevant sponsored ad.
32
+ *
33
+ * @throws on non-retryable errors (network errors, 5xx) — callers should catch
34
+ */
35
+ query(req: QueryRequest): Promise<BackendQueryResponse>;
36
+ /**
37
+ * Get relevant ads for a page (for HTML injection when crawler is detected).
38
+ * Used by middleware to inject ads into HTML responses.
39
+ */
40
+ getAdsForPage(req: {
41
+ site_id: string;
42
+ page_path: string;
43
+ }): Promise<PageAdsResponse>;
44
+ /**
45
+ * Log an ad impression back to Apptvty.
46
+ *
47
+ * Called after returning a query response that contains a `sponsored` block.
48
+ * This is what triggers the billing cycle:
49
+ * - Advertiser gets charged (debited from their USDC ad budget)
50
+ * - Publisher (the website) gets credited in USDC
51
+ *
52
+ * This call is fire-and-forget. The SDK logs a warning on failure
53
+ * but does not throw — a missed impression log is better than
54
+ * breaking the query response.
55
+ */
56
+ logImpression(impression: ImpressionLog): Promise<void>;
57
+ /** Get 30-day traffic overview (requests, AI %, crawlers, queries). */
58
+ getSiteStats(): Promise<SiteOverviewStats>;
59
+ /** Get day-by-day stats (default 30 days, max 90). */
60
+ getSiteDailyStats(days?: number): Promise<{
61
+ days: number;
62
+ stats: DailyStat[];
63
+ }>;
64
+ /** Get crawler breakdown by type (default 30 days). */
65
+ getSiteCrawlers(days?: number): Promise<{
66
+ days: number;
67
+ crawlers: CrawlerBreakdown[];
68
+ }>;
69
+ /** Get recent activity feed (last hour, default 50 items, max 200). */
70
+ getSiteActivity(limit?: number): Promise<{
71
+ activity: RecentActivityItem[];
72
+ }>;
73
+ /** Get recent agent queries (default 50, max 200). */
74
+ getSiteQueries(limit?: number): Promise<{
75
+ queries: RecentQueryItem[];
76
+ }>;
77
+ /** Get wallet balance and earnings. */
78
+ getSiteWallet(): Promise<SiteWalletInfo>;
79
+ private get;
80
+ private post;
81
+ private log;
82
+ private warn;
83
+ }
84
+ declare class ApptvtyApiError extends Error {
85
+ readonly statusCode: number;
86
+ readonly path: string;
87
+ readonly body: string;
88
+ constructor(statusCode: number, path: string, body: string);
89
+ }
90
+
91
+ /**
92
+ * Batched request logger.
93
+ *
94
+ * Queues RequestLogEntry objects in memory and flushes them in batches
95
+ * to the Apptvty API. This keeps per-request overhead near zero.
96
+ *
97
+ * Flush triggers:
98
+ * 1. Queue reaches batchSize (default 50)
99
+ * 2. flushInterval elapses (default 5s)
100
+ * 3. process.exit / SIGTERM (best-effort sync flush)
101
+ */
102
+
103
+ declare class RequestLogger {
104
+ private readonly client;
105
+ private queue;
106
+ private timer;
107
+ private flushing;
108
+ private readonly batchSize;
109
+ private readonly debug;
110
+ constructor(client: ApptvtyClient, config: ApptvtyConfig);
111
+ /** Enqueue a single log entry. Non-blocking. */
112
+ enqueue(entry: RequestLogEntry): void;
113
+ /** Flush the current queue to the API. */
114
+ flush(): Promise<void>;
115
+ /**
116
+ * Synchronous-ish flush for process shutdown.
117
+ * Fires the fetch and doesn't await to avoid blocking exit handlers.
118
+ */
119
+ private flushSync;
120
+ /** Stop the interval timer. Call when you want to fully tear down the SDK. */
121
+ destroy(): void;
122
+ private log;
123
+ }
124
+
125
+ /**
126
+ * Lightweight AI crawler detection.
127
+ *
128
+ * This is the single source of truth for crawler classification in the SDK.
129
+ * The backend (Python analytics API and TypeScript handlers) should eventually
130
+ * consume this same list rather than maintaining separate copies.
131
+ */
132
+
133
+ declare function detectCrawler(userAgent: string): CrawlerInfo;
134
+ /** Returns the list of all known crawlers for reference (e.g. for agents.txt generation) */
135
+ declare function getKnownCrawlerNames(): string[];
136
+
137
+ /**
138
+ * Framework-agnostic query endpoint handler.
139
+ *
140
+ * Serves the site's AEO (Agent Experience Optimization) query page.
141
+ *
142
+ * GET /query → Returns a self-describing discovery JSON
143
+ * GET /query?q=<question> → Returns an AI-generated answer from the site's
144
+ * indexed content, plus a sponsored ad if ads are
145
+ * enabled and a matching ad exists.
146
+ *
147
+ * When an ad is included in the response, this handler fires an async
148
+ * impression log back to Apptvty to trigger billing:
149
+ * - Advertiser is charged (debited from their USDC ad budget)
150
+ * - Publisher earns USDC (credited to their Crossmint wallet)
151
+ */
152
+
153
+ interface QueryHandlerRequest {
154
+ query: string | null;
155
+ lang: string | null;
156
+ surface_ads?: boolean;
157
+ ai_crawler?: boolean;
158
+ userAgent: string;
159
+ ipAddress: string;
160
+ /** Full URL of the request, used to build the example in the discovery response */
161
+ requestUrl: string;
162
+ }
163
+ interface QueryHandlerResponse {
164
+ status: number;
165
+ body: AgentQueryResponse | QueryEndpointDiscovery | AgentErrorResponse;
166
+ headers: Record<string, string>;
167
+ }
168
+ declare function createQueryHandler(client: ApptvtyClient, config: ApptvtyConfig): (req: QueryHandlerRequest) => Promise<QueryHandlerResponse>;
169
+
170
+ export { AgentErrorResponse, AgentQueryResponse, ApptvtyApiError, ApptvtyClient, ApptvtyConfig, CrawlerBreakdown, CrawlerInfo, DailyStat, ImpressionLog, PageAdsResponse, QueryEndpointDiscovery, RecentActivityItem, RecentQueryItem, RequestLogEntry, RequestLogger, SiteOverviewStats, SiteWalletInfo, createQueryHandler, detectCrawler, getKnownCrawlerNames };