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
@@ -0,0 +1,372 @@
1
+ import { anySignal, cacheDir, readCache, writeCache } from './cache.mjs';
2
+ import { compactText, day, exactPhrases, letters, markOrder, matchTier, relevantClasses, request } from './triage-sources.mjs';
3
+
4
+ // Optional EU (EUIPO Trademark Search API 1.1.0) and Norwegian (Patentstyret open data MCP) trademark searches.
5
+ // Both need a free key the user sets; without one the office is "off" and the results link to its own search.
6
+ // Keys are sent only to the fixed official hosts below. A failed office never reads as clear.
7
+ export const officeNames = { EU: 'EUIPO', NO: 'Patentstyret' };
8
+ const euipo = {
9
+ production: { api: 'https://api.euipo.europa.eu/trademark-search', token: 'https://euipo.europa.eu/cas-server-webapp/oidc/accessToken' },
10
+ sandbox: { api: 'https://api-sandbox.euipo.europa.eu/trademark-search', token: 'https://auth-sandbox.euipo.europa.eu/oidc/accessToken' },
11
+ };
12
+ const patentstyretMcp = 'https://api.patentstyret.no/external/open-data/mcp';
13
+ const euRecord = number => 'https://euipo.europa.eu/eSearch/#details/trademarks/' + number;
14
+ const noRecord = /^https:\/\/services\.patentstyret\.no\/search-details\/trademark\/[\w-]{4,40}$/;
15
+ // Live EU statuses: everything except withdrawn, refused, cancelled, surrendered, expired and removed marks.
16
+ const euLive = ['RECEIVED', 'UNDER_EXAMINATION', 'APPLICATION_PUBLISHED', 'REGISTRATION_PENDING', 'REGISTERED',
17
+ 'OPPOSITION_PENDING', 'APPEALED', 'CANCELLATION_PENDING', 'APPEALABLE', 'START_OF_OPPOSITION_PERIOD',
18
+ 'ACCEPTANCE_PENDING', 'ACCEPTED'];
19
+ const euDead = new Set(['WITHDRAWN', 'REFUSED', 'CANCELLED', 'SURRENDERED', 'EXPIRED', 'REMOVED_FROM_REGISTER']);
20
+ const noDead = /withdr|refus|reject|expir|ended|ceas|cancel|laps|invalid|revok|surrend|abandon|remov|dead|terminat|henlag|avsl|opph|slett|trukket|utg/i;
21
+ const noLive = /regist|pend|filed|appli|publish|oppos|appeal|exam|accept|grant|valid|active|søkt|under|innvilg/i;
22
+ const staleLimit = 30 * day;
23
+ const holds = new Map();
24
+ const tokens = new Map();
25
+ const sessions = new Map();
26
+ let rpcId = 0;
27
+
28
+ class Failure extends Error {
29
+ constructor(why, retry = false) {
30
+ super(why);
31
+ this.retry = retry;
32
+ }
33
+ }
34
+
35
+ const printable = (value, min) => {
36
+ const text = typeof value === 'string' ? value.trim() : '';
37
+ return text.length >= min && text.length <= 256 && /^[\x21-\x7e]+$/.test(text) ? text : null;
38
+ };
39
+
40
+ // Which offices have keys. EUIPO needs both the client ID and secret of an app subscribed to Trademark Search.
41
+ export function trademarkKeys(env = process.env) {
42
+ const id = printable(env?.DOMAIN_HOUND_EUIPO_CLIENT_ID, 8);
43
+ const secret = printable(env?.DOMAIN_HOUND_EUIPO_CLIENT_SECRET, 8);
44
+ const key = printable(env?.DOMAIN_HOUND_PATENTSTYRET_KEY, 16);
45
+ return {
46
+ EU: id && secret ? { id, secret, ...euipo[env.DOMAIN_HOUND_EUIPO_SANDBOX === '1' ? 'sandbox' : 'production'] } : null,
47
+ NO: key ? { key } : null,
48
+ };
49
+ }
50
+
51
+ const budget = options => Math.min(2600, (options.timeLeft?.() ?? Infinity) - 250);
52
+
53
+ function httpFailure(office, response) {
54
+ if (response.status === 429) {
55
+ const wait = Number(response.headers?.get('retry-after'));
56
+ holds.set(office, Date.now() + (wait > 0 && wait < 3600 ? wait * 1000 : 60_000));
57
+ return new Failure('rate limited');
58
+ }
59
+ if (response.status === 401 || response.status === 403) {
60
+ // A refused key stays refused for the rest of this run; the other names do not ask again.
61
+ holds.set(office, Date.now() + 10 * 60_000);
62
+ return new Failure('key refused');
63
+ }
64
+ return new Failure(response.status >= 500 ? 'unavailable' : 'request refused', response.status >= 500);
65
+ }
66
+
67
+ // One mark row in the same shape as the USPTO rows. Dead marks and loose spellings drop out.
68
+ function markRow(key, { office, text, owner, classes, status, live, url }) {
69
+ const mark = letters(text);
70
+ if (!mark || live === false) return [];
71
+ const tier = matchTier(key, mark);
72
+ if (!tier || (tier === 'Fuzzy' && key.length < 5)) return [];
73
+ const codes = [...new Set((Array.isArray(classes) ? classes : []).map(Number)
74
+ .filter(value => Number.isInteger(value) && value >= 1 && value <= 45))].sort((a, b) => a - b)
75
+ .map(value => String(value).padStart(3, '0'));
76
+ return [{ office, name: compactText(text, 65), owner: compactText(owner, 70), classes: codes, tier,
77
+ status: compactText(status, 30).toLowerCase() || 'status unavailable', live: live === true ? true : null,
78
+ registered: /^regist/i.test(String(status)), url }];
79
+ }
80
+
81
+ // Relevance follows the same class rules as USPTO. A mark whose live status is unclear never forces Avoid.
82
+ function judged(rows, category) {
83
+ const relevant = relevantClasses(category);
84
+ return rows.map(row => {
85
+ const classes = row.classes.filter(value => relevant.includes(value));
86
+ return { ...row, relevant: row.live === true && classes.length > 0, relevantClasses: classes };
87
+ });
88
+ }
89
+
90
+ function pluralForms(key) {
91
+ return [key + 's', key + 'es', key.replace(/y$/, 'ies'), key.replace(/(?:es|s)$/, ''), key.replace(/ies$/, 'y')]
92
+ .filter(value => value !== key && matchTier(key, value) === 'Near-identical');
93
+ }
94
+
95
+ // Wildcards find candidates for a vowel swap or doubled letter. The shared matcher scores the returned text.
96
+ function nearPatterns(key) {
97
+ return [...key].flatMap((letter, index) => {
98
+ const start = key.slice(0, index);
99
+ const end = key.slice(index + 1);
100
+ const forms = [start + letter + '*' + end];
101
+ if ('aeiouy'.includes(letter)) forms.push(start + '*' + end);
102
+ if (letter === key[index - 1]) forms.push(start + end);
103
+ return forms;
104
+ });
105
+ }
106
+
107
+ // RSQL for exact, spaced, split and near spellings in lower, upper and title case.
108
+ // Returns the query and whether every spelling fit under the API's 5000-character limit.
109
+ export function euipoQuery(key, input) {
110
+ const phrases = [...exactPhrases(key, input), ...pluralForms(key), ...nearPatterns(key)];
111
+ const typed = String(input ?? '').trim();
112
+ const forms = [...(/^[\p{L}\p{N} &'.-]{1,80}$/u.test(typed) ? [typed] : []),
113
+ ...phrases.flatMap(phrase => [phrase, phrase.toUpperCase(), phrase.replace(/(^|\s)([a-z])/g, (_, space, letter) => space + letter.toUpperCase())])];
114
+ const status = ' and status=in=(' + euLive.join(',') + ')';
115
+ const clauses = [];
116
+ let complete = true;
117
+ for (const form of new Set(forms)) {
118
+ const value = form.includes('*') ? form : '"' + form.replace(/["\\]/g, '\\$&') + '"';
119
+ const clause = 'wordMarkSpecification.verbalElement==' + value;
120
+ if ([...clauses, clause].join(' or ').length + status.length + 2 > 4800) {
121
+ complete = false;
122
+ break;
123
+ }
124
+ clauses.push(clause);
125
+ }
126
+ return { query: '(' + clauses.join(' or ') + ')' + status, complete };
127
+ }
128
+
129
+ async function euipoToken(config, options) {
130
+ const cached = tokens.get(config.token + config.id);
131
+ if (cached && cached.until > Date.now()) return cached.promise;
132
+ const entry = { until: Infinity };
133
+ entry.promise = (async () => {
134
+ // The EUIPO security guide sends the client credentials in the form body.
135
+ const response = await request(config.token, options, { method: 'POST', timeout: budget(options),
136
+ headers: { 'Content-Type': 'application/x-www-form-urlencoded', Accept: 'application/json' },
137
+ body: new URLSearchParams({ client_id: config.id, client_secret: config.secret, grant_type: 'client_credentials', scope: 'uid' }) });
138
+ if (!response.ok) {
139
+ await response.body?.cancel();
140
+ // An unknown client or wrong secret answers 400 invalid_client or 401.
141
+ throw httpFailure('EU', { status: response.status === 400 ? 401 : response.status, headers: response.headers });
142
+ }
143
+ const data = await response.json();
144
+ if (typeof data?.access_token !== 'string' || !data.access_token) throw new Failure('no token', true);
145
+ const lifetime = Number(data.expires_in);
146
+ entry.until = Date.now() + Math.max(30, (lifetime > 0 ? lifetime : 600) - 60) * 1000;
147
+ return data.access_token;
148
+ })();
149
+ tokens.set(config.token + config.id, entry);
150
+ entry.promise.catch(() => tokens.delete(config.token + config.id));
151
+ return entry.promise;
152
+ }
153
+
154
+ async function euipoMarks(key, input, config, options) {
155
+ const token = await euipoToken(config, options);
156
+ const { query, complete } = euipoQuery(key, input);
157
+ const response = await request(config.api + '/trademarks?' + new URLSearchParams({ query, page: '0', size: '100' }), options, {
158
+ timeout: budget(options), headers: { Authorization: 'Bearer ' + token, 'X-IBM-Client-Id': config.id, Accept: 'application/json' },
159
+ });
160
+ if (!response.ok) {
161
+ await response.body?.cancel();
162
+ if (response.status === 401) tokens.delete(config.token + config.id);
163
+ throw httpFailure('EU', response);
164
+ }
165
+ const data = await response.json();
166
+ if (!Array.isArray(data?.trademarks)) throw new Failure('unreadable answer', true);
167
+ const { totalElements } = data;
168
+ let partial = !complete || !Number.isSafeInteger(totalElements) || totalElements < 0
169
+ || totalElements !== data.trademarks.length;
170
+ const rows = data.trademarks.flatMap(item => {
171
+ const number = /^(?:\d{9}|W\d{8}[A-Z]?)$/.test(item?.applicationNumber) ? item.applicationNumber : null;
172
+ const status = typeof item?.status === 'string' ? item.status : '';
173
+ if (euDead.has(status)) return [];
174
+ const text = item?.wordMarkSpecification?.verbalElement;
175
+ const live = euLive.includes(status) ? true : null;
176
+ if (live === null || !letters(text) || !number || !Array.isArray(item?.niceClasses)) partial = true;
177
+ return markRow(key, { office: 'EU', text,
178
+ owner: (Array.isArray(item?.applicants) ? item.applicants : []).map(person => person?.name).find(name => typeof name === 'string') ?? '',
179
+ classes: item?.niceClasses, status: status.replace(/_/g, ' '), live,
180
+ url: number ? euRecord(number) : null });
181
+ });
182
+ return { rows, partial };
183
+ }
184
+
185
+ // Patentstyret: the documented MCP search (JSON-RPC over HTTP). The search tool's argument names come from
186
+ // its own schema, so a renamed argument is picked up without a release.
187
+ async function mcpPost(key, session, body, options) {
188
+ const response = await request(patentstyretMcp, options, { method: 'POST', timeout: budget(options), headers: {
189
+ 'Content-Type': 'application/json', Accept: 'application/json, text/event-stream', 'Ocp-Apim-Subscription-Key': key,
190
+ ...(session?.id && { 'Mcp-Session-Id': session.id }), ...(session?.version && { 'MCP-Protocol-Version': session.version }),
191
+ }, body: JSON.stringify(body) });
192
+ if (!response.ok) {
193
+ await response.body?.cancel();
194
+ if (response.status === 404 && session) sessions.delete(key);
195
+ throw response.status === 404 && session ? new Failure('session ended', true) : httpFailure('NO', response);
196
+ }
197
+ return response;
198
+ }
199
+
200
+ function jsonOrNull(text) {
201
+ try { return JSON.parse(text); } catch { return null; }
202
+ }
203
+
204
+ async function rpc(key, session, method, params, options) {
205
+ const id = ++rpcId;
206
+ const response = await mcpPost(key, session, { jsonrpc: '2.0', id, method, params }, options);
207
+ const text = await response.text();
208
+ const messages = /text\/event-stream/i.test(response.headers.get('content-type') ?? '')
209
+ ? text.split(/\r?\n\r?\n/).map(event => jsonOrNull(event.split(/\r?\n/).filter(line => line.startsWith('data:'))
210
+ .map(line => line.slice(5).trimStart()).join('\n')))
211
+ : [jsonOrNull(text)];
212
+ const message = messages.flat().find(item => item?.id === id);
213
+ if (!message) throw new Failure('unreadable answer', true);
214
+ if (message.error) throw new Failure('search refused');
215
+ return { result: message.result, response };
216
+ }
217
+
218
+ // The search tool and its text and size arguments, from tools/list.
219
+ export function searchTool(tools) {
220
+ const tool = (Array.isArray(tools) ? tools : []).find(item => item?.name === 'search_trademarks');
221
+ const properties = tool?.inputSchema?.properties;
222
+ if (!properties || typeof properties !== 'object') return null;
223
+ const entries = Object.entries(properties);
224
+ const strings = entries.filter(([, schema]) => schema?.type === 'string' || schema?.type?.includes?.('string'));
225
+ const text = strings.find(([name]) => /^(?:query|q|search_?text|search_?term|search|text|term|keywords?|word_?mark|mark_?text|mark|trademark|name)$/i.test(name))?.[0]
226
+ ?? strings.find(([name]) => tool.inputSchema.required?.includes(name))?.[0];
227
+ const [size, sizeSchema] = entries.find(([name, schema]) => ['integer', 'number'].includes(schema?.type)
228
+ && /^(?:size|limit|page_?size|max(?:_?results)?|top|take|count|rows)$/i.test(name)) ?? [];
229
+ return text ? { text, ...(size && { size, limit: Math.max(1, Math.min(50, Number(sizeSchema.maximum) || 50)) }) } : null;
230
+ }
231
+
232
+ async function mcpSession(key, options) {
233
+ if (!sessions.has(key)) {
234
+ const opening = (async () => {
235
+ const { result, response } = await rpc(key, null, 'initialize', {
236
+ protocolVersion: '2025-06-18', capabilities: {}, clientInfo: { name: 'domain-hound', version: '0.1' },
237
+ }, options);
238
+ const session = { id: printable(response.headers.get('mcp-session-id'), 1) ?? undefined,
239
+ version: typeof result?.protocolVersion === 'string' ? result.protocolVersion.slice(0, 20) : '2025-06-18' };
240
+ await (await mcpPost(key, session, { jsonrpc: '2.0', method: 'notifications/initialized' }, options)).body?.cancel();
241
+ const tool = searchTool((await rpc(key, session, 'tools/list', {}, options)).result?.tools);
242
+ if (!tool) throw new Failure('search tool not found');
243
+ return { ...session, tool };
244
+ })();
245
+ sessions.set(key, opening);
246
+ opening.catch(() => sessions.delete(key));
247
+ }
248
+ return sessions.get(key);
249
+ }
250
+
251
+ const textOf = value => typeof value === 'string' ? value : typeof value?.$ === 'string' ? value.$ : '';
252
+
253
+ function partyName(party) {
254
+ const name = party?.contact?.contactTypeChoiceSequence?.name?.entityName ?? party?.contact?.name?.entityName;
255
+ return [name?.transliterationName?.[0], name?.phraseType, name?.organizationStandardName, name].map(textOf).find(Boolean) ?? '';
256
+ }
257
+
258
+ // Cases in WIPO ST.96 JSON, as in Patentstyret's published dummy case, wherever the result list nests them.
259
+ export function patentstyretCases(data) {
260
+ const cases = [];
261
+ let visited = 0;
262
+ const walk = (value, depth) => {
263
+ if (!value || typeof value !== 'object' || depth > 8 || ++visited > 5000) return;
264
+ if (value.trademarkApplication && typeof value.trademarkApplication === 'object') cases.push(value.trademarkApplication);
265
+ else if (value.trademarkBag && typeof value.trademarkBag === 'object') cases.push(value);
266
+ else for (const child of Array.isArray(value) ? value : Object.values(value)) walk(child, depth + 1);
267
+ };
268
+ walk(data, 0);
269
+ const total = data && typeof data === 'object' && !Array.isArray(data) ? Object.entries(data)
270
+ .find(([name, value]) => /^(?:total(?:_?(?:count|hits|results|elements))?|number_?of_?hits|hit_?count|count)$/i.test(name)
271
+ && Number.isSafeInteger(value))?.[1] : undefined;
272
+ return { cases, total };
273
+ }
274
+
275
+ function caseRow(key, item) {
276
+ const mark = item?.trademarkBag?.trademark?.[0];
277
+ const words = mark?.markRepresentation?.markReproduction?.wordMarkSpecification;
278
+ const number = textOf(mark?.trademarkTypeChoice1?.applicationNumber?.[0]?.applicationNumberText);
279
+ const status = textOf(mark?.markCurrentStatusCode);
280
+ const classes = (Array.isArray(mark?.goodsServicesBag?.goodsServices) ? mark.goodsServicesBag.goodsServices : [])
281
+ .flatMap(goods => (goods?.classDescriptionBag?.classDescription ?? []).map(entry => entry?.classNumber));
282
+ const url = typeof item?.caseUrl === 'string' && noRecord.test(item.caseUrl) ? item.caseUrl
283
+ : /^\d{6,12}$/.test(number) ? 'https://services.patentstyret.no/search-details/trademark/' + number : null;
284
+ return markRow(key, { office: 'NO', text: textOf(words?.markVerbalElementText) || textOf(words?.markSignificantVerbalElementText),
285
+ owner: partyName(item?.holderBag?.holder?.[0]) || partyName(mark?.applicantBag?.applicant?.[0]),
286
+ classes, status, live: !status ? null : noDead.test(status) ? false : noLive.test(status) ? true : null, url });
287
+ }
288
+
289
+ async function patentstyretSearch(key, session, query, options) {
290
+ const { tool } = session;
291
+ const { result } = await rpc(key, session, 'tools/call', { name: 'search_trademarks',
292
+ arguments: { [tool.text]: query, ...(tool.size && { [tool.size]: tool.limit }) } }, options);
293
+ if (result?.isError) throw new Failure('search refused');
294
+ const content = Array.isArray(result?.content) ? result.content : [];
295
+ const data = result?.structuredContent ?? jsonOrNull(content.filter(part => part?.type === 'text').map(part => part.text).join(''));
296
+ if (data == null || typeof data !== 'object') throw new Failure('unreadable answer');
297
+ const { cases, total } = patentstyretCases(data);
298
+ const empty = Array.isArray(data) ? data.length === 0 : Array.isArray(data.results) && data.results.length === 0;
299
+ if (!cases.length && !empty && !(total > 0)) throw new Failure('unreadable answer');
300
+ return { cases, partial: total !== undefined ? total > cases.length : Boolean(tool.size && cases.length >= tool.limit) };
301
+ }
302
+
303
+ async function patentstyretMarks(key, input, config, options) {
304
+ const session = await mcpSession(config.key, options);
305
+ const spaced = input.replace(/([a-z])([A-Z])/g, '$1 $2').toLowerCase().replace(/[^\p{L}\p{N}]+/gu, ' ').trim();
306
+ const queries = [...new Set([key, spaced].filter(Boolean))];
307
+ const answers = await Promise.all(queries.map(query => patentstyretSearch(config.key, session, query, options)));
308
+ // The glued and spaced searches can return the same case once each.
309
+ const rows = answers.flatMap(answer => answer.cases.flatMap(item => caseRow(key, item)));
310
+ return { rows: [...new Map(rows.map(row => [row.url ?? row.name + row.status, row])).values()],
311
+ partial: answers.some(answer => answer.partial) || rows.some(row => row.live === null || !row.url || !row.classes.length) };
312
+ }
313
+
314
+ const fetchers = { EU: euipoMarks, NO: patentstyretMarks };
315
+
316
+ // One office for one name. States: off (no key), ok (marks, partial when the answer was cut short) or failed.
317
+ // A failed office keeps the marks of an earlier answer, labelled with its date, and is never read as clear.
318
+ // One retry, only for a transient failure, and only while the shared time budget lasts.
319
+ export async function checkOffice(office, name, input, options = {}) {
320
+ const config = trademarkKeys(options.env ?? process.env)[office];
321
+ if (!config) return { office, state: 'off' };
322
+ const { directory = cacheDir, now = new Date() } = options;
323
+ const key = letters(name);
324
+ const source = config.api === euipo.sandbox.api ? 'eu-sandbox' : office.toLowerCase();
325
+ const filename = 'trademark-' + source + '-' + key + '.json';
326
+ const saved = await readCache(directory, filename);
327
+ const age = now.getTime() - saved?.at;
328
+ const savedRows = Array.isArray(saved?.rows) ? saved.rows : null;
329
+ const finish = (state, rows, extra = {}) => ({ office, state,
330
+ marks: judged(rows, options.category).sort(markOrder(key)), ...extra });
331
+ if (savedRows && age >= 0 && age < day) return finish('ok', savedRows, { partial: false, checkedAt: new Date(saved.at).toISOString() });
332
+ const duration = Math.floor(budget(options));
333
+ const deadline = performance.now() + duration;
334
+ const attempt = async () => {
335
+ if ((holds.get(office) ?? 0) > Date.now()) return { failed: 'rate limited or key refused earlier in this run' };
336
+ if (sourceOptions.signal.aborted || budget(sourceOptions) < 700) return { failed: 'out of time' };
337
+ try {
338
+ return await fetchers[office](key, String(input ?? name), config, sourceOptions);
339
+ } catch (error) {
340
+ return error instanceof Failure ? { failed: error.message, retry: error.retry } : { failed: 'no answer', retry: true };
341
+ }
342
+ };
343
+ const controller = new AbortController();
344
+ const sourceOptions = { ...options, timeLeft: () => deadline - performance.now(),
345
+ signal: anySignal([options.signal, controller.signal].filter(Boolean)) };
346
+ const timer = setTimeout(() => controller.abort(), Math.max(1, duration));
347
+ let answer;
348
+ try {
349
+ answer = await attempt();
350
+ if (answer.retry && !sourceOptions.signal.aborted && budget(sourceOptions) >= 2000) answer = await attempt();
351
+ } finally {
352
+ clearTimeout(timer);
353
+ }
354
+ if (!answer.failed) {
355
+ if (!answer.partial) await writeCache(directory, filename, { at: now.getTime(), rows: answer.rows }).catch(() => {});
356
+ return finish('ok', answer.rows, { partial: answer.partial, checkedAt: now.toISOString() });
357
+ }
358
+ // Marks from an earlier answer keep their date, so an outage never hides a known mark.
359
+ const stale = savedRows && age >= 0 && age < staleLimit
360
+ ? savedRows.map(row => ({ ...row, checkedAt: new Date(saved.at).toISOString().slice(0, 10) })) : [];
361
+ return finish('failed', stale, { why: answer.failed, ...(stale.length && { checkedAt: new Date(saved.at).toISOString() }) });
362
+ }
363
+
364
+ // Only a complete answer can support "no mark found" for that office.
365
+ export const officeAnswered = result => result?.state === 'ok' && !result.partial;
366
+
367
+ // Clears the in-process token, session and hold memory (tests).
368
+ export function resetOffices() {
369
+ holds.clear();
370
+ tokens.clear();
371
+ sessions.clear();
372
+ }
@@ -1,13 +1,18 @@
1
1
  import { anySignal, cacheDir, readCache, writeCache } from './cache.mjs';
2
+ import { checkSocialHandles, handlePlatforms } from './handles.mjs';
3
+ import { setTimeout as delay } from 'node:timers/promises';
2
4
 
3
5
  const uspto = 'https://tmsearch.uspto.gov';
4
6
  const githubState = 'triage-github-limit.json';
5
7
  export const day = 86_400_000;
6
8
  const userAgent = 'DomainHound/1.0 (public name lookup)';
9
+ // Relevant Nice classes per category, shared by every trademark office. Software covers 9, 35 and 42.
7
10
  const niceClasses = new Map(Object.entries({
8
- travel: ['039', '043'], software: ['009', '042'], finance: ['036'], retail: ['035'],
11
+ travel: ['039', '043'], software: ['009', '035', '042'], finance: ['036'], retail: ['035'],
9
12
  health: ['044'], education: ['041'], food: ['043', '030'], media: ['038', '041'],
10
13
  }));
14
+ const techClasses = ['009', '042'];
15
+ export const relevantClasses = category => niceClasses.get(String(category ?? '').trim().toLowerCase()) ?? niceClasses.get('software');
11
16
  const wikidataHeaders = { 'User-Agent': 'DomainHound/0.1 (https://domainhound.dev)' };
12
17
  const brandTypes = new Set([
13
18
  'Q783794', 'Q4830453', 'Q891723', 'Q167037', // Companies
@@ -22,13 +27,8 @@ export const trademarkSearches = {
22
27
  WIPO: 'https://branddb.wipo.int/',
23
28
  Norway: 'https://search.patentstyret.no/',
24
29
  };
25
- export const handleSearches = {
26
- GitHub: 'https://github.com/{name}',
27
- npm: 'https://www.npmjs.com/package/{name}',
28
- PyPI: 'https://pypi.org/project/{name}/',
29
- X: 'https://x.com/{name}',
30
- YouTube: 'https://www.youtube.com/@{name}',
31
- };
30
+ // Handle pages in display order, with {name} for the handle.
31
+ export const handleSearches = Object.fromEntries(handlePlatforms.map(platform => [platform.id, platform.link('{name}')]));
32
32
 
33
33
  // Latin letters for name matching: accents drop, and letters without a decomposition fold too (ø -> o, æ -> ae).
34
34
  const folds = [[/æ/g, 'ae'], [/ø/g, 'o'], [/œ/g, 'oe'], [/ß/g, 'ss'], [/[đð]/g, 'd'], [/þ/g, 'th'], [/ł/g, 'l'], [/ı/g, 'i']];
@@ -56,7 +56,7 @@ export async function readJson(url, options, init) {
56
56
  return null;
57
57
  }
58
58
 
59
- function exactPhrases(label, input) {
59
+ export function exactPhrases(label, input) {
60
60
  const spaced = input.replace(/([a-z])([A-Z])/g, '$1 $2').toLowerCase()
61
61
  .replace(/[^a-z0-9]+/g, ' ').trim();
62
62
  // A glued name can have an unknown word boundary. Try each two-word spelling in one request.
@@ -93,7 +93,7 @@ export function matchTier(a, b) {
93
93
  }
94
94
 
95
95
  export async function searchMarks(name, input, options = {}) {
96
- const relevant = niceClasses.get(options.category?.trim().toLowerCase()) ?? niceClasses.get('software');
96
+ const relevant = relevantClasses(options.category);
97
97
  const variants = exactPhrases(letters(name), input);
98
98
  const matches = variants.map(query => ({ match_phrase: { wordmark: { query, boost: 3 } } }));
99
99
  const key = variants[0];
@@ -124,17 +124,24 @@ export async function searchMarks(name, input, options = {}) {
124
124
  .map(value => String(value).match(/\b\d{3}\b/)?.[0]).filter(Boolean);
125
125
  const owner = String([].concat(row.ownerName ?? []).at(-1) ?? '')
126
126
  .replace(/\s+\([^;]*;\s*[A-Z ,.-]+\)$/, '').replace(/\s+\([^)]*\)$/, '');
127
- return [{ name: compactText(row.wordmark, 65), owner: compactText(owner, 70),
127
+ const serial = /^\d{8}$/.test(row.id) ? row.id : null;
128
+ return [{ office: 'US', name: compactText(row.wordmark, 65), owner: compactText(owner, 70),
128
129
  classes, relevant: classes.some(value => relevant.includes(value)), relevantClasses: classes.filter(value => relevant.includes(value)),
129
- tier, registered: row.registered === true,
130
- serial: /^\d{8}$/.test(row.id) ? row.id : null }];
131
- }).sort((a, b) => markWeight(b, key) - markWeight(a, key) || Number(b.registered) - Number(a.registered));
130
+ tier, registered: row.registered === true, live: true, status: row.registered === true ? 'registered' : 'applied',
131
+ serial, url: serial ? usptoRecord(serial) : null }];
132
+ }).sort(markOrder(key));
132
133
  }
133
134
 
135
+ export const usptoRecord = serial => 'https://tsdr.uspto.gov/#caseNumber=' + serial
136
+ + '&caseSearchType=US_APPLICATION&caseType=DEFAULT&searchType=statusSearch';
137
+
138
+ // Strongest mark first: closer tier, then a relevant class, then a registered mark.
139
+ export const markOrder = key => (a, b) => markWeight(b, key) - markWeight(a, key) || Number(b.registered) - Number(a.registered);
140
+
134
141
  function markWeight(mark, key) {
135
142
  const tier = ['Fuzzy', 'Near-identical', 'Exact'].indexOf(mark.tier);
136
143
  const firstLetter = Number(letters(mark.name)[0] === key[0]);
137
- const tech = Number(mark.classes.some(value => niceClasses.get('software').includes(value)));
144
+ const tech = Number(mark.classes.some(value => techClasses.includes(value)));
138
145
  return 10 * tier + (mark.relevant ? tier ? 25 : 5 : 0) + firstLetter + 0.2 * tech;
139
146
  }
140
147
 
@@ -162,7 +169,7 @@ export function searchApps(name, input, options = {}) {
162
169
  async function fetchApps(name, input, options) {
163
170
  const data = await readJson('https://itunes.apple.com/search?' + new URLSearchParams({
164
171
  term: input, country: 'us', entity: 'software', limit: '25',
165
- }), options);
172
+ }), options, { timeout: 5000 });
166
173
  if (!Array.isArray(data?.results)) return null;
167
174
  const rows = data.results.flatMap(row => {
168
175
  if (typeof row?.trackName !== 'string' || !/^\d{4,}$/.test(row.trackId) || !appNameMatches(name, row.trackName)) return [];
@@ -188,18 +195,34 @@ export function searchEntities(name, input, options = {}) {
188
195
  return cacheTractionSource('wikidata', name, options, () => fetchEntities(name, input, options));
189
196
  }
190
197
 
198
+ // Wikidata can return a "too busy" error inside an HTTP 200 when searches overlap.
199
+ let wikidataSearches = Promise.resolve();
200
+ function searchWikidata(url, options) {
201
+ const turn = wikidataSearches.then(async () => {
202
+ for (const wait of [0, 250, 500]) {
203
+ if (wait) await delay(wait);
204
+ if (options.signal?.aborted) return null;
205
+ const data = await readJson(url, options, { timeout: 5000, headers: wikidataHeaders });
206
+ if (data?.error?.code !== 'cirrussearch-too-busy-error') return data;
207
+ }
208
+ return null;
209
+ });
210
+ wikidataSearches = turn.catch(() => {});
211
+ return turn;
212
+ }
213
+
191
214
  async function fetchEntities(name, input, options) {
192
215
  const api = 'https://www.wikidata.org/w/api.php?';
193
- const data = await readJson(api + new URLSearchParams({
216
+ const data = await searchWikidata(api + new URLSearchParams({
194
217
  action: 'wbsearchentities', search: input, language: 'en', format: 'json', limit: '15',
195
- }), options, { headers: wikidataHeaders });
218
+ }), options);
196
219
  if (!Array.isArray(data?.search)) return null;
197
220
  const key = letters(name);
198
221
  const exact = data.search.filter(row => /^Q\d+$/.test(row.id) && letters(row.label) === key);
199
222
  if (!exact.length) return [];
200
223
  const getClaims = async (ids, props = 'claims') => (await readJson(api + new URLSearchParams({
201
224
  action: 'wbgetentities', ids: ids.join('|'), props, format: 'json',
202
- }), options, { timeout: 1200, headers: wikidataHeaders }))?.entities;
225
+ }), options, { timeout: options.detailTimeoutMs ?? 3000, headers: wikidataHeaders }))?.entities;
203
226
  // The same request returns sitelinks and the official website (P856) for traction.
204
227
  const details = await getClaims(exact.map(row => row.id), 'claims|sitelinks');
205
228
  if (!details && options.cacheLifetime) return null;
@@ -225,13 +248,6 @@ async function fetchEntities(name, input, options) {
225
248
  });
226
249
  }
227
250
 
228
- const handleUrls = {
229
- npm: name => 'https://registry.npmjs.org/' + name,
230
- PyPI: name => 'https://pypi.org/simple/' + name + '/',
231
- X: name => 'https://x.com/' + name,
232
- YouTube: name => 'https://www.youtube.com/@' + name,
233
- };
234
-
235
251
  async function searchGitHub(name, options) {
236
252
  const { directory = cacheDir, now = new Date() } = options;
237
253
  try {
@@ -269,16 +285,8 @@ async function searchGitHub(name, options) {
269
285
  } catch { return { status: 'unknown' }; }
270
286
  }
271
287
 
272
- async function checkHandle(service, name, options) {
273
- try {
274
- if (options.signal?.aborted) return 'unknown';
275
- const response = await request(handleUrls[service](name), options, { redirect: 'manual', timeout: 2200 });
276
- await response.body?.cancel();
277
- if (response.status === 404) return 'free';
278
- return response.status === 200 ? 'taken' : 'unknown';
279
- } catch { return 'unknown'; }
280
- }
281
-
288
+ // Same-name evidence from GitHub and npm: the account or package (GitHub users API, npm registry) and, for small
289
+ // screens, GitHub repositories with the name. options.social may carry this name's handle rows from a shared run.
282
290
  export async function checkHandles(name, options = {}) {
283
291
  const { directory = cacheDir, now = new Date() } = options;
284
292
  const filename = 'triage-handles-' + name + '.json';
@@ -287,22 +295,11 @@ export async function checkHandles(name, options = {}) {
287
295
  const age = now.getTime() - entry?.at;
288
296
  return age >= 0 && age < day;
289
297
  };
298
+ const social = options.social ? await options.social
299
+ : (await checkSocialHandles([{ name, platforms: ['GitHub', 'npm'], links: false }], options)).get(name);
300
+ const state = platform => social?.find(entry => entry.platform === platform)?.state ?? 'check';
290
301
  const getGitHub = async () => {
291
- let status = saved.githubProfile?.status;
292
- if (!fresh(saved.githubProfile) || !['free', 'taken'].includes(status)) {
293
- const profile = async () => {
294
- try {
295
- const response = await request(handleSearches.GitHub.replace('{name}', name), options, {
296
- redirect: 'manual', timeout: 2200,
297
- });
298
- await response.body?.cancel();
299
- return response.status === 200 ? 'taken' : response.status === 404 ? 'free' : 'unknown';
300
- } catch { return 'unknown'; }
301
- };
302
- status = await profile();
303
- if (status === 'unknown' && options.retryUnavailable && !options.signal?.aborted) status = await profile();
304
- if (status !== 'unknown') saved.githubProfile = { status, at: now.getTime() };
305
- }
302
+ const status = state('GitHub');
306
303
  if (fresh(saved.githubSearch) && saved.githubSearch.result?.count !== undefined) {
307
304
  return { ...saved.githubSearch.result, status };
308
305
  }
@@ -311,18 +308,9 @@ export async function checkHandles(name, options = {}) {
311
308
  githubTail = turn.catch(() => {});
312
309
  const result = await turn;
313
310
  if (result.count !== undefined) saved.githubSearch = { result, at: now.getTime() };
314
- return { ...result, status: status === 'unknown' && result.status === 'taken' ? 'taken' : status };
311
+ return { ...result, status: status === 'check' && result.status === 'taken' ? 'taken' : status };
315
312
  };
316
- const [github, found] = await Promise.all([getGitHub(), Promise.all(Object.keys(handleUrls).map(async service => {
317
- const entry = saved[service];
318
- if (fresh(entry) && ['taken', 'free'].includes(entry.status)) return [service, entry.status];
319
- let status = await checkHandle(service, name, options);
320
- if (options.retryUnavailable && status === 'unknown' && !options.signal?.aborted) {
321
- status = await checkHandle(service, name, options);
322
- }
323
- if (status === 'taken' || status === 'free') saved[service] = { status, at: now.getTime() };
324
- return [service, status];
325
- }))]);
326
- await writeCache(directory, filename, saved).catch(() => {});
327
- return { github, handles: { GitHub: github.status, ...Object.fromEntries(found) } };
313
+ const github = await getGitHub();
314
+ await writeCache(directory, filename, { githubSearch: saved.githubSearch }).catch(() => {});
315
+ return { github, handles: { GitHub: github.status, npm: state('npm') }, social };
328
316
  }