dsh-molbio-tools 0.28.1 → 0.28.2

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/lib/client.js CHANGED
@@ -1668,15 +1668,35 @@ window.__ModuleLoader__.load({
1668
1668
  const parts = [...cleaned.matchAll(/\d+(?:\.\.\d+)?/g)];
1669
1669
  const numbers = [...cleaned.matchAll(/\d+/g)].map((match) => Number(match[0]));
1670
1670
  if (numbers.length === 0) return undefined;
1671
+ // Reduce with a loop, never `Math.min(...numbers)`: a 20 Mb join() with a few
1672
+ // hundred thousand parts is a real NCBI record shape, and spreading it into
1673
+ // the argument list throws `RangeError: Maximum call stack size exceeded`
1674
+ // instead of returning a span.
1675
+ let start = numbers[0];
1676
+ let end = numbers[0];
1677
+ for (const number of numbers) {
1678
+ if (number < start) start = number;
1679
+ if (number > end) end = number;
1680
+ }
1671
1681
  return {
1672
- start: Math.min(...numbers),
1673
- end: Math.max(...numbers),
1682
+ start,
1683
+ end,
1674
1684
  strand: /complement/i.test(raw) ? -1 : 1,
1675
1685
  raw: raw.trim(),
1676
1686
  multiPart: parts.length > 1,
1677
1687
  };
1678
1688
  }
1679
1689
 
1690
+ /** Does this location still have an unclosed `(` (i.e. it wraps onto the next line)? */
1691
+ function isLocationOpen(text) {
1692
+ let depth = 0;
1693
+ for (const character of text) {
1694
+ if (character === '(') depth += 1;
1695
+ else if (character === ')') depth = Math.max(0, depth - 1);
1696
+ }
1697
+ return depth > 0;
1698
+ }
1699
+
1680
1700
  /** Parse one qualifier line: /key="value" (or unquoted value). */
1681
1701
  function parseQualifier(line) {
1682
1702
  const match = /^\s*\/?([a-zA-Z_][a-zA-Z0-9_]*)\s*=\s*(?:"([^"]*)"|(\S+))/.exec(line);
@@ -1709,6 +1729,31 @@ window.__ModuleLoader__.load({
1709
1729
  let inOrigin = false;
1710
1730
  let currentFeature = undefined;
1711
1731
  let currentQualifier = undefined;
1732
+ let currentLocation = '';
1733
+ let locationOpen = false;
1734
+ let placed = false;
1735
+
1736
+ /** Publish the current feature once its location can be placed. */
1737
+ const placeCurrentFeature = () => {
1738
+ if (currentFeature === undefined) return;
1739
+ const parsedLocation = parseLocation(currentLocation);
1740
+ if (parsedLocation === undefined) return;
1741
+ currentFeature.location = parsedLocation;
1742
+ if (!placed) {
1743
+ features.push(currentFeature);
1744
+ placed = true;
1745
+ }
1746
+ };
1747
+
1748
+ /** Count a feature that never got a placeable location, then reset per-feature state. */
1749
+ const finishFeature = () => {
1750
+ if (currentFeature !== undefined && !placed) skippedFeatures += 1;
1751
+ currentFeature = undefined;
1752
+ currentQualifier = undefined;
1753
+ currentLocation = '';
1754
+ locationOpen = false;
1755
+ placed = false;
1756
+ };
1712
1757
 
1713
1758
  for (let i = locusIndex; i < lines.length; i++) {
1714
1759
  const line = lines[i];
@@ -1719,29 +1764,35 @@ window.__ModuleLoader__.load({
1719
1764
  }
1720
1765
  if (inFeatures) {
1721
1766
  if (/^ORIGIN/.test(line)) {
1767
+ finishFeature();
1722
1768
  inFeatures = false;
1723
1769
  inOrigin = true;
1724
1770
  continue;
1725
1771
  }
1726
1772
  if (/^\s{5}\S/.test(line)) {
1727
1773
  // New feature: 5 spaces, then type and location.
1774
+ finishFeature();
1728
1775
  const match = /^\s{5}(\S+)\s*(.*)$/.exec(line);
1729
1776
  if (match === null) {
1730
1777
  skippedFeatures += 1;
1731
1778
  continue;
1732
1779
  }
1733
- currentFeature = {
1734
- type: match[1],
1735
- location: parseLocation(match[2] ?? ''),
1736
- qualifiers: {},
1737
- };
1738
- if (currentFeature.location === undefined) {
1739
- // No digits in the location: the feature cannot be placed. It is
1740
- // dropped, and the caller reports the count.
1741
- skippedFeatures += 1;
1742
- continue;
1743
- }
1744
- features.push(currentFeature);
1780
+ currentFeature = { type: match[1], location: undefined, qualifiers: {} };
1781
+ currentLocation = match[2] ?? '';
1782
+ locationOpen = isLocationOpen(currentLocation);
1783
+ placeCurrentFeature();
1784
+ continue;
1785
+ }
1786
+ // A location wider than the column wraps onto 21-space continuation lines
1787
+ // (`join(1..10,30..40,` + `50..60,70..80)`), which is how NCBI writes any
1788
+ // long join(). Such a line belongs to the LOCATION. It used to be read as
1789
+ // a qualifier continuation only, so the span silently stopped at the first
1790
+ // line and every downstream coordinate (map, batch table, feature counts)
1791
+ // sat on the wrong bases.
1792
+ if (locationOpen && /^\s{21}[0-9()][0-9,().^<>?\s]*$/.test(line)) {
1793
+ currentLocation += line.trim();
1794
+ locationOpen = isLocationOpen(currentLocation);
1795
+ placeCurrentFeature();
1745
1796
  continue;
1746
1797
  }
1747
1798
  if (/^\s{21}\//.test(line) && currentFeature !== undefined) {
@@ -4938,6 +4989,11 @@ window.__ModuleLoader__.load({
4938
4989
  for (const rawLine of text.split(/\r?\n/)) {
4939
4990
  const line = rawLine.trim();
4940
4991
  if (line === '') continue;
4992
+ // FASTA's comment convention: a line starting with ';' is a comment, not
4993
+ // sequence. It used to be appended verbatim (cleanSequence keeps letters),
4994
+ // so a commented file reported a longer sequence and a wrong GC% with no
4995
+ // warning — the most expensive kind of wrong answer.
4996
+ if (line.startsWith(';')) continue;
4941
4997
  if (line.startsWith('>')) {
4942
4998
  if (current !== undefined && current.sequence !== '') entries.push(current);
4943
4999
  const header = line.slice(1).trim();
@@ -6320,6 +6376,10 @@ window.__ModuleLoader__.load({
6320
6376
  for (let length = opts.probeLenMin; length <= opts.probeLenMax; length++) {
6321
6377
  for (let start = windowStart; start + length - 1 <= windowEnd; start++) {
6322
6378
  const sequence = work.slice(start, start + length);
6379
+ // An ambiguous base has no nearest-neighbour parameters, so `primerTm`
6380
+ // silently treats that step as 0 and the candidate gets a plausible-looking
6381
+ // Tm. A probe with an N cannot be ordered, so it must not be proposed.
6382
+ if (!/^[ACGT]+$/.test(sequence)) continue;
6323
6383
  const evaluated = evaluateProbe(sequence, {
6324
6384
  tmOpts: opts.tmOpts,
6325
6385
  ctMolar: opts.ctMolar,
@@ -9726,10 +9786,22 @@ window.__ModuleLoader__.load({
9726
9786
  return parts.join(' · ');
9727
9787
  }
9728
9788
 
9729
- /** The URL a paper's title links to, when it has one. */
9789
+ /**
9790
+ * The URL a paper's title links to, when it has one.
9791
+ *
9792
+ * Only http(s) survives: the value reaches an `<a href>` in the panel, and
9793
+ * `paper.url` comes from tool arguments and from web results — neither is a
9794
+ * trusted scheme (a `javascript:` URL would run on click). The PMID branch is
9795
+ * digits-only for the same reason.
9796
+ */
9730
9797
  function paperLink(paper) {
9731
- if (typeof paper.url === 'string' && paper.url !== '') return paper.url;
9732
- if (typeof paper.pmid === 'string' && paper.pmid !== '') return `https://pubmed.ncbi.nlm.nih.gov/${paper.pmid}/`;
9798
+ if (typeof paper.url === 'string') {
9799
+ const url = paper.url.trim();
9800
+ if (/^https?:\/\//i.test(url)) return url;
9801
+ }
9802
+ if (typeof paper.pmid === 'string' && /^\d+$/.test(paper.pmid.trim())) {
9803
+ return `https://pubmed.ncbi.nlm.nih.gov/${paper.pmid.trim()}/`;
9804
+ }
9733
9805
  return undefined;
9734
9806
  }
9735
9807
 
package/package.json CHANGED
@@ -1,12 +1,12 @@
1
1
  {
2
2
  "name": "dsh-molbio-tools",
3
- "version": "0.28.1",
3
+ "version": "0.28.2",
4
4
  "description": "Zero-dependency molecular-biology plugin bundle for the DeepSeek Harness: sequence analysis, primer design (incl. cross-intron qPCR primers, TaqMan hydrolysis/MGB probes with ordering CSV and multiplex compatibility, duplex thermodynamics (ΔH/ΔS/ΔG37/Tm with hairpin and dimer checks)), in-silico PCR, cloning simulation, SnapGene .dna parsing and plasmid maps, Sanger verification, protein tools (incl. helical wheel, hydropathy and charge-pH plots), methylation-aware restriction analysis with double-digest buffer checks, qPCR analysis and plotting, multiple sequence alignment that conserves every input residue, conservation analysis, sequence logos, codon-usage analysis, phylogenetic trees with bootstrap support, Newick I/O and long-name label wrapping, CpG-island/GC-skew composition analysis, k-mer dotplots, read-level FASTQ QC, vector/adapter contamination screening, FASTQ trimming/filtering, batch file analysis with CSV export, silent restriction-site mutagenesis, family-aware CRISPR gRNA design (SpCas9/SaCas9/Cas12a/Cas13) with off-target search, an opt-in hand-off that shows a generated plot to the model as an attached image, plus a browser-side right-sidebar panel (plasmid maps, sequence logos, and a rotatable realistic 3D ball-and-stick/space-filling preview of PDB/mmCIF/SDF structures drawn in the Web GUI) and a literature/protocol/experiment record system.",
5
5
  "type": "module",
6
6
  "main": "index.mjs",
7
7
  "engines": {
8
8
  "node": ">=24",
9
- "dsh": ">=0.2.1-rc.2 <0.3.0-0"
9
+ "dsh": ">=0.2.2-rc.2 <0.3.0-0"
10
10
  },
11
11
  "exports": {
12
12
  ".": "./index.mjs",
@@ -17,7 +17,10 @@
17
17
  },
18
18
  "scripts": {
19
19
  "build:client": "node build/client-bundle.mjs",
20
- "test": "node --run test:unit && node test/prompt.mjs && node test/contract.mjs && node test/drift-probe.mjs && node test/preset-health.mjs && node test/release.mjs && node test/benchmark-profile.mjs && node test/benchmark-score.mjs && node test/benchmark-coverage.mjs && node test/benchmark-changed.mjs && node --run bench:offline",
20
+ "check": "node build/check.mjs",
21
+ "check:strict": "node build/check.mjs --strict",
22
+ "check:suites": "node build/check.mjs --suites",
23
+ "test": "node build/check.mjs && node --run test:unit && node test/prompt.mjs && node test/contract.mjs && node test/drift-probe.mjs && node test/preset-health.mjs && node test/release.mjs && node test/benchmark-profile.mjs && node test/benchmark-score.mjs && node test/benchmark-coverage.mjs && node test/benchmark-changed.mjs && node --run bench:offline",
21
24
  "test:unit": "node test/smoke.mjs && node test/svgpng.mjs && node test/svgio.mjs && node test/charts.mjs && node test/structure.mjs && node test/client.mjs && node test/panel-render.mjs && node test/map-card.mjs && node test/client-mount.mjs",
22
25
  "test:smoke": "node test/smoke.mjs",
23
26
  "test:prompt": "node test/prompt.mjs",
@@ -106,11 +109,11 @@
106
109
  "compatibility": {
107
110
  "dshReleases": {
108
111
  "0.2.1-rc.1": "unknown",
109
- "0.2.1-rc.2": "compatible",
110
- "0.2.1-rc.3": "compatible",
112
+ "0.2.1-rc.2": "unknown",
113
+ "0.2.1-rc.3": "unknown",
111
114
  "0.2.1-rc.4": "unknown",
112
- "0.2.1-rc.5": "compatible",
113
- "0.2.2-rc.1": "compatible",
115
+ "0.2.1-rc.5": "unknown",
116
+ "0.2.2-rc.1": "unknown",
114
117
  "0.2.2-rc.2": "compatible",
115
118
  "0.2.2-rc.3": "compatible",
116
119
  "0.2.2-rc.4": "unknown",
package/pcr.mjs CHANGED
@@ -39,6 +39,14 @@ export const PCR_DEFAULTS = {
39
39
  min_size: 0,
40
40
  max_size: 100000,
41
41
  max_products: 200,
42
+ /**
43
+ * Hard ceiling on (forward site × reverse site) evaluations. A poly-A template
44
+ * with an 8-mer primer on each side yields ~n²/2 pairs: without a ceiling a
45
+ * 5 kb template allocates 12 million amplicon objects and a 1 Mb one exhausts
46
+ * memory. Reaching it sets `truncated`, so the caller is told the answer is
47
+ * partial instead of receiving a silent sample.
48
+ */
49
+ max_pair_evaluations: 200_000,
42
50
  /** Product sequences longer than this are not returned inline (size is). */
43
51
  max_returned_sequence: 5000,
44
52
  };
@@ -53,10 +61,13 @@ function baseMatches(primerBase, templateBase) {
53
61
  /** The product sequence of a template, taking the top strand with a modular slice. */
54
62
  function sliceSequence(sequence, start, length) {
55
63
  if (length >= sequence.length) {
56
- // More than one full turn of a circular template: tile it.
64
+ // More than one full turn of a circular template: tile it. Tiling to
65
+ // `length` was not enough — the slice starts at `start`, so the buffer needs
66
+ // `start + length` bases or a full-length product came back short (a 43 bp
67
+ // product starting at offset 10 returned 33 bases).
57
68
  let out = '';
58
- while (out.length < length) out += sequence;
59
- return out.slice(start, start + length) || out;
69
+ while (out.length < start + length) out += sequence;
70
+ return out.slice(start, start + length);
60
71
  }
61
72
  if (start + length <= sequence.length) return sequence.slice(start, start + length);
62
73
  return sequence.slice(start) + sequence.slice(0, start + length - sequence.length);
@@ -83,9 +94,13 @@ export function findBindingSites(template, primer, strand, options = {}) {
83
94
  const probe = strand === 'reverse' ? reverseComplement(primer) : primer;
84
95
  const length = template.length;
85
96
  if (!circular && length < probe.length) return [];
86
- const limit = circular ? length : length - probe.length;
97
+ // A circular template has exactly `length` start positions. Scanning
98
+ // `start <= length` examined position `length`, which is position 0 again, so
99
+ // one real site was reported twice (as start=61 on a 60 bp template) and the
100
+ // duplicated site produced a duplicate amplicon.
101
+ const windows = circular ? length : length - probe.length + 1;
87
102
  const sites = [];
88
- for (let start = 0; start <= limit; start++) {
103
+ for (let start = 0; start < windows; start++) {
89
104
  let mismatches = 0;
90
105
  let mismatchPositions = [];
91
106
  let matched = true;
@@ -154,8 +169,15 @@ export function simulatePair(template, pair, options = {}) {
154
169
  const reverseSites = findBindingSites(template, reverse, 'reverse', { ...settings, circular });
155
170
  const amplicons = [];
156
171
  let outOfRange = 0;
157
- for (const forwardSite of forwardSites) {
172
+ let pairsCapped = false;
173
+ let evaluated = 0;
174
+ outer: for (const forwardSite of forwardSites) {
158
175
  for (const reverseSite of reverseSites) {
176
+ if (evaluated >= settings.max_pair_evaluations) {
177
+ pairsCapped = true;
178
+ break outer;
179
+ }
180
+ evaluated += 1;
159
181
  // A product must run from the forward site's 3' end to the reverse
160
182
  // site's 5' end, i.e. the reverse site has to lie "after" it.
161
183
  const productStartIndex = forwardSite.start_index;
@@ -206,7 +228,7 @@ export function simulatePair(template, pair, options = {}) {
206
228
  reverse_sites: reverseSites,
207
229
  amplicons: capped,
208
230
  amplicon_count: capped.length,
209
- truncated: amplicons.length > capped.length,
231
+ truncated: pairsCapped || amplicons.length > capped.length,
210
232
  out_of_range: outOfRange,
211
233
  on_target_count: onTarget.length,
212
234
  off_target_count: capped.length - onTarget.length,
package/phylo.mjs CHANGED
@@ -1019,12 +1019,6 @@ export function renderTreeSvg(tree, {
1019
1019
  };
1020
1020
  });
1021
1021
  blocks = new Map(fitted.map((entry) => [entry.leafNode, entry.block]));
1022
- if (process.env.MOLBIO_PROBE_RADIAL === '1' && !fitted.every((entry) => entry.fits)) {
1023
- for (const entry of fitted.filter((e) => !e.fits)) {
1024
- const slot = (2 * Math.PI * (entry.reach + LABEL_GAP + entry.block.depth / 2)) / leaves.length;
1025
- console.log(` FAIL size=${size} ${entry.leafNode.name.slice(0, 14)} angle=${(entry.angle * 180 / Math.PI).toFixed(0)} anchor=${entry.anchor} reach=${entry.reach.toFixed(1)} w=${entry.block.width.toFixed(1)} h=${entry.block.height.toFixed(1)} depth=${entry.block.depth.toFixed(1)} lines=${entry.block.lines.length} slot=${slot.toFixed(1)} plot=${fitsInPlot(entry.angle, entry.anchor, entry.reach, entry.block, size)} slotOk=${fitsAngularSlot(entry.reach, entry.block, leaves.length)}`);
1026
- }
1027
- }
1028
1022
  if (fitted.every((entry) => entry.fits) || size <= minimumLeafFont) break;
1029
1023
  size = Math.max(minimumLeafFont, size - 0.5);
1030
1024
  }
package/seqio.mjs CHANGED
@@ -21,6 +21,11 @@ export function parseFasta(text) {
21
21
  for (const rawLine of text.split(/\r?\n/)) {
22
22
  const line = rawLine.trim();
23
23
  if (line === '') continue;
24
+ // FASTA's comment convention: a line starting with ';' is a comment, not
25
+ // sequence. It used to be appended verbatim (cleanSequence keeps letters),
26
+ // so a commented file reported a longer sequence and a wrong GC% with no
27
+ // warning — the most expensive kind of wrong answer.
28
+ if (line.startsWith(';')) continue;
24
29
  if (line.startsWith('>')) {
25
30
  if (current !== undefined && current.sequence !== '') entries.push(current);
26
31
  const header = line.slice(1).trim();
package/taqman.mjs CHANGED
@@ -251,6 +251,10 @@ export function probeCandidates(template, forwardInterval, reverseInterval, opts
251
251
  for (let length = opts.probeLenMin; length <= opts.probeLenMax; length++) {
252
252
  for (let start = windowStart; start + length - 1 <= windowEnd; start++) {
253
253
  const sequence = work.slice(start, start + length);
254
+ // An ambiguous base has no nearest-neighbour parameters, so `primerTm`
255
+ // silently treats that step as 0 and the candidate gets a plausible-looking
256
+ // Tm. A probe with an N cannot be ordered, so it must not be proposed.
257
+ if (!/^[ACGT]+$/.test(sequence)) continue;
254
258
  const evaluated = evaluateProbe(sequence, {
255
259
  tmOpts: opts.tmOpts,
256
260
  ctMolar: opts.ctMolar,
package/test/client.mjs CHANGED
@@ -558,6 +558,12 @@ assert.equal(panelCore.paperSummary(parsedLibrary.papers[2]), '');
558
558
  assert.equal(panelCore.paperLink(parsedLibrary.papers[0]), 'https://pubmed.ncbi.nlm.nih.gov/12345/');
559
559
  assert.equal(panelCore.paperLink(parsedLibrary.papers[1]), 'https://example.org/review');
560
560
  assert.equal(panelCore.paperLink(parsedLibrary.papers[2]), undefined);
561
+ // The link reaches an <a href>, and paper.url comes from tool arguments and web
562
+ // results — neither is a trusted scheme, so only http(s) may survive.
563
+ assert.equal(panelCore.paperLink({ url: 'javascript:alert(1)' }), undefined, 'a javascript: URL never becomes a link');
564
+ assert.equal(panelCore.paperLink({ url: 'file:///etc/passwd' }), undefined);
565
+ assert.equal(panelCore.paperLink({ url: 'https://example.org/x', pmid: '12ab' }), 'https://example.org/x');
566
+ assert.equal(panelCore.paperLink({ pmid: '12ab' }), undefined, 'a non-numeric PMID derives no link');
561
567
  assert.equal(panelCore.LIBRARY_FILE, 'papers.json');
562
568
  // The panel's file path matches the tool's default (papers.mjs DEFAULT_LIBRARY_FILE).
563
569
  const { DEFAULT_LIBRARY_FILE } = await import('../papers.mjs');
package/test/contract.mjs CHANGED
@@ -472,7 +472,7 @@ check('the published tarball carries the client half and exactly one plugin mani
472
472
  // SUBMISSION_PACKAGE_AMBIGUOUS, plus a duplicate 427 KB client bundle in every
473
473
  // download. The panel does not disappear for npm users: the root package's own
474
474
  // `lib/client.js` already carries it (the panel-only package exists for people
475
- // who want the tab without the 64 tools).
475
+ // who want the tab without the 72 tools).
476
476
  assert.ok(
477
477
  !files.includes('packages'),
478
478
  'the root tarball must not embed packages/molbio-panel: a second `dsh` manifest inside one package is an ambiguous submission, and the panel is published separately',
package/test/release.mjs CHANGED
@@ -45,7 +45,7 @@ import {
45
45
  versionShapeProblem,
46
46
  workspacePublishProblem,
47
47
  } from '../build/release-preflight.mjs';
48
- import { releaseNotes } from '../build/release-notes.mjs';
48
+ import { extractReleaseBullets, releaseNotes, renderNotes } from '../build/release-notes.mjs';
49
49
 
50
50
  const ROOT = resolve(import.meta.dirname, '..');
51
51
  const manifestOf = (directory) => JSON.parse(readFileSync(join(ROOT, directory, 'package.json'), 'utf8'));
@@ -174,19 +174,26 @@ const notes = [];
174
174
  notes.push(`CHANGELOG has a ${real.body.length}-character section for ${version}`);
175
175
  }
176
176
 
177
- // ── (5) the notes are the CHANGELOG's text, plus readable facts ─────────────
177
+ // ── (5) a Release carries new tools and fixes, and nothing else ─────────────
178
178
 
179
179
  {
180
+ const section = changelogSection(readFileSync(join(ROOT, 'CHANGELOG.md'), 'utf8'), version);
181
+ const bullets = extractReleaseBullets(section.body);
182
+ assert.ok(bullets.new.length + bullets.fix.length > 0, `the CHANGELOG entry for ${version} must carry "### 新增工具" or "### 修复" bullets`);
180
183
  const body = releaseNotes(`v${version}`, { root: ROOT });
181
- assert.ok(body.includes(changelogSection(readFileSync(join(ROOT, 'CHANGELOG.md'), 'utf8'), version).body.slice(0, 60)), 'the notes carry the CHANGELOG body');
182
- assert.ok(body.includes(`\`dsh-molbio-tools@${version}\``), 'the notes name the root version');
183
- assert.ok(body.includes('dsh-molbio-panel@'), 'the notes name the panel entry as well');
184
- assert.ok(body.includes('npm install -g dsh-molbio-tools'), 'and say how to install');
185
- assert.ok(body.includes(`blob/v${version}/CHANGELOG.md`), 'and link the full entry at the released tag');
184
+ for (const line of body.split('\n')) {
185
+ if (line === '' || line === '## 新增工具' || line === '## 修复') continue;
186
+ assert.match(line, /^- /, `release notes may carry only tool/fix bullets, got: ${line}`);
187
+ }
188
+ assert.ok(!/npm install|npm entries|CHANGELOG|blob\/v/.test(body), 'no install block, no admin text, no full-entry link');
189
+ // The parser ignores everything outside the two headings, and refuses an empty result.
190
+ assert.deepEqual(extractReleaseBullets('intro\n\n### 细节\n\n- internal only\n'), { new: [], fix: [] });
191
+ assert.deepEqual(extractReleaseBullets('### 新增工具\n\n- tool a\n\n### 修复\n\n- fixed b\n - detail stays in the CHANGELOG\n'), { new: ['tool a'], fix: ['fixed b'] });
192
+ assert.throws(() => renderNotes({ new: [], fix: [] }), /no release-note bullets/);
186
193
  // A tag with no section must refuse rather than publish empty notes.
187
194
  assert.throws(() => releaseNotes('v9.9.9', { root: ROOT }), /no "## 9\.9\.9" section/);
188
195
  assert.throws(() => releaseNotes('0.19.0', { root: ROOT }), /not the release form/);
189
- notes.push('release notes are derived from the CHANGELOG, and refuse an absent section');
196
+ notes.push('release notes carry only new tools and fixes, and refuse an empty section');
190
197
  }
191
198
 
192
199
  // ── (6) the manifest fields a profile needs ─────────────────────────────────
package/test/smoke.mjs CHANGED
@@ -36,7 +36,8 @@ const lib = await import('../lib.mjs');
36
36
  const view = await import('../view.mjs');
37
37
  const snapgene = await import('../snapgene.mjs');
38
38
  const { fastqQcReport } = await import('../fastq-qc.mjs');
39
- const { entryStats } = await import('../seqio.mjs');
39
+ const { entryStats, parseFasta } = await import('../seqio.mjs');
40
+ const { analyzeSequenceFile, globMatches } = await import('../batch.mjs');
40
41
  const { reverseComplement: reverseComplementOf } = lib;
41
42
 
42
43
  // The auto-view opener would spawn real viewer processes on the machine
@@ -228,6 +229,35 @@ async function run(toolName, args) {
228
229
  return value;
229
230
  }
230
231
 
232
+ // ── FASTA comment lines ──────────────────────────────────────────────────────
233
+ {
234
+ // FASTA's "a line starting with ; is a comment" convention. Such a line used to
235
+ // be appended to the sequence (letters survive cleanSequence), so a commented
236
+ // file reported a longer sequence and a wrong GC% with no warning.
237
+ const parsed = parseFasta('>a first\nACGT\n; a comment line\n; another\nTTTT\n');
238
+ assert.equal(parsed.length, 1);
239
+ assert.equal(parsed[0].sequence, 'ACGTTTTT', 'a ";" line is a comment, not sequence');
240
+ assert.equal(parsed[0].id, 'a');
241
+ assert.equal(parsed[0].description, 'first');
242
+ }
243
+
244
+ // ── argument validation: an undeclared key is an ERROR, never a silent default ─
245
+ {
246
+ const gc = registered.find((tool) => tool.name === 'molbio_gc_content');
247
+ await assert.rejects(
248
+ () => gc.execute({ sequence: 'ACGT', window_size: 10 }, fakeExec),
249
+ /unknown argument "window_size"/,
250
+ 'a misspelled argument must fail loudly instead of running with the default',
251
+ );
252
+ await assert.rejects(() => gc.execute({ sequence: 'ACGT', window: 1.5 }, fakeExec), /expected an integer/);
253
+ const map = registered.find((tool) => tool.name === 'molbio_plasmid_map');
254
+ await assert.rejects(
255
+ () => map.execute({ sequence: 'ACGT', features: [{ label: 'x', start: 1, end: 2, strand: 7 }] }, fakeExec),
256
+ /must be one of 1, -1/,
257
+ 'a numeric enum is enforced like a string one',
258
+ );
259
+ }
260
+
231
261
  /** Deterministic pseudo-random DNA for fixtures. */
232
262
  function makeTemplate(n, seed = 42) {
233
263
  let s = seed;
@@ -266,6 +296,12 @@ function makeTemplate(n, seed = 42) {
266
296
  calls.length = 0;
267
297
  assert.equal(await view.openDefaultViewer('/tmp/map.svg', { platform: 'linux', env: {}, run: fakeRun }), false, 'headless Linux never spawns a viewer');
268
298
  assert.equal(calls.length, 0);
299
+ // Only a rendered document may reach the OS opener. `output_path: "x.cmd"` used
300
+ // to write SVG text into a .cmd and then Invoke-Item EXECUTED it — the one way
301
+ // out of the tool sandbox.
302
+ assert.equal(await view.openDefaultViewer(at('evil.cmd'), { platform: 'win32', env: {}, run: fakeRun }), false, 'a script extension is never handed to the OS');
303
+ assert.equal(await view.openDefaultViewer(at('evil.ps1'), { platform: 'win32', env: {}, run: fakeRun }), false);
304
+ assert.equal(calls.length, 0, 'and no opener process starts');
269
305
  }
270
306
 
271
307
  {
@@ -572,6 +608,29 @@ function makeTemplate(n, seed = 42) {
572
608
  assert.deepEqual([junction.features[0].start, junction.features[0].end], [123, 124], 'a ^ junction reads as 123..124');
573
609
  assert.equal(junction.features[0].location, '123^124', 'and its original spelling is kept');
574
610
  assert.equal(junction.features[0].multi_part, false, 'a junction is one point, not several parts');
611
+
612
+ // A join() wider than the column wraps onto 21-space continuation lines. Those
613
+ // are LOCATION continuations: reading them as qualifier continuations silently
614
+ // dropped every part after the first line (1..100 came out as 1..60).
615
+ const folded = [
616
+ 'LOCUS TESTREC 200 bp DNA circular SYN 01-JAN-2020',
617
+ 'FEATURES Location/Qualifiers',
618
+ ' misc_feature join(1..10,50..60,',
619
+ ' 70..80,90..100)',
620
+ ' /label="folded"',
621
+ 'ORIGIN',
622
+ ' 1 acgtacgtac gtacgtacgt acgtacgtac gtgtacgtac gtacgtacgt acgtacgtac',
623
+ '//',
624
+ ].join('\n');
625
+ const foldedOut = await run('molbio_parse_genbank', { genbank: folded });
626
+ assert.deepEqual([foldedOut.features[0].start, foldedOut.features[0].end], [1, 100], 'a wrapped join() keeps every part');
627
+ assert.equal(foldedOut.features[0].label, 'folded', 'and its qualifier still attaches to the feature');
628
+
629
+ // The span is reduced with a loop, never Math.max(...numbers): a 130k-part
630
+ // join() threw RangeError instead of returning a coordinate.
631
+ const manyParts = Array.from({ length: 130000 }, (_, index) => `${index + 1}..${index + 2}`).join(',');
632
+ const bigJoin = await run('molbio_parse_genbank', { genbank: record(`join(${manyParts})`, 'big') });
633
+ assert.deepEqual([bigJoin.features[0].start, bigJoin.features[0].end], [1, 130001], 'a very large join() is still a span');
575
634
  }
576
635
 
577
636
  // ── plasmid map ─────────────────────────────────────────────────────────────
@@ -2836,6 +2895,23 @@ if (savedNcbiEnv.MOLBIO_NCBI_API_KEY !== undefined) process.env.MOLBIO_NCBI_API_
2836
2895
  const nested = await run('molbio_batch_analyze', { directory: 'batch', pattern: '*.fa', recursive: true, output_path: at('nested.csv') });
2837
2896
  assert.ok(nested.files.some((row) => row.path === 'batch/sub/nested.fa'));
2838
2897
 
2898
+ // Glob matching is linear. Translating `*` to `.*` backtracked exponentially
2899
+ // (measured ~1.4 s for this pattern on a 28-character name); the two-pointer
2900
+ // matcher answers immediately and keeps the same `*`/`?` semantics.
2901
+ const globStarted = Date.now();
2902
+ assert.equal(globMatches('*a*a*a*a*a*a*a*a*a*a*b', 'a'.repeat(28) + 'c'), false);
2903
+ assert.ok(Date.now() - globStarted < 100, 'a pathological glob pattern stays linear');
2904
+ assert.equal(globMatches('*.fa', 'x.fa'), true);
2905
+ assert.equal(globMatches('?', 'ab'), false);
2906
+
2907
+ // A 1 Mb genome at a 1 aa minimum yields ~166k ORFs. Reducing their lengths
2908
+ // must be a loop: Math.max(...lengths) threw RangeError and turned the row into
2909
+ // an "error" for a perfectly valid file.
2910
+ const genome = 'ATGTAA'.repeat(166666);
2911
+ const bigOrf = analyzeSequenceFile({ path: 'genome.fa', text: `>genome\n${genome}`, orfMinAa: 1 });
2912
+ assert.ok(bigOrf.orf_count > 0, 'ORF scanning still runs on a 1 Mb sequence');
2913
+ assert.equal(bigOrf.error, '');
2914
+
2839
2915
  // A limit is reported, not silently applied.
2840
2916
  const limited = await run('molbio_batch_analyze', { directory: 'batch', pattern: '*.fa', max_files: 1, output_path: at('limited.csv') });
2841
2917
  assert.equal(limited.file_count, 1);
@@ -3583,7 +3659,10 @@ if (savedNcbiEnv.MOLBIO_NCBI_API_KEY !== undefined) process.env.MOLBIO_NCBI_API_
3583
3659
  '@rna_r', 'ACGT' + reverseComplementOf(smallRna) + 'ACGT', '+', 'I'.repeat(8 + smallRna.length),
3584
3660
  '',
3585
3661
  ].join('\n');
3586
- const qcRna = await run('molbio_fastq_qc', { fastq: smallRnaFastq, adapter_scan_reads: 10, max_plot_bases: 100 });
3662
+ // No `adapter_scan_reads` here: that is an internal FASTQ_QC_DEFAULTS knob, not a
3663
+ // tool parameter. It used to be accepted-and-ignored; the argument validator now
3664
+ // rejects an undeclared key, which is how this test found the lie.
3665
+ const qcRna = await run('molbio_fastq_qc', { fastq: smallRnaFastq, max_plot_bases: 100 });
3587
3666
  assert.deepEqual(
3588
3667
  qcRna.adapter.hits.map((hit) => [hit.name, hit.reads, hit.percent]),
3589
3668
  [["Illumina Small RNA 5'", 2, 100]],
@@ -4181,6 +4260,45 @@ if (savedNcbiEnv.MOLBIO_NCBI_API_KEY !== undefined) process.env.MOLBIO_NCBI_API_
4181
4260
  assert.equal(circular.pairs[0].amplicons[0].wraps_origin, true);
4182
4261
  assert.equal(circular.pairs[0].amplicons[0].sequence, TEMPLATE.slice(150) + TEMPLATE.slice(0, 30), 'the slice wraps as template[151..200] + template[1..30]');
4183
4262
 
4263
+ // 6b. A circular template has exactly `length` start positions. Scanning the
4264
+ // extra one reported position 0 a second time (start=61 on a 60 bp
4265
+ // template) and drew the same amplicon twice.
4266
+ const dupe = await run('molbio_pcr_simulate', {
4267
+ template: 'ACGTACGT' + 'T'.repeat(52),
4268
+ primer_pairs: [{ name: 'dupe', forward: 'ACGTACGT', reverse: rc('ACGTACGT') }],
4269
+ circular: true,
4270
+ min_size: 8,
4271
+ max_size: 100,
4272
+ gel_path: at('pcr-dupe.svg'),
4273
+ });
4274
+ assert.equal(dupe.pairs[0].forward_sites.length, 1, 'no duplicate site at the wrap');
4275
+ assert.deepEqual(dupe.pairs[0].forward_sites.map((site) => site.start), [1]);
4276
+
4277
+ // 6c. A product as long as the template must come back whole: tiling to
4278
+ // `length` instead of `start + length` truncated a full-turn product.
4279
+ const fullTurn = 'ACGTTGCAAGTCCTAGGATCCGATATCGGCTAACGTTAACCGG';
4280
+ const fullTurnOut = await run('molbio_pcr_simulate', {
4281
+ template: fullTurn,
4282
+ primer_pairs: [{ name: 'turn', forward: fullTurn.slice(10, 18), reverse: rc(fullTurn.slice(2, 10)) }],
4283
+ circular: true,
4284
+ min_size: 8,
4285
+ max_size: 100,
4286
+ gel_path: at('pcr-turn.svg'),
4287
+ });
4288
+ assert.equal(fullTurnOut.pairs[0].amplicons[0].size, 43);
4289
+ assert.equal(fullTurnOut.pairs[0].amplicons[0].sequence, fullTurn.slice(10) + fullTurn.slice(0, 10), 'a full-turn product is not truncated');
4290
+
4291
+ // 6d. A poly-A template yields ~n²/2 candidate pairs. The evaluation budget
4292
+ // must stop that before it allocates millions of amplicons, and SAY so.
4293
+ const poly = await run('molbio_pcr_simulate', {
4294
+ template: 'A'.repeat(1200),
4295
+ primer_pairs: [{ name: 'poly', forward: 'AAAAAAAA', reverse: 'TTTTTTTT' }],
4296
+ max_size: 100000,
4297
+ gel_path: at('pcr-poly.svg'),
4298
+ });
4299
+ assert.equal(poly.pairs[0].truncated, true, 'the pair budget reports a partial answer');
4300
+ assert.ok(poly.pairs[0].amplicon_count <= 200);
4301
+
4184
4302
  // 7. Screening a different template (a vector) answers "does this pair also
4185
4303
  // amplify the backbone".
4186
4304
  const screened = await run('molbio_pcr_simulate', {
package/view.mjs CHANGED
@@ -15,8 +15,19 @@ import { spawn } from 'node:child_process';
15
15
  import { release as osRelease } from 'node:os';
16
16
  import { extname } from 'node:path';
17
17
 
18
+ /**
19
+ * The ONLY extensions this opener will hand to the operating system.
20
+ *
21
+ * Auto-view writes a caller-named file and then asks the desktop to OPEN it, so
22
+ * the extension decides what the OS runs. Without this whitelist, a call with
23
+ * `output_path: "x.cmd"` wrote SVG text into a .cmd and `Invoke-Item` executed
24
+ * it — the one path out of the tool sandbox. Everything this package generates
25
+ * is SVG (the document set below), so a narrower whitelist costs nothing.
26
+ */
27
+ const VIEWABLE_EXTENSIONS = new Set(['.html', '.htm', '.xhtml', '.svg']);
28
+
18
29
  /** Documents a browser renders, opened with the default browser when one can be named. */
19
- const BROWSER_DOCUMENTS = new Set(['.html', '.htm', '.xhtml', '.svg']);
30
+ const BROWSER_DOCUMENTS = VIEWABLE_EXTENSIONS;
20
31
 
21
32
  function present(value) {
22
33
  return value !== undefined && value !== '';
@@ -128,6 +139,7 @@ export async function openDefaultViewer(path, internals = {}) {
128
139
  const env = internals.env ?? process.env;
129
140
  const wsl = platform === 'linux' && isWsl(internals);
130
141
  const ext = extname(path).toLowerCase();
142
+ if (!VIEWABLE_EXTENSIONS.has(ext)) return false;
131
143
  if (!wsl && BROWSER_DOCUMENTS.has(ext) && await openInBrowser(path, internals)) return true;
132
144
  if (platform === 'darwin') {
133
145
  await runCommand('open', [path], internals);