File size: 27,838 Bytes
9e6ad61 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 | /**
* Разбор одной записи Bright Data ChatGPT Scraper: названные компании по порядку, их сайты,
* источники ответа, состоялся ли ответ. Только правила, без моделей.
*
* Что считаем «названной компанией»: название, которое видно в тексте ответа: карточки карты в начале
* ответа (строка «Map data is currently unavailable **Имя** 4.9…»), пункты списков, заголовки,
* первая колонка таблиц, отдельные жирные названия. Метки на карте (поле map), которых нет в тексте,
* не считаем: пользователь их видит только если откроет карту. Из поля map берём сайты.
* Логика имён по мотивам chatgpt-watch.mjs (validName, looksLikeCompany, nameKey).
*/
// Чистка 1: однословный пункт без сайта отбрасываем, только если это тема или район из наших ответов
// («Implants», «Rhinoplasty», «Midtown»). Весь словарь не годится: «Victorious», «Huge», «Sparrow» это компании.
import { readFileSync, existsSync } from 'node:fs';
const TOPIC1 = /^(?:implants?|rhinoplasty|acne|calisthenics|liposuction|lipo|bbl|braces|invisalign|aligners|veneers|whitening|botox|fillers?|facelifts?|ecommerce|e-commerce|seo|ppc|sem|branding|ux|ui|therapy|anxiety|depression|trauma|ocd|ptsd|adhd|couples|teens?|kids|children|adults?|families|budget|luxury|commercial|residential|emergency|repairs?|installation|maintenance|hardscape|hardscaping|lighting|irrigation|construction|drainage|pavers|patios?|pools?|plumbing|electrical|hvac|cleaning|orthodontics|dermatology|surgery|rehab|rehabilitation|sports|spine|pelvic|vestibular|pediatric|cosmetic|general|family|medical|mohs|psoriasis|eczema|rosacea|color|balayage|blonding|extensions|curly|cuts?|brakes?|transmission|diagnostics|tires?|alignment|insurance|auto|home|life|renters|business|manhattan|brooklyn|queens|bronx|midtown|downtown|uptown|intown|buckhead|decatur|wynwood|brickell|coronado|soho|tribeca|chelsea|harlem|astoria|williamsburg|fishtown|montrose|galleria|westside|eastside|scottsdale|tempe|chandler|mesa|gilbert|glendale|pasadena|burbank|evanston|plano|frisco|irving|arlington|katy|kendall|doral|aventura|hialeah|overall|value|convenience)$/i;
const dictWord = (w) => TOPIC1.test(String(w));
// Деловые слова: с ними район или тема становятся названием («Buckhead Dental Associates», «North Cleaning ATL»).
const BIZ = /\b(?:LLC|L\.L\.C|Inc|Co|Corp|Company|Group|Team|Agency|Studio|Studios|Salon|Spa|Dental|Dentistry|Dentist|Orthodontics?|Ortho|Dermatology|Derm|Plumbing|Plumbers?|Rooter|Electric|Electrical|Electricians?|Heating|Cooling|HVAC\s+\w+|Service|Tires?|Body|Shop|Care|Turf|Botanical|State Farm|Allstate|Farmers|Nationwide|Compass|Redfin|Sotheby'?s?|Keller Williams|Coldwell Banker|eXp|RE\/MAX|Douglas Elliman|Corcoran|Comparion|Americorp|EveryPlace|Mechanical|Landscap\w*|Lawn|Gardens?|Outdoor\w*|Cleaning|Cleaners|Maids?|Auto|Automotive|Garage|Motors|Collision|Insurance|Realty|Realtors?|REALTOR®?|Real Estate|Properties|Homes|Marketing|Media|Digital|Design|Interactive|Creative|Partners|Associates|Clinic|Center|Centre|Health|Medicine|Medical|Surgery|Surgical|Aesthetics?|Therapy|Therapists?|Physio\w*|Rehab\w*|Counseling|Psychology|Psychiatry|Wellness|Chiropractic|Spine|Fitness|Training|Trainers?|Performance|Gym|Hair|Beauty|Barbers?|Services|Solutions|Pros|Experts|Specialists|Works|Labs?|Institute|Practice|Consulting|Brokerage|Builders|Construction|Contractors?|SEO\s+\w+|PT)\b/;
// Человек: «Dr.», регалии, или первое слово из словаря имён (macOS /usr/share/dict/propernames) и 2-3 слова.
const FIRST = existsSync('/usr/share/dict/propernames') ? new Set(readFileSync('/usr/share/dict/propernames', 'utf8').split('\n').map((w) => w.trim()).filter(Boolean)) : new Set();
const isPerson = (side) => { const t = String(side).trim(); const w = t.split(/\s+/);
return /^Dr\.?\s/.test(t) || /,\s*(?:MD|DDS|DMD|PhD|PsyD|LCSW|LPC|DPT|PT|DO)\b|\s(?:MD|DDS|DMD|PhD|PsyD)$/.test(t) || (w.length >= 2 && w.length <= 3 && FIRST.has(w[0])); };
// Слова-услуги: название целиком из них это тема, а не компания («Drain Cleaning», «Commercial HVAC»).
const SERVICEWORD = /^(?:air|conditioning|ac|a\/c|commercial|residential|hvac|drain|drains|cleaning|sewer|repair|repairs|replacement|installation|technical|seo|ppc|local|emergency|water|heater|heaters|tankless|leak|leaks|detection|panel|panels|upgrade|upgrades|wiring|ev|charger|chargers|deep|move-out|move-in|recurring|maintenance|tune-up|furnace|duct|ducts|google|ads|maps|content|link|building|web|website|design|ecommerce|e-commerce|dtc|b2b|saas|enterprise|small|business|family|cosmetic|general|pediatric|sports|orthopedic|post-surgical|surgical|knee|back|neck|shoulder|pain|injury|injuries|acl|pelvic|floor|vestibular|anxiety|depression|trauma|ocd|ptsd|couples|teens|adults|kids|braces|invisalign|implants|veneers|whitening|liposuction|bbl|rhinoplasty|facelift|tummy|tuck|breast|augmentation|botox|fillers|acne|psoriasis|eczema|mohs|skin|cancer|hair|color|cut|cuts|balayage|extensions|brakes|brake|transmission|engine|diagnostics|european|domestic|luxury|budget|value|premium|high-end)$/i;
const PLACE_START = /^(?:North|South|East|West|Northeast|Northwest|Southeast|Southwest|Central|Downtown|Uptown|Midtown|Lower|Upper|Greater|Inner|Near|Old|Historic)\b/;
// Ручные решения по сырым ответам (scripts/not-companies.json): что правила не ловят, с причиной.
const NC_FILE = new URL('./not-companies.json', import.meta.url);
const NC = existsSync(NC_FILE) ? JSON.parse(readFileSync(NC_FILE, 'utf8')) : { items: [], keep: [] };
export const NOT_COMPANY = new Map((NC.items || []).map((x) => [x.name, x.why]));
export const KEEP_COMPANY = new Map((NC.keep || []).map((x) => [x.name, x.why]));
export function placeOrTopic(n) {
const name = String(n || '').trim();
if (KEEP_COMPANY.has(name)) return false;
const ws = name.toLowerCase().split(/\s+|\s*\/\s*/).filter(Boolean);
if (ws.length && ws.every((w) => SERVICEWORD.test(w))) return 'услуга';
if (BIZ.test(name) || name.split(/\s*\/\s*/).some(isPerson)) return false;
if (PLACE_START.test(name)) return 'район';
if (/\//.test(name)) return 'район или тема через «/»';
return false;
}
export const hostOf = (u) => { try { return new URL(u).host.toLowerCase().replace(/^www\./, ''); } catch { return null; } };
const norm = (s) => String(s || '').toLowerCase().normalize('NFKD').replace(/[^\p{L}\p{N}]+/gu, '');
// Источник по ссылке: google.com/maps отдельно от google.com, поддомены yelp и т.п. к корню.
export function sourceOf(url) {
const h = hostOf(url);
if (!h) return null;
if (/(^|\.)google\.[a-z.]+$/.test(h) && /\/maps/.test(url)) return 'google.com/maps';
if (h === 'maps.google.com' || h === 'maps.app.goo.gl') return 'google.com/maps';
const parts = h.split('.');
const sld = /^(co|com|org|net|gov|ac)\.[a-z]{2}$/.test(parts.slice(-2).join('.')) ? 3 : 2;
return parts.slice(-sld).join('.');
}
// Площадки и справочники: это источники, а не компании ниши.
const PLATFORM = /^(?:google(?: maps| reviews| business(?: profile)?)?|yelp|bbb|better business bureau|reddit|angi|angie'?s list|homeadvisor|thumbtack|houzz|nextdoor|facebook|instagram|tiktok|youtube|linkedin|avvo|justia|martindale(?:-hubbell)?|super ?lawyers|best lawyers|findlaw|lawyers\.com|nolo|healthgrades|zocdoc|vitals|webmd|ratemds|realself|psychology today|zillow|realtor\.com|redfin|trulia|homes\.com|clutch(?:\.co)?|upcity|designrush|sortlist|goodfirms|expertise(?:\.com)?|bark|porch|care\.com|winnie|kiddie academy finder|the knot|weddingwire|zola|tripadvisor|groupon|carfax|repairpal|mapquest|yellow ?pages|manta|chamber of commerce|indeed|glassdoor|trustpilot|consumer ?affairs|forbes(?: advisor)?|nerdwallet|bankrate|us news|u\.s\. news|d magazine|texas monthly|time out|eater|wikipedia|chatgpt|openai)$/i;
const ADVICE_START = /^(?:#|(?:for|if|when|to|ask|how|what|why|which|who|where|questions?|check|look|make|avoid|consider|best|top|tips?|bottom line|summary|quick|my|our|your|a|an|the best|note|overall|options?|budget|price|cost|pricing|reviews?|why|key|important|recommended|recommendations?|shortlist|step)\b)/i;
const TIP_START = /^(?:based|located|available|serving|interview|buying|selling|renting|hiring|choosing|finding|getting|notable|honorable|bonus|runner-up|top-rated|budget-friendly|typical|check|ask|compare|look|make|get|use|consider|avoid|verify|review|visit|read|find|choose|be|keep|hire|work|talk|request|confirm|research|search|start|set|don['’]?t|do|always|never|try|budget|plan|think|focus|note|watch|insist|negotiate|inspect|call|book|schedule|see)\b/i;
// Слова, из которых не бывает названия целиком: «Family Law», «Downtown», «Emergency Service».
const GENERIC_ONLY = /^(?:(?:the|best|top|good|great|affordable|budget|luxury|premium|high[- ]end|local|nearby|emergency|family|general|cosmetic|pediatric|residential|commercial|full[- ]service|independent|boutique|large|small|big|national|regional|chain|franchise|downtown|north|south|east|west|central|area|city|county|metro|option|options|pick|picks|choice|choices|alternative|alternatives|service|services|company|companies|firm|firms|agency|agencies|practice|practices|clinic|clinics|office|offices|team|teams|group|law|lawyer|lawyers|attorney|attorneys|dentist|dentists|dental|care|center|centers|shop|shops|salon|salons|studio|studios|provider|providers|specialist|specialists|expert|experts|reviews?|rating|ratings|price|prices|cost|costs|insurance|seo|ppc|sem|cro|ux|ui|ads|marketing|branding|design|web|website|websites|digital|local|and|&|or|of|for|in|with|near|me|you|your|my|if|to|a|an)\s*)+$/i;
// Регалии после запятой: «Robert B. Mitchell, D.D.S., P.A», «Courtney Dyer, PT, DPT, OCS».
export const CRED = /^(?:MD|M\.D\.?|DO|DDS|D\.D\.S\.?|DMD|PhD|Ph\.D\.?|PsyD|LCSW|LPC|LMFT|LCPC|PT|DPT|OCS|FAAD|FACS|MPH|MBA|MS|MA|MSCE|P\.?A\.?|P\.?C\.?|LLC|Inc\.?|Jr\.?|Sr\.?|CSCS|FAAOMPT|ABPP|REALTOR®?|DC|NP|RN)$/i;
const STALL = /^\W*(?:I[’']?ll|I will|Let me|I[’']m going to|I am going to)\s+(?:check|compare|look|search|find|research|pull|gather|review|go through|narrow|identify)/i;
export function looksLikeCompany(name) {
const n = String(name || '').trim().replace(/[.:]$/, '');
if (!n || TIP_START.test(n) || ADVICE_START.test(n)) return false;
if (PLATFORM.test(n) || GENERIC_ONLY.test(n)) return false;
if (n.length > 70 || n.length < 2) return false;
if (/[?"“”«»]|https?:|\[\d+\]|^!/.test(n)) return false;
// Год, «34,000+», «etc», хвосты-обобщения («… options», «… agents/teams», «… rankings») это не названия.
if (/\s(?:or|vs\.?|versus)\s/.test(n)) return false;
// Чистка 1 (04.10.2026): оценки и диапазоны («4.9–5.0», «3–5 Dallas therapists»), стрелки («100A → 200A»).
if (!/\p{L}{2}/u.test(n) || /^\d+(?:\.\d+)?\s*[–—-]\s*\d/.test(n) || /[→←⇒]/.test(n)) return false;
// Адреса («1770 Saint James Pl #210», «5101 S Kedzie Ave, Chicago») и счёт вида «30 San Diego practices».
if (/^\d{2,6}\s/.test(n) && (/#\s?\d|\bSuite\b|\bUnit\b|,\s*\p{Lu}/u.test(n) || /\b(?:St|Street|Ave|Avenue|Rd|Road|Blvd|Boulevard|Dr|Drive|Pl|Place|Ln|Lane|Ct|Court|Hwy|Highway|Pkwy|Parkway|Way|Fwy|Expy)\.?$/i.test(n))) return false;
if (/^\d/.test(n) && /\b(?:practices|clinics|agencies|companies|firms|shops|salons|options|dentists|therapists|lawyers|agents|providers|places|businesses|spots|picks|locations|studios)$/i.test(n)) return false;
// Лицензии и разрешения («NYC Department of Buildings license», «Licensed Master Plumber»).
if (/\b(?:license|licence|licensed|licensing|permit|permits)\b/i.test(n)) return false;
// Строчное содержательное слово («SEO agencies in Atlanta», «Pre-construction», «Older Chicago home»).
// Служебные слова и «team» («Mike McCann's team») допустимы; iCatch, eXp проходят (есть заглавная).
if (n.split(/[\s\-\/]+/).some((w) => /^[a-z][a-z'’]{2,}$/.test(w) && !/^(?:of|and|the|in|at|by|for|with|on|de|la|del|da|von|van|team|to|from|vs)$/.test(w))) return false;
// Организации и сертификаты, а не компании ниши: «American Board of Plastic Surgery», «… certified».
if (/\b(?:certified|certification|accredited|accreditation|board-certified)\b/i.test(n)) return false;
if (/^(?:the\s+)?(?:American|National|International|U\.?S\.?)\s+(?:Board|Academy|Society|Association|College|Council|Federation)\b|\b(?:Board|Society|Academy|Council) of\b|\bAssociation$/i.test(n)) return false;
// Площадки и инструменты в начале названия («Google Search Console + GA4 reporting», «RepairPal …»).
if (/^(?:google|yelp|clutch|zillow|bbb|angi|thumbtack|houzz|healthgrades|zocdoc|realself|redfin|facebook|instagram|reddit|chatgpt|openai|aad|repairpal|expertise\.com|psychology today|upcity|designrush|carfax)\b/i.test(n)) return false;
// Обрывки речи: «So, if I».
if (/^(?:so|and|but|or|then|also|plus),?\s/i.test(n) || /(?:^|\s)I(?:\s|$|')/.test(n)) return false;
if (/\/\s*\p{Ll}/u.test(n)) return false; // «Career/burnout»
if (/\b\d(?:\.\d)?\s*\/\s*(?:5|10)\b|★|\bstars?\b|\breviews?\b/i.test(n)) return false; // оценки «5.0/5 on Google»
if (/\b(?:19|20)\d{2}\b|^\d{1,3}(?:,\d{3})+|^\d+(?:\.\d+)?\s+[a-z]|^\d+(?:\.\d+)?$|^\d+\.\d|\d\+|\betc\b|\b1-on-1\b/i.test(n)) return false;
if (/\b(?:options|picks|choices|agents(?:\/teams)?|teams|rankings?|awards?|lists?|purchase|neighborhoods?|areas?|suburbs?|guide|directory|reviews|search|platforms?|sites|websites|code|codes|zip|zips|experience|approach|pricing|prices|costs?|convenience|option|alternatives?|purchase)$/i.test(n)) return false;
const words = n.split(/\s+/).filter(Boolean);
if (words.length > 8) return false;
if (words.length === 1) return /^[\p{Lu}\p{N}]/u.test(n) && n.length >= 3;
// Большинство слов с заглавной буквы (союзы и предлоги не считаем).
const content = words.filter((w) => !/^(?:of|and|&|the|at|in|for|on|by|de|la|y|-|–|a)$/i.test(w));
return content.length > 0 && content.filter((w) => /^[\p{Lu}\p{N}("'’]/u.test(w)).length * 3 >= content.length * 2;
}
// Чистка названия: скобки, хвост после « — », « - », «: », звёздочки, ссылки, сноски, оценки карты.
export function cleanName(raw) {
let s = String(raw || '')
.replace(/\\([[\]()*_.\-#+!])/g, '$1')
.replace(/!\[[^\]]*\]\([^)]*\)/g, '')
.replace(/\[([^\]]*)\]\([^)]*\)/g, '$1')
.replace(/[\u2B50\u2605\u2606\uFE0F\u{1F300}-\u{1FAFF}\u2600-\u27BF]/gu, '')
.replace(/\[\d+\]/g, '')
.replace(/\s+#\d+\b/g, '')
.replace(/\*\*|__/g, '')
.replace(/^\s*(?:[-*•]\s*|\d+[.)](?:\s+|$))/, '')
.replace(/^#+\s*/, '')
.replace(/^\d+[.)]\s+/, '');
s = s.split(/\s[—–-]\s|:\s|:$|\s\|\s|\s(?:has|is|was|are|were|offers|specializes|stands|earns)\s|\s(?:at|with|from)\s+[\d~≈]/)[0];
s = s.replace(/\s*\((?:[^)]*)\)?\s*$/, '').replace(/\s*\([^)]*\)\s*/g, ' ');
return s.replace(/\s+/g, ' ').trim().replace(/^[\s,;:]+|[\s.,;:]+$/g, '');
}
const TAILS = /\b(?:the|inc|llc|llp|pllc|plc|pc|p\.?c|pa|p\.?a|ltd|limited|co|corp|corporation|company|dds|dmd|md|esq|cpa)\b/gi;
export function nameKey(name) {
return norm(String(name || '').replace(/&/g, ' and ').replace(/[.,]/g, ' ').replace(TAILS, ' '));
}
/** Названия из текста ответа в порядке появления. */
export function namesFromText(md) {
const text = String(md || '').replace(/\r/g, '');
const found = []; // { name, at, via }
const push = (raw, at, via) => {
const name = cleanName(raw);
// «Wesley Ulloa, Eddie Blanco, and Joel Freis»: перечисление в одной строке, делим на части.
const parts = name.split(/,\s+(?:and\s+)?|\s+and\s+(?=[\p{Lu}])/u);
// Только вне карточек карты и только если каждая часть похожа на имя человека (2-3 слова):
// «Affordable Plumbing, Rooter and Water Heaters» это одно название.
if (via !== 'mapcard' && /,\s+(?:and\s+)?[\p{Lu}]/u.test(name) && /\s(?:and|&)\s/.test(name) && parts.length >= 3 && parts.every((x) => looksLikeCompany(x.trim()) && /^\S+(?:\s\S+){1,2}$/.test(x.trim()))) {
parts.forEach((x, i) => found.push({ name: x.trim(), at: at + i, via }));
return;
}
// Перечень «A, B, and C», который не разделился (есть однословные части), названием не считаем.
// Карточка карты всегда конкретное заведение («Top Notch Plumbing», «More Than Movement»): фильтры советов не нужны.
if (via === 'mapcard') { if (name.length >= 2 && name.length <= 120 && !PLATFORM.test(name)) found.push({ name, at, via }); return; }
if (/,\s+(?:and|&)\s/.test(name)) return;
// «HSS, Cynergy, Spear»: три и больше коротких частей через запятую без регалий это перечень, не название.
const cparts = name.split(/,\s+/);
if (cparts.length >= 3 && cparts.every((x) => x.split(/\s+/).length <= 3) && !cparts.slice(1).some((x) => CRED.test(x.trim()))) {
return; // делить небезопасно (части бывают районами и регалиями), отбрасываем целиком
}
if (looksLikeCompany(name)) found.push({ name, at, via });
};
let offset = 0;
let tableHead = null; let tableOk = false; let tableRank = false;
const lines = text.split('\n');
for (let i = 0; i < lines.length; i += 1) {
const line = lines[i];
const at = offset; offset += line.length + 1;
const l = line.trim();
if (!l) continue;
if (/Map data is currently unavailable/i.test(l)) {
for (const m of l.matchAll(/\*\*([^*]{2,90})\*\*/g)) push(m[1], at + m.index, 'mapcard');
continue;
}
if (/^Log in|Sign up for free/i.test(l)) continue;
if (/^(?:(?:[-*•]|\d+[.)])\s+)?(?:Worked for|Thought for|Searching the web|Searched \d+|Reading|Thinking)\b/i.test(l)) continue;
if (/^\|/.test(l)) {
if (/^\|\s*:?-{2,}/.test(l)) continue;
const cell = l.split('|')[1] || '';
// Строка шапки: следующая строка разделитель «|---|».
if (/^\|\s*:?-{2,}/.test((lines[i + 1] || '').trim())) {
tableHead = cell.replace(/\*\*/g, '').trim();
// Чистка 1: первую ячейку берём, только если шапка говорит, что в колонке компании или люди.
tableOk = /^(?:firm|agency|agencies|company|companies|business|practice|practices|clinic|provider|name|salon|shop|studio|dentist|doctor|physician|surgeon|dermatologist|therapist|trainer|gym|agent|realtor|team|broker|brokerage|contractor|plumber|electrician|landscaper|option|pick|recommendation|choice|orthodontist|chiropractor|cleaner|cleaning service|service provider|insurer|office|group|who)s?\b/i.test(tableHead);
tableRank = /^(?:#|no\.?|rank|ranking|place)$/i.test(tableHead);
continue;
}
// Первая ячейка жирная: это название. Иначе, если жирные названия в других ячейках
// («| Local Miami business | **Headquarters Digital Marketing** |»), берём их, а первую ячейку нет.
const cells = l.split('|').slice(1, -1);
const boldOther = cells.slice(1).flatMap((c) => [...c.matchAll(/\*\*([^*]{2,90})\*\*/g)].map((m) => m[1]));
if (tableOk) push(cell, at, 'table');
else if (boldOther.length) boldOther.forEach((b, j) => push(b, at + j, 'table'));
else if (tableRank && cells[1]) push(cells[1], at, 'table');
continue;
}
tableHead = null; tableOk = false; tableRank = false;
const heading = l.match(/^#{1,6}\s+(.*)$/);
if (heading) { push(heading[1], at, 'heading'); continue; }
const item = l.match(/^(?:[-*•]|\d+[.)])\s+(.*)$/);
if (item) {
const body = item[1].trim();
const bold = body.match(/^(?:\d+[.)]\s*)?\*\*([^*]{2,90})\*\*(\s*:)?/);
// «**Sparrow** — …» название; «**Ownership:** …» пункт-критерий (двоеточие).
if (bold) { push(bold[1], at, /:\s*$/.test(bold[1]) || bold[2] ? 'list1' : 'listb'); continue; }
const link = body.match(/^\[([^\]]{2,90})\]\(/);
if (link) { push(link[1], at, 'list'); continue; }
// Пункт без жирного: название до тире или двоеточия, пункт короткий или с пояснением.
// Одно слово без жирного («Ownership», «Developer») чаще пункт проверки, такое берём только если
// это метка на карте (проверка в parseRecord по via 'list1').
if (/\s[—–-]\s|:\s/.test(body) || body.split(/\s+/).length <= 8) push(body, at, cleanName(body).split(/\s+/).length === 1 ? 'list1' : 'list');
continue;
}
// Абзац, который целиком одно жирное название («**Smile Dental**»).
const solo = l.match(/^\*\*([^*]{2,90})\*\*\s*(?:[—–:-].*)?$/);
if (solo) { push(solo[1], at, 'bold'); continue; }
// Жирные названия внутри абзаца берём, только если похожи на имя собственное (проверка looksLikeCompany).
for (const m of l.matchAll(/\*\*([^*]{2,140})\*\*/g)) {
const raw = m[1];
if (/:$/.test(raw.trim())) continue;
// «**local Miami businesses**», «**pure SEO specialist**»: жирная фраза со строчного слова не название (iCatch, eXp проходят).
if (/^[a-z]+\s/.test(raw.trim())) continue;
push(raw, at + m.index, 'inline');
}
}
return found;
}
/** Одна запись → разбор. */
const words = (k) => String(k || '').toLowerCase().replace(/&/g, ' and ').replace(/[.,'’]/g, '').replace(TAILS, ' ').split(/[^\p{L}\p{N}]+/u).filter(Boolean);
const wordPrefix = (a, b, min = 4) => { const x = words(a); const y = words(b); const n = Math.min(x.length, y.length); return n > 0 && x.slice(0, n).join(' ') === y.slice(0, n).join(' ') && x.slice(0, n).join('').length >= min; };
const PLACE = /^[\p{L} .'-]+,\s*(?:(?!MD$|DO$|PA$|PC$|DC$|NP$|PT$|OD$)[A-Z]{2}|Thailand|USA|United States|Texas|California|Florida|New York|Illinois|Arizona|Pennsylvania|Georgia|Washington|Massachusetts|Colorado|Nevada|Tennessee|North Carolina)$/u;
export function parseRecord(r, { city = '' } = {}) {
const md = r?.answer_text_markdown || r?.answer_text || '';
const map = Array.isArray(r?.map) ? r.map : [];
const mapSite = new Map();
for (const m of map) if (m?.name) mapSite.set(nameKey(m.name), m.website_url || null);
const cites = Array.isArray(r?.citations) ? r.citations : [];
const search = Array.isArray(r?.search_sources) ? r.search_sources : [];
// Ссылки в тексте рядом с названием: «[Smile Dental](https://smiledental.com)».
const linkSite = new Map();
for (const m of String(md).matchAll(/\[([^\]]{2,90})\]\((https?:[^)\s]+)\)/g)) linkSite.set(nameKey(cleanName(m[1])), m[2]);
const raw = namesFromText(md);
const named = []; const seen = new Map();
for (const x of raw) {
const k = nameKey(x.name);
if (!k || k.length < 3) continue;
if (PLACE.test(x.name) || (city && (nameKey(x.name) === nameKey(city) || nameKey(x.name) === nameKey(`${city} city`)))) continue;
// Склейка: тот же ключ, или один начинается с другого (не короче 6 букв), или совпадают первые слова.
let hit = null;
for (const [kk, idx] of seen) if (kk === k || (Math.min(kk.length, k.length) >= 6 && (kk.startsWith(k) || k.startsWith(kk))) || (words(x.name).length < words(named[idx].name).length && wordPrefix(named[idx].name, x.name, named[idx].via === 'mapcard' ? 3 : 4))) { hit = idx; break; }
if (hit !== null) continue;
seen.set(k, named.length);
let site = mapSite.get(k) ?? null;
if (!site) for (const [mk, ms] of mapSite) if (ms && Math.min(mk.length, k.length) >= 6 && (mk.startsWith(k) || k.startsWith(mk))) { site = ms; break; }
if (!site) site = linkSite.get(k) || null;
// Сайт из ссылок-источников, если домен явно совпадает с названием («smiledental.com» и «Smile Dental»).
if (!site) {
for (const c of [...cites, ...search]) {
const h = hostOf(c?.url); if (!h) continue;
const core = norm(h.split('.').slice(-2, -1)[0]);
if (core.length >= 5 && (k.startsWith(core) || core.startsWith(k.slice(0, Math.max(6, Math.min(k.length, core.length)))))) { site = c.url; break; }
}
}
const domain = site ? sourceOf(site) : null;
// Чистка 1: районы, темы через «/», услуги и названия из списка решений (вне карты и без сайта).
if (x.via !== 'mapcard' && (NOT_COMPANY.has(x.name) || (!mapSite.has(k) && !domain && placeOrTopic(x.name)))) { seen.delete(k); continue; }
// Одно слово («Ownership», «Developer») берём, только если это карточка карты или у него нашёлся сайт.
if (words(x.name).length === 1 && x.via !== 'mapcard' && !mapSite.has(k) && !domain && (!['listb', 'table'].includes(x.via) || dictWord(x.name.replace(/[^\p{L}]/gu, '')))) { seen.delete(k); continue; }
const social = domain && /^(?:facebook\.com|instagram\.com|wa\.me|linktr\.ee|yelp\.com|google\.com\/maps|linkedin\.com|tiktok\.com|x\.com|twitter\.com)$/.test(domain);
named.push({ name: x.name, key: k, pos: named.length + 1, via: x.via, domain: social ? null : domain });
}
const citedDomains = [...new Set(cites.filter((c) => c?.url && c.cited !== false).map((c) => sourceOf(c.url)).filter(Boolean))];
const searchDomains = [...new Set(search.map((c) => sourceOf(c?.url)).filter(Boolean))];
const webSearch = r?.web_search_triggered === true || r?.web_search_triggered === 'True' || r?.web_search_triggered === 'true';
const plain = String(r?.answer_text || md).trim();
// Состоявшийся ответ по заданию: был поиск, или карта, или хотя бы одно название.
const ok = Boolean(webSearch || map.length || named.length);
return {
ok, webSearch, mapCount: map.length, named, sources: citedDomains, searchSources: searchDomains,
stall: STALL.test(plain), hasMapCard: /Map data is currently unavailable/i.test(md), chars: plain.length,
};
}
|