rdkit-esm 0.4.3 → 0.5.0-rc.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 (3) hide show
  1. package/dist/index.d.ts +164 -16
  2. package/dist/index.js +191 -36
  3. package/package.json +1 -1
package/dist/index.d.ts CHANGED
@@ -18,6 +18,9 @@ interface JSMol {
18
18
  */
19
19
  delete(): void;
20
20
 
21
+ /** Returns true if the underlying C++ object has already been deleted (added by Emscripten) */
22
+ isDeleted(): boolean;
23
+
21
24
  // string representations
22
25
 
23
26
  /** Returns the SMILES string */
@@ -317,8 +320,9 @@ interface JSMol {
317
320
  * ```
318
321
  * @param maxCoverage maximum fraction of the molecule that can be covered by abbreviations
319
322
  * @param areLinkers if true, definitions are treated as linker abbreviations (first atom must be a dummy `*`)
323
+ * @private This method is not exposed
320
324
  */
321
- condense_abbreviations_from_defs(definitions: string, maxCoverage: number, areLinkers: boolean): string;
325
+ //condense_abbreviations_from_defs(definitions: string, maxCoverage: number, areLinkers: boolean): string;
322
326
 
323
327
  // coord generation
324
328
 
@@ -500,6 +504,42 @@ interface JSMol {
500
504
  * @param height height in pixels
501
505
  */
502
506
  draw_to_canvas_with_offset(canvas: HTMLCanvasElement, offsetx: number, offsety: number, width: number, height: number): void;
507
+
508
+ // PNG I/O
509
+
510
+ /**
511
+ * Embeds molecule data (pickle, SMILES, molblock) into a PNG.
512
+ * Returns the updated PNG as a Uint8Array.
513
+ *
514
+ * @param png PNG data as Uint8Array
515
+ */
516
+ add_to_png_blob(png: Uint8Array): Uint8Array;
517
+ /** @see add_to_png_blob */
518
+ add_to_png_blob(png: Uint8Array, details: JSONString): Uint8Array;
519
+
520
+ // coordinates
521
+
522
+ /**
523
+ * Returns the 3D atom coordinates of the molecule's conformer.
524
+ * Each entry is a `[x, y, z]` triple.
525
+ */
526
+ get_coords(): [number, number, number][];
527
+
528
+ // MMPA fragmentation
529
+
530
+ /**
531
+ * Performs MMPA (Matched Molecular Pairs Analysis) fragmentation.
532
+ * Returns cores and sidechains as two `MolList` objects.
533
+ * Requires RDKit built with `RDK_BUILD_MINIMAL_LIB_MMPA`.
534
+ *
535
+ * @param minCuts minimum number of cuts
536
+ * @param maxCuts maximum number of cuts
537
+ * @param maxCutBonds maximum number of bonds that can be cut
538
+ */
539
+ get_mmpa_frags(minCuts: number, maxCuts: number, maxCutBonds: number): {
540
+ cores: MolList;
541
+ sidechains: MolList;
542
+ };
503
543
  }
504
544
  interface JSReaction extends Pick<JSMol, 'delete' | 'draw_to_canvas' | 'draw_to_canvas_with_highlights' | 'get_svg' | 'get_svg_with_highlights'> {
505
545
  is_Deleted(): boolean;
@@ -559,7 +599,7 @@ interface SubstructLibrary {
559
599
  *
560
600
  * @param i index of the molecule
561
601
  */
562
- get_pattern_fp(i: number): Uint8Array;
602
+ get_pattern_fp_as_uint8array(i: number): Uint8Array;
563
603
 
564
604
  /**
565
605
  * Get a molecule from the library
@@ -608,6 +648,29 @@ interface SubstructLibrary {
608
648
  * @param numThreads number of threads to use
609
649
  */
610
650
  count_matches(q: JSMol, useChirality: boolean, numThreads: number): number;
651
+
652
+ /** Return the number of molecules in the library */
653
+ size(): number;
654
+
655
+ /**
656
+ * Get all molecules from the library matching the substructure query.
657
+ * Returns matching indices as a Uint32Array (more efficient than `get_matches`).
658
+ *
659
+ * @param q query molecule
660
+ */
661
+ get_matches_as_uint32array(q: JSMol): Uint32Array;
662
+ /**
663
+ * @param q query molecule
664
+ * @param maxResults maximum number of results
665
+ */
666
+ get_matches_as_uint32array(q: JSMol, maxResults: number): Uint32Array;
667
+ /**
668
+ * @param q query molecule
669
+ * @param useChirality set to true to enable chiral substructure searching
670
+ * @param numThreads number of threads to use
671
+ * @param maxResults maximum number of results
672
+ */
673
+ get_matches_as_uint32array(q: JSMol, useChirality: boolean, numThreads: number, maxResults: number): Uint32Array;
611
674
  }
612
675
  interface MolList {
613
676
  /**
@@ -676,6 +739,7 @@ interface StringList extends EmscriptenVector<string> {}
676
739
  /** Returns a new SubstructLibrary instance */
677
740
  interface SubstructLibraryConstructor {
678
741
  new (): SubstructLibrary;
742
+ new (initialCapacity: number): SubstructLibrary;
679
743
  }
680
744
  interface MolListConstructor {
681
745
  new (): MolList;
@@ -1061,9 +1125,9 @@ type RDKitDepictionDetails = {
1061
1125
  forceCoords: boolean;
1062
1126
  /** Draw wavy bonds for double bonds with unspecified stereo */
1063
1127
  wavyBonds: boolean;
1064
- /** Return atom drawing coordinates in the output JSON
1128
+ /** Return atom drawing coordinates in the output JSON
1065
1129
  * IMPORTANT: this changes the output format in the case of get_svg...()
1066
- */
1130
+ */
1067
1131
  returnDrawCoords: boolean;
1068
1132
  };
1069
1133
  type RDKitRxnDepictionDetails = RDKitDepictionDetails & {
@@ -1370,6 +1434,42 @@ type RDKitGetUint8ArrayOptions = {
1370
1434
  */
1371
1435
  properties: PropertyPickleOptionsKeys[];
1372
1436
  };
1437
+ type RDKitConfigureOptions = {
1438
+ /** Switch between RDKit's built-in coordinate generator and CoordGen. */
1439
+ preferCoordgen: boolean;
1440
+ /** Use the legacy stereo perception algorithm. */
1441
+ useLegacyStereoPerception: boolean;
1442
+ /** Perceive chirality on non-tetrahedral stereocenters (square-planar, trigonal-bipyramidal, etc.). */
1443
+ allowNonTetrahedralChirality: boolean;
1444
+ /** When true, RDKit error messages also appear in the console (uses set_log_tee).
1445
+ * Default: false (capture-only when a fail listener is set). */
1446
+ enableLogging: boolean;
1447
+ };
1448
+ type RDKitParseOperation = 'getMol' | 'getQMol' | 'getRxn';
1449
+ type RDKitParseErrorEvent = {
1450
+ input: string | Uint8Array;
1451
+ message: string;
1452
+ operation: RDKitParseOperation;
1453
+ };
1454
+ type RDKitFailCallback = (event: RDKitParseErrorEvent) => void;
1455
+ type RDKitEvents = {
1456
+ addErrorListener(callback: RDKitFailCallback): () => void;
1457
+ };
1458
+ type RDKitGetMolOptions = RDKitGetMolOpt & {
1459
+ throwOnError: boolean;
1460
+ };
1461
+ type RDKitGetQMolOptions = {
1462
+ throwOnError: boolean;
1463
+ };
1464
+ type RDKitGetRxnOptions = RDKitRxnDetails & {
1465
+ throwOnError: boolean;
1466
+ };
1467
+ type RDKitCondenseAbbreviationsOptions = {
1468
+ /** @default 0.4 */
1469
+ maxCoverage: number;
1470
+ /** @default false */
1471
+ useLinkers: boolean;
1472
+ };
1373
1473
  //#endregion
1374
1474
  //#region src/fingerprints/fingerprints.types.d.ts
1375
1475
  type FingerprintType = 'Morgan' | 'Pattern' | 'AtomPair' | 'TopologicalTorsion' | 'RDKit' | 'MACCS';
@@ -1548,10 +1648,14 @@ declare class Mol implements Disposable {
1548
1648
  isValid(): boolean;
1549
1649
  /** Returns the number of atoms in the molecule */
1550
1650
  get numAtoms(): number;
1651
+ /** Returns the number of heavy atoms in the molecule (excluding hydrogens and dummy atoms) */
1652
+ get numHeavyAtoms(): number;
1551
1653
  /** Returns the number of bonds in the molecule */
1552
1654
  get numBonds(): number;
1553
1655
  /** Returns 0 if no coords, 2 for 2D, 3 for 3D */
1554
1656
  hasCoords(): 0 | 2 | 3;
1657
+ /** Returns the coordinates of each atom in the molecule as an array of [x, y, z] tuples */
1658
+ getCoords(): [number, number, number][];
1555
1659
  /** Returns stereo tags (CIP codes) for the molecule */
1556
1660
  getStereoTags(): RDKitStereoTags;
1557
1661
  /** Returns the V2000 Molfile representation of the aromatic form */
@@ -1613,10 +1717,7 @@ declare class Mol implements Disposable {
1613
1717
  * Condenses functional group abbreviations in the molecule
1614
1718
  * @param options - Abbreviation options
1615
1719
  */
1616
- condenseAbbreviations(options?: {
1617
- maxCoverage?: number;
1618
- useLinkers?: boolean;
1619
- }): string;
1720
+ condenseAbbreviations(options?: Partial<RDKitCondenseAbbreviationsOptions>): RDKitSubstructMatch;
1620
1721
  drawToCanvas(canvas: HTMLCanvasElement, options?: Partial<RDKitDepictionDetails>): void;
1621
1722
  /**
1622
1723
  * Returns the disconnected fragments of the molecule
@@ -1630,9 +1731,13 @@ declare class Mol implements Disposable {
1630
1731
  fragToAtoms: number[][];
1631
1732
  };
1632
1733
  mols: MolArray;
1734
+ delete: () => void;
1735
+ [Symbol.dispose](): void;
1633
1736
  };
1634
1737
  /** Returns a copy of the molecule */
1635
1738
  copy(): Mol;
1739
+ /** Returns true if the underlying C++ object has been deleted */
1740
+ get isDeleted(): boolean;
1636
1741
  /**
1637
1742
  * Deletes the underlying C++ molecule object from memory.
1638
1743
  *
@@ -1715,7 +1820,7 @@ declare const computeFingerprintSimilarity: (a: Fingerprint, b: Fingerprint, met
1715
1820
  //#endregion
1716
1821
  //#region src/rdkit.d.ts
1717
1822
  /** Result of a Maximum Common Substructure (MCS) computation */
1718
- interface MCSResult {
1823
+ interface MCSResult extends Disposable {
1719
1824
  numAtoms: number;
1720
1825
  numBonds: number;
1721
1826
  canceled: boolean;
@@ -1729,6 +1834,7 @@ interface MCSResult {
1729
1834
  * object (via `.delete()` or `using`) to avoid memory leaks.
1730
1835
  */
1731
1836
  get qmol(): Mol | null;
1837
+ delete(): void;
1732
1838
  }
1733
1839
  /**
1734
1840
  * The main RDKit wrapper providing a typed, camelCase API over the WASM module.
@@ -1743,6 +1849,7 @@ interface MCSResult {
1743
1849
  */
1744
1850
  declare class RDKit {
1745
1851
  #private;
1852
+ readonly events: RDKitEvents;
1746
1853
  /** @internal */
1747
1854
  constructor(mod: RDKitModule);
1748
1855
  /**
@@ -1750,16 +1857,22 @@ declare class RDKit {
1750
1857
  *
1751
1858
  * @param input - SMILES, SMARTS, MolFile, or JSON string
1752
1859
  * @param options - Molecule parsing options
1753
- * @returns A Mol instance, or null if the input is invalid
1860
+ * @returns A Mol instance, or null if the input is invalid.
1861
+ * Pass `{ throwOnError: true }` to throw a {@link RDKitParseError} instead.
1754
1862
  */
1755
- getMol(input: string | Uint8Array, options?: Partial<RDKitGetMolOpt>): Mol | null;
1863
+ getMol(input: string | Uint8Array, options?: Partial<RDKitGetMolOptions> & {
1864
+ throwOnError: true;
1865
+ }): Mol;
1756
1866
  /**
1757
1867
  * Creates a query molecule from a SMARTS string.
1758
1868
  *
1759
1869
  * @param input - SMARTS string
1760
- * @returns A Mol instance, or null if the input is invalid
1870
+ * @returns A Mol instance, or null if the input is invalid.
1871
+ * Pass `{ throwOnError: true }` to throw a {@link RDKitParseError} instead.
1761
1872
  */
1762
- getQMol(input: string): Mol | null;
1873
+ getQMol(input: string, options?: Partial<RDKitGetQMolOptions> & {
1874
+ throwOnError: true;
1875
+ }): Mol;
1763
1876
  /**
1764
1877
  * Computes the Maximum Common Substructure (MCS) of a set of molecules.
1765
1878
  *
@@ -1773,9 +1886,12 @@ declare class RDKit {
1773
1886
  *
1774
1887
  * @param input - Reaction SMARTS, SMILES, or RXN block string
1775
1888
  * @param options - Reaction parsing options
1776
- * @returns A Reaction instance, or null if the input is invalid
1889
+ * @returns A Reaction instance, or null if the input is invalid.
1890
+ * Pass `{ throwOnError: true }` to throw a {@link RDKitParseError} instead.
1777
1891
  */
1778
- getRxn(input: string, options?: Partial<RDKitRxnDetails>): Reaction | null;
1892
+ getRxn(input: string, options: Partial<RDKitGetRxnOptions> & {
1893
+ throwOnError: true;
1894
+ }): Reaction;
1779
1895
  /**
1780
1896
  * Performs R-Group Decomposition on a set of molecules against one or more cores.
1781
1897
  *
@@ -1792,6 +1908,12 @@ declare class RDKit {
1792
1908
  getRGD(core: string | string[] | Mol | Mol[], molecules: string[] | Mol[], options?: Partial<RDKitGetRgdOptions>): RGDRow[] | null;
1793
1909
  molzip(mol1: Mol, mol2: Mol): Mol | null;
1794
1910
  computeFingerprintsSimilarity(...args: Parameters<typeof computeFingerprintSimilarity>): number;
1911
+ /**
1912
+ * Applies global configuration options to the RDKit module.
1913
+ *
1914
+ * @param options - One or more options to configure
1915
+ */
1916
+ configure(options: Partial<RDKitConfigureOptions>): void;
1795
1917
  /** Returns the RDKit version string */
1796
1918
  get version(): string;
1797
1919
  /** The underlying RDKitModule for direct access to the raw API */
@@ -1839,4 +1961,30 @@ interface InitRDKitOptions {
1839
1961
  declare function initRDKit(options?: Partial<InitRDKitOptions>): Promise<RDKit>;
1840
1962
  declare function initRDKit<T extends typeof RDKit>(options: Partial<InitRDKitOptions> | undefined, constructor: T): Promise<InstanceType<T>>;
1841
1963
  //#endregion
1842
- export { type ColourPalette, type DrawColour, Fingerprint, type InitRDKitOptions, type JSMol, type JSReaction, type MCSResult, Mol, MolArray, type MolList, RDKit, type RDKitAlignedCoordsOptions, type RDKitAtomPairFPOptions, type RDKitDepictionDetails, type RDKitDescriptors, type RDKitGetMCSOptions, type RDKitGetMolBlockOptions, type RDKitGetMolOpt, type RDKitGetRgdOptions, type RDKitGetSmilesOptions, type RDKitJson, type RDKitJsonAtom, type RDKitJsonBond, type RDKitJsonConformer2D, type RDKitJsonConformer3D, type RDKitJsonExtension, type RDKitJsonMolecule, type RDKitMCSResult, type RDKitModule, type RDKitMorganFPOptions, type RDKitPatternFPOptions, type RDKitRdkitFpOptions, type RDKitRemoveHsOptions, type RDKitRxnDetails, type RDKitStereoTags, type RDKitSubstructMatch, type RDKitTopologicalTorsionFPOptions, type RGDRow, Reaction, initRDKit };
1964
+ //#region src/logger.d.ts
1965
+ declare class RDKitParseError extends Error {
1966
+ readonly input: string | Uint8Array;
1967
+ readonly rdkitMessage: string;
1968
+ constructor(input: string | Uint8Array, rdkitMessage: string);
1969
+ }
1970
+ /**
1971
+ * Type guard for RDKitParseError.
1972
+ * @param error The error to check.
1973
+ * @returns True if the error is an instance of RDKitParseError, false otherwise.
1974
+ * @example
1975
+ * ```ts
1976
+ * try {
1977
+ * rdkit.getMol('invalid input', { throwOnError: true });
1978
+ * } catch (e) {
1979
+ * if (isRDKitParseError(e)) {
1980
+ * console.error('Parsing failed for input:', e.input);
1981
+ * console.error('RDKit message:', e.rdkitMessage);
1982
+ * } else {
1983
+ * console.error('Unexpected error:', e);
1984
+ * }
1985
+ * }
1986
+ * ```
1987
+ */
1988
+ declare const isRDKitParseError: (error: unknown) => error is RDKitParseError;
1989
+ //#endregion
1990
+ export { type ColourPalette, type DrawColour, Fingerprint, type InitRDKitOptions, type JSMol, type JSReaction, type MCSResult, Mol, MolArray, type MolList, RDKit, type RDKitAlignedCoordsOptions, type RDKitAtomPairFPOptions, type RDKitConfigureOptions, type RDKitDepictionDetails, type RDKitDescriptors, type RDKitEvents, type RDKitFailCallback, type RDKitGetMCSOptions, type RDKitGetMolBlockOptions, type RDKitGetMolOpt, type RDKitGetMolOptions, type RDKitGetQMolOptions, type RDKitGetRgdOptions, type RDKitGetRxnOptions, type RDKitGetSmilesOptions, type RDKitJson, type RDKitJsonAtom, type RDKitJsonBond, type RDKitJsonConformer2D, type RDKitJsonConformer3D, type RDKitJsonExtension, type RDKitJsonMolecule, type RDKitMCSResult, type RDKitModule, type RDKitMorganFPOptions, RDKitParseError, type RDKitParseErrorEvent, type RDKitParseOperation, type RDKitPatternFPOptions, type RDKitRdkitFpOptions, type RDKitRemoveHsOptions, type RDKitRxnDetails, type RDKitStereoTags, type RDKitSubstructMatch, type RDKitTopologicalTorsionFPOptions, type RGDRow, Reaction, initRDKit, isRDKitParseError };
package/dist/index.js CHANGED
@@ -3890,6 +3890,11 @@ function fromStringArraytoMolList(mols, module$1, isQuery = false) {
3890
3890
  }
3891
3891
  const isMolArray = (arr) => arr.length > 0 && arr[0] instanceof Mol;
3892
3892
 
3893
+ //#endregion
3894
+ //#region src/abbreviations/abbreviations.ts
3895
+ const DEFAULT_MAX_COVERAGE = .4;
3896
+ const DEFAULT_USE_LINKERS = false;
3897
+
3893
3898
  //#endregion
3894
3899
  //#region src/formats/cxsmiles.ts
3895
3900
  /**
@@ -4255,6 +4260,10 @@ var Mol = class Mol {
4255
4260
  get numAtoms() {
4256
4261
  return this.jsMol.get_num_atoms();
4257
4262
  }
4263
+ /** Returns the number of heavy atoms in the molecule (excluding hydrogens and dummy atoms) */
4264
+ get numHeavyAtoms() {
4265
+ return this.jsMol.get_num_atoms(true);
4266
+ }
4258
4267
  /** Returns the number of bonds in the molecule */
4259
4268
  get numBonds() {
4260
4269
  return this.jsMol.get_num_bonds();
@@ -4263,6 +4272,10 @@ var Mol = class Mol {
4263
4272
  hasCoords() {
4264
4273
  return this.jsMol.has_coords();
4265
4274
  }
4275
+ /** Returns the coordinates of each atom in the molecule as an array of [x, y, z] tuples */
4276
+ getCoords() {
4277
+ return this.jsMol.get_coords();
4278
+ }
4266
4279
  /** Returns stereo tags (CIP codes) for the molecule */
4267
4280
  getStereoTags() {
4268
4281
  return JSON.parse(this.jsMol.get_stereo_tags());
@@ -4373,10 +4386,9 @@ var Mol = class Mol {
4373
4386
  */
4374
4387
  condenseAbbreviations(options) {
4375
4388
  const mol = this.jsMol;
4376
- if (!options) return mol.condense_abbreviations();
4377
- const { maxCoverage, useLinkers } = options;
4378
- if (maxCoverage !== void 0 && useLinkers !== void 0) return mol.condense_abbreviations(maxCoverage, useLinkers);
4379
- return mol.condense_abbreviations();
4389
+ const { maxCoverage = DEFAULT_MAX_COVERAGE, useLinkers = DEFAULT_USE_LINKERS } = options ?? {};
4390
+ const raw = mol.condense_abbreviations(maxCoverage, useLinkers);
4391
+ return JSON.parse(raw);
4380
4392
  }
4381
4393
  drawToCanvas(canvas, options) {
4382
4394
  const mol = this.jsMol;
@@ -4403,13 +4415,21 @@ var Mol = class Mol {
4403
4415
  atomToFrag: parsed.frags,
4404
4416
  fragToAtoms: parsed.fragsMolAtomMapping
4405
4417
  },
4406
- mols
4418
+ mols,
4419
+ delete: () => mols.delete(),
4420
+ [Symbol.dispose]() {
4421
+ mols.delete();
4422
+ }
4407
4423
  };
4408
4424
  }
4409
4425
  /** Returns a copy of the molecule */
4410
4426
  copy() {
4411
4427
  return new Mol(this.jsMol.copy(), this.#module);
4412
4428
  }
4429
+ /** Returns true if the underlying C++ object has been deleted */
4430
+ get isDeleted() {
4431
+ return this.#jsMol === null || this.#jsMol.isDeleted();
4432
+ }
4413
4433
  /**
4414
4434
  * Deletes the underlying C++ molecule object from memory.
4415
4435
  *
@@ -4531,6 +4551,23 @@ var Reaction = class {
4531
4551
  //#endregion
4532
4552
  //#region src/rgd.ts
4533
4553
  /**
4554
+ * The result of an R-Group Decomposition, as an array of {@link RGDRow} with
4555
+ * batch lifecycle management.
4556
+ *
4557
+ * Call {@link delete} (or use the `using` keyword) to delete every `Mol`
4558
+ * in all rows at once.
4559
+ */
4560
+ var RGDResult = class extends Array {
4561
+ /** Deletes every non-deleted Mol across all rows */
4562
+ delete() {
4563
+ for (const row of this) for (const mol of Object.values(row)) if (!mol.isDeleted) mol.delete();
4564
+ }
4565
+ /** Disposable support — allows use with the `using` keyword */
4566
+ [Symbol.dispose]() {
4567
+ this.delete();
4568
+ }
4569
+ };
4570
+ /**
4534
4571
  * Performs R-Group Decomposition on a set of molecules against one or more cores.
4535
4572
  *
4536
4573
  * This is a one-shot helper that handles all the boilerplate of the raw RDKit
@@ -4572,16 +4609,116 @@ function decomposeRGroups(core, molecules, options, module$1) {
4572
4609
  jsMol?.delete();
4573
4610
  }
4574
4611
  rgd.process();
4575
- const result = rgd.get_rgroups_as_rows().map((row) => {
4612
+ const rawRows = rgd.get_rgroups_as_rows();
4613
+ const result = new RGDResult();
4614
+ for (const row of rawRows) {
4576
4615
  const wrappedRow = {};
4577
4616
  for (const [label, jsMol] of Object.entries(row)) wrappedRow[label] = new Mol(jsMol, module$1);
4578
- return wrappedRow;
4579
- });
4617
+ result.push(wrappedRow);
4618
+ }
4580
4619
  rgd.delete();
4581
4620
  if (deleteCore) resolvedCore.delete();
4582
4621
  return result;
4583
4622
  }
4584
4623
 
4624
+ //#endregion
4625
+ //#region src/logger.ts
4626
+ var RDKitParseError = class extends Error {
4627
+ input;
4628
+ rdkitMessage;
4629
+ constructor(input, rdkitMessage) {
4630
+ const preview = input instanceof Uint8Array ? `<Uint8Array length=${input.length}>` : input.length > 80 ? `${input.slice(0, 80)}…` : input;
4631
+ super(`RDKit failed to parse: ${preview}${rdkitMessage ? `\n${rdkitMessage}` : ""}`);
4632
+ this.name = "RDKitParseError";
4633
+ this.input = input;
4634
+ this.rdkitMessage = rdkitMessage;
4635
+ }
4636
+ };
4637
+ /**
4638
+ * Type guard for RDKitParseError.
4639
+ * @param error The error to check.
4640
+ * @returns True if the error is an instance of RDKitParseError, false otherwise.
4641
+ * @example
4642
+ * ```ts
4643
+ * try {
4644
+ * rdkit.getMol('invalid input', { throwOnError: true });
4645
+ * } catch (e) {
4646
+ * if (isRDKitParseError(e)) {
4647
+ * console.error('Parsing failed for input:', e.input);
4648
+ * console.error('RDKit message:', e.rdkitMessage);
4649
+ * } else {
4650
+ * console.error('Unexpected error:', e);
4651
+ * }
4652
+ * }
4653
+ * ```
4654
+ */
4655
+ const isRDKitParseError = (error) => {
4656
+ return error instanceof Error && error.name === "RDKitParseError" && "input" in error && "rdkitMessage" in error;
4657
+ };
4658
+ /**
4659
+ * RDKitLogger manages RDKit error capture and dispatch to listeners, as well as optional console logging.
4660
+ */
4661
+ var RDKitLogger = class {
4662
+ #mod;
4663
+ #capture = null;
4664
+ #callback = null;
4665
+ #enableLogging = false;
4666
+ #throwOnError = false;
4667
+ constructor(mod) {
4668
+ this.#mod = mod;
4669
+ }
4670
+ #activate() {
4671
+ if (this.#capture) return;
4672
+ this.#capture = (this.#enableLogging ? this.#mod.set_log_tee : this.#mod.set_log_capture)("rdApp.error") ?? null;
4673
+ }
4674
+ /**
4675
+ * Called from configure({ enableLogging }). Switches between tee and capture
4676
+ * if already active; otherwise applies enable/disable_logging for the no-capture case.
4677
+ */
4678
+ setEnableLogging(enable) {
4679
+ this.#enableLogging = enable;
4680
+ if (this.#capture) {
4681
+ this.#capture.delete();
4682
+ this.#capture = null;
4683
+ this.#activate();
4684
+ } else enable ? this.#mod.enable_logging("rdApp.error") : this.#mod.disable_logging("rdApp.error");
4685
+ }
4686
+ /** Single callback slot — replaces any previous. Returns cleanup function. */
4687
+ addCallback(fn) {
4688
+ this.#callback = fn;
4689
+ this.#activate();
4690
+ return () => {
4691
+ if (this.#callback === fn) this.#callback = null;
4692
+ };
4693
+ }
4694
+ /**
4695
+ * Call before each WASM parse operation.
4696
+ * Stores throwOnError state, activates capture if needed, clears the buffer.
4697
+ * Fast path: no-op when neither throwOnError nor capture is active.
4698
+ */
4699
+ reset(throwOnError) {
4700
+ this.#throwOnError = throwOnError;
4701
+ if (!throwOnError && !this.#capture) return;
4702
+ if (throwOnError) this.#activate();
4703
+ this.#capture?.clear_buffer();
4704
+ }
4705
+ /**
4706
+ * Call on null return from WASM. Reads buffer, fires callback, throws if throwOnError.
4707
+ * No-op when reset() took the fast path (capture still null).
4708
+ */
4709
+ handleError(input, operation) {
4710
+ if (!this.#capture) return;
4711
+ const message = this.#capture.get_buffer().trim();
4712
+ this.#capture.clear_buffer();
4713
+ this.#callback?.({
4714
+ input,
4715
+ message,
4716
+ operation
4717
+ });
4718
+ if (this.#throwOnError) throw new RDKitParseError(input, message);
4719
+ }
4720
+ };
4721
+
4585
4722
  //#endregion
4586
4723
  //#region src/rdkit.ts
4587
4724
  /**
@@ -4597,35 +4734,36 @@ function decomposeRGroups(core, molecules, options, module$1) {
4597
4734
  */
4598
4735
  var RDKit = class {
4599
4736
  #mod;
4737
+ #logger;
4738
+ events;
4600
4739
  /** @internal */
4601
4740
  constructor(mod) {
4602
4741
  this.#mod = mod;
4742
+ this.#logger = new RDKitLogger(mod);
4743
+ this.events = { addErrorListener: (cb) => this.#logger.addCallback(cb) };
4603
4744
  }
4604
- /**
4605
- * Creates a molecule from a variety of input formats.
4606
- *
4607
- * @param input - SMILES, SMARTS, MolFile, or JSON string
4608
- * @param options - Molecule parsing options
4609
- * @returns A Mol instance, or null if the input is invalid
4610
- */
4611
4745
  getMol(input, options) {
4746
+ const { throwOnError = false, ...wasmOptions } = options ?? {};
4747
+ this.#logger.reset(throwOnError);
4612
4748
  let jsMol;
4613
4749
  if (input instanceof Uint8Array) {
4614
4750
  if (options) console.warn("Options are ignored when getMol is called with a binary input (pikkle).");
4615
4751
  jsMol = this.#mod.get_mol_from_uint8array(input);
4616
- } else jsMol = options ? this.#mod.get_mol(input, JSON.stringify(options)) : this.#mod.get_mol(input);
4617
- if (!jsMol) return null;
4752
+ } else jsMol = Object.keys(wasmOptions).length > 0 ? this.#mod.get_mol(input, JSON.stringify(wasmOptions)) : this.#mod.get_mol(input);
4753
+ if (!jsMol) {
4754
+ this.#logger.handleError(input, "getMol");
4755
+ return null;
4756
+ }
4618
4757
  return new Mol(jsMol, this.#mod);
4619
4758
  }
4620
- /**
4621
- * Creates a query molecule from a SMARTS string.
4622
- *
4623
- * @param input - SMARTS string
4624
- * @returns A Mol instance, or null if the input is invalid
4625
- */
4626
- getQMol(input) {
4759
+ getQMol(input, options) {
4760
+ const { throwOnError = false } = options ?? {};
4761
+ this.#logger.reset(throwOnError);
4627
4762
  const jsMol = this.#mod.get_qmol(input);
4628
- if (!jsMol) return null;
4763
+ if (!jsMol) {
4764
+ this.#logger.handleError(input, "getQMol");
4765
+ return null;
4766
+ }
4629
4767
  return new Mol(jsMol, this.#mod);
4630
4768
  }
4631
4769
  /**
@@ -4661,24 +4799,29 @@ var RDKit = class {
4661
4799
  const jsMol = mod.get_qmol(s);
4662
4800
  cachedQmol = jsMol ? new Mol(jsMol, mod) : null;
4663
4801
  return cachedQmol;
4802
+ },
4803
+ delete() {
4804
+ if (cachedQmol && !cachedQmol.isDeleted) cachedQmol.delete();
4805
+ },
4806
+ [Symbol.dispose]() {
4807
+ if (cachedQmol && !cachedQmol.isDeleted) cachedQmol.delete();
4664
4808
  }
4665
4809
  };
4666
4810
  }
4667
- /**
4668
- * Creates a Reaction from a reaction SMARTS, SMILES, or RXN block.
4669
- *
4670
- * @param input - Reaction SMARTS, SMILES, or RXN block string
4671
- * @param options - Reaction parsing options
4672
- * @returns A Reaction instance, or null if the input is invalid
4673
- */
4674
4811
  getRxn(input, options) {
4812
+ const { throwOnError = false, ...wasmOptions } = options ?? {};
4813
+ this.#logger.reset(throwOnError);
4814
+ let jsRxn = null;
4675
4815
  try {
4676
- const jsRxn = options ? this.#mod.get_rxn(input, JSON.stringify(options)) : this.#mod.get_rxn(input);
4677
- if (!jsRxn) return null;
4678
- return new Reaction(jsRxn, this.#mod);
4816
+ jsRxn = Object.keys(wasmOptions).length > 0 ? this.#mod.get_rxn(input, JSON.stringify(wasmOptions)) : this.#mod.get_rxn(input);
4679
4817
  } catch {
4818
+ jsRxn = null;
4819
+ }
4820
+ if (!jsRxn) {
4821
+ this.#logger.handleError(input, "getRxn");
4680
4822
  return null;
4681
4823
  }
4824
+ return new Reaction(jsRxn, this.#mod);
4682
4825
  }
4683
4826
  /**
4684
4827
  * Performs R-Group Decomposition on a set of molecules against one or more cores.
@@ -4704,6 +4847,18 @@ var RDKit = class {
4704
4847
  computeFingerprintsSimilarity(...args) {
4705
4848
  return computeFingerprintSimilarity(...args);
4706
4849
  }
4850
+ /**
4851
+ * Applies global configuration options to the RDKit module.
4852
+ *
4853
+ * @param options - One or more options to configure
4854
+ */
4855
+ configure(options) {
4856
+ const { preferCoordgen, useLegacyStereoPerception, allowNonTetrahedralChirality, enableLogging } = options;
4857
+ if (preferCoordgen !== void 0) this.#mod.prefer_coordgen(preferCoordgen);
4858
+ if (useLegacyStereoPerception !== void 0) this.#mod.use_legacy_stereo_perception(useLegacyStereoPerception);
4859
+ if (allowNonTetrahedralChirality !== void 0) this.#mod.allow_non_tetrahedral_chirality(allowNonTetrahedralChirality);
4860
+ if (enableLogging !== void 0) this.#logger.setEnableLogging(enableLogging);
4861
+ }
4707
4862
  /** Returns the RDKit version string */
4708
4863
  get version() {
4709
4864
  return this.#mod.version();
@@ -4743,4 +4898,4 @@ async function initRDKit(options, constructor = RDKit) {
4743
4898
  }
4744
4899
 
4745
4900
  //#endregion
4746
- export { Fingerprint, Mol, MolArray, RDKit, Reaction, initRDKit };
4901
+ export { Fingerprint, Mol, MolArray, RDKit, RDKitParseError, Reaction, initRDKit, isRDKitParseError };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "rdkit-esm",
3
- "version": "0.4.3",
3
+ "version": "0.5.0-rc.0",
4
4
  "description": "RDKit minimal lib for the modern web.",
5
5
  "homepage": "https://github.com/tandemai/rdkit-esm#readme",
6
6
  "bugs": {