domain-hound 0.1.7 → 0.1.9

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 (45) hide show
  1. package/.agents/plugins/marketplace.json +1 -1
  2. package/.claude-plugin/marketplace.json +2 -2
  3. package/.claude-plugin/plugin.json +2 -2
  4. package/README.md +89 -24
  5. package/clis/domain-check/company-search.mjs +1 -0
  6. package/clis/domain-check/dossier.mjs +16 -13
  7. package/clis/domain-check/google-play.mjs +11 -48
  8. package/clis/domain-check/google-search.mjs +3 -2
  9. package/clis/domain-check/handles.mjs +235 -106
  10. package/clis/domain-check/index.mjs +49 -28
  11. package/clis/domain-check/name-score.mjs +348 -0
  12. package/clis/domain-check/name-search.mjs +70 -18
  13. package/clis/domain-check/naming-method.mjs +37 -8
  14. package/clis/domain-check/price-catalog.mjs +33 -14
  15. package/clis/domain-check/price-snapshot.json +91 -0
  16. package/clis/domain-check/prices.mjs +5 -0
  17. package/clis/domain-check/public-name-checks.mjs +275 -0
  18. package/clis/domain-check/score-log.mjs +54 -0
  19. package/clis/domain-check/triage-sources.mjs +4 -1
  20. package/clis/domain-check/triage.mjs +131 -83
  21. package/clis/domain-check/youtube-handle.mjs +18 -0
  22. package/clis/portfolio/checks.mjs +456 -0
  23. package/clis/portfolio/discover.mjs +175 -0
  24. package/clis/portfolio/move.mjs +297 -0
  25. package/clis/portfolio/page.mjs +140 -0
  26. package/clis/portfolio/portfolio.mjs +212 -0
  27. package/clis/portfolio/store.mjs +62 -0
  28. package/clis/portfolio/transfer-prices.mjs +41 -0
  29. package/clis/spaceship/client.mjs +35 -19
  30. package/clis/spaceship/tools.mjs +105 -17
  31. package/clis/spaceship/transfer.mjs +332 -0
  32. package/display.mjs +62 -61
  33. package/dossier.mjs +8 -5
  34. package/hosted-results.mjs +157 -0
  35. package/hosted.mjs +164 -0
  36. package/package.json +21 -3
  37. package/plugin.json +8 -8
  38. package/results-style.mjs +3 -0
  39. package/results.mjs +149 -94
  40. package/server.json +4 -4
  41. package/server.mjs +216 -28
  42. package/share.mjs +18 -6
  43. package/site/r/share-format.mjs +23 -8
  44. package/skills/naming/SKILL.md +76 -0
  45. package/watch.mjs +3 -3
@@ -6,7 +6,7 @@ import { promisify } from 'node:util';
6
6
  import { apiShops, cachedSignals, confirmDomain, confirmingShops, lightConfirm } from './confirm.mjs';
7
7
  import { checkDomainSite } from './com-site.mjs';
8
8
  import { appStoreSearchLink, googleSearchLink, nameCheckLines, playSearchLink } from './google-search.mjs';
9
- import { applyLiveSite, asciiDomain, domainEnding, canRecommend, defaultEndings, eligibilityNotes, endingTier, listQuote, mergeQuote, nameCandidates, normalizeName, pickName,
9
+ import { applyLiveSite, asciiDomain, domainEnding, canRecommend, choosePick, defaultEndings, eligibilityNotes, listQuote, mergeQuote, nameCandidates, normalizeName, pickName,
10
10
  premiumRisk, rankName, registrationStatus, searchCandidates, searchName, termCosts, unicodeName, validEligibility, validEndings,
11
11
  withPremiumRisk, withoutListPrice } from './name-search.mjs';
12
12
  import { bundledCatalog, catalogOffers, datedListPrices, isListPriceUsable, loadCachedCatalog, refreshPrices } from './price-catalog.mjs';
@@ -14,6 +14,7 @@ import { lookupRegistrations } from './registry.mjs';
14
14
  import { namingRecipe, purchaseLine } from './naming-method.mjs';
15
15
  import { progressReporter } from './progress.mjs';
16
16
  import { namePresence, triageNames } from './triage.mjs';
17
+ import { validCandidate } from './name-score.mjs';
17
18
  import { refreshTranco } from './traction.mjs';
18
19
  import {
19
20
  catalogPrice, dynadotOffer, linkable, money, offer, porkbunOffer, rankedFirstYear, shops, shopSearchUrl, threeYearCost, transferStrategy, vatNorway,
@@ -280,8 +281,8 @@ function quoteTime(value) {
280
281
  }
281
282
 
282
283
  const agentLegend = {
283
- nc: 'Free at the registry; list price, not confirmed',
284
- ok: 'Free, price confirmed at the shop (at = quote time)',
284
+ nc: 'Available at the registry. List price, not confirmed',
285
+ ok: 'Available. Price confirmed at the shop (at = quote time)',
285
286
  prem: 'Premium: price at the shop, never a list price',
286
287
  resale: 'Taken, possible resale',
287
288
  shop_check: 'Registry did not settle; check at a shop',
@@ -292,7 +293,7 @@ const agentLegend = {
292
293
  term: 'Years per payment when more than one',
293
294
  jump: 'Renewal over twice the first annual price',
294
295
  risk: 'Short name: may be premium, price at the shop',
295
- likely_free: 'Registry silent, DNS has no delegation: likely free, confirm at a shop',
296
+ likely_free: 'Registry silent, DNS has no delegation: possibly available, confirm at a shop',
296
297
  likely_taken: 'Registry silent, DNS has a delegation: likely taken',
297
298
  };
298
299
  const googleEndings = new Set(['app', 'dev']);
@@ -328,15 +329,14 @@ function agentPrice({ firstPayment: now, renewalPayment: renew, threeYear: y3, m
328
329
  const quoteClock = value => typeof value === 'string' ? value.match(/T(\d{2}:\d{2})/)?.[1] ?? null : null;
329
330
 
330
331
  function compactAgentResult(groups, names, complete, checkedAt, batch, rateLimited = false, liveCheck = null,
331
- { eligible, otherEndings, requested = [] } = {}) {
332
+ { eligible, otherEndings, requested = [], budget } = {}) {
332
333
  const buyUrlTemplate = {};
333
334
  const shopCheckWhy = {};
334
335
  const listPrices = {};
335
336
  const checkedEndings = new Set();
336
337
  const byName = new Map();
337
338
  let priceListDate;
338
- let best;
339
- let bestTier;
339
+ const confirmedPicks = [];
340
340
  for (const { name, results } of groups) {
341
341
  const taken = [], resale = [], free = [], shop_check = [], reserved = [], likelyFree = [], likelyTaken = [];
342
342
  for (const row of results) {
@@ -389,19 +389,17 @@ function compactAgentResult(groups, names, complete, checkedAt, batch, rateLimit
389
389
  const at = confirmed ? quoteClock(row.quotedAt ?? row.checkedAt) : null;
390
390
  free.push({ d, s: confirmed ? 'ok' : 'nc', ...(!standard && price), ...(premium && { prem: row.premium ?? true }),
391
391
  ...(at && { at }) });
392
- if (confirmed && !premium && canRecommend(row.tld, eligible) && !premiumRisk(row.domain)) {
392
+ if (confirmed && !premium && canRecommend(row.tld, eligible) && !premiumRisk(row.domain)
393
+ && (budget == null || (row.firstPayment ?? Infinity) <= budget)) {
393
394
  const { now, renew, y3, term, jump } = price;
394
395
  const buyUrl = row.buyUrl ?? shopSearchUrl(shopId, row.domain);
395
- // The cheapest confirmed quote in the most attractive tier is the pick; rows are already sorted by tier, then
396
- // first payment within a name.
397
- const tier = endingTier(row.domain, requested, eligible);
398
- if (best && (bestTier < tier || bestTier === tier && (best.priceNow ?? Infinity) <= (now ?? Infinity))) continue;
399
- bestTier = tier;
400
- best = { domain: row.domain, status: 'free-confirmed', ...(now != null && { priceNow: now }), ...(at && { at }),
401
- ...(renew != null && { renewal: renew }), ...(y3 != null && { threeYear: y3 }),
402
- ...(term && { term }),
403
- ...(jump && { renewalNote: 'Renews at $' + renew.toFixed(2) }),
404
- ...(shop && { shop }), ...(buyUrl && { buyUrl }) };
396
+ // Every confirmed quote competes; the shared pick rule chooses among them below.
397
+ confirmedPicks.push({ domain: row.domain, now: row.firstPayment ?? null, total: row.threeYear ?? null,
398
+ best: { domain: row.domain, status: 'free-confirmed', ...(now != null && { priceNow: now }), ...(at && { at }),
399
+ ...(renew != null && { renewal: renew }), ...(y3 != null && { threeYear: y3 }),
400
+ ...(term && { term }),
401
+ ...(jump && { renewalNote: 'Renews at $' + renew.toFixed(2) }),
402
+ ...(shop && { shop }), ...(buyUrl && { buyUrl }) } });
405
403
  }
406
404
  }
407
405
  const unicode = unicodeName(name);
@@ -411,6 +409,7 @@ function compactAgentResult(groups, names, complete, checkedAt, batch, rateLimit
411
409
  // Subsets of shop_check with a DNS likelihood; only a registry or shop settles them.
412
410
  ...(likelyFree.length && { likely_free: likelyFree }), ...(likelyTaken.length && { likely_taken: likelyTaken }) });
413
411
  }
412
+ const best = choosePick(confirmedPicks, { requested, eligible, budget })?.best;
414
413
  const result = {
415
414
  ...(!batch && names[0].includes('.') && {
416
415
  purchaseAdvice: 'For a purchase request, include this sentence even when the domain is taken: ' + purchaseLine,
@@ -439,7 +438,7 @@ function compactAgentResult(groups, names, complete, checkedAt, batch, rateLimit
439
438
  // Fourteen endings for twenty long names: an unconfirmed list-price row drops its s, as the display layer does.
440
439
  if (batch && Buffer.byteLength(JSON.stringify(result)) >= 7900) {
441
440
  for (const row of byName.values()) if (row.free) row.free = row.free.map(({ s, ...option }) => s === 'nc' ? option : { ...option, s });
442
- result.legend = { ...result.legend, d: agentLegend.d + '; a free entry without s is nc' };
441
+ result.legend = { ...result.legend, d: agentLegend.d + '; an available entry without s is nc' };
443
442
  }
444
443
  return result;
445
444
  }
@@ -448,17 +447,24 @@ function compactAgentResult(groups, names, complete, checkedAt, batch, rateLimit
448
447
  // the pick is sent to a shop, so no shop sees the other names. DOMAIN_HOUND_SHOP_QUOTES=top4 adds up to three runners-up.
449
448
  export const shopQuoteCount = (env = process.env) => env?.DOMAIN_HOUND_SHOP_QUOTES === 'top4' ? 4 : 1;
450
449
 
451
- // The shop quote goes to the pick: the first preferred ending in order, else the cheapest upfront payment in the most
452
- // attractive tier. explicit lists exact domains the person typed; like preferred endings, they are never demoted.
450
+ // The shop quote goes to the pick (and, with top4, the next picks): the shared pick rule (quality order within $60 over 3 years, or within the cap the
451
+ // person gave), with preferred endings first in the person's order. explicit lists exact domains the person typed; like
452
+ // preferred endings, they rank first. cap is the person's upfront budget: it also drops rows that cost more upfront.
453
453
  export function lightTargets(rows, eligible, count = 1, preferred = [], cap, explicit = []) {
454
454
  const requested = [...preferred, ...explicit];
455
455
  const inScope = rows.filter(row => (!preferred.length || preferred.includes(row.tld))
456
456
  && (cap == null || (row.firstPayment ?? Infinity) <= cap));
457
- const top = preferred.length ? preferred.map(tld => pickName(inScope.filter(row => row.tld === tld), eligible)).find(Boolean)
458
- : pickName(inScope, eligible, requested);
459
- const others = rankName(inScope.filter(row => row !== top && ['probably-free', 'premium'].includes(row.status)
457
+ // The pick first, then the next picks the same rule would make, then any other free or premium row in the quality order.
458
+ const picks = [];
459
+ for (let rest = inScope; picks.length < count;) {
460
+ const next = pickName(rest, eligible, requested, cap);
461
+ if (!next) break;
462
+ picks.push(next);
463
+ rest = rest.filter(row => row !== next);
464
+ }
465
+ const others = rankName(inScope.filter(row => !picks.includes(row) && ['probably-free', 'premium'].includes(row.status)
460
466
  && canRecommend(row.tld, eligible)), requested, eligible);
461
- return [top, ...others].filter(Boolean).slice(0, count);
467
+ return [...picks, ...others].slice(0, count);
462
468
  }
463
469
 
464
470
  export async function agentResult(input, options = {}) {
@@ -545,7 +551,8 @@ export async function agentResult(input, options = {}) {
545
551
  const exactCom = names.length === 1 && names[0].endsWith('.com') ? names[0] : null;
546
552
  const otherEndings = exactCom ? await endingBenchmarks(exactCom, options) : null;
547
553
  const result = compactAgentResult(rankedGroups, names, complete, checkedAt, batch, rateLimited,
548
- options.browser ? liveCheckFor(candidate, quote) : null, { eligible: options.eligible, otherEndings, requested });
554
+ options.browser ? liveCheckFor(candidate, quote) : null, { eligible: options.eligible, otherEndings, requested,
555
+ budget: options.upfrontCap });
549
556
  if (asked.size) result.shopAsked = [...asked];
550
557
  if (options.receipt) result.receiptDetails = rankedGroups.map(({ results, sites }) => ({ endings: results.map(row => ({
551
558
  domain: row.domain, source: row.source, checkedAt: row.checkedAt, priceAt: row.priceCheckedAt,
@@ -564,7 +571,8 @@ async function endingBenchmarks(domain, options) {
564
571
  const bundled = options.bundledCatalog === undefined ? bundledCatalog : options.bundledCatalog;
565
572
  const catalog = await loadCachedCatalog(options.directory).catch(() => null);
566
573
  const prices = {};
567
- for (const tld of defaultEndings.filter(ending => ending !== 'com' && canRecommend(ending, options.eligible))) {
574
+ const endings = [...new Set([...defaultEndings, ...(options.eligible ?? [])])];
575
+ for (const tld of endings.filter(ending => ending !== 'com' && canRecommend(ending, options.eligible))) {
568
576
  const quote = listQuote(catalog, { domain: label + '.' + tld, tld }, now, bundled);
569
577
  if (quote.price == null) continue;
570
578
  const costs = termCosts(tld, quote.price, quote.renewal);
@@ -670,6 +678,17 @@ function readGeo(value) {
670
678
  return null;
671
679
  }
672
680
 
681
+ // Per-name naming evidence from the calling agent ({"Name":{"realWord":true,...}}); invalid input is ignored, which leaves
682
+ // every semantic ban unchecked for the score.
683
+ function readCandidates(value) {
684
+ try {
685
+ const candidates = JSON.parse(value ?? '');
686
+ if (candidates && typeof candidates === 'object' && !Array.isArray(candidates) && Object.keys(candidates).length <= 20
687
+ && Object.entries(candidates).every(([key, entry]) => key.length <= 100 && validCandidate(entry))) return candidates;
688
+ } catch { /* ignored */ }
689
+ return null;
690
+ }
691
+
673
692
  function lookupArgs(args) {
674
693
  const options = {};
675
694
  const positional = [];
@@ -687,6 +706,7 @@ function lookupArgs(args) {
687
706
  else if (arg === '--confirm') options.browser = true;
688
707
  else if (arg === '--geo' && options.geo === undefined) options.geo = readGeo(args[++index]);
689
708
  else if (arg === '--about' && options.about === undefined) options.about = (args[++index] ?? '').slice(0, 160);
709
+ else if (arg === '--candidates' && options.candidates === undefined) options.candidates = readCandidates(args[++index]);
690
710
  else positional.push(arg);
691
711
  }
692
712
  return { options, positional };
@@ -695,7 +715,8 @@ function lookupArgs(args) {
695
715
  function triageOutput(result, options) {
696
716
  if (options.compact) {
697
717
  for (const row of result.names ?? []) {
698
- row.checks = nameCheckLines(row).map(({ label, text, link }) => label + ': ' + text + ' · ' + link);
718
+ row.checks = nameCheckLines(row).map(({ label, text, link, linkLabel }) =>
719
+ (linkLabel ? text + ' · ' + linkLabel : label + ': ' + text) + ' · ' + link);
699
720
  }
700
721
  }
701
722
  return result;
@@ -0,0 +1,348 @@
1
+ import { foldLatin } from './triage-sources.mjs';
2
+ import { scoreBand, scoreLabel } from '../../site/r/share-format.mjs';
3
+
4
+ // Name score v1 (2026-11-25): how clear the road is for one name, 0 to 100. It is not a probability; it stays a
5
+ // ranking of checked evidence until logged outcomes calibrate it.
6
+ // Order: bans (in code, before anything is scored), then hard filters on the checked evidence, then the points.
7
+ // A check that failed or is missing is never clear: it earns 40% of its component (rounded down) and a reason
8
+ // that says "Not checked" (or "Still checking" while the follow-up runs).
9
+ export const scoreVersion = 'v1';
10
+ export { scoreBand, scoreLabel };
11
+ export const scoreWeights = { domain: 22, price: 3, trademark: 25, rivals: 20, apps: 8, handles: 7, quality: 15 };
12
+ const componentOrder = Object.keys(scoreWeights);
13
+ export const endingPoints = { com: 22, ai: 19, io: 16, dev: 14, app: 12, co: 10, so: 8, me: 6, si: 4, xyz: 2, tech: 2 };
14
+ // v1 scores endings within $60 over 3 years; a larger budget the person gave widens the picks, not this filter.
15
+ export const scoreCapUsd = 60;
16
+ // Until the EU office answers, a clean US screen still leaves the trademark component at 20 of 25.
17
+ export const trademarkCapWithoutEu = 20;
18
+ // A failed USPTO or rival check, or naming bans the caller left unchecked, keep a name out of Strong.
19
+ export const uncheckedCap = 79;
20
+ const handleWeights = { GitHub: 3, npm: 2, Bluesky: 2 };
21
+ const unknownPart = max => Math.floor(max * 0.4);
22
+
23
+ // The evidence keys the caller supplies per name, for the bans code cannot decide on its own.
24
+ export const candidateFields = {
25
+ recipe: ['odd-pair', 'pun', 'blend', 'insider', 'phrase', 'other'],
26
+ relation: ['direct', 'loose', 'none'],
27
+ spellings: 'integer',
28
+ realWord: 'boolean',
29
+ descriptive: 'boolean',
30
+ misspelled: 'boolean',
31
+ narrow: 'boolean',
32
+ soundsLike: ['none', 'competitor', 'drug', 'pokemon'],
33
+ badMeaning: ['none', 'mild', 'severe'],
34
+ language: ['english', 'asked', 'other'],
35
+ };
36
+ const banEvidence = ['realWord', 'descriptive', 'misspelled', 'narrow', 'soundsLike'];
37
+
38
+ export function validCandidate(value) {
39
+ if (!value || typeof value !== 'object' || Array.isArray(value)) return false;
40
+ return Object.entries(value).every(([key, field]) => {
41
+ if (!Object.hasOwn(candidateFields, key)) return false;
42
+ const rule = candidateFields[key];
43
+ if (rule === 'boolean') return typeof field === 'boolean';
44
+ if (rule === 'integer') return Number.isInteger(field) && field >= 1 && field <= 5;
45
+ return rule.includes(field);
46
+ });
47
+ }
48
+
49
+ // The words of a name as typed: spaces, hyphens, digits and camel case split it ("LoomAI" -> loom, ai).
50
+ function words(input) {
51
+ return String(input ?? '').normalize('NFC').replace(/(\p{Ll})(\p{Lu})/gu, '$1 $2').replace(/(\p{Lu})(\p{Lu}\p{Ll})/gu, '$1 $2')
52
+ .toLowerCase().split(/[^\p{L}\p{N}]+/u).filter(Boolean);
53
+ }
54
+
55
+ export const letterCount = input => foldLatin(input).replace(/[^a-z]/g, '').length;
56
+
57
+ // Spoken syllables: vowel groups per word, a silent final e dropped, at least one per word.
58
+ export function syllableCount(input) {
59
+ const parts = String(input ?? '').replace(/([a-z])([A-Z])/g, '$1 $2').toLowerCase()
60
+ .normalize('NFKD').replace(/\p{M}/gu, '').match(/[a-z]+/g) ?? [];
61
+ return parts.reduce((total, part) => {
62
+ const spoken = /[^aeiouy]le$/.test(part) ? part : part.replace(/([aeiouy].*[^aeiouy])e$/, '$1');
63
+ return total + Math.max(1, (spoken.match(/[aeiouy]+/g) ?? []).length);
64
+ }, 0);
65
+ }
66
+
67
+ const banned = new Set(['ai', 'gpt', 'bot', 'smart']);
68
+ const botWords = new Set(['robot', 'abbot', 'sabot', 'talbot']);
69
+ const generic = ['hub', 'base', 'flow', 'labs', 'lab', 'apps', 'app', 'pro'];
70
+ const ioWords = new Set(['studio', 'radio', 'patio', 'audio', 'ratio', 'folio', 'polio', 'cheerio', 'portfolio', 'oratorio', 'trio', 'brio']);
71
+
72
+ // The deterministic bans, then the bans the caller's evidence decides. Returns the first ban, or null.
73
+ export function nameBan(input, candidate = {}) {
74
+ const text = String(input ?? '').trim();
75
+ const parts = words(text);
76
+ const key = foldLatin(text).replace(/[^a-z0-9]/g, '');
77
+ const last = parts.at(-1) ?? '';
78
+ if (/[\d_-]/.test(text)) return 'Numbers or hyphens';
79
+ if (candidate.language === 'other' || (/[^\x00-\x7F]/.test(text) && candidate.language !== 'asked')) return 'Not English';
80
+ if (parts.some(part => banned.has(part)) || key.includes('gpt') || key.startsWith('smart')
81
+ || (/bot$/.test(key) && !botWords.has(last))) return 'AI, GPT, bot or smart in the name';
82
+ if (letterCount(text) > 12) return 'Over 12 letters';
83
+ if (syllableCount(text) > 3) return 'Over 3 syllables';
84
+ if ((last.length > 4 && last.endsWith('ify')) || /[bcdghjkmnpqrstvwxz]ly$/.test(last)
85
+ || (last.length >= 4 && last.endsWith('io') && !ioWords.has(last))) return 'Trend ending (-ly, -ify, -io)';
86
+ if (!/[aeiouy]/.test(key) || /[bcdfgklmnpstvz]r$/.test(last)) return 'Dropped vowels';
87
+ if ((parts.length > 1 && parts.some(part => generic.includes(part)))
88
+ || (parts.length === 1 && generic.some(word => key.endsWith(word) && key.length - word.length >= 3))) {
89
+ return 'Subject word plus a generic word';
90
+ }
91
+ if (candidate.descriptive === true) return 'Pure descriptive';
92
+ if (candidate.realWord === false) return 'Pure invented, no real word inside';
93
+ if (candidate.misspelled === true) return 'Deliberate misspelling';
94
+ if (['competitor', 'drug', 'pokemon'].includes(candidate.soundsLike)) {
95
+ return 'Sounds like a ' + (candidate.soundsLike === 'pokemon' ? 'Pokemon' : candidate.soundsLike);
96
+ }
97
+ if (candidate.narrow === true) return 'Too narrow for the product';
98
+ return null;
99
+ }
100
+
101
+ const money = value => '$' + value.toFixed(2);
102
+ const listed = items => items.length < 3 ? items.join(' and ') : items.slice(0, -1).join(', ') + ' and ' + items.at(-1);
103
+ const unknownText = (state, what) => (state === 'pending' ? 'Still checking: ' : 'Not checked: ') + what;
104
+ const known = value => typeof value === 'number' && Number.isFinite(value);
105
+
106
+ function domainParts(options, cap) {
107
+ const fits = (options ?? []).filter(option => option && known(option.total) && Math.round(option.total * 100) <= Math.round(cap * 100)
108
+ && option.registry === true);
109
+ const scored = fits.map(option => {
110
+ const ending = endingPoints[option.ending] ?? 0;
111
+ const price = option.total <= 30 ? 3 : option.total <= 45 ? 2 : 1;
112
+ return { ...option, ending: option.ending, points: ending, price };
113
+ }).sort((a, b) => b.points + b.price - a.points - a.price || a.total - b.total);
114
+ return scored[0] ?? null;
115
+ }
116
+
117
+ // marks: { us: 'ok' | 'unknown' | 'pending', eu: 'ok' | 'unknown' | 'pending' | 'off', list: [{ tier, sameClass, live }] }
118
+ function trademarkPart(marks) {
119
+ const list = Array.isArray(marks?.list) ? marks.list : [];
120
+ const identical = mark => mark.tier === 'Exact';
121
+ // Fuzzy (one edit) counts as near-identical; a mark with no class or no live status counts against the name.
122
+ // A dead mark is skipped. Only an identical mark with a verified live status in your classes is a hard filter; one whose
123
+ // status is unclear scores as the worst scored case instead.
124
+ const marksLeft = list.filter(mark => mark && mark.live !== false);
125
+ if (marksLeft.some(mark => identical(mark) && mark.sameClass === true && mark.live === true)) {
126
+ return { filtered: 'Identical live trademark in your classes' };
127
+ }
128
+ // Unknown classes (null) score as your classes.
129
+ const worst = marksLeft.reduce((low, mark) => Math.min(low, mark.sameClass !== false ? 5 : identical(mark) ? 12 : 18), 25);
130
+ const usState = marks?.us === 'ok' ? 'ok' : marks?.us === 'pending' ? 'pending' : 'unknown';
131
+ const texts = { 5: marksLeft.some(mark => identical(mark) && mark.sameClass !== false) ? 'Identical trademark, status or class unclear'
132
+ : 'Near-identical trademark in your classes', 12: 'Identical trademark in another class',
133
+ 18: 'Near-identical trademark in another class' };
134
+ if (usState !== 'ok') {
135
+ // A hit from another office still counts when the US check failed.
136
+ const points = Math.min(worst, unknownPart(25));
137
+ return { points, state: usState, losses: [{ loss: 25 - points, text: unknownText(usState, 'US trademarks'), unknown: true }] };
138
+ }
139
+ const losses = worst < 25 ? [{ loss: 25 - worst, text: texts[worst] }] : [];
140
+ let points = worst;
141
+ const euState = marks?.eu === 'ok' ? 'ok' : marks?.eu === 'pending' ? 'pending' : 'unknown';
142
+ if (euState !== 'ok') {
143
+ losses.push({ loss: Math.max(0, points - trademarkCapWithoutEu), text: unknownText(euState, 'EU trademarks'), unknown: true });
144
+ points = Math.min(points, trademarkCapWithoutEu);
145
+ }
146
+ return { points, state: 'ok', losses, best: worst === 25 ? 'No trademark match found' + (euState === 'ok' ? ' in the US or EU' : ' in the US') : null };
147
+ }
148
+
149
+ // rivals: { state: 'ok' | 'unknown' | 'pending', list: [{ level: 'strong' | 'some' | 'none' | 'dormant', sameSubject }], company }
150
+ // list holds the rivals already measured, even when another source failed, so a known strong same-subject rival still
151
+ // filters the name. company is true only with evidence of a same-name registered company in the same sector.
152
+ function rivalPart(rivals) {
153
+ const state = rivals?.state === 'ok' ? 'ok' : rivals?.state === 'pending' ? 'pending' : 'unknown';
154
+ let points = 20;
155
+ let text = null;
156
+ for (const rival of Array.isArray(rivals?.list) ? rivals.list : []) {
157
+ // Without a subject (no about or category), a rival's subject is unclear and counts as yours, short of the filter.
158
+ const same = rival.sameSubject;
159
+ if (rival.level === 'strong' && same === true) return { filtered: 'Same-name rival with strong traction in your subject' };
160
+ const [value, label] = rival.level === 'strong' ? [4, same === false ? 'Same-name rival with strong traction'
161
+ : 'Same-name rival with strong traction, subject unclear']
162
+ : rival.level === 'some' ? same === false ? [12, 'Same-name use with some traction']
163
+ : [5, same === true ? 'Same-name rival in your subject' : 'Same-name use with some traction, subject unclear']
164
+ : rival.level === 'dormant' ? [18, 'Dormant same-name site'] : [20, null];
165
+ if (value < points) [points, text] = [value, label];
166
+ }
167
+ const losses = text ? [{ loss: 20 - points, text }] : [];
168
+ if (state !== 'ok' && points > unknownPart(20)) {
169
+ losses.push({ loss: points - unknownPart(20), text: unknownText(state, 'rivals'), unknown: true });
170
+ points = unknownPart(20);
171
+ } else if (state !== 'ok') losses.push({ loss: 0, text: unknownText(state, 'rivals'), unknown: true });
172
+ if (rivals?.company === true) losses.push({ loss: 3, text: 'Same-name registered company in your sector' });
173
+ return { points: Math.max(0, points - (rivals?.company === true ? 3 : 0)), state, losses,
174
+ best: state === 'ok' && points === 20 && rivals?.company !== true ? 'No same-name rival found' : null };
175
+ }
176
+
177
+ // apps: { state: 'ok' | 'unknown' | 'pending', list: [{ sameCategory: true | false | null }] }; list keeps the hits
178
+ // one store returned even when the other store failed.
179
+ function appPart(apps) {
180
+ const state = apps?.state === 'ok' ? 'ok' : apps?.state === 'pending' ? 'pending' : 'unknown';
181
+ const list = Array.isArray(apps?.list) ? apps.list : [];
182
+ const same = list.some(app => app?.sameCategory !== false);
183
+ const unclear = same && !list.some(app => app?.sameCategory === true);
184
+ let points = !list.length ? 8 : same ? 1 : 5;
185
+ const losses = list.length ? [{ loss: 8 - points,
186
+ text: same ? unclear ? 'Same-name app, category unclear' : 'Same-name app in your category' : 'Same-name app in another category' }] : [];
187
+ if (state !== 'ok') {
188
+ losses.push({ loss: Math.max(0, points - unknownPart(8)), text: unknownText(state, 'app stores'), unknown: true });
189
+ points = Math.min(points, unknownPart(8));
190
+ }
191
+ return { points, state, losses, best: state === 'ok' && !list.length ? 'No same-name app' : null };
192
+ }
193
+
194
+ // handles: { GitHub, npm, Bluesky }: 'free' | 'taken' | 'pending' | anything else (not checked).
195
+ // The handles not checked earn 40% of their combined weight, rounded down (all three: 2 of 7).
196
+ function handlePart(handles = {}) {
197
+ let points = 0;
198
+ let missing = 0;
199
+ const taken = [];
200
+ const unknown = [];
201
+ let pending = false;
202
+ for (const [platform, weight] of Object.entries(handleWeights)) {
203
+ const state = handles?.[platform];
204
+ if (state === 'free') points += weight;
205
+ else if (state === 'taken') taken.push(platform);
206
+ else {
207
+ missing += weight;
208
+ unknown.push(platform);
209
+ if (state === 'pending') pending = true;
210
+ }
211
+ }
212
+ points += unknownPart(missing);
213
+ const losses = [];
214
+ if (taken.length) losses.push({ loss: taken.reduce((sum, platform) => sum + handleWeights[platform], 0),
215
+ text: 'Handle taken: ' + listed(taken) });
216
+ if (unknown.length) losses.push({ loss: missing - unknownPart(missing),
217
+ text: unknownText(pending ? 'pending' : 'unknown', 'handles (' + listed(unknown) + ')'), unknown: true });
218
+ return { points, state: unknown.length ? pending ? 'pending' : 'unknown' : 'ok', losses,
219
+ best: points === 7 ? 'No public profiles found on GitHub, npm or Bluesky' : null };
220
+ }
221
+
222
+ function qualityPart(name, candidate, meaning) {
223
+ const count = letterCount(name);
224
+ const syllables = syllableCount(name);
225
+ const losses = [];
226
+ const length = count <= 6 ? 4 : count <= 9 ? 3 : 1;
227
+ if (length < 4) losses.push({ loss: 4 - length, text: count + ' letters' });
228
+ const sound = syllables <= 2 ? 3 : 2;
229
+ if (sound < 3) losses.push({ loss: 1, text: 'Three syllables' });
230
+ let spelling = 0;
231
+ if (candidate.spellings === 1) spelling = 4;
232
+ else if (Number.isInteger(candidate.spellings)) losses.push({ loss: 4, text: 'More than one spelling when heard' });
233
+ else {
234
+ spelling = unknownPart(4);
235
+ losses.push({ loss: 4 - spelling, text: 'Not checked: spelling by ear', unknown: true });
236
+ }
237
+ let relation = 0;
238
+ if (candidate.relation === 'direct') relation = 4;
239
+ else if (candidate.relation === 'loose') {
240
+ relation = 2;
241
+ losses.push({ loss: 2, text: 'Loose link to the subject' });
242
+ } else if (candidate.relation === 'none') losses.push({ loss: 4, text: 'No link to the subject' });
243
+ else {
244
+ relation = unknownPart(4);
245
+ losses.push({ loss: 4 - relation, text: 'Not checked: subject fit', unknown: true });
246
+ }
247
+ const mild = meaning || candidate.badMeaning === 'mild';
248
+ if (mild) losses.push({ loss: 5, text: 'Mild bad meaning' });
249
+ const points = length + sound + spelling + relation - (mild ? 5 : 0);
250
+ return { points, state: losses.some(loss => loss.unknown) ? 'unknown' : 'ok', losses,
251
+ best: length >= 3 && sound === 3 && !mild ? 'Short and easy to say' : null };
252
+ }
253
+
254
+ // input: { name, candidate, domains: [{ ending, total, registry }], marks, rivals, apps, handles, meaning }
255
+ // meaning: the local 14-language screen ({ how }) or null. Returns { value, band, reasons, ... } or { filtered }.
256
+ export function scoreName(input) {
257
+ const candidate = validCandidate(input?.candidate) ? input.candidate : {};
258
+ const name = String(input?.name ?? '');
259
+ const ban = nameBan(name, candidate);
260
+ if (ban) return { version: scoreVersion, filtered: ban, kind: 'ban' };
261
+ if (input?.meaning?.how === 'is' || candidate.badMeaning === 'severe') return { version: scoreVersion, filtered: 'Severe bad meaning', kind: 'filter' };
262
+ const domain = domainParts(input?.domains, scoreCapUsd);
263
+ if (!domain) return { version: scoreVersion, filtered: 'No available ending with a known price within ' + money(scoreCapUsd) + ' over 3 years', kind: 'filter' };
264
+ const trademark = trademarkPart(input.marks);
265
+ const rivals = rivalPart(input.rivals);
266
+ for (const part of [trademark, rivals]) if (part.filtered) return { version: scoreVersion, filtered: part.filtered, kind: 'filter' };
267
+ const parts = {
268
+ domain: { points: domain.points, state: 'ok', best: '.' + domain.ending + ' is available, ' + money(domain.total) + ' for 3 years',
269
+ losses: domain.points < 22 ? [{ loss: 22 - domain.points, text: 'Best available ending is .' + domain.ending }] : [] },
270
+ price: { points: domain.price, state: 'ok', losses: domain.price < 3 ? [{ loss: 3 - domain.price, text: money(domain.total) + ' for 3 years' }] : [] },
271
+ trademark, rivals, apps: appPart(input.apps), handles: handlePart(input.handles),
272
+ quality: qualityPart(name, candidate, input.meaning),
273
+ };
274
+ const raw = componentOrder.reduce((sum, key) => sum + parts[key].points, 0);
275
+ const caps = [];
276
+ let value = Math.max(0, Math.min(100, raw));
277
+ const missingBans = banEvidence.filter(key => !Object.hasOwn(candidate, key));
278
+ const extra = [];
279
+ if (trademark.state !== 'ok' || rivals.state !== 'ok') {
280
+ if (value > uncheckedCap) caps.push('sources');
281
+ value = Math.min(value, uncheckedCap);
282
+ }
283
+ if (missingBans.length) {
284
+ if (value > uncheckedCap) caps.push('bans');
285
+ extra.push({ loss: Math.max(0, value - uncheckedCap), text: 'Not checked: naming bans', unknown: true });
286
+ value = Math.min(value, uncheckedCap);
287
+ }
288
+ const items = [...componentOrder.flatMap(key => parts[key].losses.map(item => ({ ...item, key }))), ...extra];
289
+ // Every check that was not done, in plain words, whether or not it cost points.
290
+ const notChecked = [...new Set(items.filter(item => item.unknown).map(item => item.text.replace(/^(?:Not checked|Still checking): /, '')))];
291
+ const losses = items.filter(item => item.loss > 0)
292
+ .sort((a, b) => b.loss - a.loss || Number(Boolean(b.unknown)) - Number(Boolean(a.unknown)));
293
+ const [best] = componentOrder.filter(key => parts[key].best && parts[key].points > 0)
294
+ .sort((a, b) => parts[b].points / scoreWeights[b] - parts[a].points / scoreWeights[a]
295
+ || componentOrder.indexOf(a) - componentOrder.indexOf(b));
296
+ const reasons = best ? [parts[best].best] : [];
297
+ const chosen = losses.slice(0, 3 - reasons.length);
298
+ // An unknown that costs points always takes one of the slots.
299
+ const unknown = losses.find(item => item.unknown);
300
+ if (unknown && !chosen.includes(unknown)) chosen[chosen.length - 1] = unknown;
301
+ reasons.push(...chosen.map(item => item.text));
302
+ const pending = componentOrder.some(key => parts[key].state === 'pending');
303
+ return {
304
+ version: scoreVersion, value, band: scoreBand(value), reasons, ...(pending && { pending: true }),
305
+ components: Object.fromEntries(componentOrder.map(key => [key, parts[key].points])),
306
+ unknown: componentOrder.filter(key => parts[key].state !== 'ok'),
307
+ notChecked,
308
+ ...(missingBans.length && { bansUnchecked: missingBans }),
309
+ ...(caps.length && { caps }),
310
+ ...(input.candidate?.recipe && candidate.recipe && { recipe: candidate.recipe }),
311
+ };
312
+ }
313
+
314
+ // The handle states the score reads: free, taken, pending or (anything else) not checked.
315
+ export function scoreHandles(rows) {
316
+ if (!Array.isArray(rows)) return {};
317
+ return Object.fromEntries(['GitHub', 'npm', 'Bluesky'].map(platform => {
318
+ const row = rows.find(entry => entry?.platform === platform);
319
+ return [platform, row?.state === 'taken' ? 'taken' : row?.state === 'not-found' ? 'free'
320
+ : row?.why === 'still checking' ? 'pending' : null];
321
+ }));
322
+ }
323
+
324
+ // The part of a score that travels in tool results and on the page: value, band, reasons, or the filter.
325
+ export function compactScore(score) {
326
+ if (!score) return null;
327
+ if (score.filtered) return { filtered: score.filtered };
328
+ return { value: score.value, band: score.band, reasons: score.reasons, ...(score.notChecked?.length && { notChecked: score.notChecked }),
329
+ ...(score.pending && { pending: true }), ...(score.overridesAvoid && { overridesAvoid: true }) };
330
+ }
331
+
332
+ // "Name score 91/100 - how clear the road is"
333
+ export function scoreHeadline(score) {
334
+ return score && known(score.value) ? 'Name score ' + score.value + '/100 - ' + scoreLabel : null;
335
+ }
336
+
337
+ // Whether a row may be a pick: the legacy Avoid guard stays, except for a scored name whose only Avoid is a strong rival in
338
+ // a different subject (overridesAvoid; the score carries that penalty). Hard filters always rule out the pick.
339
+ export function scoreEligible(row) {
340
+ return !row?.score?.filtered && (row?.verdict !== 'Avoid' || (known(row?.score?.value) && row.score.overridesAvoid === true));
341
+ }
342
+
343
+ // Ranking across names: finished scores first, highest first; then scores still waiting on checks; then names
344
+ // without a score. Returns 0 when neither has a score, so callers keep their own order.
345
+ export function compareScores(a, b) {
346
+ const tier = score => known(score?.value) ? score.pending ? 1 : 0 : 2;
347
+ return tier(a) - tier(b) || (tier(a) < 2 ? b.value - a.value : 0);
348
+ }