jbrowse-plugin-msaview 2.5.0 → 2.5.1

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 (35) hide show
  1. package/dist/LaunchMsaViewExtensionPoint/index.js +2 -1
  2. package/dist/MsaViewPanel/afterCreateAutoruns.d.ts +7 -0
  3. package/dist/MsaViewPanel/afterCreateAutoruns.js +31 -0
  4. package/dist/MsaViewPanel/loadProteinDomains.d.ts +16 -0
  5. package/dist/MsaViewPanel/loadProteinDomains.js +33 -0
  6. package/dist/MsaViewPanel/model.d.ts +189 -158
  7. package/dist/MsaViewPanel/model.js +14 -4
  8. package/dist/jbrowse-plugin-msaview.umd.production.min.js +27 -27
  9. package/dist/jbrowse-plugin-msaview.umd.production.min.js.map +4 -4
  10. package/dist/utils/domainCache.d.ts +8 -0
  11. package/dist/utils/domainCache.js +28 -0
  12. package/dist/utils/eutils.d.ts +3 -0
  13. package/dist/utils/eutils.js +14 -0
  14. package/dist/utils/msa.js +18 -15
  15. package/dist/utils/ncbiBlast.js +22 -24
  16. package/dist/utils/ncbiDomains.d.ts +39 -0
  17. package/dist/utils/ncbiDomains.js +154 -0
  18. package/dist/utils/poll.d.ts +11 -0
  19. package/dist/utils/poll.js +19 -0
  20. package/dist/utils/taxonomyNames.js +2 -1
  21. package/dist/version.d.ts +1 -1
  22. package/dist/version.js +1 -1
  23. package/package.json +14 -11
  24. package/src/LaunchMsaViewExtensionPoint/index.ts +3 -0
  25. package/src/MsaViewPanel/afterCreateAutoruns.ts +32 -0
  26. package/src/MsaViewPanel/loadProteinDomains.ts +57 -0
  27. package/src/MsaViewPanel/model.ts +19 -3
  28. package/src/utils/domainCache.ts +44 -0
  29. package/src/utils/eutils.ts +16 -0
  30. package/src/utils/msa.ts +18 -16
  31. package/src/utils/ncbiBlast.ts +27 -31
  32. package/src/utils/ncbiDomains.ts +171 -0
  33. package/src/utils/poll.ts +28 -0
  34. package/src/utils/taxonomyNames.ts +3 -1
  35. package/src/version.ts +1 -1
@@ -0,0 +1,8 @@
1
+ import type { DomainMatch } from './ncbiDomains';
2
+ interface CachedDomain {
3
+ accession: string;
4
+ matches: DomainMatch[];
5
+ }
6
+ export declare function getCachedDomains(accessions: string[]): Promise<(CachedDomain | undefined)[]>;
7
+ export declare function saveDomains(entries: CachedDomain[]): Promise<void>;
8
+ export {};
@@ -0,0 +1,28 @@
1
+ import { openDB } from 'idb';
2
+ const DB_NAME = 'jbrowse-msaview-domain-cache';
3
+ const STORE_NAME = 'domains';
4
+ const DB_VERSION = 1;
5
+ async function getDB() {
6
+ return openDB(DB_NAME, DB_VERSION, {
7
+ upgrade(db) {
8
+ if (!db.objectStoreNames.contains(STORE_NAME)) {
9
+ db.createObjectStore(STORE_NAME, { keyPath: 'accession' });
10
+ }
11
+ },
12
+ });
13
+ }
14
+ export async function getCachedDomains(accessions) {
15
+ const db = await getDB();
16
+ const tx = db.transaction(STORE_NAME, 'readonly');
17
+ const results = await Promise.all(accessions.map(accession => tx.store.get(accession)));
18
+ await tx.done;
19
+ return results;
20
+ }
21
+ export async function saveDomains(entries) {
22
+ const db = await getDB();
23
+ const tx = db.transaction(STORE_NAME, 'readwrite');
24
+ for (const entry of entries) {
25
+ await tx.store.put(entry);
26
+ }
27
+ await tx.done;
28
+ }
@@ -0,0 +1,3 @@
1
+ export declare const NCBI_TOOL = "jbrowse-plugin-msaview";
2
+ export declare const NCBI_EMAIL = "colin.diesh@gmail.com";
3
+ export declare function efetchUrl(params: Record<string, string>): string;
@@ -0,0 +1,14 @@
1
+ // NCBI asks that programmatic E-utilities requests identify themselves with a
2
+ // tool name and contact email so they can reach out before throttling, rather
3
+ // than silently rate-limiting. https://www.ncbi.nlm.nih.gov/books/NBK25497/
4
+ export const NCBI_TOOL = 'jbrowse-plugin-msaview';
5
+ export const NCBI_EMAIL = 'colin.diesh@gmail.com';
6
+ const EUTILS = 'https://eutils.ncbi.nlm.nih.gov/entrez/eutils';
7
+ export function efetchUrl(params) {
8
+ const search = new URLSearchParams({
9
+ ...params,
10
+ tool: NCBI_TOOL,
11
+ email: NCBI_EMAIL,
12
+ });
13
+ return `${EUTILS}/efetch.fcgi?${search.toString()}`;
14
+ }
package/dist/utils/msa.js CHANGED
@@ -1,4 +1,5 @@
1
- import { textfetch, timeout } from './fetch';
1
+ import { textfetch } from './fetch';
2
+ import { pollLoop } from './poll';
2
3
  const base = `https://www.ebi.ac.uk/Tools/services/rest`;
3
4
  const email = 'colin.diesh@gmail.com';
4
5
  const algorithms = {
@@ -24,20 +25,22 @@ const algorithms = {
24
25
  },
25
26
  };
26
27
  async function wait({ onProgress, jobId, algorithm, }) {
27
- // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
28
- while (true) {
29
- const result = await textfetch(`${base}/${algorithm}/status/${jobId}`);
30
- if (result === 'FINISHED') {
31
- break;
32
- }
33
- else if (result.includes('FAILURE')) {
34
- throw new Error(`Failed to run: jobId ${jobId}`);
35
- }
36
- for (let i = 0; i < 10; i++) {
37
- onProgress(`Re-checking MSA status in... ${10 - i}`);
38
- await timeout(1000);
39
- }
40
- }
28
+ await pollLoop({
29
+ intervalSeconds: 10,
30
+ onCountdown: s => {
31
+ onProgress(`Re-checking MSA status in... ${s}`);
32
+ },
33
+ check: async () => {
34
+ const result = await textfetch(`${base}/${algorithm}/status/${jobId}`);
35
+ if (result.includes('FINISHED')) {
36
+ return true;
37
+ }
38
+ if (result.includes('FAILURE')) {
39
+ throw new Error(`Failed to run: jobId ${jobId}`);
40
+ }
41
+ return false;
42
+ },
43
+ });
41
44
  }
42
45
  export async function launchMSA({ algorithm, sequence, onProgress, }) {
43
46
  const config = algorithms[algorithm];
@@ -1,4 +1,5 @@
1
- import { jsonfetch, textfetch, timeout } from './fetch';
1
+ import { jsonfetch, textfetch } from './fetch';
2
+ import { pollLoop } from './poll';
2
3
  export async function queryBlastFromRid({ rid, baseUrl, onProgress, }) {
3
4
  onProgress(`Checking BLAST status for RID: ${rid}...`);
4
5
  await waitForRid({
@@ -56,31 +57,28 @@ async function initialQuery({ query, blastProgram, blastDatabase, baseUrl, }) {
56
57
  };
57
58
  }
58
59
  async function waitForRid({ rid, onProgress, baseUrl, }) {
59
- // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
60
- while (true) {
61
- const res = await textfetch(`${baseUrl}?CMD=Get&FORMAT_OBJECT=SearchInfo&RID=${rid}`);
62
- const statusMatch = /\s+Status=(\S+)/m.exec(res);
63
- const status = statusMatch?.[1];
64
- const hasHits = /\s+ThereAreHits=yes/m.test(res);
65
- if (status === 'WAITING') {
66
- const iter = 20;
67
- for (let i = 0; i < iter; i++) {
68
- onProgress(`Re-checking BLAST status in... ${iter - i}`);
69
- await timeout(1000);
60
+ await pollLoop({
61
+ intervalSeconds: 20,
62
+ onCountdown: s => {
63
+ onProgress(`Re-checking BLAST status in... ${s}`);
64
+ },
65
+ check: async () => {
66
+ const res = await textfetch(`${baseUrl}?CMD=Get&FORMAT_OBJECT=SearchInfo&RID=${rid}`);
67
+ const status = /\s+Status=(\S+)/m.exec(res)?.[1];
68
+ const hasHits = /\s+ThereAreHits=yes/m.test(res);
69
+ if (status === 'WAITING') {
70
+ return false;
70
71
  }
71
- continue;
72
- }
73
- if (status === 'FAILED') {
74
- throw new Error(`BLAST ${rid} failed`);
75
- }
76
- if (status === 'READY') {
77
- if (hasHits) {
78
- return true;
72
+ if (status === 'FAILED') {
73
+ throw new Error(`BLAST ${rid} failed`);
79
74
  }
80
- else {
75
+ if (status === 'READY') {
76
+ if (hasHits) {
77
+ return true;
78
+ }
81
79
  throw new Error('No hits found');
82
80
  }
83
- }
84
- throw new Error(`BLAST ${rid} returned unexpected status: ${status ?? 'unknown'}`);
85
- }
81
+ throw new Error(`BLAST ${rid} returned unexpected status: ${status ?? 'unknown'}`);
82
+ },
83
+ });
86
84
  }
@@ -0,0 +1,39 @@
1
+ import type { InterProScanResults } from 'react-msaview';
2
+ export type DomainMatch = InterProScanResults['matches'][number];
3
+ /**
4
+ * Parse a GenPept (efetch db=protein&rettype=gp&retmode=xml) document into CDD
5
+ * domain and site annotations, keyed by both the versioned and primary
6
+ * accession so callers can look up by whichever NCBI returned.
7
+ */
8
+ export declare function parseCddDomains(xml: string): Map<string, {
9
+ signature: {
10
+ entry?: {
11
+ name: string;
12
+ description: string;
13
+ accession: string;
14
+ };
15
+ };
16
+ locations: {
17
+ start: number;
18
+ end: number;
19
+ }[];
20
+ }[]>;
21
+ /**
22
+ * Fetch pre-computed CDD domain and site annotations for NCBI protein
23
+ * accessions. These come baked into the GenPept records, so a single batched
24
+ * efetch returns them with no job submission or polling. Results are cached in
25
+ * IndexedDB so reopening a view doesn't refetch.
26
+ */
27
+ export declare function fetchProteinDomains(accessions: string[]): Promise<Map<string, {
28
+ signature: {
29
+ entry?: {
30
+ name: string;
31
+ description: string;
32
+ accession: string;
33
+ };
34
+ };
35
+ locations: {
36
+ start: number;
37
+ end: number;
38
+ }[];
39
+ }[]>>;
@@ -0,0 +1,154 @@
1
+ import { getCachedDomains, saveDomains } from './domainCache';
2
+ import { efetchUrl } from './eutils';
3
+ import { textfetch } from './fetch';
4
+ function field(xml, tag) {
5
+ return new RegExp(`<${tag}>(.*?)</${tag}>`, 's').exec(xml)?.[1];
6
+ }
7
+ function parseQualifiers(featureXml) {
8
+ const quals = {};
9
+ const re = /<GBQualifier>([\s\S]*?)<\/GBQualifier>/g;
10
+ let m;
11
+ while ((m = re.exec(featureXml)) !== null) {
12
+ const name = field(m[1], 'GBQualifier_name');
13
+ const value = field(m[1], 'GBQualifier_value');
14
+ // keep the first occurrence: NCBI lists the canonical value first
15
+ if (name && value !== undefined && quals[name] === undefined) {
16
+ quals[name] = value;
17
+ }
18
+ }
19
+ return quals;
20
+ }
21
+ // A feature can span several intervals: domains are usually one contiguous
22
+ // range, but CDD Sites (e.g. an active site) are a set of scattered residues
23
+ // expressed as multiple GBInterval ranges and single GBInterval_point residues.
24
+ // We collapse those to a single bounding span so a site renders as one box
25
+ // rather than a spray of 1px specks.
26
+ function parseBoundingSpan(featureXml) {
27
+ const starts = [];
28
+ const ends = [];
29
+ const re = /<GBInterval>([\s\S]*?)<\/GBInterval>/g;
30
+ let m;
31
+ while ((m = re.exec(featureXml)) !== null) {
32
+ const block = m[1];
33
+ const from = field(block, 'GBInterval_from');
34
+ const to = field(block, 'GBInterval_to');
35
+ const point = field(block, 'GBInterval_point');
36
+ if (from && to) {
37
+ starts.push(Number(from));
38
+ ends.push(Number(to));
39
+ }
40
+ else if (point) {
41
+ starts.push(Number(point));
42
+ ends.push(Number(point));
43
+ }
44
+ }
45
+ return starts.length > 0
46
+ ? { start: Math.min(...starts), end: Math.max(...ends) }
47
+ : undefined;
48
+ }
49
+ // Drop single-residue specks (acetylation/phospho points) but keep every
50
+ // genuine domain and functional site; react-msaview draws longest-first, so
51
+ // smaller features (binding sites, loops) layer on top of the domain they sit
52
+ // inside.
53
+ const MIN_FEATURE_LENGTH = 2;
54
+ function parseFeature(featureXml) {
55
+ const key = field(featureXml, 'GBFeature_key');
56
+ const quals = parseQualifiers(featureXml);
57
+ const xref = quals.db_xref;
58
+ const span = parseBoundingSpan(featureXml);
59
+ // only CDD-backed Regions/Sites are conserved-domain annotations; Regions and
60
+ // Sites without a CDD xref are UniProt-propagated point motifs we don't want
61
+ if ((key === 'Region' || key === 'Site') &&
62
+ xref?.startsWith('CDD:') &&
63
+ span &&
64
+ span.end - span.start + 1 >= MIN_FEATURE_LENGTH) {
65
+ const cddId = xref.replace('CDD:', '');
66
+ const isDomain = key === 'Region';
67
+ // a site's note (e.g. "ATP binding site [chemical binding]") is more
68
+ // specific than its generic site_type ("other"), so prefer it for the name
69
+ // — that gives each functional site its own color/legend/filter entry
70
+ const noteName = quals.note?.split(/[[(]/)[0]?.trim();
71
+ const name = isDomain
72
+ ? (quals.region_name ?? cddId)
73
+ : noteName || quals.site_type || 'site';
74
+ const accession = isDomain ? cddId : `${cddId}:${name}`;
75
+ return {
76
+ signature: { entry: { name, description: quals.note ?? name, accession } },
77
+ locations: [span],
78
+ };
79
+ }
80
+ return undefined;
81
+ }
82
+ /**
83
+ * Parse a GenPept (efetch db=protein&rettype=gp&retmode=xml) document into CDD
84
+ * domain and site annotations, keyed by both the versioned and primary
85
+ * accession so callers can look up by whichever NCBI returned.
86
+ */
87
+ export function parseCddDomains(xml) {
88
+ const byAccession = new Map();
89
+ const seqRe = /<GBSeq>([\s\S]*?)<\/GBSeq>/g;
90
+ let seqMatch;
91
+ while ((seqMatch = seqRe.exec(xml)) !== null) {
92
+ const seqXml = seqMatch[1];
93
+ const matches = [];
94
+ const featRe = /<GBFeature>([\s\S]*?)<\/GBFeature>/g;
95
+ let featMatch;
96
+ while ((featMatch = featRe.exec(seqXml)) !== null) {
97
+ const match = parseFeature(featMatch[1]);
98
+ if (match) {
99
+ matches.push(match);
100
+ }
101
+ }
102
+ for (const acc of [
103
+ field(seqXml, 'GBSeq_accession-version'),
104
+ field(seqXml, 'GBSeq_primary-accession'),
105
+ ]) {
106
+ if (acc) {
107
+ byAccession.set(acc, matches);
108
+ }
109
+ }
110
+ }
111
+ return byAccession;
112
+ }
113
+ /**
114
+ * Fetch pre-computed CDD domain and site annotations for NCBI protein
115
+ * accessions. These come baked into the GenPept records, so a single batched
116
+ * efetch returns them with no job submission or polling. Results are cached in
117
+ * IndexedDB so reopening a view doesn't refetch.
118
+ */
119
+ export async function fetchProteinDomains(accessions) {
120
+ const unique = [...new Set(accessions)].filter(Boolean);
121
+ const byAccession = new Map();
122
+ const cached = await getCachedDomains(unique);
123
+ const uncached = [];
124
+ unique.forEach((acc, i) => {
125
+ const hit = cached[i];
126
+ if (hit) {
127
+ byAccession.set(acc, hit.matches);
128
+ }
129
+ else {
130
+ uncached.push(acc);
131
+ }
132
+ });
133
+ const toCache = [];
134
+ const batchSize = 100;
135
+ for (let i = 0; i < uncached.length; i += batchSize) {
136
+ const batch = uncached.slice(i, i + batchSize);
137
+ const xml = await textfetch(efetchUrl({
138
+ db: 'protein',
139
+ id: batch.join(','),
140
+ rettype: 'gp',
141
+ retmode: 'xml',
142
+ }));
143
+ const parsed = parseCddDomains(xml);
144
+ for (const acc of batch) {
145
+ const matches = parsed.get(acc) ?? [];
146
+ byAccession.set(acc, matches);
147
+ toCache.push({ accession: acc, matches });
148
+ }
149
+ }
150
+ if (toCache.length > 0) {
151
+ await saveDomains(toCache);
152
+ }
153
+ return byAccession;
154
+ }
@@ -0,0 +1,11 @@
1
+ /**
2
+ * Poll a remote job until it reports done. `check` returns true when finished,
3
+ * false when still pending, and throws on failure. Between checks it counts down
4
+ * `intervalSeconds`, calling `onCountdown` each second so the UI can show
5
+ * progress.
6
+ */
7
+ export declare function pollLoop({ check, intervalSeconds, onCountdown, }: {
8
+ check: () => Promise<boolean>;
9
+ intervalSeconds: number;
10
+ onCountdown: (secondsRemaining: number) => void;
11
+ }): Promise<void>;
@@ -0,0 +1,19 @@
1
+ import { timeout } from './fetch';
2
+ /**
3
+ * Poll a remote job until it reports done. `check` returns true when finished,
4
+ * false when still pending, and throws on failure. Between checks it counts down
5
+ * `intervalSeconds`, calling `onCountdown` each second so the UI can show
6
+ * progress.
7
+ */
8
+ export async function pollLoop({ check, intervalSeconds, onCountdown, }) {
9
+ // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
10
+ while (true) {
11
+ if (await check()) {
12
+ return;
13
+ }
14
+ for (let i = intervalSeconds; i > 0; i--) {
15
+ onCountdown(i);
16
+ await timeout(1000);
17
+ }
18
+ }
19
+ }
@@ -1,4 +1,5 @@
1
1
  import { openDB } from 'idb';
2
+ import { efetchUrl } from './eutils';
2
3
  const DB_NAME = 'jbrowse-msaview-taxonomy-cache';
3
4
  const STORE_NAME = 'common-names';
4
5
  const DB_VERSION = 2;
@@ -53,7 +54,7 @@ export async function fetchTaxonomyInfo(taxids) {
53
54
  const batch = uncachedTaxids.slice(i, i + batchSize);
54
55
  const idsParam = batch.join(',');
55
56
  try {
56
- const response = await fetch(`https://eutils.ncbi.nlm.nih.gov/entrez/eutils/efetch.fcgi?db=taxonomy&id=${idsParam}&retmode=xml`);
57
+ const response = await fetch(efetchUrl({ db: 'taxonomy', id: idsParam, retmode: 'xml' }));
57
58
  const text = await response.text();
58
59
  // Build a map of taxid -> taxon block by finding Taxon elements.
59
60
  // Prefer entries with <LineageEx> (full top-level entries) over nested
package/dist/version.d.ts CHANGED
@@ -1 +1 @@
1
- export declare const version = "2.5.0";
1
+ export declare const version = "2.5.1";
package/dist/version.js CHANGED
@@ -1 +1 @@
1
- export const version = '2.5.0';
1
+ export const version = '2.5.1';
package/package.json CHANGED
@@ -1,5 +1,5 @@
1
1
  {
2
- "version": "2.5.0",
2
+ "version": "2.5.1",
3
3
  "license": "MIT",
4
4
  "name": "jbrowse-plugin-msaview",
5
5
  "repository": {
@@ -20,7 +20,7 @@
20
20
  "g2p_mapper": "^2.1.5",
21
21
  "idb": "^8.0.3",
22
22
  "pako-esm2": "^2.0.2",
23
- "react-msaview": "^5.1.1",
23
+ "react-msaview": "^5.4.1",
24
24
  "swr": "^2.4.1"
25
25
  },
26
26
  "devDependencies": {
@@ -28,36 +28,39 @@
28
28
  "@eslint/js": "^10.0.1",
29
29
  "@fal-works/esbuild-plugin-global-externals": "^2.1.2",
30
30
  "@jbrowse/core": "^4.3.0",
31
- "@jbrowse/mobx-state-tree": "^5.10.2",
31
+ "@jbrowse/mobx-state-tree": "^5.10.8",
32
32
  "@jbrowse/plugin-linear-genome-view": "^4.3.0",
33
33
  "@mui/icons-material": "^7.3.11",
34
34
  "@mui/material": "^7.3.11",
35
35
  "@mui/system": "^7.3.11",
36
36
  "@mui/x-data-grid": "^8.28.7",
37
37
  "@types/node": "^25.9.1",
38
- "@types/react": "^19.2.15",
39
- "@typescript-eslint/eslint-plugin": "^8.60.0",
40
- "@typescript-eslint/parser": "^8.60.0",
38
+ "@types/react": "^19.2.16",
39
+ "@typescript-eslint/eslint-plugin": "^8.60.1",
40
+ "@typescript-eslint/parser": "^8.60.1",
41
41
  "esbuild": "^0.28.0",
42
- "eslint": "^10.4.0",
42
+ "eslint": "^10.4.1",
43
43
  "eslint-plugin-import-x": "^4.16.2",
44
44
  "eslint-plugin-react": "^7.37.5",
45
45
  "eslint-plugin-react-hooks": "^7.1.1",
46
46
  "eslint-plugin-unicorn": "^64.0.0",
47
47
  "mobx": "^6.15.4",
48
48
  "mobx-react": "^9.2.2",
49
+ "msa-parsers": "5.4.1",
50
+ "pixelmatch": "^7.2.0",
51
+ "pngjs": "^7.0.0",
49
52
  "prettier": "^3.8.3",
50
53
  "pretty-bytes": "^7.1.0",
51
54
  "puppeteer": "^25.1.0",
52
- "react": "^19.2.6",
53
- "react-dom": "^19.2.6",
55
+ "react": "^19.2.7",
56
+ "react-dom": "^19.2.7",
54
57
  "rimraf": "^6.1.3",
55
58
  "rxjs": "^7.8.2",
56
59
  "serve": "^14.2.6",
57
60
  "tss-react": "^4.9.21",
58
61
  "typescript": "^6.0.3",
59
- "typescript-eslint": "^8.60.0",
60
- "vitest": "^4.1.7"
62
+ "typescript-eslint": "^8.60.1",
63
+ "vitest": "^4.1.8"
61
64
  },
62
65
  "scripts": {
63
66
  "clean": "rimraf dist",
@@ -24,6 +24,7 @@ export default function LaunchMsaViewExtensionPointF(
24
24
  labelsAlignRight,
25
25
  showBranchLen,
26
26
  querySeqName,
27
+ highlightColumns,
27
28
  }: {
28
29
  session: AbstractSessionModel
29
30
  data?: { msa: string; tree?: string }
@@ -41,6 +42,7 @@ export default function LaunchMsaViewExtensionPointF(
41
42
  labelsAlignRight?: boolean
42
43
  showBranchLen?: boolean
43
44
  querySeqName?: string
45
+ highlightColumns?: number[]
44
46
  }) => {
45
47
  if (!data && !msaFileLocation) {
46
48
  throw new Error(
@@ -61,6 +63,7 @@ export default function LaunchMsaViewExtensionPointF(
61
63
  drawNodeBubbles,
62
64
  labelsAlignRight,
63
65
  showBranchLen,
66
+ highlightColumns,
64
67
  init: {
65
68
  msaData: data?.msa,
66
69
  treeData: data?.tree,
@@ -2,6 +2,7 @@ import { getSession } from '@jbrowse/core/util'
2
2
 
3
3
  import { doLaunchBlast } from './doLaunchBlast'
4
4
  import { genomeToMSA } from './genomeToMSA'
5
+ import { loadProteinDomains } from './loadProteinDomains'
5
6
  import {
6
7
  cleanupOldData,
7
8
  generateDataStoreId,
@@ -30,6 +31,9 @@ export function loadStoredData(self: JBrowsePluginMsaViewModel) {
30
31
  if (storedData.tree) {
31
32
  self.setTree(storedData.tree)
32
33
  }
34
+ if (storedData.treeMetadata) {
35
+ self.setTreeMetadata(storedData.treeMetadata)
36
+ }
33
37
  }
34
38
  } catch (e) {
35
39
  console.error('Failed to load MSA data from IndexedDB:', e)
@@ -95,6 +99,34 @@ export function launchBlastIfNeeded(self: JBrowsePluginMsaViewModel) {
95
99
  }
96
100
  }
97
101
 
102
+ /**
103
+ * Once an accession-bearing alignment is present (fresh from BLAST or restored
104
+ * from cache), fetch NCBI CDD domains for those accessions and overlay them.
105
+ * Runs once per view; the domainsRequested guard prevents refiring when NCBI
106
+ * returns no domains (which leaves interProAnnotations undefined).
107
+ */
108
+ export function autoLoadProteinDomains(self: JBrowsePluginMsaViewModel) {
109
+ const { rows, domainsRequested, interProAnnotations } = self
110
+ const hasAccessions = self.data.treeMetadata?.includes('"Accession"') ?? false
111
+ if (
112
+ rows.length > 0 &&
113
+ hasAccessions &&
114
+ !interProAnnotations &&
115
+ !domainsRequested
116
+ ) {
117
+ self.setDomainsRequested(true)
118
+ void (async () => {
119
+ try {
120
+ await loadProteinDomains(self)
121
+ } catch (e) {
122
+ console.error('[msaview-domains] auto-load failed:', e)
123
+ } finally {
124
+ self.setProgress('')
125
+ }
126
+ })()
127
+ }
128
+ }
129
+
98
130
  export function processInit(self: JBrowsePluginMsaViewModel) {
99
131
  const { init } = self
100
132
  if (init) {
@@ -0,0 +1,57 @@
1
+ import { fetchProteinDomains } from '../utils/ncbiDomains'
2
+
3
+ import type { InterProScanResults } from 'react-msaview'
4
+
5
+ // structural subset of the MSA model: the full model type can't be used here
6
+ // because it references this very action, creating a self-referential cycle
7
+ interface DomainModel {
8
+ data: { treeMetadata?: string }
9
+ setProgress: (arg: string) => void
10
+ setDomains: (data: Record<string, InterProScanResults>) => void
11
+ }
12
+
13
+ /**
14
+ * Overlay protein domains on the alignment using NCBI's pre-computed CDD
15
+ * annotations. The BLAST workflow stores each hit's accession in treeMetadata,
16
+ * so we look those up via efetch and key the results by MSA row name (which is
17
+ * what react-msaview matches domains against).
18
+ */
19
+ export async function loadProteinDomains(self: DomainModel) {
20
+ const metadataJson = self.data.treeMetadata
21
+ if (!metadataJson) {
22
+ throw new Error('No sequence metadata available to look up domains')
23
+ }
24
+ const metadata = JSON.parse(metadataJson) as Record<
25
+ string,
26
+ Record<string, string>
27
+ >
28
+
29
+ const rowAccessions = Object.entries(metadata)
30
+ .map(([rowName, meta]) => ({ rowName, accession: meta.Accession }))
31
+ .filter((r): r is { rowName: string; accession: string } => !!r.accession)
32
+
33
+ if (rowAccessions.length === 0) {
34
+ throw new Error('No NCBI accessions found in alignment rows')
35
+ }
36
+
37
+ self.setProgress(
38
+ `Fetching protein domains from NCBI for ${rowAccessions.length} sequences...`,
39
+ )
40
+ const byAccession = await fetchProteinDomains(
41
+ rowAccessions.map(r => r.accession),
42
+ )
43
+
44
+ const annotations: Record<string, InterProScanResults> = {}
45
+ for (const { rowName, accession } of rowAccessions) {
46
+ const matches = byAccession.get(accession)
47
+ if (matches && matches.length > 0) {
48
+ annotations[rowName] = { matches, xref: [{ id: rowName }] }
49
+ }
50
+ }
51
+
52
+ if (Object.keys(annotations).length === 0) {
53
+ throw new Error('No CDD domain annotations found for these proteins')
54
+ }
55
+
56
+ self.setDomains(annotations)
57
+ }