@gcszhn/mol4agent-core 0.1.0 → 0.2.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.
package/README.md CHANGED
@@ -28,6 +28,9 @@ core: createPluginUI -> Mol* state tree -> commands -> capture
28
28
  - Commands are JSON-serializable; **loading is a method, not a command**, because
29
29
  adapter-owned bytes may not be serializable.
30
30
  - `@gcszhn/mol4agent-core/parse` is pure and works in Node and the browser.
31
+ - `@gcszhn/mol4agent-core/sources` is pure too: it turns an entry id into a
32
+ download plan (`url`, optional JSON `indexField`, format, file name). Network
33
+ access and file writes stay in the adapter.
31
34
 
32
35
  ## Install
33
36
 
@@ -37,10 +40,10 @@ pnpm add @gcszhn/mol4agent-core molstar
37
40
  pnpm add react
38
41
  ```
39
42
 
40
- The package is not published to npm yet; from this monorepo use the workspace
41
- link. The command above applies once `0.1.0` is published. `molstar` and `react`
42
- are peer dependencies. The DSH adapter bundles Mol* into a single client script;
43
- a plain web app can use the package directly.
43
+ The package is published on npm as `@gcszhn/mol4agent-core@0.2.0`; inside this
44
+ monorepo, pnpm links the workspace copy instead. `molstar` and `react` are peer
45
+ dependencies. The DSH adapter bundles Mol* into a single client script; a plain
46
+ web app can use the package directly.
44
47
 
45
48
  Build and pack:
46
49
 
@@ -57,9 +60,10 @@ Package `exports` point at `lib`, and the npm `files` allowlist includes only
57
60
 
58
61
  | Import | Exports |
59
62
  |---|---|
60
- | `@gcszhn/mol4agent-core` | `createMolViewer`, protocol types, format helpers, `summarizeStructure`, `compileSelector`, `selectorSchema` |
63
+ | `@gcszhn/mol4agent-core` | `createMolViewer`, protocol types, format helpers, source helpers, `summarizeStructure`, `compileSelector`, `selectorSchema` |
61
64
  | `@gcszhn/mol4agent-core/protocol` | `MOL_FORMATS`, `StructureData`, `MolCommand`, `StructureSelector`, `StructureSummary`, `Mol4AgentError`, and the `isMolFormat` / `isStructureData` / `isMolCommandOp` / `isPresetName` guards |
62
65
  | `@gcszhn/mol4agent-core/parse` | `summarizeStructure`, `summarizePdbLike`, `summarizeCif`, `summarizeSdf`, `summarizeMol2`, `summarizeXyz`, `summarizeGro` |
66
+ | `@gcszhn/mol4agent-core/sources` | `SOURCE_DATABASES`, `SOURCE_DATABASE_INFO`, `resolveSource`, `normalizeSourceDb`, `readSourceIndexField`, and the `isSourceDatabase` guard |
63
67
  | `@gcszhn/mol4agent-core/react` | `Mol4AgentViewer`, `Mol4AgentViewerHandle`, `Mol4AgentScene` |
64
68
 
65
69
  ## `createMolViewer`
@@ -205,7 +209,7 @@ type CommandResult =
205
209
 
206
210
  Error codes: `INVALID_COMMAND`, `UNSUPPORTED_FORMAT`, `UNSUPPORTED_REPRESENTATION`,
207
211
  `REPRESENT_FAILED`, `NO_STRUCTURE`, `LOAD_FAILED`, `CAPTURE_FAILED`,
208
- `SUMMARY_UNSUPPORTED`, `DISPOSED`.
212
+ `SUMMARY_UNSUPPORTED`, `UNSUPPORTED_SOURCE`, `INVALID_ENTRY_ID`, `DISPOSED`.
209
213
 
210
214
  ## Selectors
211
215
 
@@ -272,6 +276,44 @@ BCIF can be rendered but not summarized from raw bytes yet; `summarizeStructure`
272
276
  throws `SUMMARY_UNSUPPORTED`. A post-load viewer fallback may still expose
273
277
  `complete: false`.
274
278
 
279
+ ## Database sources
280
+
281
+ `mol_fetch` starts from an entry id instead of a local file. Core validates the
282
+ id and returns a download plan; it never performs the request or writes a file.
283
+ Adapters execute the plan with their own HTTPS and filesystem APIs.
284
+
285
+ ```ts
286
+ import { resolveSource } from '@gcszhn/mol4agent-core/sources'
287
+
288
+ resolveSource({ entryId: '1crn' })
289
+ // { sourceDb: 'rcsb-pdb', entryId: '1CRN', format: 'pdb',
290
+ // fileName: '1CRN.pdb',
291
+ // plan: { url: 'https://files.rcsb.org/download/1CRN.pdb' },
292
+ // description: 'RCSB PDB entry 1CRN (PDB format)' }
293
+
294
+ resolveSource({ entryId: 'P00533', sourceDb: 'alphafold' })
295
+ // plan: { url: 'https://alphafold.ebi.ac.uk/api/prediction/P00533',
296
+ // indexField: '0.pdbUrl' }
297
+ ```
298
+
299
+ | `source_db` | `entry_id` | Format |
300
+ |---|---|---|
301
+ | `rcsb-pdb` (default) | 4-character PDB id (`1crn`) | `pdb` |
302
+ | `rcsb-cif` | 4-character PDB id (`1crn`) | `mmcif` |
303
+ | `rcsb-bcif` | 4-character PDB id (`1crn`) | `bcif` |
304
+ | `alphafold` | UniProt accession (`P00533`) | `pdb` |
305
+ | `pubchem` | CID (`2244`) or compound name (`aspirin`) | `sdf` |
306
+ | `chembl` | `CHEMBL25`, or a bare number (`25`) | `sdf` |
307
+
308
+ `plan.indexField` marks a JSON index document: the adapter reads that dot path
309
+ and downloads the URL it names. AlphaFold file names are versioned, so
310
+ `0.pdbUrl` skips the API's array wrapper and selects the current PDB URL. Use
311
+ `readSourceIndexField(payload, field)` for that lookup.
312
+
313
+ `SOURCE_DATABASE_INFO` supplies the label, description, entry hint, and format
314
+ for tool descriptions. `normalizeSourceDb` enforces the closed list, and invalid
315
+ ids raise `Mol4AgentError` with `UNSUPPORTED_SOURCE` or `INVALID_ENTRY_ID`.
316
+
275
317
  ## Capture
276
318
 
277
319
  ```ts
@@ -347,8 +389,8 @@ sequenceDiagram
347
389
 
348
390
  ## Status
349
391
 
350
- - `protocol`, `formats`, `parse/*`, `viewer`, `select`, `react` are implemented
351
- and typechecked.
392
+ - `protocol`, `formats`, `parse/*`, `sources`, `viewer`, `select`, `react` are
393
+ implemented and typechecked.
352
394
  - Verified in headless Chrome + SwiftShader with real 1CRN PDB/CIF, 1ATP, and a
353
395
  PubChem aspirin SDF: official UI, load, cartoon/polymer-and-ligand, ligand
354
396
  highlight, focus, and PNG capture.
package/README_zh.md CHANGED
@@ -28,6 +28,9 @@ core: createPluginUI -> Mol* state tree -> commands -> capture
28
28
  - 命令是 JSON 可序列化的;**加载是方法,不是命令**,因为适配包持有的字节
29
29
  不一定可序列化。
30
30
  - `@gcszhn/mol4agent-core/parse` 是纯函数,Node 和浏览器都能用。
31
+ - `@gcszhn/mol4agent-core/sources` 同样是纯函数:把条目 id 变成下载计划
32
+ (`url`、可选的 JSON `indexField`、格式、文件名)。网络和写文件仍由适配包
33
+ 负责。
31
34
 
32
35
  ## 安装
33
36
 
@@ -37,8 +40,8 @@ pnpm add @gcszhn/mol4agent-core molstar
37
40
  pnpm add react
38
41
  ```
39
42
 
40
- 本包尚未发布到 npm;在 monorepo 内先用 workspace link,上面的命令适用于
41
- `0.1.0` 发布之后。`molstar` 和 `react` 是 peer dependencies。DSH 适配包把 Mol*
43
+ 本包已发布到 npm(`@gcszhn/mol4agent-core@0.2.0`);在 monorepo 内 pnpm 会链接
44
+ workspace 版本。`molstar` 和 `react` 是 peer dependencies。DSH 适配包把 Mol*
42
45
  打进单个 client bundle;普通 web 应用可以直接使用本包。
43
46
 
44
47
  构建与打包:
@@ -55,9 +58,10 @@ Package `exports` 指向 `lib`,npm `files` 只包含 `lib` 和 README;`src/`
55
58
 
56
59
  | Import | 导出 |
57
60
  |---|---|
58
- | `@gcszhn/mol4agent-core` | `createMolViewer`、协议类型、format 辅助函数、`summarizeStructure`、`compileSelector`、`selectorSchema` |
61
+ | `@gcszhn/mol4agent-core` | `createMolViewer`、协议类型、format 辅助函数、source 辅助函数、`summarizeStructure`、`compileSelector`、`selectorSchema` |
59
62
  | `@gcszhn/mol4agent-core/protocol` | `MOL_FORMATS`、`StructureData`、`MolCommand`、`StructureSelector`、`StructureSummary`、`Mol4AgentError`,以及 `isMolFormat` / `isStructureData` / `isMolCommandOp` / `isPresetName` 守卫 |
60
63
  | `@gcszhn/mol4agent-core/parse` | `summarizeStructure`、`summarizePdbLike`、`summarizeCif`、`summarizeSdf`、`summarizeMol2`、`summarizeXyz`、`summarizeGro` |
64
+ | `@gcszhn/mol4agent-core/sources` | `SOURCE_DATABASES`、`SOURCE_DATABASE_INFO`、`resolveSource`、`normalizeSourceDb`、`readSourceIndexField`,以及 `isSourceDatabase` 守卫 |
61
65
  | `@gcszhn/mol4agent-core/react` | `Mol4AgentViewer`、`Mol4AgentViewerHandle`、`Mol4AgentScene` |
62
66
 
63
67
  ## `createMolViewer`
@@ -202,7 +206,7 @@ type CommandResult =
202
206
 
203
207
  错误码:`INVALID_COMMAND`、`UNSUPPORTED_FORMAT`、`UNSUPPORTED_REPRESENTATION`、
204
208
  `REPRESENT_FAILED`、`NO_STRUCTURE`、`LOAD_FAILED`、`CAPTURE_FAILED`、
205
- `SUMMARY_UNSUPPORTED`、`DISPOSED`。
209
+ `SUMMARY_UNSUPPORTED`、`UNSUPPORTED_SOURCE`、`INVALID_ENTRY_ID`、`DISPOSED`。
206
210
 
207
211
  ## 选择器
208
212
 
@@ -267,6 +271,43 @@ const summary = summarizeStructure({ data: pdbText, format: 'pdb', label: '1atp.
267
271
  BCIF 可以渲染,但目前不能从 raw bytes 摘要;`summarizeStructure` 会抛
268
272
  `SUMMARY_UNSUPPORTED`。viewer 的兜底摘要仍可能返回 `complete: false`。
269
273
 
274
+ ## 数据库来源
275
+
276
+ `mol_fetch` 从条目 id 而不是本地文件开始。core 只校验 id 并返回下载计划,
277
+ 不发起请求、不写文件;实际请求和落盘由适配包用各自的 HTTPS/文件系统 API
278
+ 完成。
279
+
280
+ ```ts
281
+ import { resolveSource } from '@gcszhn/mol4agent-core/sources'
282
+
283
+ resolveSource({ entryId: '1crn' })
284
+ // { sourceDb: 'rcsb-pdb', entryId: '1CRN', format: 'pdb',
285
+ // fileName: '1CRN.pdb',
286
+ // plan: { url: 'https://files.rcsb.org/download/1CRN.pdb' },
287
+ // description: 'RCSB PDB entry 1CRN (PDB format)' }
288
+
289
+ resolveSource({ entryId: 'P00533', sourceDb: 'alphafold' })
290
+ // plan: { url: 'https://alphafold.ebi.ac.uk/api/prediction/P00533',
291
+ // indexField: '0.pdbUrl' }
292
+ ```
293
+
294
+ | `source_db` | `entry_id` | 格式 |
295
+ |---|---|---|
296
+ | `rcsb-pdb`(默认) | 4 字符 PDB id(`1crn`) | `pdb` |
297
+ | `rcsb-cif` | 4 字符 PDB id(`1crn`) | `mmcif` |
298
+ | `rcsb-bcif` | 4 字符 PDB id(`1crn`) | `bcif` |
299
+ | `alphafold` | UniProt accession(`P00533`) | `pdb` |
300
+ | `pubchem` | CID(`2244`)或化合物名(`aspirin`) | `sdf` |
301
+ | `chembl` | `CHEMBL25`,或纯数字(`25`) | `sdf` |
302
+
303
+ `plan.indexField` 表示这是一个 JSON 索引文档:适配包按点路径取值,再下载其中
304
+ 的 URL。AlphaFold 的文件名带版本号,所以 `0.pdbUrl` 跳过 API 的数组包装并取
305
+ 当前 PDB URL。取该字段可用 `readSourceIndexField(payload, field)`。
306
+
307
+ `SOURCE_DATABASE_INFO` 提供每个来源的 label、描述、entry 提示和格式,供工具
308
+ 描述使用。`normalizeSourceDb` 校验闭集;非法 id 会抛出 `Mol4AgentError`,
309
+ 错误码为 `UNSUPPORTED_SOURCE` 或 `INVALID_ENTRY_ID`。
310
+
270
311
  ## 截图
271
312
 
272
313
  ```ts
@@ -341,8 +382,8 @@ sequenceDiagram
341
382
 
342
383
  ## 状态
343
384
 
344
- - `protocol`、`formats`、`parse/*`、`viewer`、`select`、`react` 均已实现并通过
345
- typecheck。
385
+ - `protocol`、`formats`、`parse/*`、`sources`、`viewer`、`select`、`react` 均已
386
+ 实现并通过 typecheck。
346
387
  - 在 headless Chrome + SwiftShader 下用真实 1CRN PDB/CIF、1ATP 和 PubChem
347
388
  aspirin SDF 验证过:官方 UI、加载、cartoon/polymer-and-ligand、配体高亮、
348
389
  聚焦和 PNG 截图。
package/lib/index.d.ts CHANGED
@@ -8,6 +8,7 @@
8
8
  */
9
9
  export * from './protocol.ts';
10
10
  export * from './formats.ts';
11
+ export * from './sources.ts';
11
12
  export { summarizeStructure } from './parse/index.ts';
12
13
  export { createMolViewer } from './viewer.ts';
13
14
  export type { MolViewer, MolViewerOptions } from './viewer.ts';
package/lib/index.js CHANGED
@@ -8,6 +8,7 @@
8
8
  */
9
9
  export * from "./protocol.js";
10
10
  export * from "./formats.js";
11
+ export * from "./sources.js";
11
12
  export { summarizeStructure } from "./parse/index.js";
12
13
  export { createMolViewer } from "./viewer.js";
13
14
  export { compileSelector, selectorSchema } from "./select.js";
package/lib/protocol.d.ts CHANGED
@@ -138,7 +138,7 @@ export type MolCommand = {
138
138
  readonly target: StructureSelector;
139
139
  readonly text?: string;
140
140
  };
141
- export type Mol4AgentErrorCode = 'INVALID_COMMAND' | 'UNSUPPORTED_FORMAT' | 'UNSUPPORTED_REPRESENTATION' | 'REPRESENT_FAILED' | 'NO_STRUCTURE' | 'LOAD_FAILED' | 'CAPTURE_FAILED' | 'SUMMARY_UNSUPPORTED' | 'DISPOSED';
141
+ export type Mol4AgentErrorCode = 'INVALID_COMMAND' | 'UNSUPPORTED_FORMAT' | 'UNSUPPORTED_REPRESENTATION' | 'REPRESENT_FAILED' | 'NO_STRUCTURE' | 'LOAD_FAILED' | 'CAPTURE_FAILED' | 'UNSUPPORTED_SOURCE' | 'INVALID_ENTRY_ID' | 'SUMMARY_UNSUPPORTED' | 'DISPOSED';
142
142
  /** Structured failure. Tools turn this into model-facing text instead of a stack trace. */
143
143
  export declare class Mol4AgentError extends Error {
144
144
  readonly code: Mol4AgentErrorCode;
@@ -0,0 +1,65 @@
1
+ /**
2
+ * Online structure sources for `mol_fetch`.
3
+ *
4
+ * Core decides what an entry id means and where its bytes live. It never
5
+ * downloads anything: network access, filesystem writes, authorization, and
6
+ * session state belong to the adapter, which executes the returned plan.
7
+ *
8
+ * @module @gcszhn/mol4agent-core/sources
9
+ */
10
+ import { type MolFormat } from './protocol.ts';
11
+ /** Databases `mol_fetch` can download from. The first is the default. */
12
+ export declare const SOURCE_DATABASES: readonly ["rcsb-pdb", "rcsb-cif", "rcsb-bcif", "alphafold", "pubchem", "chembl"];
13
+ export type SourceDatabase = (typeof SOURCE_DATABASES)[number];
14
+ /** Stable, model-facing facts about one source database. */
15
+ export interface SourceDatabaseInfo {
16
+ readonly label: string;
17
+ readonly description: string;
18
+ /** What `entry_id` must contain for this source. */
19
+ readonly entryHint: string;
20
+ readonly format: MolFormat;
21
+ }
22
+ export declare const SOURCE_DATABASE_INFO: Readonly<Record<SourceDatabase, SourceDatabaseInfo>>;
23
+ /**
24
+ * How an adapter obtains the bytes.
25
+ *
26
+ * `url` is either the file itself or, when `indexField` is set, a JSON index
27
+ * document. In the latter case the adapter reads `indexField` (a dot path such
28
+ * as `0.pdbUrl`) from that document and downloads the URL it names.
29
+ */
30
+ export interface SourceFetchPlan {
31
+ readonly url: string;
32
+ readonly indexField?: string;
33
+ }
34
+ /** One `mol_fetch` request, before the adapter touches the network. */
35
+ export interface SourceRequest {
36
+ readonly entryId: string;
37
+ /** Defaults to `rcsb-pdb`. */
38
+ readonly sourceDb?: SourceDatabase;
39
+ }
40
+ /** A validated download plan. */
41
+ export interface ResolvedSource {
42
+ readonly sourceDb: SourceDatabase;
43
+ /** Normalized entry id, e.g. `1CRN`, `P00533`, or `CHEMBL25`. */
44
+ readonly entryId: string;
45
+ readonly format: MolFormat;
46
+ /** Suggested file name when `target_path` names a directory. */
47
+ readonly fileName: string;
48
+ readonly plan: SourceFetchPlan;
49
+ /** One-line, model-facing description, e.g. `RCSB PDB entry 1CRN (PDB format)`. */
50
+ readonly description: string;
51
+ }
52
+ /** Normalize an agent-supplied source name; `undefined` selects `rcsb-pdb`. */
53
+ export declare function normalizeSourceDb(value: string | undefined): SourceDatabase;
54
+ /** Validate an entry id and build the adapter's fetch plan. */
55
+ export declare function resolveSource(request: SourceRequest): ResolvedSource;
56
+ /**
57
+ * Read a dot path from a JSON index document (numeric segments index arrays).
58
+ *
59
+ * Used by adapters for sources whose file URL is versioned, such as AlphaFold.
60
+ * Returns undefined when the path is missing or is not a string.
61
+ */
62
+ export declare function readSourceIndexField(payload: unknown, field: string): string | undefined;
63
+ export declare function isSourceDatabase(value: unknown): value is SourceDatabase;
64
+ /** Every source database id, in display order. */
65
+ export declare function sourceDatabases(): readonly SourceDatabase[];
package/lib/sources.js ADDED
@@ -0,0 +1,231 @@
1
+ /**
2
+ * Online structure sources for `mol_fetch`.
3
+ *
4
+ * Core decides what an entry id means and where its bytes live. It never
5
+ * downloads anything: network access, filesystem writes, authorization, and
6
+ * session state belong to the adapter, which executes the returned plan.
7
+ *
8
+ * @module @gcszhn/mol4agent-core/sources
9
+ */
10
+ import { Mol4AgentError } from "./protocol.js";
11
+ /** Databases `mol_fetch` can download from. The first is the default. */
12
+ export const SOURCE_DATABASES = [
13
+ 'rcsb-pdb',
14
+ 'rcsb-cif',
15
+ 'rcsb-bcif',
16
+ 'alphafold',
17
+ 'pubchem',
18
+ 'chembl',
19
+ ];
20
+ export const SOURCE_DATABASE_INFO = {
21
+ 'rcsb-pdb': {
22
+ label: 'RCSB PDB',
23
+ description: 'Experimental structure from the RCSB Protein Data Bank, in PDB format.',
24
+ entryHint: '4-character PDB entry id, e.g. 1crn',
25
+ format: 'pdb',
26
+ },
27
+ 'rcsb-cif': {
28
+ label: 'RCSB PDB (mmCIF)',
29
+ description: 'Experimental structure from the RCSB Protein Data Bank, in mmCIF format.',
30
+ entryHint: '4-character PDB entry id, e.g. 1crn',
31
+ format: 'mmcif',
32
+ },
33
+ 'rcsb-bcif': {
34
+ label: 'RCSB PDB (BinaryCIF)',
35
+ description: 'Experimental structure from the RCSB model server, in BinaryCIF format.',
36
+ entryHint: '4-character PDB entry id, e.g. 1crn',
37
+ format: 'bcif',
38
+ },
39
+ alphafold: {
40
+ label: 'AlphaFold DB',
41
+ description: 'Predicted protein structure from AlphaFold DB, in PDB format.',
42
+ entryHint: 'UniProt accession, e.g. P00533',
43
+ format: 'pdb',
44
+ },
45
+ pubchem: {
46
+ label: 'PubChem',
47
+ description: 'Small-molecule compound from PubChem, in 3D SDF format.',
48
+ entryHint: 'PubChem CID (2244) or compound name (aspirin)',
49
+ format: 'sdf',
50
+ },
51
+ chembl: {
52
+ label: 'ChEMBL',
53
+ description: 'Small-molecule compound from ChEMBL, in SDF format.',
54
+ entryHint: 'ChEMBL id, e.g. CHEMBL25 (a bare number gets the CHEMBL prefix)',
55
+ format: 'sdf',
56
+ },
57
+ };
58
+ /** Normalize an agent-supplied source name; `undefined` selects `rcsb-pdb`. */
59
+ export function normalizeSourceDb(value) {
60
+ if (value === undefined)
61
+ return 'rcsb-pdb';
62
+ const normalized = value.trim().toLowerCase();
63
+ if (normalized === '')
64
+ return 'rcsb-pdb';
65
+ if (isSourceDatabase(normalized))
66
+ return normalized;
67
+ throw new Mol4AgentError('UNSUPPORTED_SOURCE', `unknown source_db "${value}"; supported: ${SOURCE_DATABASES.join(', ')}`);
68
+ }
69
+ /** Validate an entry id and build the adapter's fetch plan. */
70
+ export function resolveSource(request) {
71
+ const sourceDb = normalizeSourceDb(request.sourceDb);
72
+ const info = SOURCE_DATABASE_INFO[sourceDb];
73
+ if (typeof request.entryId !== 'string' || request.entryId.trim() === '') {
74
+ throw new Mol4AgentError('INVALID_ENTRY_ID', `entry_id is required for ${sourceDb} (${info.entryHint})`);
75
+ }
76
+ const entry = request.entryId.trim();
77
+ switch (sourceDb) {
78
+ case 'rcsb-pdb': {
79
+ const id = pdbEntryId(entry, sourceDb);
80
+ return {
81
+ sourceDb,
82
+ entryId: id,
83
+ format: 'pdb',
84
+ fileName: `${id}.pdb`,
85
+ plan: { url: `https://files.rcsb.org/download/${id}.pdb` },
86
+ description: `RCSB PDB entry ${id} (PDB format)`,
87
+ };
88
+ }
89
+ case 'rcsb-cif': {
90
+ const id = pdbEntryId(entry, sourceDb);
91
+ return {
92
+ sourceDb,
93
+ entryId: id,
94
+ format: 'mmcif',
95
+ fileName: `${id}.cif`,
96
+ plan: { url: `https://files.rcsb.org/download/${id}.cif` },
97
+ description: `RCSB PDB entry ${id} (mmCIF format)`,
98
+ };
99
+ }
100
+ case 'rcsb-bcif': {
101
+ const id = pdbEntryId(entry, sourceDb);
102
+ return {
103
+ sourceDb,
104
+ entryId: id,
105
+ format: 'bcif',
106
+ fileName: `${id}.bcif`,
107
+ plan: { url: `https://models.rcsb.org/${id}.bcif` },
108
+ description: `RCSB PDB entry ${id} (BinaryCIF format)`,
109
+ };
110
+ }
111
+ case 'alphafold': {
112
+ const accession = uniprotAccession(entry);
113
+ return {
114
+ sourceDb,
115
+ entryId: accession,
116
+ format: 'pdb',
117
+ fileName: `AF-${accession}-F1-model.pdb`,
118
+ plan: {
119
+ url: `https://alphafold.ebi.ac.uk/api/prediction/${accession}`,
120
+ indexField: '0.pdbUrl',
121
+ },
122
+ description: `AlphaFold DB prediction for UniProt ${accession} (PDB format)`,
123
+ };
124
+ }
125
+ case 'pubchem': {
126
+ const compound = pubchemCompound(entry);
127
+ return {
128
+ sourceDb,
129
+ entryId: compound.entryId,
130
+ format: 'sdf',
131
+ fileName: compound.fileName,
132
+ plan: { url: compound.url },
133
+ description: `PubChem compound ${compound.entryId} (3D SDF)`,
134
+ };
135
+ }
136
+ case 'chembl': {
137
+ const id = chemblId(entry);
138
+ return {
139
+ sourceDb,
140
+ entryId: id,
141
+ format: 'sdf',
142
+ fileName: `${id}.sdf`,
143
+ plan: { url: `https://www.ebi.ac.uk/chembl/api/data/molecule/${id}.sdf` },
144
+ description: `ChEMBL molecule ${id} (SDF)`,
145
+ };
146
+ }
147
+ }
148
+ }
149
+ /**
150
+ * Read a dot path from a JSON index document (numeric segments index arrays).
151
+ *
152
+ * Used by adapters for sources whose file URL is versioned, such as AlphaFold.
153
+ * Returns undefined when the path is missing or is not a string.
154
+ */
155
+ export function readSourceIndexField(payload, field) {
156
+ let current = payload;
157
+ for (const segment of field.split('.')) {
158
+ if (Array.isArray(current)) {
159
+ const index = Number(segment);
160
+ if (!Number.isInteger(index) || index < 0)
161
+ return undefined;
162
+ current = current[index];
163
+ continue;
164
+ }
165
+ if (typeof current !== 'object' || current === null)
166
+ return undefined;
167
+ current = current[segment];
168
+ }
169
+ return typeof current === 'string' ? current : undefined;
170
+ }
171
+ export function isSourceDatabase(value) {
172
+ return typeof value === 'string' && SOURCE_DATABASES.includes(value);
173
+ }
174
+ /** Every source database id, in display order. */
175
+ export function sourceDatabases() {
176
+ return SOURCE_DATABASES;
177
+ }
178
+ const PDB_ENTRY_ID = /^[0-9][A-Z0-9]{3}$/u;
179
+ const UNIPROT_ACCESSION = /^(?:[A-Z0-9]{6}|[A-Z0-9]{10})$/u;
180
+ const CHEMBL_ID = /^CHEMBL[0-9]+$/u;
181
+ const MAX_PUBCHEM_NAME = 120;
182
+ function pdbEntryId(entry, sourceDb) {
183
+ const id = entry.toUpperCase();
184
+ if (!PDB_ENTRY_ID.test(id)) {
185
+ throw new Mol4AgentError('INVALID_ENTRY_ID', `"${entry}" is not a PDB entry id for ${sourceDb}; expected 4 characters like 1crn`);
186
+ }
187
+ return id;
188
+ }
189
+ function uniprotAccession(entry) {
190
+ // Accept the AlphaFold file stem (`AF-P00533-F1`) as well as the bare accession.
191
+ const stem = /^AF-([A-Z0-9]{6}|[A-Z0-9]{10})-F[0-9]+$/u.exec(entry.toUpperCase());
192
+ const accession = stem?.[1] ?? entry.toUpperCase();
193
+ if (!UNIPROT_ACCESSION.test(accession)) {
194
+ throw new Mol4AgentError('INVALID_ENTRY_ID', `"${entry}" is not a UniProt accession for alphafold; expected 6 or 10 characters like P00533`);
195
+ }
196
+ return accession;
197
+ }
198
+ function chemblId(entry) {
199
+ const value = entry.toUpperCase();
200
+ const id = /^[0-9]+$/u.test(value) ? `CHEMBL${value}` : value;
201
+ if (!CHEMBL_ID.test(id)) {
202
+ throw new Mol4AgentError('INVALID_ENTRY_ID', `"${entry}" is not a ChEMBL id; expected CHEMBL25 or a numeric id like 25`);
203
+ }
204
+ return id;
205
+ }
206
+ function pubchemCompound(entry) {
207
+ const cid = /^(?:cid:?[ \t]*)?[0-9]+$/iu.test(entry);
208
+ if (cid) {
209
+ const id = entry.replace(/^cid:?[ \t]*/iu, '');
210
+ return {
211
+ entryId: id,
212
+ url: `https://pubchem.ncbi.nlm.nih.gov/rest/pug/compound/cid/${id}/SDF?record_type=3d`,
213
+ fileName: `pubchem-${id}.sdf`,
214
+ };
215
+ }
216
+ if (entry.length > MAX_PUBCHEM_NAME) {
217
+ throw new Mol4AgentError('INVALID_ENTRY_ID', `PubChem compound name is too long (${entry.length} characters; limit ${MAX_PUBCHEM_NAME})`);
218
+ }
219
+ if (/[\u0000-\u001f\u007f]/u.test(entry)) {
220
+ throw new Mol4AgentError('INVALID_ENTRY_ID', 'PubChem compound name contains control characters');
221
+ }
222
+ const slug = entry
223
+ .toLowerCase()
224
+ .replaceAll(/[^a-z0-9]+/gu, '-')
225
+ .replaceAll(/^-+|-+$/gu, '');
226
+ return {
227
+ entryId: entry,
228
+ url: `https://pubchem.ncbi.nlm.nih.gov/rest/pug/compound/name/${encodeURIComponent(entry)}/SDF?record_type=3d`,
229
+ fileName: `pubchem-${slug === '' ? 'compound' : slug.slice(0, 48)}.sdf`,
230
+ };
231
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@gcszhn/mol4agent-core",
3
- "version": "0.1.0",
3
+ "version": "0.2.0",
4
4
  "type": "module",
5
5
  "description": "Harness-neutral Mol* viewer engine: bytes + explicit format in, commands out.",
6
6
  "main": "./lib/index.js",
@@ -21,6 +21,11 @@
21
21
  "import": "./lib/parse/index.js",
22
22
  "default": "./lib/parse/index.js"
23
23
  },
24
+ "./sources": {
25
+ "types": "./lib/sources.d.ts",
26
+ "import": "./lib/sources.js",
27
+ "default": "./lib/sources.js"
28
+ },
24
29
  "./react": {
25
30
  "types": "./lib/react.d.ts",
26
31
  "import": "./lib/react.js",