domain-hound 0.0.0-stage → 0.1.2
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.
- package/.agents/plugins/marketplace.json +12 -0
- package/.claude-plugin/marketplace.json +12 -0
- package/.claude-plugin/plugin.json +28 -0
- package/LICENSE +21 -0
- package/README.md +63 -2
- package/assets/icon-1024.png +0 -0
- package/assets/icon-512.png +0 -0
- package/assets/icon.svg +14 -0
- package/bin/domain-hound.mjs +5 -0
- package/clis/domain-check/cache.mjs +64 -0
- package/clis/domain-check/com-site.mjs +159 -0
- package/clis/domain-check/company-search.mjs +90 -0
- package/clis/domain-check/confirm.mjs +612 -0
- package/clis/domain-check/google-play.mjs +191 -0
- package/clis/domain-check/google-search.mjs +244 -0
- package/clis/domain-check/index.mjs +636 -0
- package/clis/domain-check/name-search.mjs +248 -0
- package/clis/domain-check/naming-method.mjs +21 -0
- package/clis/domain-check/parking.mjs +27 -0
- package/clis/domain-check/price-catalog.mjs +343 -0
- package/clis/domain-check/price-snapshot.json +176 -0
- package/clis/domain-check/prices.mjs +196 -0
- package/clis/domain-check/progress.mjs +14 -0
- package/clis/domain-check/registry.mjs +274 -0
- package/clis/domain-check/terms.json +152 -0
- package/clis/domain-check/traction.mjs +603 -0
- package/clis/domain-check/triage-sources.mjs +321 -0
- package/clis/domain-check/triage.mjs +566 -0
- package/display.mjs +713 -0
- package/mcp.json +10 -0
- package/package.json +66 -4
- package/plugin.json +32 -0
- package/server.json +27 -0
- package/server.mjs +444 -0
|
@@ -0,0 +1,612 @@
|
|
|
1
|
+
import { setTimeout as delay } from 'node:timers/promises';
|
|
2
|
+
import { cacheDir, readCache, writeCache } from './cache.mjs';
|
|
3
|
+
import { money, shops, shopSearchUrl } from './prices.mjs';
|
|
4
|
+
|
|
5
|
+
const budget = 20_500;
|
|
6
|
+
const shopBudget = 10_000;
|
|
7
|
+
const cacheLifetime = 15 * 60_000;
|
|
8
|
+
const userAgent = 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0 Safari/537.36';
|
|
9
|
+
const dollars = String.raw`\$\s*(?:\d{1,3}(?:,\d{3})+|\d+)\.\d{2}`;
|
|
10
|
+
const priceLine = new RegExp('^' + dollars + '$');
|
|
11
|
+
const dynadotPrices = new RegExp('^(?:' + dollars + '){1,2}$');
|
|
12
|
+
const lastPrice = new RegExp(dollars + '$');
|
|
13
|
+
const spaceshipRenewal = new RegExp('^Renews (' + dollars + ')$', 'i');
|
|
14
|
+
const dynadotRenewal = new RegExp('^Renewal (' + dollars + ')$', 'i');
|
|
15
|
+
const namecheapPrice = new RegExp('^(' + dollars + ')/yr$', 'i');
|
|
16
|
+
const namecheapRenewal = new RegExp('^Renews at (' + dollars + ')/yr\\.?$', 'i');
|
|
17
|
+
const cloudflareQuote = new RegExp('^Buy now: ([a-z0-9.-]+) for (' + dollars + ')\\. Renews at (' + dollars + ') per year\\.$', 'i');
|
|
18
|
+
const taken = /^(?:Taken|Registered in \d{4})$/i;
|
|
19
|
+
const premiumLabel = /^(?:Premium|Premium domain)$/i;
|
|
20
|
+
const trackerRoots = [
|
|
21
|
+
'google-analytics.com', 'googletagmanager.com', 'doubleclick.net', 'googlesyndication.com',
|
|
22
|
+
'facebook.net', 'facebook.com', 'nr-data.net', 'newrelic.com', 'crazyegg.com',
|
|
23
|
+
'engagement.ai', 'spotify.com', 'clarity.ms', 'hotjar.com', 'tiktok.com', 'bing.com',
|
|
24
|
+
'googleadservices.com', 'segment.io', 'segment.com', 'ads-twitter.com', 'analytics.twitter.com',
|
|
25
|
+
];
|
|
26
|
+
const blockedResources = ['Image', 'Font', 'Media'];
|
|
27
|
+
const blockedUrls = [
|
|
28
|
+
...trackerRoots.flatMap(root => ['*://' + root + '/*', '*://*.' + root + '/*']),
|
|
29
|
+
'*://www.google.com/ccm/*', '*://www.google.com/rmkt/*', '*://www.google.com/pagead/*',
|
|
30
|
+
];
|
|
31
|
+
|
|
32
|
+
async function blockStorefrontRequests(page) {
|
|
33
|
+
let client;
|
|
34
|
+
try {
|
|
35
|
+
client = await page.context().newCDPSession(page);
|
|
36
|
+
await client.send('Network.enable');
|
|
37
|
+
await client.send('Network.setBlockedURLs', { urls: blockedUrls });
|
|
38
|
+
client.on('Fetch.requestPaused', ({ requestId }) => {
|
|
39
|
+
void client.send('Fetch.failRequest', { requestId, errorReason: 'BlockedByClient' }).catch(() => {});
|
|
40
|
+
});
|
|
41
|
+
await client.send('Fetch.enable', {
|
|
42
|
+
patterns: blockedResources.map(resourceType => ({ resourceType })),
|
|
43
|
+
});
|
|
44
|
+
} catch {
|
|
45
|
+
await client?.detach().catch(() => {});
|
|
46
|
+
await page.route?.('**/*', route => {
|
|
47
|
+
const request = route.request();
|
|
48
|
+
const url = new URL(request.url());
|
|
49
|
+
const blocked = blockedResources.some(type => type.toLowerCase() === request.resourceType()) ||
|
|
50
|
+
trackerRoots.some(root => url.hostname === root || url.hostname.endsWith('.' + root));
|
|
51
|
+
return blocked ? route.abort() : route.continue();
|
|
52
|
+
});
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
const blocked = /performing security verification|verify (?:that )?you are human|just a moment|hardcore hacker detected|access denied|awaiting verification|pork captcha/i;
|
|
57
|
+
|
|
58
|
+
function linesOf(text) {
|
|
59
|
+
return text.split('\n').map(line => line.trim()).filter(Boolean);
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
function quote(price, renewal, premium) {
|
|
63
|
+
return { available: true, premium, price, renewal };
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
function unavailable(premium = false) {
|
|
67
|
+
return { available: false, premium, price: null, renewal: null };
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
export function parseSpaceship(text, domain, badge = false) {
|
|
71
|
+
const lines = linesOf(text);
|
|
72
|
+
const [label, tld] = domain.split('.');
|
|
73
|
+
for (let i = 0; i < lines.length; i++) {
|
|
74
|
+
const start = lines[i].toLowerCase();
|
|
75
|
+
const split = start === label && lines[i + 1]?.toLowerCase() === '.' + tld;
|
|
76
|
+
if (!split && start !== domain) continue;
|
|
77
|
+
let cursor = i + (split ? 2 : 1);
|
|
78
|
+
let premium = badge;
|
|
79
|
+
const isPremium = () => premiumLabel.test(lines[cursor]);
|
|
80
|
+
if (isPremium() && priceLine.test(lines[cursor + 1])) {
|
|
81
|
+
premium = true;
|
|
82
|
+
cursor++;
|
|
83
|
+
}
|
|
84
|
+
if (taken.test(lines[cursor])) return unavailable(premium);
|
|
85
|
+
let price = null;
|
|
86
|
+
for (let count = 0; count < 2 && priceLine.test(lines[cursor]); count++) {
|
|
87
|
+
price = money(lines[cursor++]);
|
|
88
|
+
}
|
|
89
|
+
const renewalText = lines[cursor]?.match(spaceshipRenewal)?.[1];
|
|
90
|
+
if (renewalText) cursor++;
|
|
91
|
+
if (isPremium() && /^Add to cart$/i.test(lines[cursor + 1])) {
|
|
92
|
+
premium = true;
|
|
93
|
+
cursor++;
|
|
94
|
+
}
|
|
95
|
+
if (price > 0 && (renewalText || premium) && /^Add to cart$/i.test(lines[cursor])) {
|
|
96
|
+
return quote(price, money(renewalText), premium);
|
|
97
|
+
}
|
|
98
|
+
}
|
|
99
|
+
return null;
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
export function parseSpaceshipRows(rows, domains) {
|
|
103
|
+
const results = new Map();
|
|
104
|
+
const wanted = new Set(domains);
|
|
105
|
+
for (const { domain, text, premium, canBuy, currentPrice } of rows) {
|
|
106
|
+
if (!wanted.has(domain)) continue;
|
|
107
|
+
// Some rows render the cart action as an icon with an accessible label.
|
|
108
|
+
const action = canBuy && !/^Add to cart$/im.test(text) ? '\nAdd to cart' : '';
|
|
109
|
+
const parsed = parseSpaceship(text + action, domain, premium);
|
|
110
|
+
if (!parsed || (parsed.available && canBuy === false)) continue;
|
|
111
|
+
if (parsed.available && priceLine.test(currentPrice)) parsed.price = money(currentPrice);
|
|
112
|
+
const previous = results.get(domain);
|
|
113
|
+
// Prioritize explicit taken or premium disclosures from a duplicate card.
|
|
114
|
+
if (!previous || (previous.available && (!parsed.available || (parsed.premium && !previous.premium)))) {
|
|
115
|
+
results.set(domain, parsed);
|
|
116
|
+
}
|
|
117
|
+
}
|
|
118
|
+
return results;
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
export function parseDynadot(text, domain, badge = false) {
|
|
122
|
+
const [name, ...lines] = linesOf(text);
|
|
123
|
+
if (name?.toLowerCase() !== domain) return null;
|
|
124
|
+
const premium = badge || lines.some(line => premiumLabel.test(line));
|
|
125
|
+
if (lines.some(line => taken.test(line) || /^Place Backorder$/i.test(line))) return unavailable(premium);
|
|
126
|
+
const renewal = money(lines.map(line => line.match(dynadotRenewal)?.[1]).find(Boolean));
|
|
127
|
+
const prices = lines.find(line => dynadotPrices.test(line));
|
|
128
|
+
const price = money(prices?.match(lastPrice)?.[0]);
|
|
129
|
+
return price > 0 && (renewal > 0 || premium) && (premium || lines.includes('is available'))
|
|
130
|
+
? quote(price, renewal, premium) : null;
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
export function parseNamecheap(text, domain, badge = false) {
|
|
134
|
+
const [name, ...lines] = linesOf(text);
|
|
135
|
+
if (name?.toLowerCase() !== domain) return null;
|
|
136
|
+
const premium = badge || lines.some(line => premiumLabel.test(line));
|
|
137
|
+
if (lines.some(line => taken.test(line) || /^Make offer$/i.test(line))) return unavailable(premium);
|
|
138
|
+
const price = money(lines.map(line => line.match(namecheapPrice)?.[1]).find(Boolean));
|
|
139
|
+
const renewal = money(lines.map(line => line.match(namecheapRenewal)?.[1]).find(Boolean));
|
|
140
|
+
return price > 0 && lines.some(line => /^Add to cart$/i.test(line)) ? quote(price, renewal, premium) : null;
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
export function parseCloudflare(text, domain, badge = false, buyLabel = '') {
|
|
144
|
+
const lines = linesOf(text);
|
|
145
|
+
const premium = badge || lines.some(line => premiumLabel.test(line));
|
|
146
|
+
if (lines.at(-1) === 'Unavailable' && lines.slice(0, -1).join('').toLowerCase() === domain) {
|
|
147
|
+
return unavailable(premium);
|
|
148
|
+
}
|
|
149
|
+
const match = buyLabel?.match(cloudflareQuote);
|
|
150
|
+
return match?.[1].toLowerCase() === domain ? quote(money(match[2]), money(match[3]), premium) : null;
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
// Cloudflare renders a buy price before its exact-domain availability check settles.
|
|
154
|
+
export function cloudflareSettlement(domain) {
|
|
155
|
+
let searchId;
|
|
156
|
+
let exactId;
|
|
157
|
+
let settled = null;
|
|
158
|
+
return {
|
|
159
|
+
read() { return settled; },
|
|
160
|
+
receive(message) {
|
|
161
|
+
let item;
|
|
162
|
+
if (message?.type === 'results.snapshot' && Array.isArray(message.items)) {
|
|
163
|
+
item = message.items.find(row => row?.fqdn === domain);
|
|
164
|
+
if (!item || typeof item.id !== 'string' || !Number.isSafeInteger(message.searchId)) return;
|
|
165
|
+
if (searchId !== message.searchId || exactId !== item.id) settled = null;
|
|
166
|
+
searchId = message.searchId;
|
|
167
|
+
exactId = item.id;
|
|
168
|
+
} else if (message?.type === 'results.delta' && exactId && message.searchId === searchId &&
|
|
169
|
+
Array.isArray(message.patches)) {
|
|
170
|
+
item = message.patches.find(row => row?.id === exactId);
|
|
171
|
+
}
|
|
172
|
+
if (item?.status === 'taken') settled = { available: false, premium: false };
|
|
173
|
+
if (item?.status === 'available' && typeof item.premium === 'boolean') {
|
|
174
|
+
settled = { available: true, premium: item.premium };
|
|
175
|
+
}
|
|
176
|
+
},
|
|
177
|
+
};
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
const adapters = {
|
|
181
|
+
spaceship: {
|
|
182
|
+
rows: '[data-zid="instantSearchMainResult"], [data-zid="instantSearchDomainListItem"]',
|
|
183
|
+
name: '[data-zid="instantSearchMainResultName"], [data-zid="instantSearchDomainName"]',
|
|
184
|
+
premium: '.domain-status-icons-icon-premium, [aria-label="Premium"]',
|
|
185
|
+
parse: parseSpaceship,
|
|
186
|
+
},
|
|
187
|
+
dynadot: {
|
|
188
|
+
rows: '.result-row',
|
|
189
|
+
name: '.search-domain-word',
|
|
190
|
+
premium: '[aria-label="Premium"], [title="Premium"]',
|
|
191
|
+
parse: parseDynadot,
|
|
192
|
+
},
|
|
193
|
+
namecheap: {
|
|
194
|
+
rows: 'section.standard article',
|
|
195
|
+
name: 'h2',
|
|
196
|
+
premium: '.premium, [aria-label="Premium"], [title="Premium"]',
|
|
197
|
+
parse: parseNamecheap,
|
|
198
|
+
},
|
|
199
|
+
cloudflare: {
|
|
200
|
+
rows: '.registrar-result-card',
|
|
201
|
+
name: '[data-domain-name]',
|
|
202
|
+
premium: '[aria-label="Premium"], [title="Premium"]',
|
|
203
|
+
buyLabel: 'button[aria-label^="Buy now:"]',
|
|
204
|
+
parse: parseCloudflare,
|
|
205
|
+
},
|
|
206
|
+
};
|
|
207
|
+
|
|
208
|
+
async function readResult(page, adapter, domain, timeout) {
|
|
209
|
+
const { rows, name, premium, buyLabel } = adapter;
|
|
210
|
+
return page.locator('body').evaluate((body, selectors) => {
|
|
211
|
+
const exact = [...body.querySelectorAll(selectors.rows)].filter(row => {
|
|
212
|
+
const name = row.querySelector(selectors.name);
|
|
213
|
+
return name?.textContent.replace(/\s/g, '').toLowerCase() === selectors.domain &&
|
|
214
|
+
row.getClientRects().length > 0;
|
|
215
|
+
});
|
|
216
|
+
return {
|
|
217
|
+
rows: exact.map(row => {
|
|
218
|
+
const cart = selectors.cart && [...row.querySelectorAll('button, [role="button"]')].find(button =>
|
|
219
|
+
button.matches('[data-zid="instantSearchAddToCartButton"], [data-zid="instantSearchMainResultAddToCart"], [aria-label="Add to cart"]') ||
|
|
220
|
+
button.innerText.trim() === 'Add to cart');
|
|
221
|
+
const enabled = cart ? !cart.disabled && cart.getAttribute('aria-disabled') !== 'true' : undefined;
|
|
222
|
+
return {
|
|
223
|
+
domain: selectors.domain,
|
|
224
|
+
text: row.innerText,
|
|
225
|
+
premium: row.matches(selectors.premium) || Boolean(row.querySelector(selectors.premium)),
|
|
226
|
+
buyLabel: selectors.buyLabel ? row.querySelector(selectors.buyLabel)?.getAttribute('aria-label') : '',
|
|
227
|
+
currentPrice: selectors.spaceship ? row.querySelector('.price-current')?.innerText.trim() : undefined,
|
|
228
|
+
canBuy: selectors.spaceship ? Boolean(enabled) : enabled,
|
|
229
|
+
};
|
|
230
|
+
}),
|
|
231
|
+
pageStatus: exact.length ? '' : document.title + '\n' + body.innerText.slice(0, 350),
|
|
232
|
+
};
|
|
233
|
+
}, { rows, name, premium, buyLabel, domain, spaceship: adapter === adapters.spaceship,
|
|
234
|
+
cart: adapter === adapters.spaceship || adapter === adapters.namecheap }, { timeout });
|
|
235
|
+
}
|
|
236
|
+
|
|
237
|
+
function unknown(reason) {
|
|
238
|
+
return { available: null, premium: false, price: null, renewal: null, reason };
|
|
239
|
+
}
|
|
240
|
+
|
|
241
|
+
const timedOut = 'Shop check timed out.';
|
|
242
|
+
|
|
243
|
+
async function checkShop(page, shop, domain, deadline) {
|
|
244
|
+
const remaining = () => Math.max(1, Math.ceil(deadline - performance.now()));
|
|
245
|
+
const url = shopSearchUrl(shop, domain);
|
|
246
|
+
const origin = new URL(url).origin;
|
|
247
|
+
const adapter = Object.hasOwn(adapters, shop) ? adapters[shop] : null;
|
|
248
|
+
if (!adapter) return unknown('Shop has no supported exact-domain result.');
|
|
249
|
+
if (performance.now() >= deadline) return unknown(timedOut);
|
|
250
|
+
try {
|
|
251
|
+
const response = await page.goto(url, { waitUntil: 'commit', timeout: remaining() });
|
|
252
|
+
if ([401, 403, 429].includes(response?.status())) return unknown('Shop blocked the check.');
|
|
253
|
+
if (!response?.ok()) return unknown('Shop search is unavailable.');
|
|
254
|
+
while (performance.now() < deadline) {
|
|
255
|
+
if (new URL(page.url()).origin !== origin) return unknown('Shop redirected the check.');
|
|
256
|
+
const result = await readResult(page, adapter, domain, remaining());
|
|
257
|
+
if (blocked.test(result.pageStatus)) return unknown('Shop blocked the check.');
|
|
258
|
+
if (shop === 'spaceship') {
|
|
259
|
+
const quote = parseSpaceshipRows(result.rows, [domain]).get(domain);
|
|
260
|
+
if (quote) return quote;
|
|
261
|
+
} else {
|
|
262
|
+
for (const row of result.rows) {
|
|
263
|
+
const parsed = adapter.parse(row.text, domain, row.premium, row.buyLabel);
|
|
264
|
+
if (parsed && !(parsed.available && row.canBuy === false)) return parsed;
|
|
265
|
+
}
|
|
266
|
+
}
|
|
267
|
+
await delay(Math.min(200, remaining()));
|
|
268
|
+
}
|
|
269
|
+
return unknown(timedOut);
|
|
270
|
+
} catch (error) {
|
|
271
|
+
return unknown(error?.name === 'TimeoutError' ? timedOut : 'Shop search is unavailable.');
|
|
272
|
+
}
|
|
273
|
+
}
|
|
274
|
+
|
|
275
|
+
export async function withShopPages(deadline, run, {
|
|
276
|
+
env = process.env, launch, onFailure = unknown,
|
|
277
|
+
} = {}) {
|
|
278
|
+
let browser;
|
|
279
|
+
let timer;
|
|
280
|
+
let expired = false;
|
|
281
|
+
async function work() {
|
|
282
|
+
if (!launch) {
|
|
283
|
+
try {
|
|
284
|
+
const { chromium } = await import(env.DOMAIN_HOUND_PLAYWRIGHT || 'playwright');
|
|
285
|
+
launch = options => chromium.launch(options);
|
|
286
|
+
} catch { return onFailure('Playwright is unavailable.'); }
|
|
287
|
+
}
|
|
288
|
+
if (expired) return onFailure(timedOut);
|
|
289
|
+
try {
|
|
290
|
+
browser = await launch({ headless: true, timeout: Math.min(4000, Math.max(1, deadline - performance.now())) });
|
|
291
|
+
if (expired) return onFailure(timedOut);
|
|
292
|
+
const context = await browser.newContext({
|
|
293
|
+
userAgent, locale: 'en-US', viewport: { width: 1280, height: 900 }, serviceWorkers: 'block',
|
|
294
|
+
});
|
|
295
|
+
async function openPage() {
|
|
296
|
+
const page = await context.newPage();
|
|
297
|
+
try {
|
|
298
|
+
await blockStorefrontRequests(page);
|
|
299
|
+
return page;
|
|
300
|
+
} catch (error) {
|
|
301
|
+
await page.close().catch(() => {});
|
|
302
|
+
throw error;
|
|
303
|
+
}
|
|
304
|
+
}
|
|
305
|
+
return await run(async (domain, usePage) => {
|
|
306
|
+
let page;
|
|
307
|
+
try {
|
|
308
|
+
if (expired) return unknown(timedOut);
|
|
309
|
+
page = await openPage();
|
|
310
|
+
return await usePage((shop, until) => checkShop(page, shop, domain, Math.min(until, deadline)));
|
|
311
|
+
} catch {
|
|
312
|
+
return unknown('Shop search is unavailable.');
|
|
313
|
+
} finally {
|
|
314
|
+
await page?.close().catch(() => {});
|
|
315
|
+
}
|
|
316
|
+
}, openPage);
|
|
317
|
+
} catch {
|
|
318
|
+
return onFailure('Headless Chromium is unavailable.');
|
|
319
|
+
} finally {
|
|
320
|
+
// The caller's deadline also covers cleanup. Browser shutdown may continue after a result is returned.
|
|
321
|
+
void browser?.close().catch(() => {});
|
|
322
|
+
}
|
|
323
|
+
}
|
|
324
|
+
try {
|
|
325
|
+
return await Promise.race([work(), new Promise(resolve => {
|
|
326
|
+
timer = setTimeout(() => {
|
|
327
|
+
expired = true;
|
|
328
|
+
void browser?.close().catch(() => {});
|
|
329
|
+
resolve(onFailure(timedOut));
|
|
330
|
+
}, Math.max(0, Math.ceil(deadline - performance.now())));
|
|
331
|
+
})]);
|
|
332
|
+
} finally {
|
|
333
|
+
clearTimeout(timer);
|
|
334
|
+
}
|
|
335
|
+
}
|
|
336
|
+
|
|
337
|
+
export const confirmingShops = ['spaceship', 'namecheap', 'dynadot', 'cloudflare'];
|
|
338
|
+
|
|
339
|
+
function shopOrder(shop, tld, unsupported) {
|
|
340
|
+
const preferred = tld === 'no' ? 'dynadot' : 'namecheap';
|
|
341
|
+
// Spaceship's retail catalog does not cover .no and .so.
|
|
342
|
+
return [...new Set([shop, 'spaceship', preferred, ...confirmingShops])]
|
|
343
|
+
.filter(id => Object.hasOwn(adapters, id) && (id !== 'spaceship' || !unsupported?.includes(tld)))
|
|
344
|
+
.slice(0, 2);
|
|
345
|
+
}
|
|
346
|
+
|
|
347
|
+
function formatResult(start, domain, requestedShop, shop, result, now) {
|
|
348
|
+
const status = result.available === false ? 'taken' : result.available !== true ? 'could-not-confirm'
|
|
349
|
+
: result.premium ? 'premium' : 'confirmed';
|
|
350
|
+
return { ...result, shop, shopName: shops[shop]?.name ?? null, requestedShop, domain, status,
|
|
351
|
+
...fallbackNote(requestedShop, shop, status),
|
|
352
|
+
buyUrl: shopSearchUrl(shop, domain), checkedAt: now.toISOString(), ms: Math.round(performance.now() - start) };
|
|
353
|
+
}
|
|
354
|
+
|
|
355
|
+
function fallbackNote(requestedShop, shop, status) {
|
|
356
|
+
return shop !== requestedShop && status !== 'could-not-confirm'
|
|
357
|
+
? { note: `Requested ${shops[requestedShop].name}; confirmed at ${shops[shop].name}` } : {};
|
|
358
|
+
}
|
|
359
|
+
|
|
360
|
+
let spaceshipTail = Promise.resolve();
|
|
361
|
+
|
|
362
|
+
export async function confirmAtShops(domain, check, deadline, order) {
|
|
363
|
+
let shop = order[0];
|
|
364
|
+
let result;
|
|
365
|
+
for (const id of order) {
|
|
366
|
+
if (performance.now() >= deadline) break;
|
|
367
|
+
shop = id;
|
|
368
|
+
const run = () => performance.now() >= deadline ? unknown(timedOut)
|
|
369
|
+
: check(shop, Math.min(deadline, performance.now() + shopBudget));
|
|
370
|
+
if (shop === 'spaceship') {
|
|
371
|
+
const turn = spaceshipTail.then(run);
|
|
372
|
+
spaceshipTail = turn.catch(() => {});
|
|
373
|
+
result = await turn;
|
|
374
|
+
} else {
|
|
375
|
+
result = await run();
|
|
376
|
+
}
|
|
377
|
+
if (result.available !== null) break;
|
|
378
|
+
}
|
|
379
|
+
return { shop, result: result ?? unknown(timedOut) };
|
|
380
|
+
}
|
|
381
|
+
|
|
382
|
+
export async function confirmDomain(shopValue, domain, options = {}) {
|
|
383
|
+
const start = performance.now();
|
|
384
|
+
const shop = typeof shopValue === 'string' ? shopValue.toLowerCase() : null;
|
|
385
|
+
const now = options.now ?? new Date();
|
|
386
|
+
if (!domain || !Object.hasOwn(shops, shop)) return { error: 'Choose a trusted shop and a valid domain.' };
|
|
387
|
+
const directory = options.directory === undefined ? cacheDir : options.directory;
|
|
388
|
+
const filename = 'confirm-' + shop + '-' + domain + '.json';
|
|
389
|
+
const cached = options.fresh ? null : await readCache(directory, filename);
|
|
390
|
+
const age = now - Date.parse(cached?.checkedAt);
|
|
391
|
+
if (cached?.domain === domain && cached.requestedShop === shop && cached.status === 'confirmed' &&
|
|
392
|
+
cached.available === true && cached.premium === false && Object.hasOwn(adapters, cached.shop) &&
|
|
393
|
+
cached.buyUrl === shopSearchUrl(cached.shop, domain) && money(cached.price) > 0 &&
|
|
394
|
+
age >= 0 && age < cacheLifetime) {
|
|
395
|
+
return { ...cached, ...fallbackNote(shop, cached.shop, cached.status), cached: true,
|
|
396
|
+
ms: Math.round(performance.now() - start) };
|
|
397
|
+
}
|
|
398
|
+
|
|
399
|
+
const deadline = Math.min(options.deadline ?? Infinity, start + budget);
|
|
400
|
+
const tld = domain.split('.').at(-1);
|
|
401
|
+
const order = shopOrder(shop, tld, options.unsupported).slice(0, options.oneShop ? 1 : 2);
|
|
402
|
+
const run = usePage => usePage(domain, check => confirmAtShops(domain, check, deadline, order));
|
|
403
|
+
const settled = options.usePage ? await run(options.usePage) : await withShopPages(deadline, run, options);
|
|
404
|
+
const result = formatResult(start, domain, shop, settled.shop ?? shop, settled.result ?? settled, now);
|
|
405
|
+
if (result.status === 'confirmed') await writeCache(directory, filename, result).catch(() => {});
|
|
406
|
+
if (result.status === 'premium') await writeCache(directory, quoteFile(domain), result).catch(() => {});
|
|
407
|
+
return result;
|
|
408
|
+
}
|
|
409
|
+
|
|
410
|
+
// Light confirm uses documented read operations. Without a key, prices stay labelled as list prices.
|
|
411
|
+
// Spaceship: https://docs.spaceship.dev/ (domains:read) · Dynadot: https://www.dynadot.com/domain/api-commands (search).
|
|
412
|
+
const spaceshipApi = 'https://spaceship.dev/api/v1/domains/';
|
|
413
|
+
const dynadotApi = 'https://api.dynadot.com/api3.json';
|
|
414
|
+
const signalLifetime = 24 * 3_600_000;
|
|
415
|
+
const apiTimeout = 2500;
|
|
416
|
+
|
|
417
|
+
export function apiShops(env = process.env) {
|
|
418
|
+
return [
|
|
419
|
+
...(env.DOMAIN_HOUND_SPACESHIP_KEY?.trim() && env.DOMAIN_HOUND_SPACESHIP_SECRET?.trim() ? ['spaceship'] : []),
|
|
420
|
+
...(env.DOMAIN_HOUND_DYNADOT_KEY?.trim() ? ['dynadot'] : []),
|
|
421
|
+
];
|
|
422
|
+
}
|
|
423
|
+
|
|
424
|
+
const cents = value => Math.round(value * 100) / 100;
|
|
425
|
+
|
|
426
|
+
// The yearly USD price of the shortest documented period.
|
|
427
|
+
function yearly(entries) {
|
|
428
|
+
const rows = (Array.isArray(entries) ? entries : []).map(row => {
|
|
429
|
+
const years = row?.period?.unit === 'y' && Number.isSafeInteger(row.period.value) && row.period.value > 0
|
|
430
|
+
? row.period.value : null;
|
|
431
|
+
const final = row?.priceInDefaultCurrency?.finalPrice;
|
|
432
|
+
const amount = final?.currency === 'USD' && typeof final.amount === 'string' ? money(final.amount) : null;
|
|
433
|
+
return years && amount > 0 ? { years, amount } : null;
|
|
434
|
+
}).filter(Boolean).sort((a, b) => a.years - b.years);
|
|
435
|
+
return rows[0] ? cents(rows[0].amount / rows[0].years) : null;
|
|
436
|
+
}
|
|
437
|
+
|
|
438
|
+
function apiQuote(shop, domain, fields, now) {
|
|
439
|
+
return { shop, shopName: shops[shop].name, domain, buyUrl: shopSearchUrl(shop, domain), checkedAt: now.toISOString(),
|
|
440
|
+
source: 'api', price: null, renewal: null, ...fields };
|
|
441
|
+
}
|
|
442
|
+
|
|
443
|
+
// Availability: result and premiumPricing. Pricing: priceClass and the register and renew price lists.
|
|
444
|
+
// premiumPricing marks a premium name even when it carries no price.
|
|
445
|
+
export function parseSpaceshipApi(availability, pricing, domains, now = new Date()) {
|
|
446
|
+
const quotes = new Map();
|
|
447
|
+
const find = (body, domain) => (Array.isArray(body?.domains) ? body.domains : [])
|
|
448
|
+
.find(row => typeof row?.domain === 'string' && row.domain.toLowerCase() === domain);
|
|
449
|
+
for (const domain of domains) {
|
|
450
|
+
const open = find(availability, domain);
|
|
451
|
+
if (typeof open?.result !== 'string') continue;
|
|
452
|
+
if (open.result !== 'available') {
|
|
453
|
+
const status = ['reserved', 'taken'].includes(open.result) ? open.result : 'could-not-confirm';
|
|
454
|
+
quotes.set(domain, apiQuote('spaceship', domain, { status, available: status === 'could-not-confirm' ? null : false,
|
|
455
|
+
reason: 'Not offered for registration at Spaceship' }, now));
|
|
456
|
+
continue;
|
|
457
|
+
}
|
|
458
|
+
const priced = find(pricing, domain);
|
|
459
|
+
const marked = Array.isArray(open.premiumPricing) && open.premiumPricing.length > 0;
|
|
460
|
+
const premiumClass = priced?.priceClass === 'premium';
|
|
461
|
+
if (marked || premiumClass) {
|
|
462
|
+
const listed = marked ? money(open.premiumPricing.find(row => row?.operation === 'register' && row.currency === 'USD')?.price) : null;
|
|
463
|
+
// Availability does not specify a term. Price multi-year endings from the pricing endpoint only.
|
|
464
|
+
const price = (premiumClass ? yearly(priced.prices?.register) : null)
|
|
465
|
+
?? (!domain.endsWith('.ai') && listed > 0 ? listed : null);
|
|
466
|
+
quotes.set(domain, apiQuote('spaceship', domain, { status: 'premium', available: true, premium: true, price,
|
|
467
|
+
renewal: price != null && premiumClass ? yearly(priced.prices?.renew) : null }, now));
|
|
468
|
+
continue;
|
|
469
|
+
}
|
|
470
|
+
const price = priced?.priceClass === 'standard' ? yearly(priced.prices?.register) : null;
|
|
471
|
+
const renewal = priced?.priceClass === 'standard' ? yearly(priced.prices?.renew) : null;
|
|
472
|
+
quotes.set(domain, price > 0 && renewal > 0
|
|
473
|
+
? apiQuote('spaceship', domain, { status: 'confirmed', available: true, premium: false, standard: true, price, renewal }, now)
|
|
474
|
+
: apiQuote('spaceship', domain, { status: 'could-not-confirm', available: null, premium: false,
|
|
475
|
+
reason: 'Spaceship gave no explicit standard price' }, now));
|
|
476
|
+
}
|
|
477
|
+
return quotes;
|
|
478
|
+
}
|
|
479
|
+
|
|
480
|
+
// Dynadot search with show_price=1: "Price": "77.00 in USD", optionally "... and domain is not premium".
|
|
481
|
+
// Without a marker, a price that matches Dynadot's own list price is standard; any other price may be premium.
|
|
482
|
+
export function parseDynadotSearch(body, domain, list = null, now = new Date()) {
|
|
483
|
+
const response = body?.SearchResponse;
|
|
484
|
+
if (String(response?.ResponseCode) !== '0' || !Array.isArray(response.SearchResults)) return null;
|
|
485
|
+
const row = response.SearchResults.find(item => String(item?.DomainName ?? '').toLowerCase() === domain);
|
|
486
|
+
if (!row || row.Error) return null;
|
|
487
|
+
const available = String(row.Available ?? '').toLowerCase();
|
|
488
|
+
if (available === 'no') {
|
|
489
|
+
return apiQuote('dynadot', domain, { status: 'could-not-confirm', available: null,
|
|
490
|
+
reason: 'Not offered for registration at Dynadot' }, now);
|
|
491
|
+
}
|
|
492
|
+
if (available !== 'yes') return null;
|
|
493
|
+
const text = String(row.Price ?? '');
|
|
494
|
+
const price = money(text.match(/^\s*(\d[\d,]*(?:\.\d{1,2})?) in USD\b/i)?.[1]?.replace(/,/g, ''));
|
|
495
|
+
const twoYears = domain.endsWith('.ai');
|
|
496
|
+
const marker = /\bis not premium\b/i.test(text) ? false : /\bpremium\b/i.test(text) ? true : null;
|
|
497
|
+
if (marker) return apiQuote('dynadot', domain, { status: 'premium', available: true, premium: true,
|
|
498
|
+
price: !twoYears && price > 0 ? price : null }, now);
|
|
499
|
+
if (!(price > 0)) return null;
|
|
500
|
+
// The legacy response gives one amount with no term or renewal. A list match can disambiguate .ai.
|
|
501
|
+
const yearsMatch = list && (twoYears ? [1, 2] : [1]).find(years => Math.abs(price - cents(list.firstYear * years)) < 0.011);
|
|
502
|
+
if (yearsMatch || marker === false && !twoYears) {
|
|
503
|
+
const yearlyPrice = yearsMatch ? list.firstYear : price;
|
|
504
|
+
return apiQuote('dynadot', domain, { status: 'confirmed', available: true, premium: false, standard: marker === false || undefined,
|
|
505
|
+
price: yearlyPrice }, now);
|
|
506
|
+
}
|
|
507
|
+
return apiQuote('dynadot', domain, { status: 'premium', available: true, premium: 'possible',
|
|
508
|
+
price: twoYears ? null : price }, now);
|
|
509
|
+
}
|
|
510
|
+
|
|
511
|
+
async function postJson(fetcher, url, body, headers, timeout) {
|
|
512
|
+
const response = await fetcher(url, { method: 'POST', redirect: 'error', signal: AbortSignal.timeout(timeout),
|
|
513
|
+
headers: { 'Content-Type': 'application/json', Accept: 'application/json', ...headers }, body: JSON.stringify(body) });
|
|
514
|
+
if (!response.ok) {
|
|
515
|
+
await response.body?.cancel().catch(() => {});
|
|
516
|
+
throw new Error('HTTP ' + response.status);
|
|
517
|
+
}
|
|
518
|
+
return response.json();
|
|
519
|
+
}
|
|
520
|
+
|
|
521
|
+
async function spaceshipQuotes(domains, { env, fetcher, timeout, now }) {
|
|
522
|
+
const headers = { 'X-API-Key': env.DOMAIN_HOUND_SPACESHIP_KEY.trim(), 'X-API-Secret': env.DOMAIN_HOUND_SPACESHIP_SECRET.trim() };
|
|
523
|
+
const [availability, pricing] = await Promise.all([
|
|
524
|
+
postJson(fetcher, spaceshipApi + 'available', { domains }, headers, timeout),
|
|
525
|
+
postJson(fetcher, spaceshipApi + 'pricing/query', { domains }, headers, timeout).catch(() => null),
|
|
526
|
+
]);
|
|
527
|
+
return parseSpaceshipApi(availability, pricing, domains, now);
|
|
528
|
+
}
|
|
529
|
+
|
|
530
|
+
async function dynadotQuotes(domains, { env, fetcher, timeout, now, listFor, deadline }) {
|
|
531
|
+
const quotes = new Map();
|
|
532
|
+
// A regular Dynadot account checks one domain per command and one request at a time.
|
|
533
|
+
for (const domain of domains) {
|
|
534
|
+
const wait = Math.min(timeout, Math.floor(deadline - performance.now()));
|
|
535
|
+
if (wait < 300) break;
|
|
536
|
+
const url = dynadotApi + '?' + new URLSearchParams({ key: env.DOMAIN_HOUND_DYNADOT_KEY.trim(), command: 'search',
|
|
537
|
+
domain0: domain, show_price: '1', currency: 'USD' });
|
|
538
|
+
try {
|
|
539
|
+
const response = await fetcher(url, { redirect: 'error', signal: AbortSignal.timeout(wait), headers: { Accept: 'application/json' } });
|
|
540
|
+
if (!response.ok) { await response.body?.cancel().catch(() => {}); continue; }
|
|
541
|
+
const quote = parseDynadotSearch(await response.json(), domain, listFor(domain, 'dynadot'), now);
|
|
542
|
+
if (quote) quotes.set(domain, quote);
|
|
543
|
+
} catch { /* One failed check leaves that domain at its list price. */ }
|
|
544
|
+
}
|
|
545
|
+
return quotes;
|
|
546
|
+
}
|
|
547
|
+
|
|
548
|
+
const quoteFile = domain => 'quote-' + domain + '.json';
|
|
549
|
+
|
|
550
|
+
// Premium and reserved answers are kept for a day; a standard quote for 15 minutes.
|
|
551
|
+
function usableQuote(saved, domain, now) {
|
|
552
|
+
const age = now - Date.parse(saved?.checkedAt);
|
|
553
|
+
if (saved?.domain !== domain || !(age >= 0)) return false;
|
|
554
|
+
if (['premium', 'reserved'].includes(saved.status)) return age < signalLifetime;
|
|
555
|
+
return saved.status === 'confirmed' && money(saved.price) > 0 && age < cacheLifetime;
|
|
556
|
+
}
|
|
557
|
+
|
|
558
|
+
export async function cachedSignals(domains, { directory, now = new Date() } = {}) {
|
|
559
|
+
const folder = directory === undefined ? cacheDir : directory;
|
|
560
|
+
const found = new Map();
|
|
561
|
+
if (!folder) return found;
|
|
562
|
+
await Promise.all(domains.map(async domain => {
|
|
563
|
+
const saved = await readCache(folder, quoteFile(domain));
|
|
564
|
+
if (usableQuote(saved, domain, now) && ['premium', 'reserved'].includes(saved.status)) found.set(domain, saved);
|
|
565
|
+
}));
|
|
566
|
+
return found;
|
|
567
|
+
}
|
|
568
|
+
|
|
569
|
+
// Combine the shops: any premium or reserved answer wins; otherwise the cheapest explicit standard quote.
|
|
570
|
+
function combine(answers) {
|
|
571
|
+
const known = answers.filter(Boolean);
|
|
572
|
+
const premium = known.filter(quote => quote.status === 'premium');
|
|
573
|
+
if (premium.length) {
|
|
574
|
+
const explicit = premium.filter(quote => quote.premium === true);
|
|
575
|
+
const pool = explicit.length ? explicit : premium;
|
|
576
|
+
return pool.find(quote => quote.price != null) ?? pool[0];
|
|
577
|
+
}
|
|
578
|
+
const confirmed = known.filter(quote => quote.status === 'confirmed').sort((a, b) => a.price - b.price);
|
|
579
|
+
return confirmed[0] ?? known.find(quote => ['taken', 'reserved'].includes(quote.status)) ?? known[0] ?? null;
|
|
580
|
+
}
|
|
581
|
+
|
|
582
|
+
export async function lightConfirm(domains, {
|
|
583
|
+
env = process.env, fetcher = globalThis.fetch, directory, now = new Date(), deadline = performance.now() + 3000,
|
|
584
|
+
listFor = () => null,
|
|
585
|
+
} = {}) {
|
|
586
|
+
const folder = directory === undefined ? cacheDir : directory;
|
|
587
|
+
const results = new Map();
|
|
588
|
+
const wanted = [...new Set(domains)].slice(0, 20);
|
|
589
|
+
const pending = [];
|
|
590
|
+
for (const domain of wanted) {
|
|
591
|
+
const saved = folder ? await readCache(folder, quoteFile(domain)) : null;
|
|
592
|
+
if (usableQuote(saved, domain, now)) results.set(domain, { ...saved, cached: true });
|
|
593
|
+
else pending.push(domain);
|
|
594
|
+
}
|
|
595
|
+
const keyed = apiShops(env);
|
|
596
|
+
const timeout = Math.min(apiTimeout, Math.floor(deadline - performance.now()));
|
|
597
|
+
if (!pending.length || !keyed.length || timeout < 300) return results;
|
|
598
|
+
const context = { env, fetcher, timeout, now, listFor, deadline };
|
|
599
|
+
const [spaceship, dynadot] = await Promise.all([
|
|
600
|
+
keyed.includes('spaceship') ? spaceshipQuotes(pending, context).catch(() => new Map()) : new Map(),
|
|
601
|
+
keyed.includes('dynadot') ? dynadotQuotes(pending, context) : new Map(),
|
|
602
|
+
]);
|
|
603
|
+
for (const domain of pending) {
|
|
604
|
+
const quote = combine([spaceship.get(domain), dynadot.get(domain)]);
|
|
605
|
+
if (!quote) continue;
|
|
606
|
+
results.set(domain, quote);
|
|
607
|
+
if (folder && ['confirmed', 'premium', 'reserved'].includes(quote.status)) {
|
|
608
|
+
await writeCache(folder, quoteFile(domain), quote).catch(() => {});
|
|
609
|
+
}
|
|
610
|
+
}
|
|
611
|
+
return results;
|
|
612
|
+
}
|