1import crypto from 'node:crypto';
2import dns from 'node:dns/promises';
3import net from 'node:net';
4
5export interface LeadSeed {
6 businessName?: string; [key: string]: any;
7 website: string;
8 phone?: string;
9 category?: string;
10 address?: string;
11 city?: string;
12 firstName?: string;
13 lastName?: string;
14 role?: string;
15}
16
17export interface EmailVerificationResult {
18 email: string;
19 isValidFormat: boolean;
20 isDisposable: boolean;
21 hasMxRecords: boolean;
22 mxExchange?: string;
23 hasSpfOrDmarc: boolean;
24 smtpStatus: 'verified_deliverable' | 'catch_all_or_greylisted' | 'mx_verified_port25_blocked' | 'invalid_rejected' | 'skipped';
25 confidenceScore: number;
26}
27
28export interface TechAndPixelAudit {
29 adPixelsDetected: string[];
30 bookingAndCrmWidgets: string[];
31 cmsAndEcommerce: string[];
32 marketingMaturityScore: number;
33 agencyPitchAngle: string;
34}
35
36export interface EnrichedLeadRecord { [key: string]: any;
37 domain: string;
38 websiteUrl: string;
39 businessName: string;
40 category: string;
41 address: string;
42 primaryEmail: string | null;
43 verifiedEmails: string[];
44 roleEmails: string[];
45 personalEmails: string[];
46 emailVerificationStatus: string;
47 mxExchange: string | null;
48 ownerOrDecisionMakerName: string | null;
49 ownerRole: string | null;
50 phoneE164: string | null;
51 hasWhatsAppBusiness: boolean;
52 whatsAppVerificationSource: 'on_site_widget_or_link' | 'e164_normalized_mobile' | 'none';
53 whatsAppChatUrl: string | null;
54 adPixelsDetected: string[];
55 bookingAndCrmWidgets: string[];
56 cmsAndEcommerce: string[];
57 marketingMaturityScore: number;
58 agencyPitchAngle: string;
59 socialProfiles: Record<string, string>;
60 subpagesCrawled: number;
61 extractionTier: 'tier1_jsonld_http' | 'tier2_cheerio_deep' | 'tier3_playwright_stealth';
62 qualityState: 'verified_success' | 'partial_verified' | 'unverified_skipped';
63 idempotencyKey: string;
64 scrapedAt: string;
65}
66
67const DISPOSABLE_DOMAINS = new Set([
68 'mailinator.com',
69 'guerrillamail.com',
70 '10minutemail.com',
71 'tempmail.com',
72 'yopmail.com',
73 'trashmail.com',
74 'sharklasers.com',
75 'getnada.com',
76 'throwaway.email',
77 'temp-mail.org',
78 'dispostable.com',
79 'maildrop.cc',
80 'fakeinbox.com',
81 'guerrillamailblock.com',
82]);
83
84const JUNK_EMAIL_DOMAINS = new Set([
85 'sentry.io',
86 'sentry-next.wixpress.com',
87 'sentry.wixpress.com',
88 'sentry-cdn.com',
89 'wixpress.com',
90 'wixstatic.com',
91 'example.com',
92 'example.org',
93 'example.net',
94 'test.com',
95 'domain.com',
96 'yourdomain.com',
97 'placeholder.com',
98 'email.com',
99 'cloudflare.com',
100 'w3.org',
101 'schema.org',
102 'googleapis.com',
103]);
104
105const FREEMAIL_DOMAINS = new Set([
106 'gmail.com',
107 'googlemail.com',
108 'outlook.com',
109 'hotmail.com',
110 'live.com',
111 'msn.com',
112 'yahoo.com',
113 'ymail.com',
114 'icloud.com',
115 'me.com',
116 'mac.com',
117 'aol.com',
118 'proton.me',
119 'protonmail.com',
120 'zoho.com',
121 'gmx.com',
122 'mail.com',
123 'fastmail.com',
124]);
125
126const GENERIC_ROLE_PREFIXES = new Set([
127 'info',
128 'contact',
129 'hello',
130 'support',
131 'sales',
132 'office',
133 'admin',
134 'team',
135 'help',
136 'enquiries',
137 'inquiries',
138 'billing',
139 'service',
140 'careers',
141 'hr',
142 'press',
143 'media',
144 'noreply',
145 'no-reply',
146 'donotreply',
147 'do-not-reply',
148 'privacy',
149 'legal',
150 'compliance',
151 'security',
152 'abuse',
153 'postmaster',
154 'webmaster',
155 'marketing',
156 'newsletter',
157 'bookings',
158 'reservations',
159 'appointments',
160 'orders',
161 'reception',
162 'frontdesk',
163]);
164
165export function normalizeDomain(rawUrlOrDomain: string): { domain: string; canonicalUrl: string } {
166 const trimmed = rawUrlOrDomain.trim();
167 if (!trimmed) {
168 throw new Error('Empty URL or domain provided');
169 }
170 const withProtocol = /^https?:\/\//i.test(trimmed) ? trimmed : `https://${trimmed}`;
171 const parsed = new URL(withProtocol);
172 const domain = parsed.hostname.replace(/^www\./i, '').toLowerCase();
173 return {
174 domain,
175 canonicalUrl: `${parsed.protocol}//${parsed.hostname}${parsed.pathname === '/' ? '' : parsed.pathname}`,
176 };
177}
178
179export function extractJsonLdMetadata(html: string): {
180 businessName?: string; [key: string]: any;
181 emails: string[];
182 phones: string[];
183 founderName?: string;
184 founderRole?: string;
185 address?: string;
186 socialLinks: string[];
187} {
188 const result = {
189 businessName: undefined as string | undefined,
190 emails: [] as string[],
191 phones: [] as string[],
192 founderName: undefined as string | undefined,
193 founderRole: undefined as string | undefined,
194 address: undefined as string | undefined,
195 socialLinks: [] as string[],
196 };
197
198 const scriptRegex = /<script[^>]+type=["']application\/ld\+json["'][^>]*>([\s\S]*?)<\/script>/gi;
199 let match: RegExpExecArray | null;
200 while ((match = scriptRegex.exec(html)) !== null) {
201 try {
202 const rawJson = match[1].trim();
203 const parsed = JSON.parse(rawJson);
204 const nodes = Array.isArray(parsed)
205 ? parsed
206 : parsed['@graph'] && Array.isArray(parsed['@graph'])
207 ? parsed['@graph']
208 : [parsed];
209
210 for (const node of nodes) {
211 if (!node || typeof node !== 'object') continue;
212 if (!result.businessName && typeof node.name === 'string' && node.name.length < 100) {
213 result.businessName = node.name.trim();
214 }
215 if (typeof node.email === 'string') {
216 result.emails.push(node.email.replace(/^mailto:/i, '').trim());
217 }
218 if (typeof node.telephone === 'string') {
219 result.phones.push(node.telephone.trim());
220 }
221 if (Array.isArray(node.sameAs)) {
222 for (const link of node.sameAs) {
223 if (typeof link === 'string') result.socialLinks.push(link);
224 }
225 }
226 if (node.address && typeof node.address === 'object') {
227 const parts = [
228 node.address.streetAddress,
229 node.address.addressLocality,
230 node.address.addressRegion,
231 node.address.postalCode,
232 node.address.addressCountry,
233 ].filter((p) => typeof p === 'string' && p.trim().length > 0);
234 if (parts.length > 0 && !result.address) {
235 result.address = parts.join(', ');
236 }
237 }
238 const personCandidates = [
239 ...(Array.isArray(node.founder) ? node.founder : node.founder ? [node.founder] : []),
240 ...(Array.isArray(node.founders) ? node.founders : []),
241 ...(Array.isArray(node.employee) ? node.employee : node.employee ? [node.employee] : []),
242 ];
243 for (const p of personCandidates) {
244 if (p && typeof p === 'object' && typeof p.name === 'string' && !result.founderName) {
245 result.founderName = p.name.trim();
246 result.founderRole = typeof p.jobTitle === 'string' ? p.jobTitle.trim() : 'Founder / Owner';
247 }
248 }
249 }
250 } catch {
251
252 }
253 }
254
255 return result;
256}
257
258export function extractEmailsAndDecisionMakers(
259 html: string,
260 domain: string,
261 targetRoles: string[],
262 seedFirstName?: string,
263 seedLastName?: string,
264 seedRole?: string,
265): {
266 personalEmails: string[];
267 roleEmails: string[];
268 permutatedCandidates: string[];
269 ownerName: string | null;
270 ownerRole: string | null;
271} {
272 const jsonLd = extractJsonLdMetadata(html);
273
274
275 const deobfuscated = html
276 .replace(/@/g, '@')
277 .replace(/\s*\[\s*at\s*\]\s*/gi, '@')
278 .replace(/\s*\(\s*at\s*\)\s*/gi, '@')
279 .replace(/\s*\[\s*dot\s*\]\s*/gi, '.');
280
281 const rawMatches = new Set<string>();
282 for (const e of jsonLd.emails) rawMatches.add(e.toLowerCase());
283
284 const mailtoRegex = /mailto:([a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,24})/gi;
285 let m: RegExpExecArray | null;
286 while ((m = mailtoRegex.exec(deobfuscated)) !== null) {
287 rawMatches.add(m[1].toLowerCase());
288 }
289
290 const emailRegex = /\b([a-zA-Z0-9._%+-]{1,64}@[a-zA-Z0-9.-]{1,120}\.[a-zA-Z]{2,18})\b/g;
291 while ((m = emailRegex.exec(deobfuscated)) !== null) {
292 rawMatches.add(m[1].toLowerCase());
293 }
294
295 const personalEmails: string[] = [];
296 const roleEmails: string[] = [];
297
298 const isTargetDomainEmail = (email: string) => {
299 const emailDom = email.split('@')[1] ?? '';
300 return emailDom === domain || emailDom.endsWith(`.${domain}`);
301 };
302
303 for (const candidate of rawMatches) {
304 const [localPart, emailDomain] = candidate.split('@');
305 if (!localPart || !emailDomain) continue;
306 if (JUNK_EMAIL_DOMAINS.has(emailDomain)) continue;
307 if (!isTargetDomainEmail(candidate) && !FREEMAIL_DOMAINS.has(emailDomain)) continue;
308 if (/\.(png|jpg|jpeg|gif|svg|webp|woff|woff2|ttf|css|js)$/i.test(candidate)) continue;
309 if (/^\d+x\d+/.test(localPart)) continue;
310
311 if (GENERIC_ROLE_PREFIXES.has(localPart.toLowerCase())) {
312 roleEmails.push(candidate);
313 } else {
314 personalEmails.push(candidate);
315 }
316 }
317
318
319 let ownerName: string | null = null;
320 let ownerRole: string | null = null;
321
322 if (seedFirstName && seedLastName) {
323 ownerName = `${seedFirstName.trim()} ${seedLastName.trim()}`;
324 ownerRole = seedRole || 'Decision Maker';
325 } else if (jsonLd.founderName) {
326 ownerName = jsonLd.founderName;
327 ownerRole = jsonLd.founderRole || 'Founder / Owner';
328 } else {
329 const plainText = html
330 .replace(/<script[\s\S]*?<\/script>/gi, ' ')
331 .replace(/<style[\s\S]*?<\/style>/gi, ' ')
332 .replace(/<[^>]+>/g, ' ')
333 .replace(/\s+/g, ' ');
334
335 const rolePattern = targetRoles
336 .map((r) => r.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'))
337 .join('|');
338 const nameNearRoleRegex = new RegExp(
339 `\\b([A-Z][a-z]{2,15}\\s+[A-Z][a-z]{2,18})\\s*(?:,|\\-|–|\\||is\\s+our|is\\s+the)?\\s*(${rolePattern})\\b`,
340 'i',
341 );
342 const roleMatch = nameNearRoleRegex.exec(plainText);
343 if (roleMatch) {
344 ownerName = roleMatch[1].trim();
345 ownerRole = roleMatch[2].trim();
346 }
347 }
348
349
350 personalEmails.sort((a, b) => Number(isTargetDomainEmail(b)) - Number(isTargetDomainEmail(a)));
351 roleEmails.sort((a, b) => Number(isTargetDomainEmail(b)) - Number(isTargetDomainEmail(a)));
352
353
354 const permutatedCandidates: string[] = [];
355 const hasSameDomainPersonalEmail = personalEmails.some(isTargetDomainEmail);
356 if (ownerName && !hasSameDomainPersonalEmail) {
357 const parts = ownerName
358 .toLowerCase()
359 .replace(/[^a-z\s]/g, '')
360 .split(/\s+/)
361 .filter(Boolean);
362 if (parts.length >= 2) {
363 const first = parts[0];
364 const last = parts[parts.length - 1];
365 permutatedCandidates.push(
366 `${first}@${domain}`,
367 `${first}.${last}@${domain}`,
368 `${first}${last[0]}@${domain}`,
369 );
370 }
371 }
372
373 return {
374 personalEmails,
375 roleEmails,
376 permutatedCandidates,
377 ownerName,
378 ownerRole,
379 };
380}
381
382export async function verifyEmailDomainAndSmtp(
383 email: string,
384 enableLiveNetworkChecks = true,
385): Promise<EmailVerificationResult> {
386 const clean = email.trim().toLowerCase();
387 const isValidFormat = /^[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,18}$/i.test(clean);
388 if (!isValidFormat) {
389 return {
390 email: clean,
391 isValidFormat: false,
392 isDisposable: false,
393 hasMxRecords: false,
394 hasSpfOrDmarc: false,
395 smtpStatus: 'invalid_rejected',
396 confidenceScore: 0,
397 };
398 }
399
400 const domain = clean.split('@')[1];
401 const isDisposable = DISPOSABLE_DOMAINS.has(domain);
402 if (isDisposable) {
403 return {
404 email: clean,
405 isValidFormat: true,
406 isDisposable: true,
407 hasMxRecords: false,
408 hasSpfOrDmarc: false,
409 smtpStatus: 'invalid_rejected',
410 confidenceScore: 5,
411 };
412 }
413
414 if (!enableLiveNetworkChecks) {
415 return {
416 email: clean,
417 isValidFormat: true,
418 isDisposable: false,
419 hasMxRecords: true,
420 hasSpfOrDmarc: true,
421 smtpStatus: 'skipped',
422 confidenceScore: 80,
423 };
424 }
425
426 let hasMxRecords = false;
427 let mxExchange: string | undefined;
428 let hasSpfOrDmarc = false;
429
430 try {
431 const mxRecords = await dns.resolveMx(domain);
432 if (mxRecords && mxRecords.length > 0) {
433 mxRecords.sort((a, b) => a.priority - b.priority);
434 hasMxRecords = true;
435 mxExchange = mxRecords[0].exchange;
436 }
437 } catch {
438 hasMxRecords = false;
439 }
440
441 if (!hasMxRecords) {
442 return {
443 email: clean,
444 isValidFormat: true,
445 isDisposable: false,
446 hasMxRecords: false,
447 hasSpfOrDmarc: false,
448 smtpStatus: 'invalid_rejected',
449 confidenceScore: 10,
450 };
451 }
452
453 try {
454 const txtRecords = await dns.resolveTxt(domain);
455 const flatTxt = txtRecords.map((r) => r.join('')).join(' ');
456 if (/v=spf1/i.test(flatTxt)) {
457 hasSpfOrDmarc = true;
458 }
459 } catch {
460
461 }
462
463
464 const smtpStatus = await probeSmtpDeliverability(mxExchange!, clean, domain);
465 const confidenceScore =
466 smtpStatus === 'verified_deliverable'
467 ? 98
468 : smtpStatus === 'mx_verified_port25_blocked'
469 ? hasSpfOrDmarc
470 ? 88
471 : 82
472 : smtpStatus === 'catch_all_or_greylisted'
473 ? 76
474 : 20;
475
476 return {
477 email: clean,
478 isValidFormat: true,
479 isDisposable: false,
480 hasMxRecords: true,
481 mxExchange,
482 hasSpfOrDmarc,
483 smtpStatus,
484 confidenceScore,
485 };
486}
487
488function probeSmtpDeliverability(
489 mxHost: string,
490 targetEmail: string,
491 domain: string,
492): Promise<EmailVerificationResult['smtpStatus']> {
493 return new Promise((resolve) => {
494 const socket = new net.Socket();
495 let step = 0;
496 let resolved = false;
497
498 const finish = (status: EmailVerificationResult['smtpStatus']) => {
499 if (!resolved) {
500 resolved = true;
501 socket.destroy();
502 resolve(status);
503 }
504 };
505
506 socket.setTimeout(2200);
507 socket.on('timeout', () => finish('mx_verified_port25_blocked'));
508 socket.on('error', () => finish('mx_verified_port25_blocked'));
509
510 socket.connect(25, mxHost);
511
512 socket.on('data', (chunk) => {
513 const msg = chunk.toString();
514 if (step === 0 && /^220/.test(msg)) {
515 step = 1;
516 socket.write(`EHLO verifier.${domain}\r\n`);
517 } else if (step === 1 && /^250/.test(msg)) {
518 step = 2;
519 socket.write(`MAIL FROM:<verify@${domain}>\r\n`);
520 } else if (step === 2 && /^250/.test(msg)) {
521 step = 3;
522 socket.write(`RCPT TO:<${targetEmail}>\r\n`);
523 } else if (step === 3) {
524 socket.write('QUIT\r\n');
525 if (/^250/.test(msg)) {
526 finish('verified_deliverable');
527 } else if (/^55\d/.test(msg)) {
528 finish('invalid_rejected');
529 } else {
530 finish('catch_all_or_greylisted');
531 }
532 }
533 });
534 });
535}
536
537export function normalizeAndCheckWhatsApp(
538 rawPhone: string | undefined,
539 html: string,
540 defaultCallingCode = '+1',
541): {
542 phoneE164: string | null;
543 hasWhatsAppBusiness: boolean;
544 whatsAppVerificationSource: 'on_site_widget_or_link' | 'e164_normalized_mobile' | 'none';
545 whatsAppChatUrl: string | null;
546} {
547
548 const waLinkRegex =
549 /(?:https?:\/\/(?:wa\.me|api\.whatsapp\.com\/send|chat\.whatsapp\.com)\/?(?:\?phone=)?|whatsapp:\/\/send\?phone=)(\+?\d{7,15})/i;
550 const waMatch = waLinkRegex.exec(html);
551 if (waMatch && waMatch[1]) {
552 const digits = waMatch[1].replace(/\D/g, '');
553 const e164 = `+${digits}`;
554 return {
555 phoneE164: e164,
556 hasWhatsAppBusiness: true,
557 whatsAppVerificationSource: 'on_site_widget_or_link',
558 whatsAppChatUrl: `https://wa.me/${digits}`,
559 };
560 }
561
562
563 const hasWaWidget =
564 /whatsapp-widget|wati\.io|whatchimp|wa\.me\/|api\.whatsapp\.com/i.test(html);
565
566
567 let candidatePhone = rawPhone;
568 if (!candidatePhone) {
569 const telMatch = /href=["']tel:([+\d\s().-]{7,22})["']/i.exec(html);
570 if (telMatch) candidatePhone = telMatch[1];
571 }
572
573 if (!candidatePhone) {
574 return {
575 phoneE164: null,
576 hasWhatsAppBusiness: hasWaWidget,
577 whatsAppVerificationSource: hasWaWidget ? 'on_site_widget_or_link' : 'none',
578 whatsAppChatUrl: null,
579 };
580 }
581
582 const cleanPrefix = defaultCallingCode.startsWith('+')
583 ? defaultCallingCode.slice(1)
584 : defaultCallingCode;
585 const trimmed = candidatePhone.trim();
586 const digitsOnly = trimmed.replace(/\D/g, '');
587
588 if (digitsOnly.length < 7 || digitsOnly.length > 15) {
589 return {
590 phoneE164: null,
591 hasWhatsAppBusiness: hasWaWidget,
592 whatsAppVerificationSource: hasWaWidget ? 'on_site_widget_or_link' : 'none',
593 whatsAppChatUrl: null,
594 };
595 }
596
597 let fullDigits = digitsOnly;
598 if (!trimmed.startsWith('+')) {
599 if (digitsOnly.length === 10) {
600 fullDigits = `${cleanPrefix}${digitsOnly}`;
601 } else if (digitsOnly.length === 11 && digitsOnly.startsWith('0')) {
602 fullDigits = `${cleanPrefix}${digitsOnly.slice(1)}`;
603 }
604 }
605
606 const phoneE164 = `+${fullDigits}`;
607 return {
608 phoneE164,
609 hasWhatsAppBusiness: hasWaWidget,
610 whatsAppVerificationSource: hasWaWidget
611 ? 'on_site_widget_or_link'
612 : 'e164_normalized_mobile',
613 whatsAppChatUrl: `https://wa.me/${fullDigits}`,
614 };
615}
616
617export function detectPixelsAndTechStack(html: string): TechAndPixelAudit {
618 const adPixels = new Set<string>();
619 const bookingAndCrm = new Set<string>();
620 const cmsAndEcommerce = new Set<string>();
621
622
623 if (/connect\.facebook\.net.*fbevents\.js|fbq\s*\(\s*['"]init['"]/i.test(html)) {
624 adPixels.add('Meta Pixel (Facebook/Instagram Ads)');
625 }
626 if (/googletagmanager\.com\/gtm\.js|GTM-[A-Z0-9]{4,10}/i.test(html)) {
627 adPixels.add('Google Tag Manager');
628 }
629 if (/googleadservices\.com\/pagead\/conversion|gtag\s*\(\s*['"]config['"]\s*,\s*['"]AW-/i.test(html)) {
630 adPixels.add('Google Ads Conversion Pixel');
631 }
632 if (/googletagmanager\.com\/gtag\/js\?id=G-|gtag\s*\(\s*['"]config['"]\s*,\s*['"]G-/i.test(html)) {
633 adPixels.add('Google Analytics 4 (GA4)');
634 }
635 if (/analytics\.tiktok\.com\/i18n\/pixel|ttq\.load\s*\(/i.test(html)) {
636 adPixels.add('TikTok Pixel');
637 }
638 if (/snap\.licdn\.com\/li\.lms-analytics|_linkedin_partner_id/i.test(html)) {
639 adPixels.add('LinkedIn Insight Tag');
640 }
641 if (/clarity\.ms\/tag\//i.test(html)) {
642 adPixels.add('Microsoft Clarity');
643 }
644
645
646 if (/assets\.calendly\.com|calendly\.com\//i.test(html)) {
647 bookingAndCrm.add('Calendly');
648 }
649 if (/(?:cdn|web)\.servicetitan\.com|scheduleengine\.net/i.test(html)) {
650 bookingAndCrm.add('ServiceTitan / ScheduleEngine');
651 }
652 if (/housecallpro\.com/i.test(html)) {
653 bookingAndCrm.add('Housecall Pro');
654 }
655 if (/getjobber\.com|clienthub\.getjobber\.com/i.test(html)) {
656 bookingAndCrm.add('Jobber');
657 }
658 if (/(?:widgets|clients)\.mindbodyonline\.com|healcode\.com/i.test(html)) {
659 bookingAndCrm.add('Mindbody');
660 }
661 if (/joinblvd\.com|boulevard\.io/i.test(html)) {
662 bookingAndCrm.add('Boulevard');
663 }
664 if (/msgsndr\.com|leadconnectorhq\.com|gohighlevel\.com/i.test(html)) {
665 bookingAndCrm.add('GoHighLevel (LeadConnector)');
666 }
667 if (/js\.hs-scripts\.com|js\.hsforms\.net|hs-analytics\.net|meetings\.hubspot\.com/i.test(html)) {
668 bookingAndCrm.add('HubSpot CRM');
669 }
670 if (/static\.klaviyo\.com/i.test(html)) {
671 bookingAndCrm.add('Klaviyo');
672 }
673 if (/widget\.intercom\.io/i.test(html)) {
674 bookingAndCrm.add('Intercom');
675 }
676 if (/code\.tidio\.co/i.test(html)) {
677 bookingAndCrm.add('Tidio Live Chat');
678 }
679
680
681 if (/cdn\.shopify\.com|Shopify\.theme/i.test(html)) {
682 cmsAndEcommerce.add('Shopify');
683 }
684 if (/wp-content\/plugins\/woocommerce|woocommerce/i.test(html)) {
685 cmsAndEcommerce.add('WooCommerce');
686 }
687 if (/wp-content\/|wp-includes\//i.test(html)) {
688 cmsAndEcommerce.add('WordPress');
689 }
690 if (/webflow\.js|data-wf-site/i.test(html)) {
691 cmsAndEcommerce.add('Webflow');
692 }
693 if (/static1\.squarespace\.com/i.test(html)) {
694 cmsAndEcommerce.add('Squarespace');
695 }
696 if (/static\.parastorage\.com|wix\.com/i.test(html)) {
697 cmsAndEcommerce.add('Wix');
698 }
699 if (/js\.stripe\.com/i.test(html)) {
700 cmsAndEcommerce.add('Stripe Checkout');
701 }
702 if (/checkout\.razorpay\.com/i.test(html)) {
703 cmsAndEcommerce.add('Razorpay');
704 }
705
706 const adPixelsDetected = Array.from(adPixels);
707 const bookingAndCrmWidgets = Array.from(bookingAndCrm);
708 const cmsAndEcommerceList = Array.from(cmsAndEcommerce);
709
710
711 let score = 15;
712 if (adPixelsDetected.some((p) => p.includes('GA4') || p.includes('Tag Manager'))) score += 15;
713 if (adPixelsDetected.some((p) => p.includes('Meta Pixel'))) score += 20;
714 if (adPixelsDetected.some((p) => p.includes('Google Ads'))) score += 20;
715 if (adPixelsDetected.some((p) => p.includes('TikTok') || p.includes('LinkedIn'))) score += 10;
716 if (bookingAndCrmWidgets.length > 0) score += 20;
717 const marketingMaturityScore = Math.min(100, score);
718
719
720 const hasMeta = adPixelsDetected.some((p) => p.includes('Meta Pixel'));
721 const hasGoogleAds = adPixelsDetected.some((p) => p.includes('Google Ads'));
722 const hasBooking = bookingAndCrmWidgets.length > 0;
723
724 let agencyPitchAngle = '';
725 if (hasGoogleAds && !hasMeta) {
726 agencyPitchAngle =
727 'Spending on Google Ads without a Meta Retargeting Pixel — pitch Meta/Instagram retargeting to recover 70%+ of unconverted paid search traffic.';
728 } else if (hasMeta && !hasGoogleAds) {
729 agencyPitchAngle =
730 'Active Meta Pixel but no Google Ads conversion tracking — pitch high-intent Google Search/Maps capture for bottom-of-funnel buyers.';
731 } else if (!hasMeta && !hasGoogleAds && !hasBooking) {
732 agencyPitchAngle =
733 'Zero paid ad pixels or automated booking widgets detected — prime candidate for turnkey Local SEO, WhatsApp missed-call text-back, and booking automation.';
734 } else if ((hasMeta || hasGoogleAds) && !hasBooking) {
735 agencyPitchAngle =
736 'Running paid ad pixels without an instant booking/chat widget — pitch AI chat / WhatsApp conversion widget to double landing page lead capture.';
737 } else {
738 agencyPitchAngle =
739 'Marketing-mature business running both ad pixels and CRM/booking automation — pitch AI voice/WhatsApp speed-to-lead workflow or creative hook testing.';
740 }
741
742 return {
743 adPixelsDetected,
744 bookingAndCrmWidgets,
745 cmsAndEcommerce: cmsAndEcommerceList,
746 marketingMaturityScore,
747 agencyPitchAngle,
748 };
749}
750
751export function extractSocialProfiles(html: string): Record<string, string> {
752 const profiles: Record<string, string> = {};
753 const patterns: Array<[string, RegExp]> = [
754 ['linkedin', /https?:\/\/(?:www\.|[a-z]{2}\.)?linkedin\.com\/(?:company|in)\/[a-zA-Z0-9_-]+/i],
755 ['instagram', /https?:\/\/(?:www\.)?instagram\.com\/(?!p\/|reel\/|explore\/)[a-zA-Z0-9_.]{2,30}/i],
756 ['facebook', /https?:\/\/(?:www\.)?facebook\.com\/(?!sharer|tr\?|plugins)[a-zA-Z0-9.]{3,50}/i],
757 ['tiktok', /https?:\/\/(?:www\.)?tiktok\.com\/@[a-zA-Z0-9_.]{2,35}/i],
758 ['youtube', /https?:\/\/(?:www\.)?youtube\.com\/(?:@[a-zA-Z0-9_-]+|channel\/[a-zA-Z0-9_-]+|c\/[a-zA-Z0-9_-]+)/i],
759 ['twitter', /https?:\/\/(?:www\.)?(?:twitter\.com|x\.com)\/(?!intent|share)[a-zA-Z0-9_]{2,30}/i],
760 ];
761
762 for (const [network, regex] of patterns) {
763 const match = regex.exec(html);
764 if (match) {
765 profiles[network] = match[0];
766 }
767 }
768 return profiles;
769}
770
771export function discoverContactSubpages(html: string, baseUrl: string, maxSubpages: number): string[] {
772 if (maxSubpages <= 0) return [];
773 const subpages = new Set<string>();
774 const base = new URL(baseUrl);
775 const linkRegex = /href=["']([^"'#]+)["']/gi;
776 const highSignalPathRegex =
777 /\b(contact|about|team|leadership|founder|impressum|legal|our-story|staff|management)\b/i;
778
779 let match: RegExpExecArray | null;
780 while ((match = linkRegex.exec(html)) !== null) {
781 try {
782 const resolved = new URL(match[1], base.origin);
783 if (resolved.hostname.replace(/^www\./i, '') !== base.hostname.replace(/^www\./i, '')) {
784 continue;
785 }
786 if (resolved.pathname === base.pathname || resolved.pathname === '/') continue;
787 if (highSignalPathRegex.test(resolved.pathname)) {
788 subpages.add(resolved.href);
789 if (subpages.size >= maxSubpages) break;
790 }
791 } catch {
792
793 }
794 }
795 return Array.from(subpages);
796}
797
798export function createWebhookSignature(payloadJson: string, secret: string): string {
799 return crypto.createHmac('sha256', secret).update(payloadJson).digest('hex');
800}