@crewhaus/tool-kyc 0.7.0

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.
@@ -0,0 +1,409 @@
1
+ /**
2
+ * Sanctions screening: candidates and evidence, never a verdict.
3
+ *
4
+ * Three decisions shape this file, and all three are deliberate departures
5
+ * from what a screening tool is usually asked for.
6
+ *
7
+ * 1. **No verdict.** A sanctions match is a legal determination with legal
8
+ * consequences, and it is made by a person. This returns the candidates it
9
+ * found, the basis for each one, and the version of every list it read. The
10
+ * shipped precedent is `@crewhaus/tool-money`'s `RefundAbuseCheck`, which
11
+ * returns ratios and counts and says "a person decides" — same reasoning,
12
+ * higher stakes.
13
+ *
14
+ * 2. **The evidence is the product.** The score is the least trustworthy thing
15
+ * here: the lists carry transliterations of names that were never written in
16
+ * the Latin alphabet, and aliases the publisher itself marks as low quality.
17
+ * What survives an audit two years later is not "0.87", it is "screened
18
+ * against OFAC SDN version 20260901, published 2026-09-01, retrieved
19
+ * 2026-09-02". So a list that cannot say what version it is gets REFUSED,
20
+ * and the whole screen fails rather than quietly producing a number.
21
+ *
22
+ * 3. **Nothing leaves the machine.** Screening happens locally against a
23
+ * snapshot the operator holds. A counterparty's name sent to a third-party
24
+ * screening API is a disclosure of who you are about to pay, to somebody who
25
+ * did not need to know — and this package has no endpoint for it.
26
+ */
27
+ import { MAX_HITS_PER_CALL, TOKEN_ALIGNMENT_FLOOR, alignTokens, buildTokenWeights, canonicalizeName, rankNamesCapped, round6, scoreEach, unseenTokenWeight, } from "./names";
28
+ /**
29
+ * The first pass is a FILTER, not a score.
30
+ *
31
+ * It is set loose on purpose: the whole-string comparison and the weighted
32
+ * token comparison disagree, and the token pass routinely raises a pair the
33
+ * string pass scored 0.6 — that is the entire reason the token pass exists.
34
+ * Filtering at the reporting threshold would throw those away before they were
35
+ * scored properly.
36
+ *
37
+ * A loose floor is NOT enough on its own, which cost this file a false clean.
38
+ * Jaro-Winkler scores "kharoubi" against "mohammed kharoubi" at 0.35 — no
39
+ * usable floor is below that — because its prefix bonus rewards names that
40
+ * begin alike, so a subject supplied as a surname scored 0.35 and a subject
41
+ * supplied as the same person's given name scored 0.89. Screening by surname
42
+ * returned no candidate, no near miss and no truncation flag, on a person who
43
+ * was on the list. Containment is exactly what the two-direction token scorer
44
+ * below exists to handle, and it never ran, because the name never reached it.
45
+ * So the shortlist is a UNION of this pass and `shortlistByToken`.
46
+ */
47
+ export const PREFILTER_FLOOR = 0.5;
48
+ /** How many survivors per subject go through to the expensive pass, per pass. */
49
+ export const PREFILTER_WIDTH = 5;
50
+ const DAY_MS = 86_400_000;
51
+ /**
52
+ * Check a snapshot carries the evidence a screening needs to be worth anything.
53
+ *
54
+ * A list with no version is not a cheaper list, it is an unusable one: the
55
+ * result it produces cannot be reproduced, defended or dated. The staleness
56
+ * check is the same argument in the other direction — "no matches" against a
57
+ * list from March is a sentence about March.
58
+ */
59
+ export function checkSnapshot(snapshot, nowMs, maxAgeDays) {
60
+ const label = `${snapshot.source} ${snapshot.version}`.trim();
61
+ let publishedMs;
62
+ let retrievedMs;
63
+ try {
64
+ publishedMs = requireInstant(snapshot.publishedAt, `${label}: publishedAt`);
65
+ retrievedMs = requireInstant(snapshot.retrievedAt, `${label}: retrievedAt`);
66
+ }
67
+ catch (err) {
68
+ return { list: label, reason: err.message };
69
+ }
70
+ if (snapshot.entries.length === 0) {
71
+ return {
72
+ list: label,
73
+ reason: `${label} has no entries — an empty list produces "no candidates" for every subject, which reads exactly like a clean screen`,
74
+ };
75
+ }
76
+ // The two orderings a real snapshot cannot break, checked BEFORE the age.
77
+ //
78
+ // Age is clamped at zero, so a publishedAt in the future — a mistyped year
79
+ // in the file, a wrong clock where the copy was taken — made the staleness
80
+ // gate vacuous and permanent: `ageDays: 0` for ever, on the evidence record,
81
+ // reading as "published today". A control that cannot be evaluated must not
82
+ // count as one that held. These two comparisons catch it without inventing a
83
+ // tolerance, because they are facts about the snapshot rather than about how
84
+ // stale it is allowed to be.
85
+ if (publishedMs > retrievedMs) {
86
+ return {
87
+ list: label,
88
+ reason: `${label} says it was published at ${snapshot.publishedAt} and retrieved at ${snapshot.retrievedAt} — a copy cannot predate the thing it is a copy of, so one of the two dates is wrong and the age computed from them would be meaningless`,
89
+ };
90
+ }
91
+ if (retrievedMs > nowMs) {
92
+ return {
93
+ list: label,
94
+ reason: `${label} says it was retrieved at ${snapshot.retrievedAt}, which is after the screening ran — either the clock is wrong or this is a replay against a list that did not exist yet, and a screen dated before its own evidence proves nothing`,
95
+ };
96
+ }
97
+ const ageDays = Math.max(0, Math.floor((nowMs - publishedMs) / DAY_MS));
98
+ if (maxAgeDays > 0 && ageDays > maxAgeDays) {
99
+ return {
100
+ list: label,
101
+ reason: `${label} was published ${ageDays} days ago, over the ${maxAgeDays}-day limit — these lists change on business days, so screening against this one would date the answer to ${snapshot.publishedAt}. Refresh it, or raise maxAgeDays deliberately.`,
102
+ };
103
+ }
104
+ return { ageDays };
105
+ }
106
+ function requireInstant(value, field) {
107
+ if (!/(?:Z|[+-]\d{2}:?\d{2})$/i.test(value.trim())) {
108
+ throw new Error(`${field} ("${value}") has no UTC offset — an offset-less timestamp means local time, and the date on a screening record is the part that matters later`);
109
+ }
110
+ const parsed = Date.parse(value.trim());
111
+ if (Number.isNaN(parsed))
112
+ throw new Error(`${field} ("${value}") is not a valid ISO-8601 instant`);
113
+ return parsed;
114
+ }
115
+ /**
116
+ * Legal suffixes come off organisations, never people.
117
+ *
118
+ * "Co" is a legal form in "Hanjin Shipping Co" and a syllable in a person's
119
+ * name; an entry whose kind is unknown is treated as an organisation because
120
+ * the lists that omit the field are entity-heavy vessel and company lists.
121
+ */
122
+ function dropsSuffixes(kind) {
123
+ return kind !== "person";
124
+ }
125
+ async function indexList(snapshot, listIndex) {
126
+ const names = [];
127
+ for (let entryIndex = 0; entryIndex < snapshot.entries.length; entryIndex++) {
128
+ const entry = snapshot.entries[entryIndex];
129
+ const drop = dropsSuffixes(entry.kind);
130
+ names.push({
131
+ listIndex,
132
+ entryIndex,
133
+ matchedName: entry.name,
134
+ matchedOn: "primary",
135
+ quality: "strong",
136
+ canonical: await canonicalizeName(entry.name, { dropLegalSuffixes: drop }),
137
+ });
138
+ for (const alias of entry.aliases ?? []) {
139
+ names.push({
140
+ listIndex,
141
+ entryIndex,
142
+ matchedName: alias.name,
143
+ matchedOn: "alias",
144
+ quality: alias.quality ?? "strong",
145
+ canonical: await canonicalizeName(alias.name, { dropLegalSuffixes: drop }),
146
+ });
147
+ }
148
+ }
149
+ return { names };
150
+ }
151
+ function indexPoolTokens(pool) {
152
+ const postings = new Map();
153
+ for (let at = 0; at < pool.length; at++) {
154
+ for (const token of new Set(pool[at].canonical.tokens)) {
155
+ const list = postings.get(token);
156
+ if (list === undefined)
157
+ postings.set(token, [at]);
158
+ else
159
+ list.push(at);
160
+ }
161
+ }
162
+ // Sorted so the vocabulary a token is ranked against is the same array on
163
+ // every run: `FuzzyMatch` breaks ties on candidate index.
164
+ return { vocabulary: [...postings.keys()].sort(), postings, aligned: new Map() };
165
+ }
166
+ /**
167
+ * Every pool name that shares a token with the subject, rarest token first.
168
+ *
169
+ * The rarest-first order is what makes the cap survivable: when `width` runs
170
+ * out, the slots have already gone to the tokens that discriminate, and it is
171
+ * the "mohammed"s that get dropped rather than the surname. Truncation is
172
+ * reported either way.
173
+ *
174
+ * Tokens are aligned at `TOKEN_ALIGNMENT_FLOOR`, the SAME floor the scorer
175
+ * uses, so the shortlist and the score agree about what counts as the same
176
+ * word. A shortlist built at a looser floor is padding for the expensive pass;
177
+ * one built at a tighter floor hides pairs the scorer would have matched.
178
+ */
179
+ async function shortlistByToken(name, index, weightOf, width) {
180
+ const tokens = [...new Set(name.tokens)].sort((a, b) => weightOf(b) - weightOf(a) || (a < b ? -1 : a > b ? 1 : 0));
181
+ const indices = [];
182
+ const seen = new Set();
183
+ let truncated = false;
184
+ for (const token of tokens) {
185
+ let aligned = index.aligned.get(token);
186
+ if (aligned === undefined) {
187
+ const ranked = await rankNamesCapped(token, index.vocabulary, TOKEN_ALIGNMENT_FLOOR, MAX_HITS_PER_CALL);
188
+ aligned = { matches: ranked.hits.map((hit) => hit.candidate), capped: ranked.capped };
189
+ index.aligned.set(token, aligned);
190
+ }
191
+ if (aligned.capped)
192
+ truncated = true;
193
+ for (const match of aligned.matches) {
194
+ for (const at of index.postings.get(match) ?? []) {
195
+ if (seen.has(at))
196
+ continue;
197
+ if (indices.length >= width)
198
+ return { indices, truncated: true };
199
+ seen.add(at);
200
+ indices.push(at);
201
+ }
202
+ }
203
+ }
204
+ return { indices, truncated };
205
+ }
206
+ function corroborate(subject, entry) {
207
+ const country = subject.country === undefined
208
+ ? "not supplied"
209
+ : (entry.countries ?? []).length === 0
210
+ ? "absent on the list entry"
211
+ : (entry.countries ?? []).some((value) => value.toLowerCase() === subject.country?.toLowerCase())
212
+ ? "matches"
213
+ : `differs (entry: ${(entry.countries ?? []).join(", ")})`;
214
+ const dob = subject.dateOfBirth === undefined
215
+ ? "not supplied"
216
+ : (entry.datesOfBirth ?? []).length === 0
217
+ ? "absent on the list entry"
218
+ : (entry.datesOfBirth ?? []).some((value) => value === subject.dateOfBirth)
219
+ ? "matches"
220
+ : (entry.datesOfBirth ?? []).some((value) => value.slice(0, 4) === subject.dateOfBirth?.slice(0, 4))
221
+ ? "year matches, day differs"
222
+ : `differs (entry: ${(entry.datesOfBirth ?? []).join(", ")})`;
223
+ return { country, dateOfBirth: dob, usedForScoring: false };
224
+ }
225
+ /**
226
+ * Screen every subject against every list.
227
+ *
228
+ * The clock is a parameter. A screening record that says when it ran is only
229
+ * worth something if the "when" is the same on the machine that ran it and the
230
+ * machine that replays it.
231
+ */
232
+ export async function screenSubjects(subjects, snapshots, ages, policy, nowMs) {
233
+ const indexed = [];
234
+ for (let i = 0; i < snapshots.length; i++) {
235
+ const { names } = await indexList(snapshots[i], i);
236
+ indexed.push(...names);
237
+ }
238
+ // Token weights come from the lists in front of us, not from a fixed table.
239
+ const weights = buildTokenWeights(indexed.map((n) => n.canonical.tokens));
240
+ const fallbackWeight = unseenTokenWeight(indexed.length);
241
+ const weightOf = (token) => weights.get(token) ?? fallbackWeight;
242
+ const strongPool = indexed.filter((n) => n.quality === "strong");
243
+ const weakPool = policy.includeWeakAliases ? indexed.filter((n) => n.quality === "weak") : [];
244
+ // Built once, not once per subject: this array is as long as every name on
245
+ // every list, and rebuilding it inside the loop would copy the whole corpus
246
+ // for each counterparty in a batch.
247
+ const strongHaystack = strongPool.map((n) => n.canonical.canonical);
248
+ const weakHaystack = weakPool.map((n) => n.canonical.canonical);
249
+ // Same argument: the postings depend on the lists, not on the subject.
250
+ const strongTokens = indexPoolTokens(strongPool);
251
+ const weakTokens = indexPoolTokens(weakPool);
252
+ const results = [];
253
+ for (const subject of subjects) {
254
+ const subjectNames = [subject.name, ...(subject.aliases ?? [])];
255
+ const canonicals = await Promise.all(subjectNames.map((name) => canonicalizeName(name, { dropLegalSuffixes: subject.kind !== "person" })));
256
+ const primary = canonicals[0];
257
+ const strong = await scorePool(canonicals, strongPool, strongHaystack, strongTokens, snapshots, subject, policy, weightOf);
258
+ const weak = await scorePool(canonicals, weakPool, weakHaystack, weakTokens, snapshots, subject, policy, weightOf);
259
+ const below = [...strong.below, ...weak.below];
260
+ results.push({
261
+ subjectId: subject.id,
262
+ name: subject.name,
263
+ canonical: primary.canonical,
264
+ namesCompared: strongPool.length + weakPool.length,
265
+ shortlisted: strong.shortlisted + weak.shortlisted,
266
+ candidates: strong.candidates,
267
+ weakAliasCandidates: weak.candidates,
268
+ bestScoreBelowThreshold: below.length === 0 ? null : round6(Math.max(...below)),
269
+ ...(strong.candidates.length === 0 && weak.candidates.length === 0
270
+ ? {
271
+ // The sentence an operator acts on, so the shortlist cap belongs
272
+ // IN it. "Nothing reached the threshold" beside a separate
273
+ // `prefilterTruncated: true` field reads as a clean screen to
274
+ // anybody who reads the note and not the field — and the hole is
275
+ // exactly what the note is for.
276
+ note: `no name reached the threshold against the lists in the evidence record. That is not a clearance: it is this threshold, against these list versions, on these spellings.${strong.truncated || weak.truncated
277
+ ? " It is also not the whole list: the shortlist filled its cap, so names past it were never scored — raise limit, or narrow the lists."
278
+ : ""}`,
279
+ }
280
+ : {}),
281
+ ...(strong.truncated || weak.truncated ? { prefilterTruncated: true } : {}),
282
+ });
283
+ }
284
+ return {
285
+ evidence: {
286
+ screenedAt: new Date(nowMs).toISOString(),
287
+ lists: snapshots.map((snapshot, i) => ({
288
+ source: snapshot.source,
289
+ version: snapshot.version,
290
+ publishedAt: snapshot.publishedAt,
291
+ retrievedAt: snapshot.retrievedAt,
292
+ ...(snapshot.sourceUrl === undefined ? {} : { sourceUrl: snapshot.sourceUrl }),
293
+ entries: snapshot.entries.length,
294
+ names: indexed.filter((n) => n.listIndex === i).length,
295
+ ageDays: ages[i] ?? 0,
296
+ })),
297
+ policy: {
298
+ ...policy,
299
+ matcher: "@crewhaus/tool-text FuzzyMatch (Jaro-Winkler), aligned per token and weighted by each token's rarity across these lists, scored in both directions",
300
+ normalisation: "NFKC, zero-width and bidirectional controls removed, lowercased, diacritics folded, punctuation split, legal forms dropped from organisation names",
301
+ },
302
+ },
303
+ subjects: results,
304
+ note: "Candidates and evidence only. Whether any of these IS the subject, and what to do about it, is a determination a person makes — this tool does not make it and does not score it.",
305
+ };
306
+ }
307
+ async function scorePool(subjectNames, pool,
308
+ /** `pool`'s canonical names, in the same order. */
309
+ haystack,
310
+ /** `pool`'s token postings, so containment can be shortlisted too. */
311
+ tokenIndex, snapshots, subject, policy, weightOf) {
312
+ if (pool.length === 0) {
313
+ return { candidates: [], below: [], shortlisted: 0, truncated: false };
314
+ }
315
+ const width = policy.limit * PREFILTER_WIDTH;
316
+ const seen = new Map();
317
+ let truncated = false;
318
+ const remember = (at, score) => {
319
+ const previous = seen.get(at);
320
+ if (previous === undefined || score > previous)
321
+ seen.set(at, score);
322
+ };
323
+ for (const name of subjectNames) {
324
+ // Pass one: whole-string similarity. `capped` comes from the ranker rather
325
+ // than from comparing the hit count with `width`, because the per-call hit
326
+ // cap is 100 and `width` can be 250 — that comparison could never be true,
327
+ // so the shortlist silently lost everything past the hundredth name while
328
+ // the result said nothing had been truncated.
329
+ const whole = await rankNamesCapped(name.canonical, haystack, PREFILTER_FLOOR, width);
330
+ if (whole.capped)
331
+ truncated = true;
332
+ for (const hit of whole.hits)
333
+ remember(hit.index, hit.score);
334
+ // Pass two: shared tokens, which is the half a whole-string score cannot
335
+ // see. Without it a surname never reaches the scorer that was built for it.
336
+ const byToken = await shortlistByToken(name, tokenIndex, weightOf, width);
337
+ if (byToken.truncated)
338
+ truncated = true;
339
+ const added = byToken.indices.filter((at) => !seen.has(at));
340
+ if (added.length > 0) {
341
+ // These arrive with no whole-string score, and reporting 0 for one would
342
+ // put a number in the evidence that nobody computed. It costs one ranked
343
+ // call per hundred names added.
344
+ const scores = await scoreEach(name.canonical, added.map((at) => haystack[at]));
345
+ added.forEach((at, position) => remember(at, scores[position] ?? 0));
346
+ }
347
+ }
348
+ const candidates = [];
349
+ const below = [];
350
+ for (const [index, wholeString] of seen) {
351
+ const indexedName = pool[index];
352
+ const snapshot = snapshots[indexedName.listIndex];
353
+ const entry = snapshot.entries[indexedName.entryIndex];
354
+ // Both directions. A one-token subject aligns perfectly INTO any entry that
355
+ // contains that token — "Ali" would score 1.0 against every Ali on the
356
+ // list — so the entry's unmatched tokens have to cost something too.
357
+ let best = null;
358
+ for (const name of subjectNames) {
359
+ const forward = await alignTokens(name.tokens, indexedName.canonical.tokens, weightOf);
360
+ const reverse = await alignTokens(indexedName.canonical.tokens, name.tokens, weightOf);
361
+ if (best === null || f1(forward.score, reverse.score) > f1(best.forward, best.reverse)) {
362
+ best = { forward: forward.score, reverse: reverse.score, alignments: forward.alignments };
363
+ }
364
+ }
365
+ const forward = best?.forward ?? 0;
366
+ const reverse = best?.reverse ?? 0;
367
+ const score = f1(forward, reverse);
368
+ if (score < policy.threshold) {
369
+ below.push(score);
370
+ continue;
371
+ }
372
+ candidates.push({
373
+ list: snapshot.source,
374
+ listVersion: snapshot.version,
375
+ entryId: entry.id,
376
+ entryName: entry.name,
377
+ entryKind: entry.kind ?? "unknown",
378
+ matchedName: indexedName.matchedName,
379
+ matchedOn: indexedName.matchedOn,
380
+ aliasQuality: indexedName.quality,
381
+ score,
382
+ scoreForward: forward,
383
+ scoreReverse: reverse,
384
+ scoreWholeString: round6(wholeString),
385
+ alignments: best?.alignments ?? [],
386
+ droppedSuffixes: indexedName.canonical.droppedSuffixes,
387
+ corroboration: corroborate(subject, entry),
388
+ programs: entry.programs ?? [],
389
+ });
390
+ }
391
+ // Score first, then list source, then entry id: two runs over the same
392
+ // snapshot produce the same order, which is what makes a diff of two
393
+ // screening records readable.
394
+ candidates.sort((a, b) => b.score - a.score ||
395
+ (a.list < b.list ? -1 : a.list > b.list ? 1 : 0) ||
396
+ (a.entryId < b.entryId ? -1 : a.entryId > b.entryId ? 1 : 0));
397
+ return {
398
+ candidates: candidates.slice(0, policy.limit),
399
+ below,
400
+ shortlisted: seen.size,
401
+ truncated,
402
+ };
403
+ }
404
+ /** Harmonic mean of the two directions; zero when either direction is zero. */
405
+ function f1(forward, reverse) {
406
+ if (forward <= 0 || reverse <= 0)
407
+ return 0;
408
+ return round6((2 * forward * reverse) / (forward + reverse));
409
+ }
@@ -0,0 +1,137 @@
1
+ /**
2
+ * VAT identification numbers: the local grammar, and how each register's
3
+ * answer maps onto the three outcomes.
4
+ *
5
+ * The rule that shapes this whole file: **`unavailable` never collapses into
6
+ * `notFound`.** VIES is a proxy — it forwards the question to the member
7
+ * state's own system, and those systems go down, individually, routinely, for
8
+ * hours. A tool that reports an outage as "this VAT number is not valid" makes
9
+ * a harness charge domestic VAT on an intra-community supply, or refuse to,
10
+ * because a government server was being rebooted. So every code VIES publishes
11
+ * is mapped explicitly here, and anything unrecognised fails to `unavailable`
12
+ * rather than to a verdict.
13
+ *
14
+ * The second rule: a syntax pass is not a registration, and a registration is
15
+ * not an identity. Both facts travel with the answer instead of being folded
16
+ * into one boolean.
17
+ */
18
+ /** The three outcomes. There is deliberately no boolean anywhere in this file. */
19
+ export type VatOutcome = "found" | "notFound" | "unavailable";
20
+ export type VatCountry = {
21
+ /** The code as the VAT id is written — `EL` for Greece, not `GR`. */
22
+ readonly code: string;
23
+ readonly name: string;
24
+ /** The number part, after the country prefix. */
25
+ readonly pattern: RegExp;
26
+ /** The shape in words, for a result that has to explain a refusal. */
27
+ readonly shape: string;
28
+ readonly register: "vies" | "hmrc";
29
+ readonly note?: string;
30
+ };
31
+ /**
32
+ * Per-country syntax, as a table.
33
+ *
34
+ * A generic "two letters then 8-12 alphanumerics" check passes ids that VIES
35
+ * then rejects, which is the worst of both: a local check that gives false
36
+ * confidence and a remote call that was avoidable. The awkward ones are the
37
+ * point of having a table at all — Ireland's letter in the MIDDLE, the
38
+ * Netherlands' mandatory B in position ten, Spain's letter-or-digit at each
39
+ * end, Greece filing under EL.
40
+ */
41
+ export declare const VAT_COUNTRIES: Readonly<Record<string, VatCountry>>;
42
+ export type ParsedVatId = {
43
+ readonly ok: true;
44
+ readonly country: VatCountry;
45
+ /** The number part, uppercased, with separators removed. */
46
+ readonly number: string;
47
+ /** Country code + number, which is what goes on an invoice. */
48
+ readonly canonical: string;
49
+ } | {
50
+ readonly ok: false;
51
+ readonly reason: string;
52
+ };
53
+ /**
54
+ * Split an id into country and number.
55
+ *
56
+ * Spaces, dots and hyphens are removed because every register prints them
57
+ * differently and none of them stores them. The country either prefixes the
58
+ * id or is passed separately; when both are given and disagree, that is an
59
+ * error rather than a silent preference, because guessing which one the caller
60
+ * meant is how an Irish number gets checked against Italy's grammar.
61
+ */
62
+ export declare function parseVatId(raw: string, declaredCountry?: string): ParsedVatId;
63
+ export type ChecksumResult = {
64
+ readonly algorithm: string;
65
+ /** `null` when this package does not have that country's algorithm. */
66
+ readonly passed: boolean | null;
67
+ readonly note?: string;
68
+ };
69
+ /**
70
+ * The UK's check digits, which are real arithmetic rather than a shape.
71
+ *
72
+ * Two variants are in circulation: the original "mod 97" and the "mod 9755"
73
+ * used for numbers issued from 2004, which differs only by adding 55 before
74
+ * the modulus. Both are accepted, because a number issued under one is not
75
+ * invalid for failing the other — and which one applies is not recorded
76
+ * anywhere on the number.
77
+ *
78
+ * This is the only country whose arithmetic is implemented here. The other
79
+ * twenty-seven have twenty-seven different algorithms, and a checksum written
80
+ * from memory that reports `passed: true` for everything is worse than no
81
+ * checksum at all: it converts "we did not check" into "we checked and it was
82
+ * fine". So they report `passed: null`.
83
+ */
84
+ export declare function gbCheckDigits(number: string): ChecksumResult;
85
+ export type SyntaxCheck = {
86
+ readonly wellFormed: boolean;
87
+ readonly country: string;
88
+ readonly countryName: string;
89
+ readonly number: string;
90
+ readonly canonical: string;
91
+ readonly shape: string;
92
+ readonly checksum: ChecksumResult;
93
+ readonly reason?: string;
94
+ readonly note?: string;
95
+ };
96
+ /** Check one parsed id against its country's grammar, and its check digits if we own them. */
97
+ export declare function checkSyntax(parsed: Extract<ParsedVatId, {
98
+ ok: true;
99
+ }>): SyntaxCheck;
100
+ export type RegisterAnswer = {
101
+ readonly outcome: VatOutcome;
102
+ /** Why this outcome, in the register's own vocabulary where it has one. */
103
+ readonly basis: string;
104
+ /** The register's code, verbatim, so an operator can look it up. */
105
+ readonly code?: string;
106
+ readonly registration?: {
107
+ readonly name?: string;
108
+ readonly address?: string;
109
+ };
110
+ readonly requestDate?: string;
111
+ readonly consultationNumber?: string;
112
+ readonly consultationNumberAbsent?: string;
113
+ /** Present only on `unavailable`: whether asking again later could help. */
114
+ readonly retryable?: boolean;
115
+ /** VIES's own approximate-match verdict on a name we passed it, if we did. */
116
+ readonly nameMatch?: string;
117
+ };
118
+ /**
119
+ * Read a VIES answer.
120
+ *
121
+ * `isValid: true` is the only shape that produces `found`, and only when the
122
+ * accompanying code agrees. An unrecognised code produces `unavailable` with
123
+ * the code quoted — a code this package has never seen is a reason to stop,
124
+ * not a reason to guess which side of the line it falls on.
125
+ */
126
+ export declare function mapViesResponse(body: unknown, requesterSupplied: boolean): RegisterAnswer;
127
+ /**
128
+ * Read an HMRC answer.
129
+ *
130
+ * HMRC's shape is different in a way that matters: it answers 404 for a number
131
+ * that is not registered, which the HTTP layer classifies as `notFound`, and
132
+ * 503 with a maintenance code for an outage. The failure path lives in the
133
+ * caller; this reads the 200 body.
134
+ */
135
+ export declare function mapHmrcResponse(body: unknown, requesterSupplied: boolean): RegisterAnswer;
136
+ /** The codes HMRC returns in an error body, and what each one means for us. */
137
+ export declare function hmrcErrorMeaning(code: string | undefined, status: number | undefined): string;