openchemlib-search-wasm 1.2.0 → 2.1.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.
Files changed (59) hide show
  1. package/README.md +290 -3
  2. package/lib/functionKeys/dictionary.json +72071 -0
  3. package/lib/functionKeys/index.d.ts +105 -0
  4. package/lib/functionKeys/index.d.ts.map +1 -0
  5. package/lib/functionKeys/index.js +98 -0
  6. package/lib/functionKeys/index.js.map +1 -0
  7. package/lib/functions.d.ts +38 -0
  8. package/lib/functions.d.ts.map +1 -0
  9. package/lib/functions.js +54 -0
  10. package/lib/functions.js.map +1 -0
  11. package/lib/hex.d.ts +31 -0
  12. package/lib/hex.d.ts.map +1 -0
  13. package/lib/hex.js +41 -0
  14. package/lib/hex.js.map +1 -0
  15. package/lib/index.d.ts +140 -2
  16. package/lib/index.d.ts.map +1 -1
  17. package/lib/index.js +184 -7
  18. package/lib/index.js.map +1 -1
  19. package/lib/records.d.ts +45 -0
  20. package/lib/records.d.ts.map +1 -0
  21. package/lib/records.js +96 -0
  22. package/lib/records.js.map +1 -0
  23. package/lib/scan.d.ts +99 -7
  24. package/lib/scan.d.ts.map +1 -1
  25. package/lib/scan.js +158 -11
  26. package/lib/scan.js.map +1 -1
  27. package/lib/strongHash.d.ts +9 -0
  28. package/lib/strongHash.d.ts.map +1 -0
  29. package/lib/strongHash.js +56 -0
  30. package/lib/strongHash.js.map +1 -0
  31. package/lib/substructureSearch.d.ts +8 -5
  32. package/lib/substructureSearch.d.ts.map +1 -1
  33. package/lib/substructureSearch.js +28 -5
  34. package/lib/substructureSearch.js.map +1 -1
  35. package/lib/types.d.ts +120 -3
  36. package/lib/types.d.ts.map +1 -1
  37. package/lib/types.js +17 -1
  38. package/lib/types.js.map +1 -1
  39. package/lib/wasm/load.d.ts.map +1 -1
  40. package/lib/wasm/load.js +9 -1
  41. package/lib/wasm/load.js.map +1 -1
  42. package/lib/wasm/log.d.ts +36 -0
  43. package/lib/wasm/log.d.ts.map +1 -0
  44. package/lib/wasm/log.js +52 -0
  45. package/lib/wasm/log.js.map +1 -0
  46. package/package.json +6 -3
  47. package/src/functionKeys/index.ts +181 -0
  48. package/src/functions.ts +56 -0
  49. package/src/hex.ts +43 -0
  50. package/src/index.ts +269 -5
  51. package/src/records.ts +142 -0
  52. package/src/scan.ts +259 -16
  53. package/src/strongHash.ts +57 -0
  54. package/src/substructureSearch.ts +29 -6
  55. package/src/types.ts +171 -2
  56. package/src/wasm/load.ts +10 -1
  57. package/src/wasm/log.ts +66 -0
  58. package/wasm/data.js +1 -1
  59. package/wasm/runtime.d.ts +6 -0
package/lib/wasm/load.js CHANGED
@@ -1,5 +1,6 @@
1
1
  import { wasmGzipBase64 } from '../../wasm/data.js';
2
2
  import { load } from '../../wasm/runtime.js';
3
+ import { createConsoleImport } from "./log.js";
3
4
  let modulePromise;
4
5
  /**
5
6
  * The ceiling on the module's linear memory. The runtime otherwise declares the largest maximum it
@@ -22,7 +23,14 @@ export function loadOCL() {
22
23
  }
23
24
  async function instantiate() {
24
25
  const wasmBytes = await gunzip(base64ToBytes(wasmGzipBase64));
25
- const teavm = await load(wasmBytes, { memory: { maxSize: MAX_LINEAR_MEMORY } });
26
+ const teavm = await load(wasmBytes, {
27
+ memory: { maxSize: MAX_LINEAR_MEMORY },
28
+ // The runtime's own `teavmConsole` puts Java's System.out on `console.log`, so OpenChemLib's
29
+ // "Tautomer count exceeds maximum" lands on the host's stdout — see src/wasm/log.ts.
30
+ installImports(imports) {
31
+ imports.teavmConsole = createConsoleImport();
32
+ },
33
+ });
26
34
  return teavm.exports;
27
35
  }
28
36
  function base64ToBytes(base64) {
@@ -1 +1 @@
1
- {"version":3,"file":"load.js","sourceRoot":"","sources":["../../src/wasm/load.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,cAAc,EAAE,MAAM,oBAAoB,CAAC;AACpD,OAAO,EAAE,IAAI,EAAE,MAAM,uBAAuB,CAAC;AAG7C,IAAI,aAA6C,CAAC;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AC,CAAC,KAAK,CAAC,CAAC;SAC7B,MAAM,EAAE;SACR,WAAW,CAAC,IAAI,mBAAmB,CAAC,MAAM,CAAC,CAAC,CAAC;IAChD,OAAO,IAAI,UAAU,CAAC,MAAM,IAAI,QAAQ,CAAC,MAAM,CAAC,CAAC,WAAW,EAAE,CAAC,CAAC;AAClE,CAAC"}
@@ -0,0 +1,36 @@
1
+ /** Which of Java's two standard streams a line came from. */
2
+ export type LogStream = 'stdout' | 'stderr';
3
+ /** Called with one line OpenChemLib wrote to a standard stream. */
4
+ export type LogHandler = (message: string, stream: LogStream) => void;
5
+ /** TeaVM imports one character sink per stream; it writes a character at a time. */
6
+ interface TeaVMConsole {
7
+ putcharStdout: (code: number) => void;
8
+ putcharStderr: (code: number) => void;
9
+ }
10
+ /**
11
+ * Routes what OpenChemLib writes to Java's standard streams wherever you want it.
12
+ *
13
+ * Nothing is written anywhere by default, and that is the point: OpenChemLib prints
14
+ * `Tautomer count exceeds maximum: <idcode>` for every molecule whose tautomers it stops
15
+ * enumerating, which an import emits thousands of times, and the generated TeaVM runtime maps that
16
+ * onto `console.log` — the same stream a host writing structured logs is using, whose output it
17
+ * then corrupts. The message says nothing a caller can act on; the hash is still returned and still
18
+ * identifies the molecule. So the default is to drop it, and a host that wants it says where.
19
+ *
20
+ * It applies whether or not the module has been instantiated yet, so it can be set at startup or
21
+ * around one call.
22
+ *
23
+ * ```js
24
+ * setLogHandler((message, stream) => logger.debug({ stream }, message));
25
+ * ```
26
+ * @param next - Called once per line, or `null` to go back to discarding them.
27
+ */
28
+ export declare function setLogHandler(next: LogHandler | null): void;
29
+ /**
30
+ * Builds the `teavmConsole` import that replaces the generated runtime's own, which calls
31
+ * `console.log` and `console.error`.
32
+ * @returns The import object to install over it.
33
+ */
34
+ export declare function createConsoleImport(): TeaVMConsole;
35
+ export {};
36
+ //# sourceMappingURL=log.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"log.d.ts","sourceRoot":"","sources":["../../src/wasm/log.ts"],"names":[],"mappings":"AAAA,6DAA6D;AAC7D,MAAM,MAAM,SAAS,GAAG,QAAQ,GAAG,QAAQ,CAAC;AAE5C,mEAAmE;AACnE,MAAM,MAAM,UAAU,GAAG,CAAC,OAAO,EAAE,MAAM,EAAE,MAAM,EAAE,SAAS,KAAK,IAAI,CAAC;AAEtE,oFAAoF;AACpF,UAAU,YAAY;IACpB,aAAa,EAAE,CAAC,IAAI,EAAE,MAAM,KAAK,IAAI,CAAC;IACtC,aAAa,EAAE,CAAC,IAAI,EAAE,MAAM,KAAK,IAAI,CAAC;CACvC;AAMD;;;;;;;;;;;;;;;;;GAiBG;AACH,wBAAgB,aAAa,CAAC,IAAI,EAAE,UAAU,GAAG,IAAI,GAAG,IAAI,CAE3D;AAED;;;;GAIG;AACH,wBAAgB,mBAAmB,IAAI,YAAY,CAKlD"}
@@ -0,0 +1,52 @@
1
+ const NEWLINE = 10;
2
+ let handler = null;
3
+ /**
4
+ * Routes what OpenChemLib writes to Java's standard streams wherever you want it.
5
+ *
6
+ * Nothing is written anywhere by default, and that is the point: OpenChemLib prints
7
+ * `Tautomer count exceeds maximum: <idcode>` for every molecule whose tautomers it stops
8
+ * enumerating, which an import emits thousands of times, and the generated TeaVM runtime maps that
9
+ * onto `console.log` — the same stream a host writing structured logs is using, whose output it
10
+ * then corrupts. The message says nothing a caller can act on; the hash is still returned and still
11
+ * identifies the molecule. So the default is to drop it, and a host that wants it says where.
12
+ *
13
+ * It applies whether or not the module has been instantiated yet, so it can be set at startup or
14
+ * around one call.
15
+ *
16
+ * ```js
17
+ * setLogHandler((message, stream) => logger.debug({ stream }, message));
18
+ * ```
19
+ * @param next - Called once per line, or `null` to go back to discarding them.
20
+ */
21
+ export function setLogHandler(next) {
22
+ handler = next;
23
+ }
24
+ /**
25
+ * Builds the `teavmConsole` import that replaces the generated runtime's own, which calls
26
+ * `console.log` and `console.error`.
27
+ * @returns The import object to install over it.
28
+ */
29
+ export function createConsoleImport() {
30
+ return {
31
+ putcharStdout: lineSink('stdout'),
32
+ putcharStderr: lineSink('stderr'),
33
+ };
34
+ }
35
+ /**
36
+ * Collects characters into a line and hands each finished one to the current handler.
37
+ * @param stream - The stream these characters belong to.
38
+ * @returns The per-character callback the runtime imports.
39
+ */
40
+ function lineSink(stream) {
41
+ let line = '';
42
+ return (code) => {
43
+ if (code === NEWLINE) {
44
+ handler?.(line, stream);
45
+ line = '';
46
+ }
47
+ else {
48
+ line += String.fromCodePoint(code);
49
+ }
50
+ };
51
+ }
52
+ //# sourceMappingURL=log.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"log.js","sourceRoot":"","sources":["../../src/wasm/log.ts"],"names":[],"mappings":"AAYA,MAAM,OAAO,GAAG,EAAE,CAAC;AAEnB,IAAI,OAAO,GAAsB,IAAI,CAAC;AAEtC;;;;;;;;;;;;;;;;;GAiBG;AACH,MAAM,UAAU,aAAa,CAAC,IAAuB;IACnD,OAAO,GAAG,IAAI,CAAC;AACjB,CAAC;AAED;;;;GAIG;AACH,MAAM,UAAU,mBAAmB;IACjC,OAAO;QACL,aAAa,EAAE,QAAQ,CAAC,QAAQ,CAAC;QACjC,aAAa,EAAE,QAAQ,CAAC,QAAQ,CAAC;KAClC,CAAC;AACJ,CAAC;AAED;;;;GAIG;AACH,SAAS,QAAQ,CAAC,MAAiB;IACjC,IAAI,IAAI,GAAG,EAAE,CAAC;IACd,OAAO,CAAC,IAAY,EAAE,EAAE;QACtB,IAAI,IAAI,KAAK,OAAO,EAAE,CAAC;YACrB,OAAO,EAAE,CAAC,IAAI,EAAE,MAAM,CAAC,CAAC;YACxB,IAAI,GAAG,EAAE,CAAC;QACZ,CAAC;aAAM,CAAC;YACN,IAAI,IAAI,MAAM,CAAC,aAAa,CAAC,IAAI,CAAC,CAAC;QACrC,CAAC;IACH,CAAC,CAAC;AACJ,CAAC"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "openchemlib-search-wasm",
3
- "version": "1.2.0",
3
+ "version": "2.1.0",
4
4
  "type": "module",
5
5
  "description": "Batch substructure and similarity search over idcodes, with OpenChemLib compiled to WebAssembly",
6
6
  "keywords": [
@@ -28,6 +28,7 @@
28
28
  "benchmark-scan": "node benchmark/scan.mjs",
29
29
  "build": "npm run build-wasm && npm run build-embed",
30
30
  "build-embed": "node build/embed-wasm.mjs",
31
+ "build-function-keys": "node scripts/build-function-keys.mjs",
31
32
  "build-wasm": "node scripts/build-wasm.mjs",
32
33
  "check-types": "tsc --noEmit",
33
34
  "check-wasm": "node scripts/check-wasm.mjs",
@@ -45,10 +46,12 @@
45
46
  "tsc-build": "tsc --project tsconfig.build.json"
46
47
  },
47
48
  "exports": {
48
- ".": "./lib/index.js"
49
+ ".": "./lib/index.js",
50
+ "./function-keys": "./lib/functionKeys/index.js"
49
51
  },
50
52
  "imports": {
51
- "#lib": "./src/index.ts"
53
+ "#lib": "./src/index.ts",
54
+ "#function-keys": "./src/functionKeys/index.ts"
52
55
  },
53
56
  "files": [
54
57
  "lib",
@@ -0,0 +1,181 @@
1
+ import { INDEX_WORDS } from '../types.ts';
2
+
3
+ import dictionary from './dictionary.json' with { type: 'json' };
4
+
5
+ /**
6
+ * Where a key's answer comes from: one of the 512 function bits a record stores, a bit of the FragFp
7
+ * or the screen that holds exactly the same molecules, or a substructure search run when asked.
8
+ */
9
+ export type FunctionKeyTier = 'stored' | 'existingPlane' | 'onDemand';
10
+
11
+ /** One named function key: a functional group, a ring, a substituent, a natural product class. */
12
+ export interface FunctionKey {
13
+ /** Stable identifier. */
14
+ id: string;
15
+ /** The name to show. No other key carries it as name or synonym, case aside. */
16
+ name: string;
17
+ /** The other names it answers to, each also unique across the dictionary. */
18
+ synonyms: string[];
19
+ /** A key of {@link getFunctionCategories}. */
20
+ category: string;
21
+ /** A finer group within the category. */
22
+ subcategory: string;
23
+ tier: FunctionKeyTier;
24
+ /** For a `stored` key: its bit in the function words, 0 to 511. */
25
+ plane?: number;
26
+ /** For an `existingPlane` key: the fingerprint holding its bit. */
27
+ fingerprint?: 'fragFp' | 'screen';
28
+ /** For an `existingPlane` key: its bit in that fingerprint, 0 to 511. */
29
+ bit?: number;
30
+ /** The share of the 1,034,054 PubChem molecules it was counted on that hold it. */
31
+ prevalence: number;
32
+ /** Where its definition comes from: keys of {@link getFunctionKeySources}. */
33
+ sources: string[];
34
+ /** The SMARTS it was compiled from, absent for a key given as an idcode. */
35
+ smarts?: string;
36
+ /**
37
+ * Its query fragments, as idcodes: a molecule holds the key when it holds any of them, which is
38
+ * what `substructureSearch(key.fragments, entries)` tests.
39
+ */
40
+ fragments: string[];
41
+ }
42
+
43
+ /** A source the dictionary's definitions come from, and the licence they are used under. */
44
+ export interface FunctionKeySource {
45
+ name: string;
46
+ url: string;
47
+ licence: string;
48
+ }
49
+
50
+ /** Where a key's bit sits in the 48-word record of `getMoleculeRecords`. */
51
+ export interface RecordBit {
52
+ /** The word of the record: FragFp words first, then the screen, then the function bits. */
53
+ word: number;
54
+ /** The bit within that word. */
55
+ mask: number;
56
+ }
57
+
58
+ /** What {@link searchFunctionKeys} takes. */
59
+ export interface SearchFunctionKeysOptions {
60
+ /**
61
+ * Only the keys of this tier.
62
+ * @default every tier
63
+ */
64
+ tier?: FunctionKeyTier;
65
+ /**
66
+ * Only the keys of this category.
67
+ * @default every category
68
+ */
69
+ category?: string;
70
+ /**
71
+ * The most keys to return.
72
+ * @default no limit
73
+ */
74
+ limit?: number;
75
+ }
76
+
77
+ const KEYS = dictionary.keys as FunctionKey[];
78
+ let byName: Map<string, FunctionKey> | undefined;
79
+
80
+ /**
81
+ * Returns every function key: the 512 stored ones in bit order, then those equal to a FragFp or
82
+ * screen bit, then those computed on demand, by category and prevalence.
83
+ * @returns The keys. They are shared: do not modify them.
84
+ */
85
+ export function getFunctionKeys(): readonly FunctionKey[] {
86
+ return KEYS;
87
+ }
88
+
89
+ /**
90
+ * Finds a key by its id, its name or one of its synonyms, case aside.
91
+ * @param nameOrId - What to look up, such as `thioether`, `Boc` or `pyridin_2_one`.
92
+ * @returns The key, or undefined when nothing carries that name.
93
+ */
94
+ export function getFunctionKey(nameOrId: string): FunctionKey | undefined {
95
+ if (!byName) {
96
+ byName = new Map();
97
+ for (const key of KEYS) {
98
+ for (const name of [key.id, key.name, ...key.synonyms]) {
99
+ if (!byName.has(name.toLowerCase())) {
100
+ byName.set(name.toLowerCase(), key);
101
+ }
102
+ }
103
+ }
104
+ }
105
+ return byName.get(nameOrId.trim().toLowerCase());
106
+ }
107
+
108
+ /**
109
+ * Finds the keys whose id, name or synonyms hold every word of a text, case aside: an exact name
110
+ * first, then names starting with the text, then the rest, each by prevalence.
111
+ * @param text - Words to look for, such as `aromatic amine` or `lactam`.
112
+ * @param options - Narrows the result; see {@link SearchFunctionKeysOptions}.
113
+ * @returns The matching keys, best first.
114
+ */
115
+ export function searchFunctionKeys(
116
+ text: string,
117
+ options: SearchFunctionKeysOptions = {},
118
+ ): FunctionKey[] {
119
+ const { tier, category, limit = Number.POSITIVE_INFINITY } = options;
120
+ const wanted = text.trim().toLowerCase();
121
+ const words = wanted.split(/\s+/).filter(Boolean);
122
+ const scored: Array<{ key: FunctionKey; rank: number }> = [];
123
+ for (const key of KEYS) {
124
+ if (
125
+ (tier && key.tier !== tier) ||
126
+ (category && key.category !== category)
127
+ ) {
128
+ continue;
129
+ }
130
+ const names = [key.name, ...key.synonyms].map((name) => name.toLowerCase());
131
+ const haystack = `${key.id.toLowerCase()}\n${names.join('\n')}`;
132
+ if (!words.every((word) => haystack.includes(word))) continue;
133
+ const rank = names.includes(wanted)
134
+ ? 0
135
+ : names.some((name) => name.startsWith(wanted))
136
+ ? 1
137
+ : 2;
138
+ scored.push({ key, rank });
139
+ }
140
+ scored.sort((a, b) => a.rank - b.rank || b.key.prevalence - a.key.prevalence);
141
+ return scored.slice(0, limit).map(({ key }) => key);
142
+ }
143
+
144
+ /**
145
+ * Returns the categories keys are grouped in, in display order.
146
+ * @returns Category id to its title, such as `carbonyl` to `Carbonyl groups`.
147
+ */
148
+ export function getFunctionCategories(): Readonly<Record<string, string>> {
149
+ return dictionary.categories;
150
+ }
151
+
152
+ /**
153
+ * Returns the sources the definitions come from, with their licences, for attribution.
154
+ * @returns Source id, as a key's `sources` names it, to its name, address and licence.
155
+ */
156
+ export function getFunctionKeySources(): Readonly<
157
+ Record<string, FunctionKeySource>
158
+ > {
159
+ return dictionary.sources;
160
+ }
161
+
162
+ /**
163
+ * Says where a key's answer sits in a record of `getMoleculeRecords`, so a stored record answers it
164
+ * with one mask test: `(record[word] & mask) !== 0`.
165
+ * @param key - The key.
166
+ * @returns The word and mask, or undefined for a key computed on demand, which a record does not hold.
167
+ */
168
+ export function getRecordBit(key: FunctionKey): RecordBit | undefined {
169
+ let base: number;
170
+ let bit: number;
171
+ if (key.tier === 'stored' && key.plane !== undefined) {
172
+ base = 2 * INDEX_WORDS;
173
+ bit = key.plane;
174
+ } else if (key.tier === 'existingPlane' && key.bit !== undefined) {
175
+ base = key.fingerprint === 'screen' ? INDEX_WORDS : 0;
176
+ bit = key.bit;
177
+ } else {
178
+ return undefined;
179
+ }
180
+ return { word: base + (bit >> 5), mask: 1 << (31 - (bit & 31)) };
181
+ }
@@ -0,0 +1,56 @@
1
+ import { buildFunctions, readFunctionKeys } from './scan.ts';
2
+ import { INDEX_WORDS } from './types.ts';
3
+
4
+ /**
5
+ * Builds the 512 function bits of one idcode, as sixteen 32-bit words: bit i is set when any
6
+ * fragment of stored function key i is a substructure of the molecule.
7
+ *
8
+ * The keys are named chemistry — thioether, aromatic ring, uracil, Boc — so a question in words
9
+ * becomes bit arithmetic over stored words. Their names, categories and synonyms, and the keys that
10
+ * are computed on demand instead, are in the dictionary of `openchemlib-search-wasm/function-keys`.
11
+ * A key's bit always agrees with a substructure search for its fragments. The words are laid out
12
+ * as {@link getFunctionKeyFragments} shows.
13
+ * @param idCode - The molecule to read, as an idcode.
14
+ * @returns Sixteen words. An idcode that will not parse gives sixteen zeros.
15
+ */
16
+ export function getFunction(idCode: string): Int32Array {
17
+ const result = new Int32Array(INDEX_WORDS);
18
+ buildFunctions([idCode], result, 0, 1);
19
+ return result;
20
+ }
21
+
22
+ /**
23
+ * Builds the 512 function bits of every idcode, sixteen 32-bit words each.
24
+ *
25
+ * See {@link getFunction}. Each molecule's FragFp and screen are built too, because a key's fragment
26
+ * is only tried on a molecule holding its query words; `getMoleculeRecords` returns all three
27
+ * from one parse. The words are written into one buffer and returned as a view per molecule.
28
+ * @param idCodes - The molecules to read, as idcodes.
29
+ * @returns One sixteen-word view per idcode, in order.
30
+ */
31
+ export function getFunctions(idCodes: string[]): Int32Array[] {
32
+ const all = new Int32Array(idCodes.length * INDEX_WORDS);
33
+ buildFunctions(idCodes, all, 0, idCodes.length);
34
+ const words = new Array<Int32Array>(idCodes.length);
35
+ for (let i = 0; i < idCodes.length; i++) {
36
+ words[i] = all.subarray(i * INDEX_WORDS, (i + 1) * INDEX_WORDS);
37
+ }
38
+ return words;
39
+ }
40
+
41
+ /**
42
+ * Returns the fragments of the 512 stored function keys, in bit order: bit i of {@link getFunction}
43
+ * is set when any fragment of key i is a substructure of the molecule. Bit i sits in word `i >> 5`,
44
+ * the first key in the highest bit of word 0:
45
+ *
46
+ * ```js
47
+ * const held = (words, i) => (words[i >> 5] & (1 << (31 - (i & 31)))) !== 0;
48
+ * ```
49
+ *
50
+ * The list is frozen with the module: changing, adding or reordering a key changes every stored
51
+ * record, so it only changes in a major release.
52
+ * @returns 512 arrays of idcodes, each a key's fragments. The arrays are the caller's own.
53
+ */
54
+ export function getFunctionKeyFragments(): string[][] {
55
+ return readFunctionKeys();
56
+ }
package/src/hex.ts ADDED
@@ -0,0 +1,43 @@
1
+ /** How many hex digits a 64-bit hash always writes. */
2
+ const HASH_HEX_DIGITS = 16;
3
+
4
+ const HASH_HEX = /^[0-9a-f]{16}$/i;
5
+
6
+ /**
7
+ * Formats a hash as the 16 lowercase hex digits of its 64-bit pattern.
8
+ *
9
+ * A hash is a signed 64-bit integer, which `JSON.stringify` refuses outright — and a JSON number
10
+ * could not carry it anyway, since 64 bits does not fit a double. Hex is what crosses an API: it is
11
+ * always 16 characters whatever the value, it compares and sorts as a string, and it survives a
12
+ * round trip through anything that handles text.
13
+ *
14
+ * `hash.toString(16)` is not this: it writes `-1` for `-1n`, where the pattern is
15
+ * `ffffffffffffffff`, and it pads nothing.
16
+ *
17
+ * A database that stores the hash in an integer column can format it on the way out instead, and
18
+ * SQLite's `printf('%016x', hash)` produces exactly this string.
19
+ *
20
+ * ```js
21
+ * hashToHex(getNoStereoTautomerHash(idCode)); // 'eb14b9bc9ab4dd52'
22
+ * ```
23
+ * @param hash - The hash to format.
24
+ * @returns Its 16 hex digits, lowercase and zero-padded.
25
+ */
26
+ export function hashToHex(hash: bigint): string {
27
+ return BigInt.asUintN(64, hash).toString(16).padStart(HASH_HEX_DIGITS, '0');
28
+ }
29
+
30
+ /**
31
+ * Reads back what {@link hashToHex} wrote, so a hash that arrived as text can be compared against
32
+ * one that was computed, or bound to an integer column.
33
+ * @param hex - The 16 hex digits, in either case.
34
+ * @returns The signed 64-bit hash.
35
+ * @throws {SyntaxError} When the string is not 16 hex digits — a truncated or `0x`-prefixed hash
36
+ * would otherwise read as a different, valid-looking value.
37
+ */
38
+ export function hexToHash(hex: string): bigint {
39
+ if (!HASH_HEX.test(hex)) {
40
+ throw new SyntaxError(`not a 16-digit hex hash: ${JSON.stringify(hex)}`);
41
+ }
42
+ return BigInt.asIntN(64, BigInt(`0x${hex}`));
43
+ }