apptvty 0.1.4 → 0.2.0

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 (37) hide show
  1. package/README.md +37 -17
  2. package/dist/chunk-2KXDQCUZ.mjs +177 -0
  3. package/dist/chunk-2KXDQCUZ.mjs.map +1 -0
  4. package/dist/{chunk-XOWRKLFM.mjs → chunk-454YBHM2.mjs} +62 -34
  5. package/dist/chunk-454YBHM2.mjs.map +1 -0
  6. package/dist/chunk-OTPVLSG5.mjs +1084 -0
  7. package/dist/chunk-OTPVLSG5.mjs.map +1 -0
  8. package/dist/cli.js +75 -16
  9. package/dist/index.d.mts +138 -20
  10. package/dist/index.d.ts +138 -20
  11. package/dist/index.js +403 -45
  12. package/dist/index.js.map +1 -1
  13. package/dist/index.mjs +7 -3
  14. package/dist/middleware/express.d.mts +24 -5
  15. package/dist/middleware/express.d.ts +24 -5
  16. package/dist/middleware/express.js +676 -14
  17. package/dist/middleware/express.js.map +1 -1
  18. package/dist/middleware/express.mjs +4 -2
  19. package/dist/middleware/nextjs.d.mts +29 -6
  20. package/dist/middleware/nextjs.d.ts +29 -6
  21. package/dist/middleware/nextjs.js +641 -40
  22. package/dist/middleware/nextjs.js.map +1 -1
  23. package/dist/middleware/nextjs.mjs +4 -2
  24. package/dist/setup.d.mts +9 -0
  25. package/dist/setup.d.ts +9 -0
  26. package/dist/setup.js +6 -2
  27. package/dist/setup.js.map +1 -1
  28. package/dist/setup.mjs +6 -2
  29. package/dist/setup.mjs.map +1 -1
  30. package/dist/{types-C1oUTCsT.d.mts → types-D2A_0sPm.d.mts} +116 -2
  31. package/dist/{types-C1oUTCsT.d.ts → types-D2A_0sPm.d.ts} +116 -2
  32. package/package.json +1 -1
  33. package/dist/chunk-RGUS6IL6.mjs +0 -87
  34. package/dist/chunk-RGUS6IL6.mjs.map +0 -1
  35. package/dist/chunk-WATTAPBA.mjs +0 -502
  36. package/dist/chunk-WATTAPBA.mjs.map +0 -1
  37. package/dist/chunk-XOWRKLFM.mjs.map +0 -1
package/dist/index.d.ts CHANGED
@@ -1,25 +1,47 @@
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';
1
+ import { C as CrawlerInfo, A as ApptvtyConfig, R as RequestLogEntry, Q as QueryRequest, B as BackendQueryResponse, P as PageAdsResponse, I as ImpressionLog, S as SiteOverviewStats, D as DailyStat, a as RecentActivityItem, b as RecentQueryItem, c as CrawlerBreakdown, d as SiteWalletInfo, e as CreateCampaignParams, f as CampaignRecord, U as UpdateCampaignParams, g as InsufficientBalanceError, h as AgentQueryResponse, i as QueryEndpointDiscovery, j as AgentErrorResponse } from './types-D2A_0sPm.js';
2
+ export { k as CampaignStatus, l as PageAd, m as QuerySource, n as SponsoredAd } from './types-D2A_0sPm.js';
3
3
  export { createNextjsQueryHandler, withApptvty } from './middleware/nextjs.js';
4
4
  export { createExpressMiddleware, createExpressQueryHandler } from './middleware/express.js';
5
5
  import 'next/server';
6
6
  import 'node:http';
7
7
 
8
8
  /**
9
- * HTTP client for the Apptvty API.
9
+ * Lightweight AI crawler detection.
10
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
11
+ * This is the single source of truth for crawler classification in the SDK.
12
+ * The backend (Python analytics API and TypeScript handlers) should eventually
13
+ * consume this same list rather than maintaining separate copies.
15
14
  */
16
15
 
16
+ declare function detectCrawler(userAgent: string): CrawlerInfo;
17
+ /** Returns the list of all known crawlers for reference (e.g. for agents.txt generation) */
18
+ declare function getKnownCrawlerNames(): string[];
19
+ interface ScraperServiceInfo {
20
+ isScraperService: boolean;
21
+ /** Identifier of the matched service, or null if not a scraper service. */
22
+ name: string | null;
23
+ }
24
+ /**
25
+ * Detect whether the request comes from a known content-extraction scraper service
26
+ * (Jina, FireCrawl, Cloudflare Browser Rendering, etc.) rather than a direct AI crawler.
27
+ *
28
+ * Use this alongside detectCrawler() — scraper services are a distinct category:
29
+ * they proxy on behalf of an AI consumer but apply their own readability transform.
30
+ */
31
+ declare function detectScraperService(userAgent: string): ScraperServiceInfo;
32
+
17
33
  declare class ApptvtyClient {
18
34
  private readonly baseUrl;
19
35
  private readonly apiKey;
20
36
  private readonly siteId;
21
37
  private readonly debug;
38
+ private x402Token?;
22
39
  constructor(config: ApptvtyConfig);
40
+ /**
41
+ * Set the X402 (LSAT) token for subsequent requests.
42
+ * This is called after the agent has successfully paid an X402 challenge.
43
+ */
44
+ setX402Token(macaroon: string, preimage: string): void;
23
45
  /**
24
46
  * Send a batch of request log entries to the Apptvty ingestion API.
25
47
  * Called by the logger's auto-flush — not called directly by user code.
@@ -61,6 +83,10 @@ declare class ApptvtyClient {
61
83
  days: number;
62
84
  stats: DailyStat[];
63
85
  }>;
86
+ /** Get recent activity logs (last 48h). */
87
+ getRecentActivity(siteId: string, limit?: number, offset?: number): Promise<RecentActivityItem[]>;
88
+ /** Get recent agent queries. */
89
+ getRecentQueries(siteId: string, limit?: number, offset?: number): Promise<RecentQueryItem[]>;
64
90
  /** Get crawler breakdown by type (default 30 days). */
65
91
  getSiteCrawlers(days?: number): Promise<{
66
92
  days: number;
@@ -76,7 +102,87 @@ declare class ApptvtyClient {
76
102
  }>;
77
103
  /** Get wallet balance and earnings. */
78
104
  getSiteWallet(): Promise<SiteWalletInfo>;
105
+ /**
106
+ * Create an ad campaign. The campaign goes live immediately once the wallet
107
+ * has sufficient balance.
108
+ *
109
+ * If the wallet balance is too low, throws `ApptvtyInsufficientBalanceError`
110
+ * which includes deposit instructions so the agent can fund the wallet and retry.
111
+ *
112
+ * @example
113
+ * // Site-based: ad copy derived from your site's crawled content
114
+ * const campaign = await client.createCampaign({
115
+ * name: 'My Kubernetes Blog',
116
+ * advertiser_site_id: 'site_abc123',
117
+ * keywords: ['kubernetes', 'devops', 'containers'],
118
+ * categories: ['technology'],
119
+ * bid_per_view_usdc: 0.001,
120
+ * daily_budget_usdc: 1.0,
121
+ * total_budget_usdc: 20.0,
122
+ * });
123
+ *
124
+ * // Static: manually written ad copy
125
+ * const campaign = await client.createCampaign({
126
+ * name: 'My Blog — Static',
127
+ * ad_text: 'Deep dives on Kubernetes, written by practitioners.',
128
+ * landing_url: 'https://myblog.com',
129
+ * keywords: ['kubernetes', 'devops'],
130
+ * categories: ['technology'],
131
+ * bid_per_view_usdc: 0.001,
132
+ * daily_budget_usdc: 1.0,
133
+ * total_budget_usdc: 10.0,
134
+ * });
135
+ */
136
+ createCampaign(params: CreateCampaignParams): Promise<CampaignRecord>;
137
+ /**
138
+ * List all campaigns for this account.
139
+ * Also returns the schema (valid categories, minimum bid) so the agent
140
+ * knows valid field values without guessing.
141
+ */
142
+ listCampaigns(): Promise<{
143
+ campaigns: CampaignRecord[];
144
+ total: number;
145
+ schema: {
146
+ valid_categories: string[];
147
+ valid_statuses: string[];
148
+ bid_per_view_usdc_minimum: number;
149
+ };
150
+ }>;
151
+ /**
152
+ * Get a single campaign by ID, including current spend and impression count.
153
+ * `budget_remaining_usdc` tells the agent how much budget is left before
154
+ * the campaign auto-pauses.
155
+ */
156
+ getCampaign(campaignId: string): Promise<CampaignRecord>;
157
+ /**
158
+ * Partially update a campaign. Only fields present in `params` are changed.
159
+ *
160
+ * @example
161
+ * // Pause a campaign
162
+ * await client.updateCampaign(id, { status: 'paused' });
163
+ *
164
+ * // Increase bid and daily budget
165
+ * await client.updateCampaign(id, { bid_per_view_usdc: 0.002, daily_budget_usdc: 5.0 });
166
+ */
167
+ updateCampaign(campaignId: string, params: UpdateCampaignParams): Promise<CampaignRecord>;
168
+ /**
169
+ * Pause a campaign immediately. Equivalent to updateCampaign(id, { status: 'paused' }).
170
+ * Campaigns are never deleted — billing history is retained.
171
+ */
172
+ pauseCampaign(campaignId: string): Promise<void>;
173
+ /**
174
+ * Resume a paused campaign.
175
+ */
176
+ resumeCampaign(campaignId: string): Promise<void>;
79
177
  private get;
178
+ private patch;
179
+ private delete;
180
+ /**
181
+ * Settle an X402 challenge from the site's own USDC wallet balance.
182
+ * Called automatically when `post()` receives a 402 with an X402 header.
183
+ * Returns the preimage on success, or throws if the wallet balance is too low.
184
+ */
185
+ private payX402Challenge;
80
186
  private post;
81
187
  private log;
82
188
  private warn;
@@ -87,6 +193,30 @@ declare class ApptvtyApiError extends Error {
87
193
  readonly body: string;
88
194
  constructor(statusCode: number, path: string, body: string);
89
195
  }
196
+ /**
197
+ * Thrown by createCampaign() when the wallet balance is too low.
198
+ *
199
+ * The `details` property contains everything needed to fund the wallet
200
+ * autonomously and retry — the agent can inspect `details.deposit.address`
201
+ * and send USDC on Base without human intervention.
202
+ *
203
+ * @example
204
+ * import { ApptvtyInsufficientBalanceError } from 'apptvty';
205
+ *
206
+ * try {
207
+ * await client.createCampaign(params);
208
+ * } catch (err) {
209
+ * if (err instanceof ApptvtyInsufficientBalanceError) {
210
+ * const { shortfall_usdc, deposit } = err.details;
211
+ * // Agent can now: send shortfall_usdc USDC to deposit.address on deposit.chain
212
+ * // Then retry createCampaign
213
+ * }
214
+ * }
215
+ */
216
+ declare class ApptvtyInsufficientBalanceError extends Error {
217
+ readonly details: InsufficientBalanceError | undefined;
218
+ constructor(details: InsufficientBalanceError | undefined);
219
+ }
90
220
 
91
221
  /**
92
222
  * Batched request logger.
@@ -122,18 +252,6 @@ declare class RequestLogger {
122
252
  private log;
123
253
  }
124
254
 
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
255
  /**
138
256
  * Framework-agnostic query endpoint handler.
139
257
  *
@@ -167,4 +285,4 @@ interface QueryHandlerResponse {
167
285
  }
168
286
  declare function createQueryHandler(client: ApptvtyClient, config: ApptvtyConfig): (req: QueryHandlerRequest) => Promise<QueryHandlerResponse>;
169
287
 
170
- export { AgentErrorResponse, AgentQueryResponse, ApptvtyApiError, ApptvtyClient, ApptvtyConfig, CrawlerBreakdown, CrawlerInfo, DailyStat, ImpressionLog, PageAdsResponse, QueryEndpointDiscovery, RecentActivityItem, RecentQueryItem, RequestLogEntry, RequestLogger, SiteOverviewStats, SiteWalletInfo, createQueryHandler, detectCrawler, getKnownCrawlerNames };
288
+ export { AgentErrorResponse, AgentQueryResponse, ApptvtyApiError, ApptvtyClient, ApptvtyConfig, ApptvtyInsufficientBalanceError, CampaignRecord, CrawlerBreakdown, CrawlerInfo, CreateCampaignParams, DailyStat, ImpressionLog, InsufficientBalanceError, PageAdsResponse, QueryEndpointDiscovery, RecentActivityItem, RecentQueryItem, RequestLogEntry, RequestLogger, type ScraperServiceInfo, SiteOverviewStats, SiteWalletInfo, UpdateCampaignParams, createQueryHandler, detectCrawler, detectScraperService, getKnownCrawlerNames };