openchemlib-search-wasm 2.1.2 → 2.1.3

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 (78) hide show
  1. package/LICENSE +451 -25
  2. package/README.md +12 -5
  3. package/lib/functionKeys/index.d.ts +14 -80
  4. package/lib/functionKeys/index.js +3 -98
  5. package/lib/index.d.ts +118 -258
  6. package/lib/index.js +33 -327
  7. package/package.json +24 -32
  8. package/lib/functionKeys/dictionary.json +0 -72071
  9. package/lib/functionKeys/index.d.ts.map +0 -1
  10. package/lib/functionKeys/index.js.map +0 -1
  11. package/lib/functions.d.ts +0 -38
  12. package/lib/functions.d.ts.map +0 -1
  13. package/lib/functions.js +0 -54
  14. package/lib/functions.js.map +0 -1
  15. package/lib/hex.d.ts +0 -31
  16. package/lib/hex.d.ts.map +0 -1
  17. package/lib/hex.js +0 -41
  18. package/lib/hex.js.map +0 -1
  19. package/lib/index.d.ts.map +0 -1
  20. package/lib/index.js.map +0 -1
  21. package/lib/jpath.d.ts +0 -28
  22. package/lib/jpath.d.ts.map +0 -1
  23. package/lib/jpath.js +0 -73
  24. package/lib/jpath.js.map +0 -1
  25. package/lib/records.d.ts +0 -45
  26. package/lib/records.d.ts.map +0 -1
  27. package/lib/records.js +0 -96
  28. package/lib/records.js.map +0 -1
  29. package/lib/runSearch.d.ts +0 -41
  30. package/lib/runSearch.d.ts.map +0 -1
  31. package/lib/runSearch.js +0 -50
  32. package/lib/runSearch.js.map +0 -1
  33. package/lib/scan.d.ts +0 -159
  34. package/lib/scan.d.ts.map +0 -1
  35. package/lib/scan.js +0 -281
  36. package/lib/scan.js.map +0 -1
  37. package/lib/similaritySearch.d.ts +0 -28
  38. package/lib/similaritySearch.d.ts.map +0 -1
  39. package/lib/similaritySearch.js +0 -86
  40. package/lib/similaritySearch.js.map +0 -1
  41. package/lib/strongHash.d.ts +0 -9
  42. package/lib/strongHash.d.ts.map +0 -1
  43. package/lib/strongHash.js +0 -56
  44. package/lib/strongHash.js.map +0 -1
  45. package/lib/substructureSearch.d.ts +0 -29
  46. package/lib/substructureSearch.d.ts.map +0 -1
  47. package/lib/substructureSearch.js +0 -104
  48. package/lib/substructureSearch.js.map +0 -1
  49. package/lib/types.d.ts +0 -308
  50. package/lib/types.d.ts.map +0 -1
  51. package/lib/types.js +0 -52
  52. package/lib/types.js.map +0 -1
  53. package/lib/wasm/load.d.ts +0 -10
  54. package/lib/wasm/load.d.ts.map +0 -1
  55. package/lib/wasm/load.js +0 -50
  56. package/lib/wasm/load.js.map +0 -1
  57. package/lib/wasm/log.d.ts +0 -36
  58. package/lib/wasm/log.d.ts.map +0 -1
  59. package/lib/wasm/log.js +0 -52
  60. package/lib/wasm/log.js.map +0 -1
  61. package/src/functionKeys/index.ts +0 -181
  62. package/src/functions.ts +0 -56
  63. package/src/hex.ts +0 -43
  64. package/src/index.ts +0 -458
  65. package/src/jpath.ts +0 -77
  66. package/src/records.ts +0 -142
  67. package/src/runSearch.ts +0 -99
  68. package/src/scan.ts +0 -441
  69. package/src/similaritySearch.ts +0 -104
  70. package/src/strongHash.ts +0 -57
  71. package/src/substructureSearch.ts +0 -120
  72. package/src/types.ts +0 -403
  73. package/src/wasm/load.ts +0 -59
  74. package/src/wasm/log.ts +0 -66
  75. package/wasm/data.d.ts +0 -2
  76. package/wasm/data.js +0 -3
  77. package/wasm/runtime.d.ts +0 -31
  78. package/wasm/runtime.js +0 -30
@@ -1,120 +0,0 @@
1
- import { toIdCodes } from './jpath.ts';
2
- import { runSearch } from './runSearch.ts';
3
- import type {
4
- SubstructureSearchOptions,
5
- SubstructureSearchResult,
6
- } from './types.ts';
7
- import { SubstructureResult } from './types.ts';
8
-
9
- /**
10
- * Tests a query fragment, or any of several, against many molecules and returns the ones that
11
- * contain it.
12
- *
13
- * The entries are either idcodes or objects carrying one — a database row, a candidate a prescreen
14
- * yielded — and what comes back is those same objects, so nothing has to map positions back onto
15
- * the array they came from. `result` still holds one status code per entry for a caller that wants
16
- * the whole picture rather than the hits.
17
- *
18
- * The scan is synchronous. `onStep` reports it and can stop it, but the thread is not yielded:
19
- * a caller that needs a responsive main thread slices the array across calls, or runs this in a
20
- * worker.
21
- * @param idCodeQuery - The query, as an idcode, or several: a molecule then matches when it holds
22
- * any of them, which is how a function key of `openchemlib-search-wasm/function-keys` is searched
23
- * (`substructureSearch(key.fragments, entries)`). Each is searched as a fragment whatever its own
24
- * fragment flag says, which is what `openchemlib`'s `SSSearcher` does with `setFragment(true)`.
25
- * @param entries - The molecules to test: idcodes, or objects holding one at `options.jpath`.
26
- * @param options - Where the idcode sits, how many matches are enough, and how to report progress.
27
- * @returns The matching entries, their positions, the status buffer and the counts.
28
- * @throws {Error} If the query cannot be parsed or is an empty list, if more than 100 idcodes cannot
29
- * be, or if no entry holds a string at the jpath.
30
- * @example
31
- * ```js
32
- * const { matches } = substructureSearch('gFp@DiTt@@B', rows, { jpath: 'molecule.idCode' });
33
- * ```
34
- */
35
- export function substructureSearch<Entry>(
36
- idCodeQuery: string | readonly string[],
37
- entries: readonly Entry[],
38
- options: SubstructureSearchOptions = {},
39
- ): SubstructureSearchResult<Entry> {
40
- const {
41
- jpath = 'idCode',
42
- limit = Number.MAX_SAFE_INTEGER,
43
- collect = true,
44
- onStep,
45
- stepSize,
46
- } = options;
47
-
48
- const idCodes = toIdCodes(entries, jpath);
49
- // A fresh Uint8Array is already all zeros, which is `unprocessed`.
50
- const result = new Uint8Array(entries.length);
51
- const tally = { matched: 0, unparsable: 0 };
52
- const indexes: number[] = [];
53
- const bounded = limit < entries.length;
54
-
55
- // A whole step is tallied before the limit is checked, so `matched` and `unparsable` always
56
- // describe exactly the entries that were scanned. The overshoot that buys is under one step, and
57
- // `indexes` is cut back to `limit` below.
58
- const collectRange = (from: number, to: number): boolean => {
59
- for (let i = from; i < to; i++) {
60
- const value = result[i] as number;
61
- if (value === SubstructureResult.match) {
62
- tally.matched++;
63
- if (collect) indexes.push(i);
64
- } else if (value === SubstructureResult.unparsable) {
65
- tally.unparsable++;
66
- }
67
- }
68
- return bounded && tally.matched >= limit;
69
- };
70
-
71
- const run = runSearch({
72
- mode: 'substructure',
73
- idCodeQuery: joinQueries(idCodeQuery),
74
- idCodes,
75
- result,
76
- tally,
77
- collectRange,
78
- stepSize,
79
- onStep,
80
- stoppable: bounded,
81
- });
82
-
83
- if (indexes.length > limit) indexes.length = limit;
84
- const matches = new Array<Entry>(indexes.length);
85
- for (let i = 0; i < indexes.length; i++) {
86
- matches[i] = entries[indexes[i] as number] as Entry;
87
- }
88
-
89
- return {
90
- matches,
91
- indexes,
92
- result,
93
- matched: tally.matched,
94
- unparsable: tally.unparsable,
95
- processed: run.processed,
96
- total: entries.length,
97
- elapsed: run.elapsed,
98
- stopped: run.stopped,
99
- };
100
- }
101
-
102
- /**
103
- * The query as the WebAssembly side reads it: one idcode, or several joined by `'\n'`, which no
104
- * idcode contains.
105
- * @param idCodeQuery - The query, as an idcode or several.
106
- * @returns The query string.
107
- * @throws {Error} If the list is empty or an entry holds a line break.
108
- */
109
- function joinQueries(idCodeQuery: string | readonly string[]): string {
110
- if (typeof idCodeQuery === 'string') return idCodeQuery;
111
- if (idCodeQuery.length === 0) {
112
- throw new Error('the query list is empty: give at least one idcode');
113
- }
114
- for (const idCode of idCodeQuery) {
115
- if (idCode.includes('\n')) {
116
- throw new Error(`"${idCode}" is not a valid query idcode`);
117
- }
118
- }
119
- return idCodeQuery.join('\n');
120
- }
package/src/types.ts DELETED
@@ -1,403 +0,0 @@
1
- /**
2
- * The status of one entry of a `substructureSearch` result buffer.
3
- *
4
- * `unprocessed` is what a scan that stopped on `limit` or on `onStep` leaves behind.
5
- */
6
- export const SubstructureResult = Object.freeze({
7
- /** Not tested yet. */
8
- unprocessed: 0,
9
- /** The query is a substructure of this molecule. */
10
- match: 1,
11
- /** The query is not a substructure of this molecule. */
12
- noMatch: 2,
13
- /** The idcode could not be parsed; nothing was tested. */
14
- unparsable: 3,
15
- });
16
-
17
- /**
18
- * The similarity of one entry of a `similaritySearch` result buffer: `NaN` while the entry
19
- * has not been compared yet, `-1` when its idcode could not be parsed, otherwise the Tanimoto
20
- * coefficient in [0, 1]. `0` is a legitimate similarity, which is why the "not yet" sentinel is
21
- * `NaN` and not `0`.
22
- */
23
- export const SimilarityResult = Object.freeze({
24
- /** Not compared yet. */
25
- unprocessed: Number.NaN,
26
- /** The idcode could not be parsed; nothing was compared. */
27
- unparsable: -1,
28
- });
29
-
30
- /** What a search fills: bytes for a substructure scan, floats for a similarity one. */
31
- export type ResultBuffer = Uint8Array | Float32Array;
32
-
33
- /**
34
- * Which search to run. The names are the ones `openchemlib-utils` and `openchemlib-sqlite` already
35
- * use for the same two searches.
36
- */
37
- export type SearchMode = 'substructure' | 'similarity';
38
-
39
- /** What a search has done so far, reported to `onStep`. */
40
- export interface SearchStep {
41
- /**
42
- * The buffer being filled, so a caller can render as the scan runs. It is the same buffer at
43
- * every step, and the one the result carries.
44
- */
45
- result: ResultBuffer;
46
- /** How many entries have been scanned. */
47
- processed: number;
48
- /** How many entries there are. */
49
- total: number;
50
- /** How many of the scanned entries matched. */
51
- matched: number;
52
- /** How many of them could not be parsed. */
53
- unparsable: number;
54
- /** Milliseconds since the search started. */
55
- elapsed: number;
56
- }
57
-
58
- /** What both searches take. */
59
- export interface SearchOptions {
60
- /**
61
- * Where the idcode sits in an entry, as a dot-separated jpath: `idCode`, `molecule.idCode`,
62
- * `spectra.0.idCode`. Ignored when the entries are idcodes rather than objects.
63
- * @default 'idCode'
64
- */
65
- jpath?: string;
66
- /**
67
- * Called after each step with what has been scanned so far. Return `false` to stop the search.
68
- *
69
- * It is synchronous and the scan does not yield: chunking for a responsive main thread is the
70
- * caller's to do, by slicing the array across calls or running this in a worker.
71
- */
72
- onStep?: (step: SearchStep) => boolean | void;
73
- /**
74
- * How many entries one step covers. Only meaningful alongside `onStep` or `limit`; without
75
- * either, the whole array is scanned in a single call.
76
- * @default 4096 for a substructure search, 128 for a similarity one — both about 100 ms
77
- */
78
- stepSize?: number;
79
- /**
80
- * Whether to collect `matches` and `indexes`. Turn it off to fill `result` alone, which is what a
81
- * worker writing into a shared buffer wants: on a corpus that matches often, collecting allocates
82
- * one array slot per hit for nothing.
83
- * @default true
84
- */
85
- collect?: boolean;
86
- }
87
-
88
- export interface SubstructureSearchOptions extends SearchOptions {
89
- /**
90
- * Stop once this many matches have been found. The scan stops at the end of the step that reached
91
- * it, so `matches` can overshoot by less than one step before being cut back to `limit`.
92
- * @default Number.MAX_SAFE_INTEGER
93
- */
94
- limit?: number;
95
- }
96
-
97
- export interface SimilaritySearchOptions extends SearchOptions {
98
- /**
99
- * The Tanimoto coefficient at or above which an entry counts as a match.
100
- * @default 0
101
- */
102
- threshold?: number;
103
- /**
104
- * Keep only the `limit` most similar entries. Unlike a substructure search this cannot stop the
105
- * scan early — a better match may still be coming — so it only decides how many are kept.
106
- * @default Number.MAX_SAFE_INTEGER
107
- */
108
- limit?: number;
109
- }
110
-
111
- /** What every search returns, whatever it computed. */
112
- export interface SearchResult<Entry> {
113
- /**
114
- * The entries that matched, in the order the search defines: input order for a substructure
115
- * search, most similar first for a similarity one.
116
- */
117
- matches: Entry[];
118
- /**
119
- * Their positions in the input, aligned with `matches`. Cheaper than the entries to post back
120
- * from a worker, whose caller already holds them.
121
- */
122
- indexes: number[];
123
- /**
124
- * How many of the scanned entries matched. Larger than `matches.length` when `limit` cut the
125
- * list back, and the only count there is when `collect` is off.
126
- */
127
- matched: number;
128
- /** How many idcodes could not be parsed. */
129
- unparsable: number;
130
- /** How many entries were scanned. Short of `total` when the search stopped early. */
131
- processed: number;
132
- /** How many entries there were. */
133
- total: number;
134
- /** How long the search took, in milliseconds. */
135
- elapsed: number;
136
- /** True when `limit` or `onStep` stopped the scan before the end. */
137
- stopped: boolean;
138
- }
139
-
140
- /**
141
- * `matches` and `indexes` are in **input order**, and `limit` therefore keeps the first matches
142
- * rather than an arbitrary subset. A caller that has ordered its entries by a preference — cheapest
143
- * first, lightest first — gets that preference back, which is what makes `limit` a first page
144
- * rather than a sample.
145
- */
146
- export interface SubstructureSearchResult<Entry> extends SearchResult<Entry> {
147
- /**
148
- * One {@link SubstructureResult} code per entry, in input order. Entries past `processed` are
149
- * left `unprocessed` when the search stopped early.
150
- */
151
- result: Uint8Array;
152
- }
153
-
154
- /** `matches` is ordered by descending similarity, so `limit` keeps the best. */
155
- export interface SimilaritySearchResult<Entry> extends SearchResult<Entry> {
156
- /**
157
- * The Tanimoto coefficient of each entry of `matches`, in the same order — so the two arrays are
158
- * read together. It is a separate array rather than a field on the entry because the entries are
159
- * the caller's own objects: copying each one just to hang a number on it would allocate the whole
160
- * result set a second time.
161
- */
162
- similarities: Float32Array;
163
- /** One coefficient per entry, in input order, with the {@link SimilarityResult} sentinels. */
164
- result: Float32Array;
165
- }
166
-
167
- /** The shape TeaVM exports from the WasmGC module. Both take a half-open `[from, to)` range. */
168
- export interface OCLSearch {
169
- Search: {
170
- /**
171
- * Returns how many molecules in the range contain the fragment, or any of the fragments when
172
- * the query holds several idcodes joined by `'\n'`.
173
- */
174
- ssSearch: (
175
- idCodeQuery: string,
176
- idCodes: string[],
177
- result: Uint8Array,
178
- from: number,
179
- to: number,
180
- ) => number;
181
- /** Returns how many molecules in the range were parsed and compared. */
182
- similaritySearch: (
183
- idCodeQuery: string,
184
- idCodes: string[],
185
- result: Float32Array,
186
- from: number,
187
- to: number,
188
- ) => number;
189
- /** Returns how many molecules in the range were parsed and fingerprinted. */
190
- getIndexes: (
191
- idCodes: string[],
192
- result: Int32Array,
193
- from: number,
194
- to: number,
195
- ) => number;
196
- /** Returns how many molecules in the range were parsed and screened. */
197
- getScreens: (
198
- idCodes: string[],
199
- result: Int32Array,
200
- from: number,
201
- to: number,
202
- ) => number;
203
- /** Writes the query's sixteen screen words into `result`. */
204
- getQueryScreen: (idCodeQuery: string, result: Int32Array) => void;
205
- /** Writes the query's sixteen FragFp words into `result`. */
206
- getQueryIndex: (idCodeQuery: string, result: Int32Array) => void;
207
- /** Returns FragFp's 512 key idcodes, in bit order, joined by `'\n'`. */
208
- getFragFpKeys: () => string;
209
- /** Returns the screen's 512 key idcodes, in bit order, joined by `'\n'`. */
210
- getScreenKeys: () => string;
211
- /** Returns how many molecules in the range were parsed and read. */
212
- getFunctions: (
213
- idCodes: string[],
214
- result: Int32Array,
215
- from: number,
216
- to: number,
217
- ) => number;
218
- /**
219
- * Returns the 512 stored function keys, in bit order, joined by `'\n'`: each key's fragment
220
- * idcodes joined by a space.
221
- */
222
- getFunctionKeys: () => string;
223
- /** Returns how many molecules in the range were hashed. */
224
- getNoStereoTautomerHashes: (
225
- idCodes: string[],
226
- result: BigInt64Array,
227
- tautomerCounts: Int32Array,
228
- largestFragmentOnly: boolean,
229
- maxTautomers: number,
230
- from: number,
231
- to: number,
232
- ) => number;
233
- /** Returns how many molecules in the range were hashed. */
234
- getNoStereoHashes: (
235
- idCodes: string[],
236
- result: BigInt64Array,
237
- largestFragmentOnly: boolean,
238
- from: number,
239
- to: number,
240
- ) => number;
241
- /** Returns how many molecules in the range were canonized. */
242
- getNoStereoIdCodes: (
243
- idCodes: string[],
244
- result: string[],
245
- largestFragmentOnly: boolean,
246
- from: number,
247
- to: number,
248
- ) => number;
249
- /** Returns how many molecules in the range were canonized. */
250
- getNoStereoTautomerIdCodes: (
251
- idCodes: string[],
252
- result: string[],
253
- tautomerCounts: Int32Array,
254
- largestFragmentOnly: boolean,
255
- maxTautomers: number,
256
- from: number,
257
- to: number,
258
- ) => number;
259
- /** Returns how many molecules in the range were read. */
260
- getMoleculeRecords: (
261
- idCodes: string[],
262
- canonical: string[],
263
- words: Int32Array,
264
- atomCounts: Int32Array,
265
- weights: Float64Array,
266
- noStereoHashes: BigInt64Array,
267
- tautomerHashes: BigInt64Array,
268
- tautomerCounts: Int32Array,
269
- maxTautomers: number,
270
- from: number,
271
- to: number,
272
- ) => number;
273
- /** Returns how many molecules in the range were read. */
274
- getMoleculeSizes: (
275
- idCodes: string[],
276
- atomCounts: Int32Array,
277
- weights: Float64Array,
278
- from: number,
279
- to: number,
280
- ) => number;
281
- /** Returns the query's atom floor. */
282
- getQueryAtomFloor: (idCodeQuery: string) => number;
283
- };
284
- }
285
-
286
- /** How many 32-bit words one molecule's FragFp fingerprint, its screen, or its function bits occupy. */
287
- export const INDEX_WORDS = 16;
288
-
289
- /**
290
- * How many 32-bit words one molecule's record holds in `getMoleculeRecords`: its FragFp, its screen,
291
- * then its function bits, {@link INDEX_WORDS} each.
292
- */
293
- export const RECORD_WORDS = 3 * INDEX_WORDS;
294
-
295
- /** What every hash function takes. */
296
- export interface HashOptions {
297
- /**
298
- * Whether to reduce the molecule to its largest fragment and neutralize it before hashing, so a
299
- * salt hashes as its parent structure and a hydrochloride as its free base. Off by default, which
300
- * is what `openchemlib`'s own `CanonizerUtil.getIDCode` does.
301
- * @default false
302
- */
303
- largestFragmentOnly?: boolean;
304
-
305
- /**
306
- * The ceiling on how many tautomers OpenChemLib enumerates before it settles for what it has.
307
- * Only the tautomer functions read it.
308
- *
309
- * The cost of a tautomer key is set by this, not by the molecule's size: the median molecule needs
310
- * a hundred microseconds and one in a hundred runs into the ceiling and spends the better part of
311
- * a second getting there. Lowering it bounds that tail, at the price of a key that may not be
312
- * canonical for the molecules that hit it — compare `tautomerCounts` against this value to find
313
- * them.
314
- * @default 100000 — OpenChemLib's own
315
- */
316
- maxTautomers?: number;
317
-
318
- /**
319
- * Filled with how many tautomers were enumerated for each molecule, if given. An entry that
320
- * reached {@link HashOptions.maxTautomers} is one OpenChemLib stopped early on, which is the only
321
- * signal that a key may not be canonical.
322
- *
323
- * It is the caller's buffer, `idCodes.length` entries long, so a table of flags costs one
324
- * allocation. Only the tautomer functions write it.
325
- */
326
- tautomerCounts?: Int32Array;
327
- }
328
-
329
- /** {@link HashOptions} under the name the tautomer hashes introduced it with. */
330
- export type TautomerHashOptions = HashOptions;
331
-
332
- /** What `getMoleculeRecords` takes. */
333
- export interface MoleculeRecordsOptions {
334
- /**
335
- * The ceiling on the tautomer enumeration. A molecule that reaches it takes its no-stereo hash as
336
- * its tautomer hash, because a key from a truncated enumeration is not canonical.
337
- * @default DEFAULT_MAX_TAUTOMERS
338
- */
339
- maxTautomers?: number;
340
- }
341
-
342
- /**
343
- * Everything a molecule table stores about each molecule, one entry per input idcode, in input
344
- * order. A molecule whose idcode cannot be read gets `NO_ID_CODE`, 48 zero words, 0 atoms, a `NaN`
345
- * weight, `NO_HASH` twice and a tautomer count of 0.
346
- */
347
- export interface MoleculeRecords {
348
- /**
349
- * The canonical idcode, stereochemistry included: what `openchemlib-js` gives for
350
- * `Molecule.fromIDCode(idCode).getIDCode()`.
351
- */
352
- idCodes: string[];
353
- /**
354
- * {@link RECORD_WORDS} words per molecule, at `48 * i`: the FragFp (the 16 words of `getIndexes`),
355
- * the screen (the 16 words of `getScreens`), then the function bits (the 16 words of
356
- * `getFunctions`).
357
- */
358
- words: Int32Array;
359
- /** `getAllAtoms()` of the molecule parsed without coordinates, explicit hydrogens included. */
360
- atomCounts: Int32Array;
361
- /** OpenChemLib's relative molecular weight. */
362
- weights: Float64Array;
363
- /** The value of `getNoStereoHashes`. */
364
- noStereoHashes: BigInt64Array;
365
- /**
366
- * The value of `getNoStereoTautomerHashes`, except for a molecule whose enumeration reached
367
- * `maxTautomers` or could not be canonized: that one gets its no-stereo hash.
368
- */
369
- tautomerHashes: BigInt64Array;
370
- /** How many tautomers were enumerated; at or above `maxTautomers` the enumeration was cut short. */
371
- tautomerCounts: Int32Array;
372
- }
373
-
374
- /** The size of each molecule, one entry per input idcode, in input order. */
375
- export interface MoleculeSizes {
376
- /**
377
- * `getAllAtoms()` of the molecule parsed without coordinates, explicit hydrogens included; 0 when
378
- * the idcode cannot be read.
379
- */
380
- atomCounts: Int32Array;
381
- /** OpenChemLib's relative molecular weight; `NaN` when the idcode cannot be read. */
382
- weights: Float64Array;
383
- }
384
-
385
- /**
386
- * The hash of a molecule that has none: its idcode could not be parsed, or OpenChemLib could not
387
- * canonize it. A real hash collides with it once in 2^64, so an equality test against it is a
388
- * usable "no hash" check.
389
- */
390
- export const NO_HASH = 0n;
391
-
392
- /**
393
- * The canonical idcode of a molecule that has none: its idcode could not be parsed, or OpenChemLib
394
- * could not canonize it. The empty string is never a valid idcode, so an equality test against it is
395
- * the idcode counterpart of {@link NO_HASH}.
396
- */
397
- export const NO_ID_CODE = '';
398
-
399
- /**
400
- * How many tautomers OpenChemLib enumerates before it settles for what it has, unless
401
- * {@link HashOptions.maxTautomers} says otherwise. It is OpenChemLib's own ceiling.
402
- */
403
- export const DEFAULT_MAX_TAUTOMERS = 100_000;
package/src/wasm/load.ts DELETED
@@ -1,59 +0,0 @@
1
- import { wasmGzipBase64 } from '../../wasm/data.js';
2
- import { load } from '../../wasm/runtime.js';
3
- import type { OCLSearch } from '../types.ts';
4
-
5
- import { createConsoleImport } from './log.ts';
6
-
7
- let modulePromise: Promise<OCLSearch> | undefined;
8
-
9
- /**
10
- * The ceiling on the module's linear memory. The runtime otherwise declares the largest maximum it
11
- * can — 2 GiB — for every instantiation, and a page that scans in eight workers declares eight of
12
- * them. The module's own `teavm.memoryRequirements` section asks for 33 pages and 17 KB of static
13
- * data, and the memory has never been observed to grow past its 33-page initial, so this is three
14
- * orders of magnitude of headroom over anything measured.
15
- */
16
- const MAX_LINEAR_MEMORY = 256 * 1024 * 1024;
17
-
18
- /**
19
- * Loads and instantiates the embedded OpenChemLib WasmGC module. The module is compiled once and
20
- * cached; subsequent calls return the same instance. Decoding uses only Web Platform APIs (atob +
21
- * DecompressionStream), so Node and the browser take the same path, with no filesystem and no
22
- * fetch — which is what lets a worker instantiate it from the bundle it was loaded from.
23
- * @returns The module's exports.
24
- */
25
- export function loadOCL(): Promise<OCLSearch> {
26
- modulePromise ??= instantiate();
27
- return modulePromise;
28
- }
29
-
30
- async function instantiate(): Promise<OCLSearch> {
31
- const wasmBytes = await gunzip(base64ToBytes(wasmGzipBase64));
32
- const teavm = await load(wasmBytes, {
33
- memory: { maxSize: MAX_LINEAR_MEMORY },
34
- // The runtime's own `teavmConsole` puts Java's System.out on `console.log`, so OpenChemLib's
35
- // "Tautomer count exceeds maximum" lands on the host's stdout — see src/wasm/log.ts.
36
- installImports(imports) {
37
- imports.teavmConsole = createConsoleImport();
38
- },
39
- });
40
- return teavm.exports as unknown as OCLSearch;
41
- }
42
-
43
- function base64ToBytes(base64: string): Uint8Array<ArrayBuffer> {
44
- const binary = atob(base64);
45
- const bytes = new Uint8Array(binary.length);
46
- for (let i = 0; i < binary.length; i++) {
47
- bytes[i] = binary.codePointAt(i) ?? 0;
48
- }
49
- return bytes;
50
- }
51
-
52
- async function gunzip(
53
- bytes: Uint8Array<ArrayBuffer>,
54
- ): Promise<Uint8Array<ArrayBuffer>> {
55
- const stream = new Blob([bytes])
56
- .stream()
57
- .pipeThrough(new DecompressionStream('gzip'));
58
- return new Uint8Array(await new Response(stream).arrayBuffer());
59
- }
package/src/wasm/log.ts DELETED
@@ -1,66 +0,0 @@
1
- /** Which of Java's two standard streams a line came from. */
2
- export type LogStream = 'stdout' | 'stderr';
3
-
4
- /** Called with one line OpenChemLib wrote to a standard stream. */
5
- export type LogHandler = (message: string, stream: LogStream) => void;
6
-
7
- /** TeaVM imports one character sink per stream; it writes a character at a time. */
8
- interface TeaVMConsole {
9
- putcharStdout: (code: number) => void;
10
- putcharStderr: (code: number) => void;
11
- }
12
-
13
- const NEWLINE = 10;
14
-
15
- let handler: LogHandler | null = null;
16
-
17
- /**
18
- * Routes what OpenChemLib writes to Java's standard streams wherever you want it.
19
- *
20
- * Nothing is written anywhere by default, and that is the point: OpenChemLib prints
21
- * `Tautomer count exceeds maximum: <idcode>` for every molecule whose tautomers it stops
22
- * enumerating, which an import emits thousands of times, and the generated TeaVM runtime maps that
23
- * onto `console.log` — the same stream a host writing structured logs is using, whose output it
24
- * then corrupts. The message says nothing a caller can act on; the hash is still returned and still
25
- * identifies the molecule. So the default is to drop it, and a host that wants it says where.
26
- *
27
- * It applies whether or not the module has been instantiated yet, so it can be set at startup or
28
- * around one call.
29
- *
30
- * ```js
31
- * setLogHandler((message, stream) => logger.debug({ stream }, message));
32
- * ```
33
- * @param next - Called once per line, or `null` to go back to discarding them.
34
- */
35
- export function setLogHandler(next: LogHandler | null): void {
36
- handler = next;
37
- }
38
-
39
- /**
40
- * Builds the `teavmConsole` import that replaces the generated runtime's own, which calls
41
- * `console.log` and `console.error`.
42
- * @returns The import object to install over it.
43
- */
44
- export function createConsoleImport(): TeaVMConsole {
45
- return {
46
- putcharStdout: lineSink('stdout'),
47
- putcharStderr: lineSink('stderr'),
48
- };
49
- }
50
-
51
- /**
52
- * Collects characters into a line and hands each finished one to the current handler.
53
- * @param stream - The stream these characters belong to.
54
- * @returns The per-character callback the runtime imports.
55
- */
56
- function lineSink(stream: LogStream): (code: number) => void {
57
- let line = '';
58
- return (code: number) => {
59
- if (code === NEWLINE) {
60
- handler?.(line, stream);
61
- line = '';
62
- } else {
63
- line += String.fromCodePoint(code);
64
- }
65
- };
66
- }
package/wasm/data.d.ts DELETED
@@ -1,2 +0,0 @@
1
- // Generated by build/embed-wasm.mjs — do not edit.
2
- export declare const wasmGzipBase64: string;