apptvty 0.1.5 → 0.2.1

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.
@@ -20,6 +20,7 @@ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: tru
20
20
  // src/middleware/nextjs.ts
21
21
  var nextjs_exports = {};
22
22
  __export(nextjs_exports, {
23
+ createNextjsDashboardHandler: () => createNextjsDashboardHandler,
23
24
  createNextjsQueryHandler: () => createNextjsQueryHandler,
24
25
  withApptvty: () => withApptvty
25
26
  });
@@ -39,6 +40,13 @@ var ApptvtyClient = class {
39
40
  this.siteId = config.siteId;
40
41
  this.debug = config.debug ?? false;
41
42
  }
43
+ /**
44
+ * Set the X402 (LSAT) token for subsequent requests.
45
+ * This is called after the agent has successfully paid an X402 challenge.
46
+ */
47
+ setX402Token(macaroon, preimage) {
48
+ this.x402Token = `LSAT ${macaroon}:${preimage}`;
49
+ }
42
50
  /**
43
51
  * Send a batch of request log entries to the Apptvty ingestion API.
44
52
  * Called by the logger's auto-flush — not called directly by user code.
@@ -111,6 +119,20 @@ var ApptvtyClient = class {
111
119
  async getSiteDailyStats(days = 30) {
112
120
  return this.get(`/v1/sites/${this.siteId}/stats/daily`, { days: String(days) });
113
121
  }
122
+ /** Get recent activity logs (last 48h). */
123
+ async getRecentActivity(siteId, limit = 50, offset = 0) {
124
+ return this.get(`/v1/sites/${siteId}/activity`, {
125
+ limit: String(limit),
126
+ offset: String(offset)
127
+ });
128
+ }
129
+ /** Get recent agent queries. */
130
+ async getRecentQueries(siteId, limit = 20, offset = 0) {
131
+ return this.get(`/v1/sites/${siteId}/queries`, {
132
+ limit: String(limit),
133
+ offset: String(offset)
134
+ });
135
+ }
114
136
  /** Get crawler breakdown by type (default 30 days). */
115
137
  async getSiteCrawlers(days = 30) {
116
138
  return this.get(`/v1/sites/${this.siteId}/crawlers`, { days: String(days) });
@@ -127,6 +149,106 @@ var ApptvtyClient = class {
127
149
  async getSiteWallet() {
128
150
  return this.get(`/v1/sites/${this.siteId}/wallet`);
129
151
  }
152
+ // ─── Campaign management (for coding agents) ────────────────────────────────
153
+ //
154
+ // A coding agent that installed the SDK can create and manage ad campaigns
155
+ // programmatically — no human dashboard login required.
156
+ //
157
+ // Typical agentic advertiser flow:
158
+ // 1. Check wallet balance: const w = await client.getSiteWallet()
159
+ // 2. Fund wallet if needed: send USDC to w.wallet_address on Base chain
160
+ // 3. Create campaign: await client.createCampaign({ ... })
161
+ // 4. Monitor performance: await client.getCampaign(id)
162
+ // 5. Adjust or pause: await client.updateCampaign(id, { status: 'paused' })
163
+ /**
164
+ * Create an ad campaign. The campaign goes live immediately once the wallet
165
+ * has sufficient balance.
166
+ *
167
+ * If the wallet balance is too low, throws `ApptvtyInsufficientBalanceError`
168
+ * which includes deposit instructions so the agent can fund the wallet and retry.
169
+ *
170
+ * @example
171
+ * // Site-based: ad copy derived from your site's crawled content
172
+ * const campaign = await client.createCampaign({
173
+ * name: 'My Kubernetes Blog',
174
+ * advertiser_site_id: 'site_abc123',
175
+ * keywords: ['kubernetes', 'devops', 'containers'],
176
+ * categories: ['technology'],
177
+ * bid_per_view_usdc: 0.001,
178
+ * daily_budget_usdc: 1.0,
179
+ * total_budget_usdc: 20.0,
180
+ * });
181
+ *
182
+ * // Static: manually written ad copy
183
+ * const campaign = await client.createCampaign({
184
+ * name: 'My Blog — Static',
185
+ * ad_text: 'Deep dives on Kubernetes, written by practitioners.',
186
+ * landing_url: 'https://myblog.com',
187
+ * keywords: ['kubernetes', 'devops'],
188
+ * categories: ['technology'],
189
+ * bid_per_view_usdc: 0.001,
190
+ * daily_budget_usdc: 1.0,
191
+ * total_budget_usdc: 10.0,
192
+ * });
193
+ */
194
+ async createCampaign(params) {
195
+ try {
196
+ return await this.post("/v1/campaigns", params);
197
+ } catch (err) {
198
+ if (err instanceof ApptvtyApiError && err.statusCode === 402) {
199
+ let details;
200
+ try {
201
+ const body = JSON.parse(err.body);
202
+ details = body?.error;
203
+ } catch {
204
+ }
205
+ throw new ApptvtyInsufficientBalanceError(details);
206
+ }
207
+ throw err;
208
+ }
209
+ }
210
+ /**
211
+ * List all campaigns for this account.
212
+ * Also returns the schema (valid categories, minimum bid) so the agent
213
+ * knows valid field values without guessing.
214
+ */
215
+ async listCampaigns() {
216
+ return this.get("/v1/campaigns");
217
+ }
218
+ /**
219
+ * Get a single campaign by ID, including current spend and impression count.
220
+ * `budget_remaining_usdc` tells the agent how much budget is left before
221
+ * the campaign auto-pauses.
222
+ */
223
+ async getCampaign(campaignId) {
224
+ return this.get(`/v1/campaigns/${campaignId}`);
225
+ }
226
+ /**
227
+ * Partially update a campaign. Only fields present in `params` are changed.
228
+ *
229
+ * @example
230
+ * // Pause a campaign
231
+ * await client.updateCampaign(id, { status: 'paused' });
232
+ *
233
+ * // Increase bid and daily budget
234
+ * await client.updateCampaign(id, { bid_per_view_usdc: 0.002, daily_budget_usdc: 5.0 });
235
+ */
236
+ async updateCampaign(campaignId, params) {
237
+ return this.patch(`/v1/campaigns/${campaignId}`, params);
238
+ }
239
+ /**
240
+ * Pause a campaign immediately. Equivalent to updateCampaign(id, { status: 'paused' }).
241
+ * Campaigns are never deleted — billing history is retained.
242
+ */
243
+ async pauseCampaign(campaignId) {
244
+ await this.delete(`/v1/campaigns/${campaignId}`);
245
+ }
246
+ /**
247
+ * Resume a paused campaign.
248
+ */
249
+ async resumeCampaign(campaignId) {
250
+ await this.patch(`/v1/campaigns/${campaignId}`, { status: "active" });
251
+ }
130
252
  async get(path, params) {
131
253
  const url = new URL(`${this.baseUrl}${path}`);
132
254
  if (params) {
@@ -135,9 +257,27 @@ var ApptvtyClient = class {
135
257
  const response = await fetch(url.toString(), {
136
258
  method: "GET",
137
259
  headers: {
138
- Authorization: `Bearer ${this.apiKey}`,
260
+ Authorization: this.x402Token ?? `Bearer ${this.apiKey}`,
261
+ "User-Agent": "apptvty-sdk/0.1.0"
262
+ },
263
+ signal: AbortSignal.timeout(1e4)
264
+ });
265
+ if (!response.ok) {
266
+ const text = await response.text().catch(() => "");
267
+ throw new ApptvtyApiError(response.status, path, text);
268
+ }
269
+ return response.json();
270
+ }
271
+ async patch(path, body) {
272
+ const url = `${this.baseUrl}${path}`;
273
+ const response = await fetch(url, {
274
+ method: "PATCH",
275
+ headers: {
276
+ "Authorization": this.x402Token ?? `Bearer ${this.apiKey}`,
277
+ "Content-Type": "application/json",
139
278
  "User-Agent": "apptvty-sdk/0.1.0"
140
279
  },
280
+ body: JSON.stringify(body),
141
281
  signal: AbortSignal.timeout(1e4)
142
282
  });
143
283
  if (!response.ok) {
@@ -146,22 +286,73 @@ var ApptvtyClient = class {
146
286
  }
147
287
  return response.json();
148
288
  }
289
+ async delete(path) {
290
+ const url = `${this.baseUrl}${path}`;
291
+ const response = await fetch(url, {
292
+ method: "DELETE",
293
+ headers: {
294
+ "Authorization": this.x402Token ?? `Bearer ${this.apiKey}`,
295
+ "User-Agent": "apptvty-sdk/0.1.0"
296
+ },
297
+ signal: AbortSignal.timeout(1e4)
298
+ });
299
+ if (!response.ok) {
300
+ const text = await response.text().catch(() => "");
301
+ throw new ApptvtyApiError(response.status, path, text);
302
+ }
303
+ }
304
+ /**
305
+ * Settle an X402 challenge from the site's own USDC wallet balance.
306
+ * Called automatically when `post()` receives a 402 with an X402 header.
307
+ * Returns the preimage on success, or throws if the wallet balance is too low.
308
+ */
309
+ async payX402Challenge(macaroon) {
310
+ const url = `${this.baseUrl}/v1/x402/pay`;
311
+ const response = await fetch(url, {
312
+ method: "POST",
313
+ headers: {
314
+ Authorization: `Bearer ${this.apiKey}`,
315
+ "Content-Type": "application/json",
316
+ "User-Agent": "apptvty-sdk/0.1.0"
317
+ },
318
+ body: JSON.stringify({ macaroon }),
319
+ signal: AbortSignal.timeout(1e4)
320
+ });
321
+ const text = await response.text().catch(() => "");
322
+ if (!response.ok) {
323
+ let details;
324
+ try {
325
+ details = JSON.parse(text)?.error?.details;
326
+ } catch {
327
+ }
328
+ throw new ApptvtyInsufficientBalanceError(details);
329
+ }
330
+ const json = JSON.parse(text);
331
+ return json.preimage;
332
+ }
149
333
  async post(path, body) {
150
334
  const url = `${this.baseUrl}${path}`;
151
335
  const response = await fetch(url, {
152
336
  method: "POST",
153
337
  headers: {
154
- "Authorization": `Bearer ${this.apiKey}`,
338
+ "Authorization": this.x402Token ?? `Bearer ${this.apiKey}`,
155
339
  "Content-Type": "application/json",
156
340
  "User-Agent": "apptvty-sdk/0.1.0"
157
341
  },
158
342
  body: JSON.stringify(body),
159
- // Node 18+ fetch: set a reasonable timeout via AbortSignal
160
343
  signal: AbortSignal.timeout(1e4)
161
344
  });
162
345
  if (!response.ok) {
163
346
  const text = await response.text().catch(() => "");
164
347
  if (response.status === 402) {
348
+ const authHeader = response.headers.get("WWW-Authenticate");
349
+ if (authHeader?.includes("X402") || authHeader?.includes("LSAT")) {
350
+ const macaroon = authHeader.match(/macaroon="([^"]+)"/)?.[1] || "";
351
+ const preimage = await this.payX402Challenge(macaroon);
352
+ this.setX402Token(macaroon, preimage);
353
+ this.log("X402 challenge auto-paid from wallet, retrying request");
354
+ return this.post(path, body);
355
+ }
165
356
  let dashboardUrl = "https://dashboard.apptvty.com/login";
166
357
  try {
167
358
  const json = JSON.parse(text);
@@ -197,6 +388,16 @@ var ApptvtyTrialExpiredError = class extends Error {
197
388
  this.name = "ApptvtyTrialExpiredError";
198
389
  }
199
390
  };
391
+ var ApptvtyInsufficientBalanceError = class extends Error {
392
+ constructor(details) {
393
+ const shortfall = details?.shortfall_usdc ?? "?";
394
+ super(
395
+ `Wallet balance too low to create campaign. Send ${shortfall} USDC to ${details?.deposit?.address ?? "your wallet"} on Base and retry.`
396
+ );
397
+ this.details = details;
398
+ this.name = "ApptvtyInsufficientBalanceError";
399
+ }
400
+ };
200
401
 
201
402
  // src/crawler.ts
202
403
  var KNOWN_CRAWLERS = [
@@ -306,6 +507,27 @@ function extractBotName(userAgent) {
306
507
  }
307
508
  return "unknown_ai_bot";
308
509
  }
510
+ var SCRAPER_SERVICES = [
511
+ // Jina AI Reader — r.jina.ai/URL — converts any page to clean Markdown
512
+ { name: "JinaReader", patterns: [/JinaReader/i] },
513
+ // Cloudflare Browser Rendering /crawl endpoint (open beta, announced March 2026)
514
+ { name: "Cloudflare-BrowserRendering", patterns: [/CloudflareBrowserRenderingCrawler/i] },
515
+ // FireCrawl — LLM-ready content extraction service
516
+ { name: "FireCrawl", patterns: [/FireCrawlAgent/i, /firecrawl/i] },
517
+ // Apify web scraping platform
518
+ { name: "Apify", patterns: [/ApifyBot/i] }
519
+ ];
520
+ function detectScraperService(userAgent) {
521
+ if (!userAgent) return { isScraperService: false, name: null };
522
+ for (const service of SCRAPER_SERVICES) {
523
+ for (const pattern of service.patterns) {
524
+ if (pattern.test(userAgent)) {
525
+ return { isScraperService: true, name: service.name };
526
+ }
527
+ }
528
+ }
529
+ return { isScraperService: false, name: null };
530
+ }
309
531
 
310
532
  // src/logger.ts
311
533
  var RequestLogger = class {
@@ -522,6 +744,366 @@ function getOrigin(url) {
522
744
  }
523
745
  }
524
746
 
747
+ // src/dashboard-handler.ts
748
+ function createDashboardHandler(client, config) {
749
+ return async function handleDashboard(req) {
750
+ const { path, method, authHeader } = req;
751
+ if (config.dashboardSecret) {
752
+ const url = new URL(path, "http://localhost");
753
+ const secretParam = url.searchParams.get("secret");
754
+ const bearerToken = authHeader?.startsWith("Bearer ") ? authHeader.substring(7) : null;
755
+ const isAuthorized = secretParam === config.dashboardSecret || bearerToken === config.dashboardSecret;
756
+ if (!isAuthorized) {
757
+ return jsonResponse(401, {
758
+ error: "Unauthorized",
759
+ message: "Dashboard access requires a valid secret. Please set APPTVTY_DASHBOARD_SECRET."
760
+ });
761
+ }
762
+ }
763
+ if (path.includes("/api/overview")) {
764
+ const data = await client.getSiteStats();
765
+ return jsonResponse(200, data);
766
+ }
767
+ if (path.endsWith("/api/activity")) {
768
+ const url = new URL(path, "http://localhost");
769
+ const limit = parseInt(url.searchParams.get("limit") || "50");
770
+ const offset = parseInt(url.searchParams.get("offset") || "0");
771
+ const data = await client.getRecentActivity(config.siteId, limit, offset);
772
+ return jsonResponse(200, data);
773
+ }
774
+ if (path.endsWith("/api/queries")) {
775
+ const url = new URL(path, "http://localhost");
776
+ const limit = parseInt(url.searchParams.get("limit") || "20");
777
+ const offset = parseInt(url.searchParams.get("offset") || "0");
778
+ const data = await client.getRecentQueries(config.siteId, limit, offset);
779
+ return jsonResponse(200, data);
780
+ }
781
+ if (path.endsWith("/api/stats")) {
782
+ const data = await client.getSiteDailyStats();
783
+ return jsonResponse(200, data);
784
+ }
785
+ const html = getDashboardHtml(config);
786
+ return {
787
+ status: 200,
788
+ body: html,
789
+ headers: { "Content-Type": "text/html" }
790
+ };
791
+ };
792
+ }
793
+ function jsonResponse(status, data) {
794
+ return {
795
+ status,
796
+ body: JSON.stringify(data),
797
+ headers: { "Content-Type": "application/json" }
798
+ };
799
+ }
800
+ function getDashboardHtml(config) {
801
+ return `
802
+ <!DOCTYPE html>
803
+ <html lang="en" class="dark">
804
+ <head>
805
+ <meta charset="UTF-8">
806
+ <meta name="viewport" content="width=device-width, initial-scale=1.0">
807
+ <title>Apptvty Logs \u2014 ${config.siteId}</title>
808
+ <script src="https://cdn.tailwindcss.com"></script>
809
+ <script src="https://unpkg.com/lucide@latest"></script>
810
+ <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
811
+ <style>
812
+ @import url('https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700&display=swap');
813
+ body { font-family: 'Inter', sans-serif; background-color: #09090b; color: #fafafa; }
814
+ .glass { background: rgba(24, 24, 27, 0.8); backdrop-filter: blur(12px); border: 1px solid rgba(39, 39, 42, 1); }
815
+ .gradient-text { background: linear-gradient(to right, #60a5fa, #a855f7); -webkit-background-clip: text; -webkit-text-fill-color: transparent; }
816
+ </style>
817
+ </head>
818
+ <body class="p-6">
819
+ <div id="app" class="max-w-7xl mx-auto space-y-6">
820
+ <!-- Header -->
821
+ <header class="flex justify-between items-center mb-8">
822
+ <div>
823
+ <h1 class="text-3xl font-bold gradient-text">Activity Logs</h1>
824
+ <p class="text-zinc-400">Real-time agentic insights for ${config.siteId}</p>
825
+ </div>
826
+ <div class="flex items-center gap-3">
827
+ <span class="flex h-2 w-2 rounded-full bg-green-500 animate-pulse"></span>
828
+ <span class="text-sm font-medium text-zinc-300">Live Connection</span>
829
+ </div>
830
+ </header>
831
+
832
+ <!-- Stats Grid -->
833
+ <div class="grid grid-cols-1 md:grid-cols-4 gap-4" id="stats-grid">
834
+ <div class="glass p-5 rounded-2xl animate-pulse h-24"></div>
835
+ <div class="glass p-5 rounded-2xl animate-pulse h-24"></div>
836
+ <div class="glass p-5 rounded-2xl animate-pulse h-24"></div>
837
+ <div class="glass p-5 rounded-2xl animate-pulse h-24"></div>
838
+ </div>
839
+
840
+ <!-- Main Content -->
841
+ <div class="grid grid-cols-1 lg:grid-cols-3 gap-6">
842
+ <!-- Traffic Chart -->
843
+ <div class="lg:col-span-2 glass p-6 rounded-2xl">
844
+ <h2 class="text-lg font-semibold mb-4">Traffic Overview</h2>
845
+ <div class="h-[300px]">
846
+ <canvas id="trafficChart"></canvas>
847
+ </div>
848
+ </div>
849
+
850
+ <!-- Recent Queries -->
851
+ <div class="glass p-6 rounded-2xl flex flex-col h-[400px]">
852
+ <div class="flex justify-between items-center mb-4">
853
+ <h2 class="text-lg font-semibold">Agent Queries</h2>
854
+ <button id="load-more-queries" class="text-xs text-blue-400 hover:text-blue-300 transition-colors">Load More</button>
855
+ </div>
856
+ <div id="queries-list" class="flex-1 overflow-y-auto space-y-3 custom-scrollbar">
857
+ <div class="text-zinc-500 text-sm italic">Loading queries...</div>
858
+ </div>
859
+ </div>
860
+ </div>
861
+
862
+ <!-- Real-time Activity Table -->
863
+ <div class="glass p-6 rounded-2xl overflow-hidden">
864
+ <div class="flex justify-between items-center mb-4">
865
+ <h2 class="text-lg font-semibold">Real-time Activity</h2>
866
+ <button id="load-more-activity" class="text-sm px-3 py-1 bg-zinc-800 hover:bg-zinc-700 rounded-lg text-zinc-300 transition-colors">Load More</button>
867
+ </div>
868
+ <div class="overflow-x-auto">
869
+ <table class="w-full text-left">
870
+ <thead>
871
+ <tr class="text-zinc-500 text-sm border-b border-zinc-800">
872
+ <th class="pb-3 pr-4">Timestamp</th>
873
+ <th class="pb-3 pr-4">Method</th>
874
+ <th class="pb-3 pr-4">Path</th>
875
+ <th class="pb-3 pr-4">Agent</th>
876
+ <th class="pb-3">Status</th>
877
+ </tr>
878
+ </thead>
879
+ <tbody id="activity-body" class="text-sm">
880
+ <tr><td colspan="5" class="pt-4 text-zinc-500 italic">Connecting to activity stream...</td></tr>
881
+ </tbody>
882
+ </table>
883
+ </div>
884
+ </div>
885
+ </div>
886
+
887
+ <script>
888
+ const API_BASE = window.location.pathname.replace(//$/, '');
889
+ let queryOffset = 0;
890
+ let activityOffset = 0;
891
+ const LIMIT_QUERIES = 20;
892
+ const LIMIT_ACTIVITY = 50;
893
+
894
+ async function fetchData() {
895
+ try {
896
+ // Initial load or refresh (offset 0 resets)
897
+ const [overview, stats] = await Promise.all([
898
+ fetch(\`\${API_BASE}/api/overview\`).then(r => r.json()),
899
+ fetch(\`\${API_BASE}/api/stats\`).then(r => r.json())
900
+ ]);
901
+
902
+ updateStats(overview);
903
+ initChart(stats);
904
+
905
+ // Fetch first pages if empty
906
+ if (queryOffset === 0) fetchQueries(true);
907
+ if (activityOffset === 0) fetchActivity(true);
908
+ } catch (err) {
909
+ console.error('Failed to fetch dashboard data:', err);
910
+ }
911
+ }
912
+
913
+ async function fetchQueries(replace = false) {
914
+ try {
915
+ const data = await fetch(\`\${API_BASE}/api/queries?limit=\${LIMIT_QUERIES}&offset=\${queryOffset}\`).then(r => r.json());
916
+ updateQueries(data, replace);
917
+ } catch (e) { console.error('Queries error:', e); }
918
+ }
919
+
920
+ async function fetchActivity(replace = false) {
921
+ try {
922
+ const data = await fetch(\`\${API_BASE}/api/activity?limit=\${LIMIT_ACTIVITY}&offset=\${activityOffset}\`).then(r => r.json());
923
+ updateActivity(data, replace);
924
+ } catch (e) { console.error('Activity error:', e); }
925
+ }
926
+
927
+ function updateStats(data) {
928
+ const grid = document.getElementById('stats-grid');
929
+ grid.innerHTML = \`
930
+ <div class="glass p-5 rounded-2xl">
931
+ <p class="text-zinc-400 text-xs font-medium uppercase tracking-wider mb-1">Total Requests</p>
932
+ <p class="text-2xl font-bold">\${data.total_requests_30d.toLocaleString()}</p>
933
+ </div>
934
+ <div class="glass p-5 rounded-2xl border-l-4 border-blue-500">
935
+ <p class="text-zinc-400 text-xs font-medium uppercase tracking-wider mb-1">AI Requests</p>
936
+ <p class="text-2xl font-bold">\${data.ai_requests_30d.toLocaleString()}</p>
937
+ </div>
938
+ <div class="glass p-5 rounded-2xl">
939
+ <p class="text-zinc-400 text-xs font-medium uppercase tracking-wider mb-1">AI Percentage</p>
940
+ <p class="text-2xl font-bold text-blue-400">\${data.ai_percentage.toFixed(1)}%</p>
941
+ </div>
942
+ <div class="glass p-5 rounded-2xl">
943
+ <p class="text-zinc-400 text-xs font-medium uppercase tracking-wider mb-1">Health Status</p>
944
+ <p class="text-2xl font-bold text-green-400">Optimal</p>
945
+ </div>
946
+ \`;
947
+ }
948
+
949
+ function updateQueries(data, replace) {
950
+ const list = document.getElementById('queries-list');
951
+ const items = Array.isArray(data) ? data : (data.queries || []);
952
+ const rows = items.map(q => \`
953
+ <div class="p-3 bg-zinc-900/50 rounded-xl border border-zinc-800 hover:border-zinc-700 transition-colors">
954
+ <p class="text-sm font-medium text-zinc-200">\${q.question || q.query}</p>
955
+ <div class="mt-2 flex justify-between items-center text-[10px] text-zinc-500">
956
+ <span class="flex items-center gap-1">
957
+ <i data-lucide="clock" class="w-3 h-3"></i>
958
+ \${new Date(q.timestamp).toLocaleString()}
959
+ </span>
960
+ <span class="px-2 py-0.5 rounded-full bg-blue-500/10 text-blue-400 border border-blue-500/20">
961
+ Agent Match
962
+ </span>
963
+ </div>
964
+ </div>
965
+ \`).join('');
966
+
967
+ if (replace) list.innerHTML = rows || '<div class="text-zinc-600 text-sm">No recent queries.</div>';
968
+ else list.insertAdjacentHTML('beforeend', rows);
969
+ lucide.createIcons();
970
+ }
971
+
972
+ function updateActivity(data, replace) {
973
+ const body = document.getElementById('activity-body');
974
+ const items = Array.isArray(data) ? data : (data.activity || []);
975
+ const rows = items.map(r => \`
976
+ <tr class="border-b border-zinc-800/50 hover:bg-zinc-800/20 transition-colors">
977
+ <td class="py-3 pr-4 text-zinc-400 text-xs">\${new Date(r.timestamp || r.created_at).toLocaleTimeString()}</td>
978
+ <td class="py-3 pr-4 font-mono text-[10px] tracking-tight text-blue-400">\${r.method}</td>
979
+ <td class="py-3 pr-4 text-zinc-300 max-w-xs truncate">\${r.path}</td>
980
+ <td class="py-3 pr-4 text-zinc-500">\${r.crawler_type || 'Human'}</td>
981
+ <td class="py-3">
982
+ <span class="px-2 py-0.5 rounded-md \${r.status_code >= 400 ? 'bg-red-500/10 text-red-400' : 'bg-green-500/10 text-green-400'} text-[10px] font-medium border border-current/20">
983
+ \${r.status_code || 200}
984
+ </span>
985
+ </td>
986
+ </tr>
987
+ \`).join('');
988
+
989
+ if (replace) body.innerHTML = rows || '<tr><td colspan="5" class="py-4 text-center text-zinc-600">No activity.</td></tr>';
990
+ else body.insertAdjacentHTML('beforeend', rows);
991
+ }
992
+
993
+ function initChart(stats) {
994
+ const canvas = document.getElementById('trafficChart');
995
+ if (window.myChart) window.myChart.destroy();
996
+ const ctx = canvas.getContext('2d');
997
+ window.myChart = new Chart(ctx, {
998
+ type: 'line',
999
+ data: {
1000
+ labels: stats.map(s => s.date.split('-').slice(1).join('/')),
1001
+ datasets: [
1002
+ {
1003
+ label: 'AI Requests',
1004
+ data: stats.map(s => s.ai_requests),
1005
+ borderColor: '#3b82f6',
1006
+ backgroundColor: 'rgba(59, 130, 246, 0.1)',
1007
+ fill: true,
1008
+ tension: 0.4
1009
+ },
1010
+ {
1011
+ label: 'Total Requests',
1012
+ data: stats.map(s => s.total_requests),
1013
+ borderColor: '#8b5cf6',
1014
+ backgroundColor: 'rgba(139, 92, 246, 0.1)',
1015
+ fill: true,
1016
+ tension: 0.4
1017
+ }
1018
+ ]
1019
+ },
1020
+ options: {
1021
+ responsive: true,
1022
+ maintainAspectRatio: false,
1023
+ plugins: { legend: { display: false }, tooltip: { mode: 'index', intersect: false } },
1024
+ scales: {
1025
+ y: { beginAtZero: true, grid: { color: 'rgba(39, 39, 42, 0.5)' }, ticks: { color: '#71717a' } },
1026
+ x: { grid: { display: false }, ticks: { color: '#71717a' } }
1027
+ }
1028
+ }
1029
+ });
1030
+ }
1031
+
1032
+ document.getElementById('load-more-queries').onclick = () => {
1033
+ queryOffset += LIMIT_QUERIES;
1034
+ fetchQueries(false);
1035
+ };
1036
+
1037
+ document.getElementById('load-more-activity').onclick = () => {
1038
+ activityOffset += LIMIT_ACTIVITY;
1039
+ fetchActivity(false);
1040
+ };
1041
+
1042
+ fetchData();
1043
+ setInterval(fetchData, 30000); // Polling for updates (stats only)
1044
+ </script>
1045
+ </body>
1046
+ </html>
1047
+ `;
1048
+ }
1049
+
1050
+ // src/ad-injection.ts
1051
+ var AD_INJECTION_MARKER = "<!-- apptvty-sponsored -->";
1052
+ function injectIntoHtml(html, ads, isScraperService) {
1053
+ if (!html || ads.length === 0) return html;
1054
+ if (html.includes(AD_INJECTION_MARKER)) return html;
1055
+ let modified = html;
1056
+ const contentBlock = buildContentStreamBlock(ads);
1057
+ if (modified.includes("</article>")) {
1058
+ modified = modified.replace("</article>", `${contentBlock}
1059
+ </article>`);
1060
+ } else if (modified.includes("</main>")) {
1061
+ modified = modified.replace("</main>", `${contentBlock}
1062
+ </main>`);
1063
+ } else if (!isScraperService && modified.includes("</body>")) {
1064
+ modified = modified.replace("</body>", `${contentBlock}
1065
+ </body>`);
1066
+ }
1067
+ if (!isScraperService && modified.includes("</head>")) {
1068
+ const jsonLdBlock = buildJsonLdBlock(ads);
1069
+ modified = modified.replace("</head>", `${jsonLdBlock}
1070
+ </head>`);
1071
+ }
1072
+ return modified;
1073
+ }
1074
+ function buildSponsoredHeader(ads) {
1075
+ return JSON.stringify(
1076
+ ads.map((ad) => ({ text: ad.text, url: ad.url, advertiser: ad.advertiser }))
1077
+ );
1078
+ }
1079
+ function buildContentStreamBlock(ads) {
1080
+ const paragraphs = ads.map(
1081
+ (ad) => `<p data-apptvty-sponsored="${escapeAttr(ad.impression_id)}"><strong>[Sponsored]</strong> <a href="${escapeAttr(ad.url)}" rel="sponsored noopener">${escapeHtml(ad.text)}</a> \u2014 <span>${escapeHtml(ad.advertiser)}</span></p>`
1082
+ ).join("\n");
1083
+ return `${AD_INJECTION_MARKER}
1084
+ ${paragraphs}`;
1085
+ }
1086
+ function buildJsonLdBlock(ads) {
1087
+ const entries = ads.map((ad) => ({
1088
+ "@context": "https://schema.org",
1089
+ "@type": "WPAdBlock",
1090
+ sponsor: {
1091
+ "@type": "Organization",
1092
+ name: ad.advertiser,
1093
+ url: ad.url
1094
+ },
1095
+ description: ad.text
1096
+ }));
1097
+ const ld = entries.length === 1 ? entries[0] : entries;
1098
+ return `<script type="application/ld+json">${JSON.stringify(ld)}</script>`;
1099
+ }
1100
+ function escapeHtml(s) {
1101
+ return s.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;").replace(/'/g, "&#39;");
1102
+ }
1103
+ function escapeAttr(s) {
1104
+ return s.replace(/"/g, "&quot;").replace(/'/g, "&#39;");
1105
+ }
1106
+
525
1107
  // src/middleware/nextjs.ts
526
1108
  function headersToRecord(h) {
527
1109
  const entries = h.entries();
@@ -544,8 +1126,9 @@ function withApptvty(config, next) {
544
1126
  const startMs = Date.now();
545
1127
  const userAgent = request.headers.get("user-agent") ?? "";
546
1128
  const crawlerInfo = detectCrawler(userAgent);
1129
+ const scraperService = detectScraperService(userAgent);
547
1130
  const aiCrawlerParam = parseBoolParam(request.nextUrl.searchParams.get("ai_crawler"), false);
548
- const isCrawler = crawlerInfo.isAi || aiCrawlerParam;
1131
+ const isCrawler = crawlerInfo.isAi || aiCrawlerParam || scraperService.isScraperService;
549
1132
  let response;
550
1133
  try {
551
1134
  response = next ? await next(request) : import_server.NextResponse.next();
@@ -571,14 +1154,23 @@ function withApptvty(config, next) {
571
1154
  is_ai_crawler: crawlerInfo.isAi,
572
1155
  crawler_type: crawlerInfo.name,
573
1156
  crawler_organization: crawlerInfo.organization,
574
- confidence_score: crawlerInfo.confidence
1157
+ confidence_score: crawlerInfo.confidence,
1158
+ scraper_service: scraperService.name
575
1159
  };
576
1160
  logger.enqueue(entry);
577
1161
  if (isCrawler && response.ok && !pathname.startsWith(queryPath)) {
578
1162
  const contentType = response.headers.get("content-type") ?? "";
579
1163
  if (contentType.includes("text/html")) {
580
1164
  try {
581
- const modified = await injectAdsIntoHtml(response, client, config.siteId, pathname);
1165
+ const modified = await injectAdsIntoResponse(
1166
+ response,
1167
+ client,
1168
+ config,
1169
+ pathname,
1170
+ userAgent,
1171
+ getClientIp(headers),
1172
+ scraperService.isScraperService
1173
+ );
582
1174
  if (modified) return modified;
583
1175
  } catch (err) {
584
1176
  if (config.debug) console.warn("[apptvty] Ad injection failed:", err);
@@ -614,40 +1206,54 @@ function createNextjsQueryHandler(config) {
614
1206
  });
615
1207
  };
616
1208
  }
617
- var AD_INJECTION_MARKER = "<!-- apptvty-sponsored -->";
618
- function buildAdBlock(ads) {
619
- const items = ads.map(
620
- (ad) => `<li><a href="${escapeHtml(ad.url)}" rel="nofollow">${escapeHtml(ad.text)}</a> <small>\u2014 ${escapeHtml(ad.advertiser)}</small></li>`
621
- ).join("\n");
622
- return `
623
- <section aria-label="Sponsored" data-sponsored ${AD_INJECTION_MARKER}>
624
- <h3>Sponsored</h3>
625
- <ul>${items}</ul>
626
- </section>`;
627
- }
628
- function escapeHtml(s) {
629
- return s.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;").replace(/'/g, "&#39;");
1209
+ function createNextjsDashboardHandler(config) {
1210
+ const { client } = getInstance(config);
1211
+ const handleDashboard = createDashboardHandler(client, config);
1212
+ return async function dashboardHandler(request) {
1213
+ const result = await handleDashboard({
1214
+ path: request.nextUrl.pathname + request.nextUrl.search,
1215
+ method: request.method,
1216
+ apiKey: config.apiKey,
1217
+ siteId: config.siteId,
1218
+ authHeader: request.headers.get("Authorization")
1219
+ });
1220
+ if (result.headers["Content-Type"] === "text/html") {
1221
+ return new import_server.NextResponse(result.body, {
1222
+ status: result.status,
1223
+ headers: result.headers
1224
+ });
1225
+ }
1226
+ return import_server.NextResponse.json(JSON.parse(result.body), {
1227
+ status: result.status,
1228
+ headers: result.headers
1229
+ });
1230
+ };
630
1231
  }
631
- async function injectAdsIntoHtml(response, client, siteId, pathname) {
1232
+ async function injectAdsIntoResponse(response, client, config, pathname, userAgent, ipAddress, isScraperService) {
632
1233
  const html = await response.text();
633
- if (!html || html.includes(AD_INJECTION_MARKER)) return null;
634
- const pageAds = await client.getAdsForPage({ site_id: siteId, page_path: pathname });
1234
+ if (!html) return null;
1235
+ const pageAds = await client.getAdsForPage({ site_id: config.siteId, page_path: pathname });
635
1236
  if (!pageAds.ads || pageAds.ads.length === 0) return null;
636
- const adBlock = buildAdBlock(pageAds.ads);
637
- let modified;
638
- if (html.includes("</body>")) {
639
- modified = html.replace("</body>", `${adBlock}
640
- </body>`);
641
- } else if (html.includes("</html>")) {
642
- modified = html.replace("</html>", `${adBlock}
643
- </html>`);
644
- } else {
645
- modified = html + adBlock;
1237
+ const modified = injectIntoHtml(html, pageAds.ads, isScraperService);
1238
+ if (modified === html) return null;
1239
+ const newHeaders = new Headers(response.headers);
1240
+ newHeaders.set("X-Sponsored-Content", buildSponsoredHeader(pageAds.ads));
1241
+ const timestamp = (/* @__PURE__ */ new Date()).toISOString();
1242
+ for (const ad of pageAds.ads) {
1243
+ client.logImpression({
1244
+ impression_id: ad.impression_id,
1245
+ site_id: config.siteId,
1246
+ page_path: pathname,
1247
+ agent_ua: userAgent,
1248
+ agent_ip: ipAddress,
1249
+ timestamp
1250
+ }).catch(() => {
1251
+ });
646
1252
  }
647
1253
  return new import_server.NextResponse(modified, {
648
1254
  status: response.status,
649
1255
  statusText: response.statusText,
650
- headers: new Headers(response.headers)
1256
+ headers: newHeaders
651
1257
  });
652
1258
  }
653
1259
  function parseBoolParam(value, defaultValue) {
@@ -659,6 +1265,7 @@ function shouldSkip(pathname) {
659
1265
  }
660
1266
  // Annotate the CommonJS export names for ESM import in node:
661
1267
  0 && (module.exports = {
1268
+ createNextjsDashboardHandler,
662
1269
  createNextjsQueryHandler,
663
1270
  withApptvty
664
1271
  });