domain-hound 0.1.4 → 0.1.6

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 (43) hide show
  1. package/.agents/plugins/marketplace.json +1 -0
  2. package/.claude-plugin/marketplace.json +1 -0
  3. package/.claude-plugin/plugin.json +1 -1
  4. package/README.md +106 -13
  5. package/assets/readme-search.png +0 -0
  6. package/clis/domain-check/broker-atom.mjs +78 -0
  7. package/clis/domain-check/com-site.mjs +64 -25
  8. package/clis/domain-check/confirm.mjs +10 -5
  9. package/clis/domain-check/dossier.mjs +603 -0
  10. package/clis/domain-check/google-play.mjs +24 -11
  11. package/clis/domain-check/handles.mjs +337 -0
  12. package/clis/domain-check/index.mjs +69 -20
  13. package/clis/domain-check/marketplaces.mjs +107 -0
  14. package/clis/domain-check/meaning-words.LICENSE.txt +408 -0
  15. package/clis/domain-check/meaning-words.json +2397 -0
  16. package/clis/domain-check/meaning.mjs +77 -0
  17. package/clis/domain-check/name-search.mjs +83 -13
  18. package/clis/domain-check/naming-method.mjs +6 -4
  19. package/clis/domain-check/price-catalog.mjs +20 -12
  20. package/clis/domain-check/price-snapshot.json +142 -10
  21. package/clis/domain-check/registry.mjs +112 -19
  22. package/clis/domain-check/safe-web.mjs +207 -0
  23. package/clis/domain-check/traction.mjs +2 -2
  24. package/clis/domain-check/trademarks.mjs +372 -0
  25. package/clis/domain-check/triage-sources.mjs +52 -64
  26. package/clis/domain-check/triage.mjs +262 -72
  27. package/clis/spaceship/buy.mjs +327 -0
  28. package/clis/spaceship/client.mjs +170 -0
  29. package/clis/spaceship/dns.mjs +292 -0
  30. package/clis/spaceship/quote.mjs +123 -0
  31. package/clis/spaceship/setup.mjs +81 -0
  32. package/clis/spaceship/store.mjs +104 -0
  33. package/clis/spaceship/tools.mjs +258 -0
  34. package/display.mjs +16 -9
  35. package/dossier.mjs +185 -0
  36. package/package.json +36 -5
  37. package/plugin.json +4 -3
  38. package/results-style.mjs +10 -0
  39. package/results.mjs +291 -61
  40. package/server.json +3 -3
  41. package/server.mjs +275 -59
  42. package/share.mjs +43 -0
  43. package/site/r/share-format.mjs +125 -0
@@ -1,4 +1,5 @@
1
1
  import { cacheDir, mapLimit, readCache, writeCache } from './cache.mjs';
2
+ import { setTimeout as delay } from 'node:timers/promises';
2
3
  import { withShopPages } from './confirm.mjs';
3
4
  import { appNameMatches, compactText, day, request } from './triage-sources.mjs';
4
5
 
@@ -146,29 +147,38 @@ async function lookUp(source, name, input, deadline) {
146
147
  });
147
148
  }
148
149
 
150
+ // Leave room for a retry on slow pages or failed connections within the shared clock.
151
+ const playAttemptMs = 2800;
152
+
149
153
  export async function searchAndroidApps(names, options = {}) {
150
154
  const { directory = cacheDir, now = new Date(), playBudgetMs = 12000, cacheLifetime = day } = options;
151
- const deadline = performance.now() + Math.min(12000, playBudgetMs);
155
+ const budget = Math.min(30000, playBudgetMs);
156
+ const deadline = performance.now() + budget;
157
+ const retryMs = Math.min(playAttemptMs, budget / 2);
158
+ const answered = (name, apps) => { results.set(name, apps); options.onResult?.(name, apps); };
152
159
  const results = new Map();
153
160
  const pending = (await Promise.all([...names].map(async ([name, input]) => {
154
161
  const filename = 'triage-play-' + name + '.json';
155
162
  const prior = await readCache(directory, filename);
156
163
  const age = now.getTime() - prior?.at;
157
164
  if (age >= 0 && age < cacheLifetime && Array.isArray(prior.apps) && prior.apps.every(app => Object.hasOwn(app, 'ratings')) && (!prior.apps.length || prior.version === 2)) {
158
- results.set(name, prior.apps);
165
+ answered(name, prior.apps);
159
166
  return null;
160
167
  }
161
168
  return { name, input, filename };
162
169
  }))).filter(Boolean);
170
+ const waits = budget < 1600 ? [0, 0] : [0, 350, 1200];
163
171
  const search = useSource => mapLimit(pending, 5, async ({ name, input, filename }) => {
164
172
  if (performance.now() >= deadline) return;
165
- for (let attempt = 0; attempt < 2 && performance.now() < deadline; attempt++) {
173
+ for (const pause of waits) {
174
+ if (options.signal?.aborted || deadline - performance.now() < (pause ? retryMs + pause : 1)) break;
175
+ if (pause) await delay(pause);
166
176
  let source;
167
177
  try {
168
178
  source = await useSource();
169
- const apps = await lookUp(source, name, input, Math.min(deadline, performance.now() + 2800));
179
+ const apps = await lookUp(source, name, input, Math.min(deadline, performance.now() + 8000));
170
180
  if (apps === null || performance.now() >= deadline) continue;
171
- results.set(name, apps);
181
+ answered(name, apps);
172
182
  await writeCache(directory, filename, { at: now.getTime(), apps, version: 2 }).catch(() => {});
173
183
  return;
174
184
  } catch { /* An unavailable search gives no evidence about the name. */ }
@@ -176,12 +186,15 @@ export async function searchAndroidApps(names, options = {}) {
176
186
  }
177
187
  });
178
188
  if (pending.length && performance.now() < deadline) {
179
- let browserReady = false;
180
- let browserFailed = false;
181
- await withShopPages(deadline, async (_, openPage) => {
182
- browserReady = true;
183
- await search(async () => browserSource(await openPage()));
184
- }, { ...options, onFailure: () => { browserFailed = !browserReady; return null; } });
189
+ // The public search response includes the cards. A normal lookup needs no browser or page assets.
190
+ let browserFailed = !options.launch;
191
+ if (options.launch) {
192
+ let browserReady = false;
193
+ await withShopPages(deadline, async (_, openPage) => {
194
+ browserReady = true;
195
+ await search(async () => browserSource(await openPage()));
196
+ }, { ...options, onFailure: () => { browserFailed = !browserReady; return null; } });
197
+ }
185
198
  if (browserFailed && performance.now() < deadline) {
186
199
  const parse = await import('parse5').then(module => module.parse, () => null);
187
200
  if (parse) await search(() => fetchSource(parse, options));
@@ -0,0 +1,337 @@
1
+ import { randomInt } from 'node:crypto';
2
+ import { anySignal, cacheDir, readCache, writeCache } from './cache.mjs';
3
+
4
+ // Social handles. Three states only, never "free": a missing public profile does not mean the handle can be had.
5
+ export const handleStates = {
6
+ taken: 'Taken',
7
+ 'not-found': 'No public profile found',
8
+ check: 'Check yourself',
9
+ };
10
+ const hour = 3_600_000;
11
+ // A taken handle is reused for a week, a missing one for an hour. "Check yourself" is never cached.
12
+ export const handleLifetime = { taken: 7 * 24 * hour, 'not-found': hour };
13
+ // One platform's whole run (its two controls, the exact handles and any variants) shares this budget.
14
+ export const platformBudgetMs = 2000;
15
+ export const handleVariants = name => ['get' + name, name + 'app', name + 'hq'];
16
+ const userAgent = 'DomainHound/0.1 (https://domainhound.dev)';
17
+ const githubHoldFile = 'handles-github-hold.json';
18
+
19
+ const label = value => /^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/.test(value);
20
+ const syntheticLabel = (length, pick = randomInt) => 'zq' + Array.from({ length }, () => String.fromCharCode(97 + pick(26))).join('');
21
+
22
+ async function readStrictJson(response) {
23
+ if (!/^application\/(?:[\w.+-]+\+)?json\b/i.test(response.headers.get('content-type') ?? '')) {
24
+ await response.body?.cancel().catch(() => {});
25
+ return null;
26
+ }
27
+ const text = await response.text();
28
+ if (text.length > 512 * 1024) return null;
29
+ try { return JSON.parse(text); } catch { return null; }
30
+ }
31
+
32
+ // Each automatic check uses a documented public API that needs no login. Anything the parser does not recognise is
33
+ // "check yourself".
34
+ const apis = {
35
+ // GitHub REST "Get a user" (users and organizations): https://docs.github.com/en/rest/users/users#get-a-user
36
+ GitHub: {
37
+ valid: handle => /^[a-z0-9](?:[a-z0-9]|-(?=[a-z0-9])){0,38}$/.test(handle),
38
+ url: handle => 'https://api.github.com/users/' + handle,
39
+ headers: { Accept: 'application/vnd.github+json', 'X-GitHub-Api-Version': '2022-11-28' },
40
+ read: async (response, handle) => {
41
+ const data = await readStrictJson(response);
42
+ if (response.status === 200) {
43
+ return typeof data?.login === 'string' && data.login.toLowerCase() === handle
44
+ && ['User', 'Organization'].includes(data.type) ? 'taken' : 'check';
45
+ }
46
+ if (response.status === 404) return data?.message === 'Not Found' ? 'not-found' : 'check';
47
+ return 'check';
48
+ },
49
+ controls: () => ({ taken: 'github', missing: syntheticLabel(28) }),
50
+ },
51
+ // npm registry package document: https://github.com/npm/registry/blob/main/docs/REGISTRY-API.md#getpackage
52
+ npm: {
53
+ valid: handle => handle.length <= 214,
54
+ url: handle => 'https://registry.npmjs.org/' + handle,
55
+ headers: { Accept: 'application/vnd.npm.install-v1+json' },
56
+ read: async (response, handle) => {
57
+ const data = await readStrictJson(response);
58
+ if (response.status === 200) return data?.name === handle ? 'taken' : 'check';
59
+ if (response.status === 404) return typeof data?.error === 'string' && /^not found$/i.test(data.error) ? 'not-found' : 'check';
60
+ return 'check';
61
+ },
62
+ controls: () => ({ taken: 'lodash', missing: syntheticLabel(24) }),
63
+ },
64
+ // Bluesky public AppView, com.atproto.identity.resolveHandle:
65
+ // https://docs.bsky.app/docs/api/com-atproto-identity-resolve-handle
66
+ Bluesky: {
67
+ valid: handle => handle.length >= 3 && handle.length <= 18,
68
+ identifier: handle => handle + '.bsky.social',
69
+ url: identifier => 'https://public.api.bsky.app/xrpc/com.atproto.identity.resolveHandle?handle=' + encodeURIComponent(identifier),
70
+ headers: { Accept: 'application/json' },
71
+ read: async response => {
72
+ const data = await readStrictJson(response);
73
+ if (response.status === 200) return typeof data?.did === 'string' && /^did:(?:plc|web):[a-z0-9._:%-]+$/i.test(data.did) ? 'taken' : 'check';
74
+ if (response.status === 400) {
75
+ return data?.error === 'InvalidRequest' && /^unable to resolve handle$/i.test(String(data.message ?? '').trim()) ? 'not-found' : 'check';
76
+ }
77
+ return 'check';
78
+ },
79
+ // bsky.app is Bluesky's own account.
80
+ controls: () => ({ taken: 'bsky.app', missing: syntheticLabel(14) + '.bsky.social' }),
81
+ },
82
+ };
83
+
84
+ // Display order (Lars, 2026-11-25): YouTube, X, Instagram, TikTok, Facebook, LinkedIn, then GitHub, npm, PyPI, Bluesky.
85
+ // YouTube, X, Instagram, TikTok, Facebook and LinkedIn have no public no-login lookup their terms allow: link only.
86
+ // PyPI is link only by decision.
87
+ export const handlePlatforms = [
88
+ { id: 'YouTube', link: handle => 'https://www.youtube.com/@' + handle },
89
+ { id: 'X', link: handle => 'https://x.com/' + handle },
90
+ { id: 'Instagram', link: handle => 'https://www.instagram.com/' + handle + '/' },
91
+ { id: 'TikTok', link: handle => 'https://www.tiktok.com/@' + handle },
92
+ { id: 'Facebook', link: handle => 'https://www.facebook.com/' + handle },
93
+ { id: 'LinkedIn', link: handle => 'https://www.linkedin.com/company/' + handle + '/' },
94
+ { id: 'GitHub', link: handle => 'https://github.com/' + handle, auto: true },
95
+ { id: 'npm', link: handle => 'https://www.npmjs.com/package/' + handle, auto: true },
96
+ { id: 'PyPI', link: handle => 'https://pypi.org/project/' + handle + '/' },
97
+ { id: 'Bluesky', link: handle => 'https://bsky.app/profile/' + handle + '.bsky.social', auto: true },
98
+ ];
99
+ // Shown only when the person asks for them; always check links.
100
+ export const requestPlatforms = [
101
+ { id: 'Snapchat', link: handle => 'https://www.snapchat.com/add/' + handle },
102
+ { id: 'Reddit', link: handle => 'https://www.reddit.com/user/' + handle + '/' },
103
+ { id: 'Twitch', link: handle => 'https://www.twitch.tv/' + handle },
104
+ { id: 'Threads', link: handle => 'https://www.threads.com/@' + handle },
105
+ { id: 'Pinterest', link: handle => 'https://www.pinterest.com/' + handle + '/' },
106
+ { id: 'Discord', link: () => 'https://support.discord.com/hc/en-us/articles/12620128861463-New-Usernames-Display-Names' },
107
+ ];
108
+ export const autoPlatforms = handlePlatforms.filter(platform => platform.auto).map(platform => platform.id);
109
+
110
+ // In-flight lookups and control batches are shared inside one run (one process).
111
+ const inFlight = new Map();
112
+ const controlRuns = new Map();
113
+ // Every answer this run already has, "check yourself" included, so a later step never asks again.
114
+ const runAnswers = new Map();
115
+ export function resetHandleRuns() {
116
+ inFlight.clear();
117
+ controlRuns.clear();
118
+ runAnswers.clear();
119
+ }
120
+
121
+ async function githubHeld(directory, now) {
122
+ const hold = await readCache(directory, githubHoldFile);
123
+ return hold?.until > now.getTime();
124
+ }
125
+
126
+ // One request, and one retry inside the same budget when the platform fails (5xx or no response).
127
+ async function request(platform, identifier, { fetcher, signal, githubToken }, retry = true) {
128
+ const api = apis[platform];
129
+ let failed;
130
+ // An optional token lifts GitHub's 60 requests an hour for anonymous callers. It is sent only to api.github.com.
131
+ const auth = platform === 'GitHub' && githubToken ? { Authorization: 'Bearer ' + githubToken } : {};
132
+ try {
133
+ const response = await fetcher(api.url(identifier), {
134
+ redirect: 'error', signal, headers: { 'User-Agent': userAgent, ...api.headers, ...auth },
135
+ });
136
+ failed = response.status >= 500;
137
+ const state = await api.read(response, identifier);
138
+ const limited = platform === 'GitHub' && [403, 429].includes(response.status);
139
+ if (!failed) return { state, ...(limited && { limited: Number(response.headers.get('x-ratelimit-reset')) * 1000 || null }) };
140
+ } catch {
141
+ failed = true;
142
+ }
143
+ return retry && failed && !signal?.aborted ? request(platform, identifier, { fetcher, signal, githubToken }, false) : { state: 'check' };
144
+ }
145
+
146
+ // The run's two controls for one platform: a handle known to exist and a random one that cannot. When either comes
147
+ // back wrong, every answer from that platform in this run becomes "check yourself".
148
+ function controlsFor(platform, options) {
149
+ const key = platform + '|' + (options.directory?.href ?? '');
150
+ const runs = options.controlRuns ?? controlRuns;
151
+ if (!runs.has(key)) {
152
+ const { taken, missing } = options.controls?.[platform] ?? apis[platform].controls();
153
+ runs.set(key, Promise.all([request(platform, taken, options), request(platform, missing, options)])
154
+ .then(([known, absent]) => ({ ok: known.state === 'taken' && absent.state === 'not-found',
155
+ limited: known.limited ?? absent.limited })));
156
+ }
157
+ return runs.get(key);
158
+ }
159
+
160
+ function lookup(platform, identifier, options) {
161
+ const key = platform + '|' + identifier + '|' + (options.directory?.href ?? '');
162
+ if (!inFlight.has(key)) inFlight.set(key, request(platform, identifier, options).finally(() => inFlight.delete(key)));
163
+ return inFlight.get(key);
164
+ }
165
+
166
+ const cacheFile = (platform, identifier) => 'handle-' + platform.toLowerCase() + '-' + identifier + '.json';
167
+
168
+ async function cached(directory, platform, identifier, now) {
169
+ const saved = await readCache(directory, cacheFile(platform, identifier));
170
+ const age = now.getTime() - saved?.at;
171
+ return age >= 0 && age < (handleLifetime[saved?.state] ?? 0) ? saved : null;
172
+ }
173
+
174
+ // Answer a list of handles on one platform inside one shared time budget. Cached answers need no request; any live
175
+ // request runs beside the platform's control batch, and only a passing control lets a live answer through.
176
+ async function platformBatch(platform, handles, options, deadline) {
177
+ const { directory, now } = options;
178
+ const api = apis[platform];
179
+ const runCache = options.runAnswers ?? runAnswers;
180
+ const answers = new Map();
181
+ const live = [];
182
+ for (const handle of new Set(handles)) {
183
+ if (!label(handle) || !api.valid(handle)) {
184
+ answers.set(handle, { state: 'check', why: 'cannot check this handle form' });
185
+ continue;
186
+ }
187
+ const identifier = api.identifier?.(handle) ?? handle;
188
+ const earlier = runCache.get(platform + '|' + identifier + '|' + (directory?.href ?? ''));
189
+ if (earlier) {
190
+ answers.set(handle, earlier);
191
+ continue;
192
+ }
193
+ const saved = await cached(directory, platform, identifier, now);
194
+ if (saved) answers.set(handle, { state: saved.state, checkedAt: new Date(saved.at).toISOString(), via: 'cache' });
195
+ else live.push([handle, identifier]);
196
+ }
197
+ if (!live.length && (!options.controlRuns || !answers.size)) return answers;
198
+ if (platform === 'GitHub' && await githubHeld(directory, now)) {
199
+ for (const handle of [...answers.keys(), ...live.map(([handle]) => handle)]) answers.set(handle, { state: 'check', why: 'rate limited' });
200
+ return answers;
201
+ }
202
+ const signal = options.signal ? anySignal([options.signal, deadline]) : deadline;
203
+ const run = { ...options, signal };
204
+ const [control, results] = await Promise.all([
205
+ controlsFor(platform, run),
206
+ Promise.all(live.map(([, identifier]) => lookup(platform, identifier, run))),
207
+ ]);
208
+ const limited = control.limited ?? results.find(result => result.limited !== undefined)?.limited;
209
+ if (limited !== undefined) {
210
+ const until = limited > now.getTime() ? limited : now.getTime() + hour;
211
+ await writeCache(directory, githubHoldFile, { until }).catch(() => {});
212
+ }
213
+ if (!control.ok) {
214
+ for (const handle of [...answers.keys(), ...live.map(([handle]) => handle)]) {
215
+ answers.set(handle, { state: 'check', why: 'control check failed' });
216
+ }
217
+ return answers;
218
+ }
219
+ const checkedAt = now.toISOString();
220
+ for (const [index, [handle, identifier]] of live.entries()) {
221
+ const { state } = results[index];
222
+ const key = platform + '|' + identifier + '|' + (directory?.href ?? '');
223
+ if (state === 'check') {
224
+ const answer = { state: 'check', why: 'no clear answer in time' };
225
+ answers.set(handle, answer);
226
+ runCache.set(key, answer);
227
+ continue;
228
+ }
229
+ answers.set(handle, { state, checkedAt, via: 'api' });
230
+ runCache.set(key, { state, checkedAt, via: 'api' });
231
+ await writeCache(directory, cacheFile(platform, identifier), { at: now.getTime(), state }).catch(() => {});
232
+ }
233
+ return answers;
234
+ }
235
+
236
+ function linkRow(platform, handle, why = 'link only') {
237
+ return { platform: platform.id, handle, state: 'check', link: platform.link(handle), why };
238
+ }
239
+
240
+ function selectedPlatforms(extra) {
241
+ return [...handlePlatforms, ...requestPlatforms.filter(platform => extra === true || Array.isArray(extra) && extra.includes(platform.id))];
242
+ }
243
+
244
+ export function pendingHandleRows(name, extra) {
245
+ return selectedPlatforms(extra).map(platform => linkRow(platform, name, platform.auto ? 'still checking' : 'link only'));
246
+ }
247
+
248
+ export const handlePriorities = {
249
+ developer: ['GitHub', 'npm', 'X'],
250
+ consumer: ['Instagram', 'TikTok'],
251
+ b2b: ['LinkedIn', 'X'],
252
+ media: ['YouTube', 'TikTok'],
253
+ };
254
+
255
+ // rows: [{ name, platforms?: ['GitHub', 'npm', 'Bluesky'], variants?: boolean, links?: boolean }]
256
+ // Returns a Map from name to its handle rows in display order. Exact handle first; getNAME, NAMEapp and NAMEhq only
257
+ // when the exact handle is taken, inside the same per-platform budget.
258
+ export async function checkSocialHandles(rows, {
259
+ directory = cacheDir, now = new Date(), fetcher = globalThis.fetch, signal, budgetMs = platformBudgetMs,
260
+ controls, extraPlatforms = false, env = process.env, freshRun = false,
261
+ } = {}) {
262
+ const githubToken = typeof env?.DOMAIN_HOUND_GITHUB_TOKEN === 'string' && /^[\w-]{20,255}$/.test(env.DOMAIN_HOUND_GITHUB_TOKEN)
263
+ ? env.DOMAIN_HOUND_GITHUB_TOKEN : null;
264
+ const options = { directory, now, fetcher, signal, controls, githubToken,
265
+ ...(freshRun && { controlRuns: new Map(), runAnswers: new Map() }) };
266
+ const wanted = platform => rows.filter(row => (row.platforms ?? autoPlatforms).includes(platform));
267
+ const perPlatform = new Map(await Promise.all(autoPlatforms.map(async platform => {
268
+ const names = wanted(platform);
269
+ if (!names.length) return [platform, new Map()];
270
+ const started = performance.now();
271
+ const deadline = new AbortController();
272
+ // Keep Node alive until the platform answers or the deadline aborts its requests.
273
+ const timer = setTimeout(() => {
274
+ deadline.abort(new DOMException('The operation was aborted due to timeout', 'TimeoutError'));
275
+ }, budgetMs);
276
+ try {
277
+ const exact = await platformBatch(platform, names.map(row => row.name), options, deadline.signal);
278
+ const taken = names.filter(row => row.variants && exact.get(row.name)?.state === 'taken');
279
+ const left = budgetMs - (performance.now() - started);
280
+ const variants = taken.length && left >= 300
281
+ ? await platformBatch(platform, taken.flatMap(row => handleVariants(row.name)), options, deadline.signal)
282
+ : new Map();
283
+ return [platform, { exact, variants, skipped: taken.length > 0 && left < 300 }];
284
+ } finally {
285
+ clearTimeout(timer);
286
+ }
287
+ })));
288
+ const result = new Map();
289
+ for (const row of rows) {
290
+ const platforms = selectedPlatforms(extraPlatforms);
291
+ const entries = [];
292
+ for (const platform of platforms) {
293
+ const checked = (row.platforms ?? autoPlatforms).includes(platform.id) ? perPlatform.get(platform.id) : null;
294
+ if (!platform.auto || !checked?.exact) {
295
+ if (row.links === false) continue;
296
+ entries.push(linkRow(platform, row.name, platform.auto ? 'not checked for this name' : 'link only'));
297
+ continue;
298
+ }
299
+ const answer = checked.exact.get(row.name) ?? { state: 'check', why: 'no clear answer in time' };
300
+ const entry = { platform: platform.id, handle: row.name, state: answer.state, link: platform.link(row.name),
301
+ ...(answer.checkedAt && { checkedAt: answer.checkedAt }), ...(answer.why && { why: answer.why }) };
302
+ if (row.variants && answer.state === 'taken') {
303
+ entry.variants = handleVariants(row.name).map(handle => {
304
+ const variant = checked.variants.get(handle) ?? { state: 'check', why: 'no clear answer in time' };
305
+ return { handle, state: variant.state, link: platform.link(handle),
306
+ ...(variant.checkedAt && { checkedAt: variant.checkedAt }) };
307
+ });
308
+ }
309
+ entries.push(entry);
310
+ }
311
+ result.set(row.name, entries);
312
+ }
313
+ return result;
314
+ }
315
+
316
+ // "GitHub taken · npm no public profile found · Bluesky taken; check yourself: YouTube, X, …".
317
+ export function handleSummary(entries, { limit = Infinity, manualLimit = Infinity, ordered = false } = {}) {
318
+ if (!Array.isArray(entries) || !entries.length) return null;
319
+ const checked = entries.filter(entry => entry.state !== 'check');
320
+ const open = entries.filter(entry => entry.state === 'check');
321
+ if (ordered) {
322
+ const shown = new Set([...entries.slice(0, 2), ...checked.slice(0, 2)]);
323
+ for (const entry of entries) {
324
+ if (shown.size === 4) break;
325
+ shown.add(entry);
326
+ }
327
+ const states = entries.filter(entry => shown.has(entry))
328
+ .map(entry => entry.platform + ' ' + handleStates[entry.state].toLowerCase()).join(', ');
329
+ const more = entries.length - shown.size;
330
+ return states + (more ? ' (' + more + ' more on the page)' : '');
331
+ }
332
+ const shown = checked.slice(0, limit).map(entry => entry.platform + ' ' + handleStates[entry.state].toLowerCase());
333
+ const manual = open.slice(0, manualLimit);
334
+ const more = checked.length - shown.length + open.length - manual.length;
335
+ return [shown.join(' · '), manual.length ? 'check yourself: ' + manual.map(entry => entry.platform).join(', ') : '',
336
+ more > 0 ? '(' + more + ' more on the page)' : ''].filter(Boolean).join('; ');
337
+ }
@@ -1,11 +1,12 @@
1
1
  import { execFile } from 'node:child_process';
2
+ import { getDefaultAutoSelectFamilyAttemptTimeout, setDefaultAutoSelectFamilyAttemptTimeout } from 'node:net';
2
3
  import { setTimeout as delay } from 'node:timers/promises';
3
4
  import { pathToFileURL } from 'node:url';
4
5
  import { promisify } from 'node:util';
5
6
  import { apiShops, cachedSignals, confirmDomain, confirmingShops, lightConfirm } from './confirm.mjs';
6
7
  import { checkDomainSite } from './com-site.mjs';
7
8
  import { appStoreSearchLink, googleSearchLink, nameCheckLines, playSearchLink } from './google-search.mjs';
8
- import { applyLiveSite, asciiDomain, canRecommend, defaultEndings, eligibilityNotes, listQuote, mergeQuote, nameCandidates, normalizeName, pickName,
9
+ import { applyLiveSite, asciiDomain, domainEnding, canRecommend, defaultEndings, eligibilityNotes, listQuote, mergeQuote, nameCandidates, normalizeName, pickName,
9
10
  premiumRisk, rankName, registrationStatus, searchCandidates, searchName, termCosts, unicodeName, validEligibility, validEndings,
10
11
  withPremiumRisk, withoutListPrice } from './name-search.mjs';
11
12
  import { bundledCatalog, catalogOffers, datedListPrices, isListPriceUsable, loadCachedCatalog, refreshPrices } from './price-catalog.mjs';
@@ -76,7 +77,8 @@ export function normalize(input) {
76
77
  const labels = domain.split('.');
77
78
  const label = /^[a-z\d](?:[a-z\d-]{0,61}[a-z\d])?$/;
78
79
  const tld = /^(?:[a-z]{2,63}|xn--[a-z\d](?:[a-z\d-]{0,57}[a-z\d])?)$/;
79
- return labels.length === 2 && labels.every(part => label.test(part))
80
+ return (labels.length === 2 || labels.length === 3 && labels.slice(1).join('.') === 'co.uk')
81
+ && labels.every(part => label.test(part))
80
82
  && tld.test(labels.at(-1)) ? domain : null;
81
83
  }
82
84
 
@@ -176,7 +178,7 @@ export async function checkDomain(input, {
176
178
  } = {}) {
177
179
  const domain = normalize(input);
178
180
  if (!domain) return { error: 'Enter a domain such as example.com.' };
179
- const tld = domain.split('.').at(-1);
181
+ const tld = domainEnding(domain);
180
182
  const deadline = performance.now() + totalTimeout;
181
183
  const timeout = () => Math.max(0, Math.min(maxTimeout, Math.floor(deadline - performance.now())));
182
184
  const [registrations, catalog, pricing, dynadot, confirmed, nok, signals] = await Promise.all([
@@ -430,13 +432,24 @@ function compactAgentResult(groups, names, complete, checkedAt, batch, rateLimit
430
432
  s === 'nc' ? { d, s } : { d, s, ...price });
431
433
  }
432
434
  }
435
+ // Fourteen endings for twenty long names: an unconfirmed list-price row drops its s, as the display layer does.
436
+ if (batch && Buffer.byteLength(JSON.stringify(result)) >= 7900) {
437
+ for (const row of byName.values()) if (row.free) row.free = row.free.map(({ s, ...option }) => s === 'nc' ? option : { ...option, s });
438
+ result.legend = { ...result.legend, d: agentLegend.d + '; a free entry without s is nc' };
439
+ }
433
440
  return result;
434
441
  }
435
442
 
436
- // The top pick and up to three runners-up get a light confirm: registry signals first, then a keyed shop API.
437
- export function lightTargets(rows, eligible, count = 4) {
438
- const top = pickName(rows, eligible);
439
- const others = rankName(rows.filter(row => row !== top && ['probably-free', 'premium'].includes(row.status)
443
+ // The light confirm uses registry signals first, then a keyed shop API (only with the person's own key). By default only
444
+ // 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.
445
+ export const shopQuoteCount = (env = process.env) => env?.DOMAIN_HOUND_SHOP_QUOTES === 'top4' ? 4 : 1;
446
+
447
+ export function lightTargets(rows, eligible, count = 1, preferred = [], cap) {
448
+ const inScope = rows.filter(row => (!preferred.length || preferred.includes(row.tld))
449
+ && (cap == null || (row.firstPayment ?? Infinity) <= cap));
450
+ const top = preferred.length ? preferred.map(tld => pickName(inScope.filter(row => row.tld === tld), eligible)).find(Boolean)
451
+ : pickName(inScope, eligible);
452
+ const others = rankName(inScope.filter(row => row !== top && ['probably-free', 'premium'].includes(row.status)
440
453
  && canRecommend(row.tld, eligible)));
441
454
  return [top, ...others].filter(Boolean).slice(0, count);
442
455
  }
@@ -459,7 +472,7 @@ export async function agentResult(input, options = {}) {
459
472
  if (names.includes(null)) return { error: 'Enter a valid name or exact domain.' };
460
473
  const exact = new Set(domain ? [domain] : names.filter((name, index) => batch && exactDomain(input[index])));
461
474
  const groups = [...new Set(names)].map(name => ({ name, candidates: exact.has(name)
462
- ? [{ domain: name, tld: name.split('.').at(-1), exact: true }] : nameCandidates(name, { ...options, variants: !batch }) }));
475
+ ? [{ domain: name, tld: domainEnding(name), exact: true }] : nameCandidates(name, { ...options, variants: !batch }) }));
463
476
  const keyed = apiShops(options.env ?? process.env).length > 0;
464
477
  const reserve = keyed ? 1800 : 0;
465
478
  const searchOptions = { ...options, budgetMs: Math.max(0, Math.min(remaining() - reserve, batch ? 10_700 : 2700)),
@@ -471,19 +484,22 @@ export async function agentResult(input, options = {}) {
471
484
  const rows = fast.groups.flatMap(group => group.results);
472
485
  const targets = domain ? rows.filter(row => canRecommend(row.tld, options.eligible)
473
486
  && ['probably-free', 'check-at-shop', 'premium'].includes(row.status))
474
- : lightTargets(rows, options.eligible);
487
+ : lightTargets(rows, options.eligible, shopQuoteCount(options.env ?? process.env), options.preferredEndings, options.upfrontCap);
475
488
  const [candidate] = targets;
476
489
  // A Google retry can settle every row that the first pass left waiting.
477
490
  let complete = fast.complete || !rows.some(row => row.registryReason === 'Registry lookup timed out');
478
491
  const quotes = new Map();
492
+ // The domains a shop was asked about in this lookup, for the receipt's disclosure.
493
+ const asked = new Set();
494
+ const onShopQuery = (_shop, domain) => asked.add(domain);
479
495
  if (targets.length) {
480
496
  options.onProgress?.({ stage: 'quotes' });
481
497
  const catalog = await loadCachedCatalog(options.directory);
482
- const listFor = (target, shop) => datedListPrices(catalog, target.split('.').at(-1), options.now ?? new Date(),
498
+ const listFor = (target, shop) => datedListPrices(catalog, domainEnding(target), options.now ?? new Date(),
483
499
  options.bundledCatalog === undefined ? bundledCatalog : options.bundledCatalog).find(row => row.id === shop) ?? null;
484
500
  const light = options.lightConfirm ?? lightConfirm;
485
501
  const found = await light(targets.map(row => row.domain), { env: options.env, fetcher: options.fetcher,
486
- directory: options.directory, now: options.now, deadline: performance.now() + Math.max(0, remaining() - 150), listFor })
502
+ directory: options.directory, now: options.now, deadline: performance.now() + Math.max(0, remaining() - 150), listFor, onShopQuery })
487
503
  .catch(() => new Map());
488
504
  for (const [key, value] of found) quotes.set(key, value);
489
505
  }
@@ -499,7 +515,7 @@ export async function agentResult(input, options = {}) {
499
515
  try {
500
516
  quote = await Promise.race([
501
517
  confirm(candidate.confirmShop, candidate.domain, { deadline, directory: options.directory,
502
- unsupported: ['so', 'no'], fresh: true, oneShop: batch }).catch(() => null),
518
+ unsupported: ['so', 'no'], fresh: true, oneShop: batch, onShopQuery }).catch(() => null),
503
519
  new Promise(resolve => { timer = setTimeout(resolve, remaining()); }),
504
520
  ]);
505
521
  if (!remaining() || quote === undefined) complete = false;
@@ -521,9 +537,11 @@ export async function agentResult(input, options = {}) {
521
537
  const otherEndings = exactCom ? await endingBenchmarks(exactCom, options) : null;
522
538
  const result = compactAgentResult(rankedGroups, names, complete, checkedAt, batch, rateLimited,
523
539
  options.browser ? liveCheckFor(candidate, quote) : null, { eligible: options.eligible, otherEndings });
540
+ if (asked.size) result.shopAsked = [...asked];
524
541
  if (options.receipt) result.receiptDetails = rankedGroups.map(({ results, sites }) => ({ endings: results.map(row => ({
525
542
  domain: row.domain, source: row.source, checkedAt: row.checkedAt, priceAt: row.priceCheckedAt,
526
543
  shop: row.shop, checkout: row.buyUrl, site: sites?.[row.tld], risk: row.premium === 'risk' || row.premiumRisk,
544
+ ...(row.savings && { savings: row.savings }),
527
545
  })) }));
528
546
  return result;
529
547
  }
@@ -650,6 +668,8 @@ function lookupArgs(args) {
650
668
  const arg = args[index];
651
669
  if (arg === '--ai') options.ai = true;
652
670
  else if (arg === '--endings' && !options.endings) options.endings = (args[++index] ?? '').split(',');
671
+ else if (arg === '--prefer-endings' && !options.preferredEndings) options.preferredEndings = (args[++index] ?? '').split(',');
672
+ else if (arg === '--upfront-cap' && options.upfrontCap === undefined) options.upfrontCap = Number(args[++index]);
653
673
  else if (arg === '--eligible' && !options.eligible) options.eligible = (args[++index] ?? '').split(',');
654
674
  else if (arg === '--category' && !options.category) options.category = (args[++index] ?? '').slice(0, 100);
655
675
  else if (arg === '--compact') options.compact = true;
@@ -663,12 +683,44 @@ function lookupArgs(args) {
663
683
  return { options, positional };
664
684
  }
665
685
 
686
+ function triageOutput(result, options) {
687
+ if (options.compact) {
688
+ for (const row of result.names ?? []) {
689
+ row.checks = nameCheckLines(row).map(({ label, text, link }) => label + ': ' + text + ' · ' + link);
690
+ }
691
+ }
692
+ return result;
693
+ }
694
+
695
+ function printResult(result) {
696
+ const packet = process.env.DOMAIN_HOUND_MCP_OUTPUT === '1' && !result.error ? { ...result, _mcpResult: true } : result;
697
+ console.log(JSON.stringify(packet));
698
+ }
699
+
700
+ // The name screen's first answer comes by answerMs with the checks done so far. With followUp, the slow checks keep
701
+ // running in the same process (no lookup is repeated) and a second, re-assessed result follows on the next line.
702
+ export const firstAnswerMs = 8000;
703
+ export const followUpMs = 24000;
704
+ export const lateSiteMs = 8000;
705
+ export async function triageWithFollowUp(names, options, { followUp = false, answerMs = firstAnswerMs, print = () => {} } = {}) {
706
+ if (!followUp) return triageNames(names, options);
707
+ const memo = new Map();
708
+ const run = { ...options, memo, budgetMs: options.budgetMs ?? followUpMs, lateSiteMs };
709
+ const first = await triageNames(names, { ...run, answerAt: performance.now() + answerMs });
710
+ if (first.error || !first.followUp) return first;
711
+ print(first);
712
+ return triageNames(names, run);
713
+ }
714
+
666
715
  function runConfirmation(shop, domain) {
667
716
  return confirmDomain(shop, domain, { unsupported: ['so', 'no'], fresh: true });
668
717
  }
669
718
 
670
719
  if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) {
671
720
  const args = process.argv.slice(2);
721
+ // The 250 ms default was cutting off the IPv4 leg before several public sources could connect.
722
+ // The individual request deadlines and the first-answer deadline still apply.
723
+ if (args[0] === '--triage') setDefaultAutoSelectFamilyAttemptTimeout(Math.max(900, getDefaultAutoSelectFamilyAttemptTimeout()));
672
724
  const { options, positional } = lookupArgs(args.slice(1));
673
725
  // The MCP server reads these to answer with progress when a lookup outlasts its budget.
674
726
  const onProgress = progressReporter();
@@ -690,15 +742,12 @@ if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href)
690
742
  : args[0] === '--refresh-tranco' && args.length === 1
691
743
  ? await refreshTranco({ directory: process.env.DOMAIN_HOUND_TRANCO_CACHE ? pathToFileURL(process.env.DOMAIN_HOUND_TRANCO_CACHE.replace(/\/?$/, '/')) : undefined })
692
744
  : args[0] === '--presence' && args.length === 2 ? await namePresence(args[1], { refreshTranco: true })
693
- : args[0] === '--triage' ? await triageNames(positional.length === 1 ? positional[0].split(',') : null,
694
- { ...options, refreshTranco: true })
745
+ : args[0] === '--triage' ? await triageWithFollowUp(positional.length === 1 ? positional[0].split(',') : null,
746
+ { ...options, refreshTranco: true, deferHandles: process.env.DOMAIN_HOUND_DEFER_HANDLES === '1' },
747
+ { followUp: process.env.DOMAIN_HOUND_FOLLOW_UP === '1', answerMs: Number(process.env.DOMAIN_HOUND_ANSWER_MS) || undefined,
748
+ print: first => printResult(triageOutput(first, options)) })
695
749
  : await checkDomain(args.length === 1 ? args[0] : undefined);
696
750
  if (result.error) process.exitCode = 1;
697
- if (args[0] === '--triage' && options.compact) {
698
- for (const row of result.names ?? []) {
699
- row.checks = nameCheckLines(row).map(({ label, text, link }) => label + ': ' + text + ' · ' + link);
700
- }
701
- }
702
- console.log(JSON.stringify(result));
751
+ printResult(args[0] === '--triage' ? triageOutput(result, options) : result);
703
752
  }
704
753
  }