@datagrok/helm 3.0.1 → 3.0.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (42) hide show
  1. package/CHANGELOG.md +13 -0
  2. package/CLAUDE.md +78 -92
  3. package/dist/489.js +2 -0
  4. package/dist/489.js.map +1 -0
  5. package/dist/package-test.js +1 -1
  6. package/dist/package-test.js.map +1 -1
  7. package/dist/package.js +1 -1
  8. package/dist/package.js.map +1 -1
  9. package/files/samples/helm-showcase.csv +7 -9
  10. package/package.json +12 -9
  11. package/src/helm-helper.ts +3 -0
  12. package/src/package-api.ts +1 -0
  13. package/src/package-test.ts +0 -4
  14. package/src/package.g.ts +2 -0
  15. package/src/package.ts +4 -1
  16. package/src/tests/helm-input-tests.ts +3 -3
  17. package/src/utils/helm-grid-cell-renderer.ts +3 -0
  18. package/test-console-output-1.log +344 -0
  19. package/test-playwright-report.json +118 -0
  20. package/test-record-1.mp4 +0 -0
  21. package/test-report-playwright.csv +1 -0
  22. package/tsconfig.json +2 -1
  23. package/dist/137.js +0 -2
  24. package/dist/137.js.map +0 -1
  25. package/dist/323.js +0 -2
  26. package/dist/323.js.map +0 -1
  27. package/dist/455.js +0 -2
  28. package/dist/455.js.map +0 -1
  29. package/dist/657.js +0 -2
  30. package/dist/657.js.map +0 -1
  31. package/dist/782.js +0 -2
  32. package/dist/782.js.map +0 -1
  33. package/dist/884.js +0 -2
  34. package/dist/884.js.map +0 -1
  35. package/dist/94.js +0 -2
  36. package/dist/94.js.map +0 -1
  37. package/dist/libraries_bio_src_monomer-works_seq-to-molfile-worker_ts.js +0 -16420
  38. package/dist/libraries_bio_src_monomer-works_seq-to-molfile-worker_ts.js.map +0 -1
  39. package/dist/package-dojo.js +0 -2
  40. package/dist/package-dojo.js.map +0 -1
  41. package/dist/vendors-HELM_node_modules_lru-cache_dist_esm_index_js.js +0 -1560
  42. package/dist/vendors-HELM_node_modules_lru-cache_dist_esm_index_js.js.map +0 -1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AAAoX,OAAA9X,IAAAyF,OAAAooB,MAAA7tB,KACAwf,EAAAoE,EAAA3Q,QAAAga,GAAAW,EACA,CACA,OAAankB,QAAAO,QAAAgd,SACb,CChiBA8G,UAAAC,IACA,MAAAC,QAAYA,EAAAC,UAAAA,EAAAC,gBAAAA,EAAAjJ,aAAAA,EAAAZ,SAAAA,EAAAnf,YAAAA,EAAAoJ,MAAAA,EAAAof,IAAAA,GAAuFK,EAAAI,KACnGC,EAAA,IAAA1Q,MAAAgQ,EAAApf,GACA+f,EAAA,IAAA3Q,MAAA,GACA,QAAA4Q,EAAAhgB,EAA2BggB,EAAAZ,IAAYY,EACvC,IACA,MAAAC,EAAAP,EAAAM,GACApJ,EAAA+I,EAAAA,EAAAK,QAAAhJ,EACAH,EAAA+I,EAAAA,EAAAI,QAAAhJ,EACA8I,EAAAE,EAAAhgB,GAAuCyW,GAAmBwJ,EAAAtJ,EAAAZ,EAAAnf,EAAAggB,EAAAC,EAC1D,CACA,MAAAqJ,GACA,MACAhxB,EAAA,8BAAsD8wB,MADtDE,aAAAvwB,MAAAuwB,EAAAlO,QAAAkO,EAAApuB,cAEAiuB,EAAArxB,KAAAQ,EACA,CAEAixB,YAAA,CAAkBC,SAAAN,EAAAO,SAAAN","sources":["webpack://helm/./node_modules/lru-cache/dist/esm/index.js","webpack://helm/./node_modules/@datagrok-libraries/hwe/dist/index.js","webpack://helm/./node_modules/@datagrok-libraries/bio/src/helm/consts.js","webpack://helm/./node_modules/@datagrok-libraries/bio/src/monomer-works/consts.js","webpack://helm/./node_modules/@datagrok-libraries/bio/src/monomer-works/types.js","webpack://helm/./node_modules/@datagrok-libraries/bio/src/utils/const.js","webpack://helm/./node_modules/@datagrok-libraries/bio/src/utils/macromolecule/consts.js","webpack://helm/./node_modules/@datagrok-libraries/bio/src/utils/macromolecule/types.js","webpack://helm/./node_modules/@datagrok-libraries/bio/src/monomer-works/monomer-works.js","webpack://helm/./node_modules/@datagrok-libraries/bio/src/monomer-works/to-atomic-level-utils.js","webpack://helm/./node_modules/@datagrok-libraries/bio/src/monomer-works/seq-to-molfile-worker.js"],"sourcesContent":["/**\n * @module LRUCache\n */\nconst perf = typeof performance === 'object' &&\n performance &&\n typeof performance.now === 'function'\n ? performance\n : Date;\nconst warned = new Set();\n/* c8 ignore start */\nconst PROCESS = (typeof process === 'object' && !!process ? process : {});\n/* c8 ignore start */\nconst emitWarning = (msg, type, code, fn) => {\n typeof PROCESS.emitWarning === 'function'\n ? PROCESS.emitWarning(msg, type, code, fn)\n : console.error(`[${code}] ${type}: ${msg}`);\n};\nlet AC = globalThis.AbortController;\nlet AS = globalThis.AbortSignal;\n/* c8 ignore start */\nif (typeof AC === 'undefined') {\n //@ts-ignore\n AS = class AbortSignal {\n onabort;\n _onabort = [];\n reason;\n aborted = false;\n addEventListener(_, fn) {\n this._onabort.push(fn);\n }\n };\n //@ts-ignore\n AC = class AbortController {\n constructor() {\n warnACPolyfill();\n }\n signal = new AS();\n abort(reason) {\n if (this.signal.aborted)\n return;\n //@ts-ignore\n this.signal.reason = reason;\n //@ts-ignore\n this.signal.aborted = true;\n //@ts-ignore\n for (const fn of this.signal._onabort) {\n fn(reason);\n }\n this.signal.onabort?.(reason);\n }\n };\n let printACPolyfillWarning = PROCESS.env?.LRU_CACHE_IGNORE_AC_WARNING !== '1';\n const warnACPolyfill = () => {\n if (!printACPolyfillWarning)\n return;\n printACPolyfillWarning = false;\n emitWarning('AbortController is not defined. If using lru-cache in ' +\n 'node 14, load an AbortController polyfill from the ' +\n '`node-abort-controller` package. A minimal polyfill is ' +\n 'provided for use by LRUCache.fetch(), but it should not be ' +\n 'relied upon in other contexts (eg, passing it to other APIs that ' +\n 'use AbortController/AbortSignal might have undesirable effects). ' +\n 'You may disable this with LRU_CACHE_IGNORE_AC_WARNING=1 in the env.', 'NO_ABORT_CONTROLLER', 'ENOTSUP', warnACPolyfill);\n };\n}\n/* c8 ignore stop */\nconst shouldWarn = (code) => !warned.has(code);\nconst TYPE = Symbol('type');\nconst isPosInt = (n) => n && n === Math.floor(n) && n > 0 && isFinite(n);\n/* c8 ignore start */\n// This is a little bit ridiculous, tbh.\n// The maximum array length is 2^32-1 or thereabouts on most JS impls.\n// And well before that point, you're caching the entire world, I mean,\n// that's ~32GB of just integers for the next/prev links, plus whatever\n// else to hold that many keys and values. Just filling the memory with\n// zeroes at init time is brutal when you get that big.\n// But why not be complete?\n// Maybe in the future, these limits will have expanded.\nconst getUintArray = (max) => !isPosInt(max)\n ? null\n : max <= Math.pow(2, 8)\n ? Uint8Array\n : max <= Math.pow(2, 16)\n ? Uint16Array\n : max <= Math.pow(2, 32)\n ? Uint32Array\n : max <= Number.MAX_SAFE_INTEGER\n ? ZeroArray\n : null;\n/* c8 ignore stop */\nclass ZeroArray extends Array {\n constructor(size) {\n super(size);\n this.fill(0);\n }\n}\nclass Stack {\n heap;\n length;\n // private constructor\n static #constructing = false;\n static create(max) {\n const HeapCls = getUintArray(max);\n if (!HeapCls)\n return [];\n Stack.#constructing = true;\n const s = new Stack(max, HeapCls);\n Stack.#constructing = false;\n return s;\n }\n constructor(max, HeapCls) {\n /* c8 ignore start */\n if (!Stack.#constructing) {\n throw new TypeError('instantiate Stack using Stack.create(n)');\n }\n /* c8 ignore stop */\n this.heap = new HeapCls(max);\n this.length = 0;\n }\n push(n) {\n this.heap[this.length++] = n;\n }\n pop() {\n return this.heap[--this.length];\n }\n}\n/**\n * Default export, the thing you're using this module to get.\n *\n * The `K` and `V` types define the key and value types, respectively. The\n * optional `FC` type defines the type of the `context` object passed to\n * `cache.fetch()` and `cache.memo()`.\n *\n * Keys and values **must not** be `null` or `undefined`.\n *\n * All properties from the options object (with the exception of `max`,\n * `maxSize`, `fetchMethod`, `memoMethod`, `dispose` and `disposeAfter`) are\n * added as normal public members. (The listed options are read-only getters.)\n *\n * Changing any of these will alter the defaults for subsequent method calls.\n */\nexport class LRUCache {\n // options that cannot be changed without disaster\n #max;\n #maxSize;\n #dispose;\n #disposeAfter;\n #fetchMethod;\n #memoMethod;\n /**\n * {@link LRUCache.OptionsBase.ttl}\n */\n ttl;\n /**\n * {@link LRUCache.OptionsBase.ttlResolution}\n */\n ttlResolution;\n /**\n * {@link LRUCache.OptionsBase.ttlAutopurge}\n */\n ttlAutopurge;\n /**\n * {@link LRUCache.OptionsBase.updateAgeOnGet}\n */\n updateAgeOnGet;\n /**\n * {@link LRUCache.OptionsBase.updateAgeOnHas}\n */\n updateAgeOnHas;\n /**\n * {@link LRUCache.OptionsBase.allowStale}\n */\n allowStale;\n /**\n * {@link LRUCache.OptionsBase.noDisposeOnSet}\n */\n noDisposeOnSet;\n /**\n * {@link LRUCache.OptionsBase.noUpdateTTL}\n */\n noUpdateTTL;\n /**\n * {@link LRUCache.OptionsBase.maxEntrySize}\n */\n maxEntrySize;\n /**\n * {@link LRUCache.OptionsBase.sizeCalculation}\n */\n sizeCalculation;\n /**\n * {@link LRUCache.OptionsBase.noDeleteOnFetchRejection}\n */\n noDeleteOnFetchRejection;\n /**\n * {@link LRUCache.OptionsBase.noDeleteOnStaleGet}\n */\n noDeleteOnStaleGet;\n /**\n * {@link LRUCache.OptionsBase.allowStaleOnFetchAbort}\n */\n allowStaleOnFetchAbort;\n /**\n * {@link LRUCache.OptionsBase.allowStaleOnFetchRejection}\n */\n allowStaleOnFetchRejection;\n /**\n * {@link LRUCache.OptionsBase.ignoreFetchAbort}\n */\n ignoreFetchAbort;\n // computed properties\n #size;\n #calculatedSize;\n #keyMap;\n #keyList;\n #valList;\n #next;\n #prev;\n #head;\n #tail;\n #free;\n #disposed;\n #sizes;\n #starts;\n #ttls;\n #hasDispose;\n #hasFetchMethod;\n #hasDisposeAfter;\n /**\n * Do not call this method unless you need to inspect the\n * inner workings of the cache. If anything returned by this\n * object is modified in any way, strange breakage may occur.\n *\n * These fields are private for a reason!\n *\n * @internal\n */\n static unsafeExposeInternals(c) {\n return {\n // properties\n starts: c.#starts,\n ttls: c.#ttls,\n sizes: c.#sizes,\n keyMap: c.#keyMap,\n keyList: c.#keyList,\n valList: c.#valList,\n next: c.#next,\n prev: c.#prev,\n get head() {\n return c.#head;\n },\n get tail() {\n return c.#tail;\n },\n free: c.#free,\n // methods\n isBackgroundFetch: (p) => c.#isBackgroundFetch(p),\n backgroundFetch: (k, index, options, context) => c.#backgroundFetch(k, index, options, context),\n moveToTail: (index) => c.#moveToTail(index),\n indexes: (options) => c.#indexes(options),\n rindexes: (options) => c.#rindexes(options),\n isStale: (index) => c.#isStale(index),\n };\n }\n // Protected read-only members\n /**\n * {@link LRUCache.OptionsBase.max} (read-only)\n */\n get max() {\n return this.#max;\n }\n /**\n * {@link LRUCache.OptionsBase.maxSize} (read-only)\n */\n get maxSize() {\n return this.#maxSize;\n }\n /**\n * The total computed size of items in the cache (read-only)\n */\n get calculatedSize() {\n return this.#calculatedSize;\n }\n /**\n * The number of items stored in the cache (read-only)\n */\n get size() {\n return this.#size;\n }\n /**\n * {@link LRUCache.OptionsBase.fetchMethod} (read-only)\n */\n get fetchMethod() {\n return this.#fetchMethod;\n }\n get memoMethod() {\n return this.#memoMethod;\n }\n /**\n * {@link LRUCache.OptionsBase.dispose} (read-only)\n */\n get dispose() {\n return this.#dispose;\n }\n /**\n * {@link LRUCache.OptionsBase.disposeAfter} (read-only)\n */\n get disposeAfter() {\n return this.#disposeAfter;\n }\n constructor(options) {\n const { max = 0, ttl, ttlResolution = 1, ttlAutopurge, updateAgeOnGet, updateAgeOnHas, allowStale, dispose, disposeAfter, noDisposeOnSet, noUpdateTTL, maxSize = 0, maxEntrySize = 0, sizeCalculation, fetchMethod, memoMethod, noDeleteOnFetchRejection, noDeleteOnStaleGet, allowStaleOnFetchRejection, allowStaleOnFetchAbort, ignoreFetchAbort, } = options;\n if (max !== 0 && !isPosInt(max)) {\n throw new TypeError('max option must be a nonnegative integer');\n }\n const UintArray = max ? getUintArray(max) : Array;\n if (!UintArray) {\n throw new Error('invalid max value: ' + max);\n }\n this.#max = max;\n this.#maxSize = maxSize;\n this.maxEntrySize = maxEntrySize || this.#maxSize;\n this.sizeCalculation = sizeCalculation;\n if (this.sizeCalculation) {\n if (!this.#maxSize && !this.maxEntrySize) {\n throw new TypeError('cannot set sizeCalculation without setting maxSize or maxEntrySize');\n }\n if (typeof this.sizeCalculation !== 'function') {\n throw new TypeError('sizeCalculation set to non-function');\n }\n }\n if (memoMethod !== undefined &&\n typeof memoMethod !== 'function') {\n throw new TypeError('memoMethod must be a function if defined');\n }\n this.#memoMethod = memoMethod;\n if (fetchMethod !== undefined &&\n typeof fetchMethod !== 'function') {\n throw new TypeError('fetchMethod must be a function if specified');\n }\n this.#fetchMethod = fetchMethod;\n this.#hasFetchMethod = !!fetchMethod;\n this.#keyMap = new Map();\n this.#keyList = new Array(max).fill(undefined);\n this.#valList = new Array(max).fill(undefined);\n this.#next = new UintArray(max);\n this.#prev = new UintArray(max);\n this.#head = 0;\n this.#tail = 0;\n this.#free = Stack.create(max);\n this.#size = 0;\n this.#calculatedSize = 0;\n if (typeof dispose === 'function') {\n this.#dispose = dispose;\n }\n if (typeof disposeAfter === 'function') {\n this.#disposeAfter = disposeAfter;\n this.#disposed = [];\n }\n else {\n this.#disposeAfter = undefined;\n this.#disposed = undefined;\n }\n this.#hasDispose = !!this.#dispose;\n this.#hasDisposeAfter = !!this.#disposeAfter;\n this.noDisposeOnSet = !!noDisposeOnSet;\n this.noUpdateTTL = !!noUpdateTTL;\n this.noDeleteOnFetchRejection = !!noDeleteOnFetchRejection;\n this.allowStaleOnFetchRejection = !!allowStaleOnFetchRejection;\n this.allowStaleOnFetchAbort = !!allowStaleOnFetchAbort;\n this.ignoreFetchAbort = !!ignoreFetchAbort;\n // NB: maxEntrySize is set to maxSize if it's set\n if (this.maxEntrySize !== 0) {\n if (this.#maxSize !== 0) {\n if (!isPosInt(this.#maxSize)) {\n throw new TypeError('maxSize must be a positive integer if specified');\n }\n }\n if (!isPosInt(this.maxEntrySize)) {\n throw new TypeError('maxEntrySize must be a positive integer if specified');\n }\n this.#initializeSizeTracking();\n }\n this.allowStale = !!allowStale;\n this.noDeleteOnStaleGet = !!noDeleteOnStaleGet;\n this.updateAgeOnGet = !!updateAgeOnGet;\n this.updateAgeOnHas = !!updateAgeOnHas;\n this.ttlResolution =\n isPosInt(ttlResolution) || ttlResolution === 0\n ? ttlResolution\n : 1;\n this.ttlAutopurge = !!ttlAutopurge;\n this.ttl = ttl || 0;\n if (this.ttl) {\n if (!isPosInt(this.ttl)) {\n throw new TypeError('ttl must be a positive integer if specified');\n }\n this.#initializeTTLTracking();\n }\n // do not allow completely unbounded caches\n if (this.#max === 0 && this.ttl === 0 && this.#maxSize === 0) {\n throw new TypeError('At least one of max, maxSize, or ttl is required');\n }\n if (!this.ttlAutopurge && !this.#max && !this.#maxSize) {\n const code = 'LRU_CACHE_UNBOUNDED';\n if (shouldWarn(code)) {\n warned.add(code);\n const msg = 'TTL caching without ttlAutopurge, max, or maxSize can ' +\n 'result in unbounded memory consumption.';\n emitWarning(msg, 'UnboundedCacheWarning', code, LRUCache);\n }\n }\n }\n /**\n * Return the number of ms left in the item's TTL. If item is not in cache,\n * returns `0`. Returns `Infinity` if item is in cache without a defined TTL.\n */\n getRemainingTTL(key) {\n return this.#keyMap.has(key) ? Infinity : 0;\n }\n #initializeTTLTracking() {\n const ttls = new ZeroArray(this.#max);\n const starts = new ZeroArray(this.#max);\n this.#ttls = ttls;\n this.#starts = starts;\n this.#setItemTTL = (index, ttl, start = perf.now()) => {\n starts[index] = ttl !== 0 ? start : 0;\n ttls[index] = ttl;\n if (ttl !== 0 && this.ttlAutopurge) {\n const t = setTimeout(() => {\n if (this.#isStale(index)) {\n this.#delete(this.#keyList[index], 'expire');\n }\n }, ttl + 1);\n // unref() not supported on all platforms\n /* c8 ignore start */\n if (t.unref) {\n t.unref();\n }\n /* c8 ignore stop */\n }\n };\n this.#updateItemAge = index => {\n starts[index] = ttls[index] !== 0 ? perf.now() : 0;\n };\n this.#statusTTL = (status, index) => {\n if (ttls[index]) {\n const ttl = ttls[index];\n const start = starts[index];\n /* c8 ignore next */\n if (!ttl || !start)\n return;\n status.ttl = ttl;\n status.start = start;\n status.now = cachedNow || getNow();\n const age = status.now - start;\n status.remainingTTL = ttl - age;\n }\n };\n // debounce calls to perf.now() to 1s so we're not hitting\n // that costly call repeatedly.\n let cachedNow = 0;\n const getNow = () => {\n const n = perf.now();\n if (this.ttlResolution > 0) {\n cachedNow = n;\n const t = setTimeout(() => (cachedNow = 0), this.ttlResolution);\n // not available on all platforms\n /* c8 ignore start */\n if (t.unref) {\n t.unref();\n }\n /* c8 ignore stop */\n }\n return n;\n };\n this.getRemainingTTL = key => {\n const index = this.#keyMap.get(key);\n if (index === undefined) {\n return 0;\n }\n const ttl = ttls[index];\n const start = starts[index];\n if (!ttl || !start) {\n return Infinity;\n }\n const age = (cachedNow || getNow()) - start;\n return ttl - age;\n };\n this.#isStale = index => {\n const s = starts[index];\n const t = ttls[index];\n return !!t && !!s && (cachedNow || getNow()) - s > t;\n };\n }\n // conditionally set private methods related to TTL\n #updateItemAge = () => { };\n #statusTTL = () => { };\n #setItemTTL = () => { };\n /* c8 ignore stop */\n #isStale = () => false;\n #initializeSizeTracking() {\n const sizes = new ZeroArray(this.#max);\n this.#calculatedSize = 0;\n this.#sizes = sizes;\n this.#removeItemSize = index => {\n this.#calculatedSize -= sizes[index];\n sizes[index] = 0;\n };\n this.#requireSize = (k, v, size, sizeCalculation) => {\n // provisionally accept background fetches.\n // actual value size will be checked when they return.\n if (this.#isBackgroundFetch(v)) {\n return 0;\n }\n if (!isPosInt(size)) {\n if (sizeCalculation) {\n if (typeof sizeCalculation !== 'function') {\n throw new TypeError('sizeCalculation must be a function');\n }\n size = sizeCalculation(v, k);\n if (!isPosInt(size)) {\n throw new TypeError('sizeCalculation return invalid (expect positive integer)');\n }\n }\n else {\n throw new TypeError('invalid size value (must be positive integer). ' +\n 'When maxSize or maxEntrySize is used, sizeCalculation ' +\n 'or size must be set.');\n }\n }\n return size;\n };\n this.#addItemSize = (index, size, status) => {\n sizes[index] = size;\n if (this.#maxSize) {\n const maxSize = this.#maxSize - sizes[index];\n while (this.#calculatedSize > maxSize) {\n this.#evict(true);\n }\n }\n this.#calculatedSize += sizes[index];\n if (status) {\n status.entrySize = size;\n status.totalCalculatedSize = this.#calculatedSize;\n }\n };\n }\n #removeItemSize = _i => { };\n #addItemSize = (_i, _s, _st) => { };\n #requireSize = (_k, _v, size, sizeCalculation) => {\n if (size || sizeCalculation) {\n throw new TypeError('cannot set size without setting maxSize or maxEntrySize on cache');\n }\n return 0;\n };\n *#indexes({ allowStale = this.allowStale } = {}) {\n if (this.#size) {\n for (let i = this.#tail; true;) {\n if (!this.#isValidIndex(i)) {\n break;\n }\n if (allowStale || !this.#isStale(i)) {\n yield i;\n }\n if (i === this.#head) {\n break;\n }\n else {\n i = this.#prev[i];\n }\n }\n }\n }\n *#rindexes({ allowStale = this.allowStale } = {}) {\n if (this.#size) {\n for (let i = this.#head; true;) {\n if (!this.#isValidIndex(i)) {\n break;\n }\n if (allowStale || !this.#isStale(i)) {\n yield i;\n }\n if (i === this.#tail) {\n break;\n }\n else {\n i = this.#next[i];\n }\n }\n }\n }\n #isValidIndex(index) {\n return (index !== undefined &&\n this.#keyMap.get(this.#keyList[index]) === index);\n }\n /**\n * Return a generator yielding `[key, value]` pairs,\n * in order from most recently used to least recently used.\n */\n *entries() {\n for (const i of this.#indexes()) {\n if (this.#valList[i] !== undefined &&\n this.#keyList[i] !== undefined &&\n !this.#isBackgroundFetch(this.#valList[i])) {\n yield [this.#keyList[i], this.#valList[i]];\n }\n }\n }\n /**\n * Inverse order version of {@link LRUCache.entries}\n *\n * Return a generator yielding `[key, value]` pairs,\n * in order from least recently used to most recently used.\n */\n *rentries() {\n for (const i of this.#rindexes()) {\n if (this.#valList[i] !== undefined &&\n this.#keyList[i] !== undefined &&\n !this.#isBackgroundFetch(this.#valList[i])) {\n yield [this.#keyList[i], this.#valList[i]];\n }\n }\n }\n /**\n * Return a generator yielding the keys in the cache,\n * in order from most recently used to least recently used.\n */\n *keys() {\n for (const i of this.#indexes()) {\n const k = this.#keyList[i];\n if (k !== undefined &&\n !this.#isBackgroundFetch(this.#valList[i])) {\n yield k;\n }\n }\n }\n /**\n * Inverse order version of {@link LRUCache.keys}\n *\n * Return a generator yielding the keys in the cache,\n * in order from least recently used to most recently used.\n */\n *rkeys() {\n for (const i of this.#rindexes()) {\n const k = this.#keyList[i];\n if (k !== undefined &&\n !this.#isBackgroundFetch(this.#valList[i])) {\n yield k;\n }\n }\n }\n /**\n * Return a generator yielding the values in the cache,\n * in order from most recently used to least recently used.\n */\n *values() {\n for (const i of this.#indexes()) {\n const v = this.#valList[i];\n if (v !== undefined &&\n !this.#isBackgroundFetch(this.#valList[i])) {\n yield this.#valList[i];\n }\n }\n }\n /**\n * Inverse order version of {@link LRUCache.values}\n *\n * Return a generator yielding the values in the cache,\n * in order from least recently used to most recently used.\n */\n *rvalues() {\n for (const i of this.#rindexes()) {\n const v = this.#valList[i];\n if (v !== undefined &&\n !this.#isBackgroundFetch(this.#valList[i])) {\n yield this.#valList[i];\n }\n }\n }\n /**\n * Iterating over the cache itself yields the same results as\n * {@link LRUCache.entries}\n */\n [Symbol.iterator]() {\n return this.entries();\n }\n /**\n * A String value that is used in the creation of the default string\n * description of an object. Called by the built-in method\n * `Object.prototype.toString`.\n */\n [Symbol.toStringTag] = 'LRUCache';\n /**\n * Find a value for which the supplied fn method returns a truthy value,\n * similar to `Array.find()`. fn is called as `fn(value, key, cache)`.\n */\n find(fn, getOptions = {}) {\n for (const i of this.#indexes()) {\n const v = this.#valList[i];\n const value = this.#isBackgroundFetch(v)\n ? v.__staleWhileFetching\n : v;\n if (value === undefined)\n continue;\n if (fn(value, this.#keyList[i], this)) {\n return this.get(this.#keyList[i], getOptions);\n }\n }\n }\n /**\n * Call the supplied function on each item in the cache, in order from most\n * recently used to least recently used.\n *\n * `fn` is called as `fn(value, key, cache)`.\n *\n * If `thisp` is provided, function will be called in the `this`-context of\n * the provided object, or the cache if no `thisp` object is provided.\n *\n * Does not update age or recenty of use, or iterate over stale values.\n */\n forEach(fn, thisp = this) {\n for (const i of this.#indexes()) {\n const v = this.#valList[i];\n const value = this.#isBackgroundFetch(v)\n ? v.__staleWhileFetching\n : v;\n if (value === undefined)\n continue;\n fn.call(thisp, value, this.#keyList[i], this);\n }\n }\n /**\n * The same as {@link LRUCache.forEach} but items are iterated over in\n * reverse order. (ie, less recently used items are iterated over first.)\n */\n rforEach(fn, thisp = this) {\n for (const i of this.#rindexes()) {\n const v = this.#valList[i];\n const value = this.#isBackgroundFetch(v)\n ? v.__staleWhileFetching\n : v;\n if (value === undefined)\n continue;\n fn.call(thisp, value, this.#keyList[i], this);\n }\n }\n /**\n * Delete any stale entries. Returns true if anything was removed,\n * false otherwise.\n */\n purgeStale() {\n let deleted = false;\n for (const i of this.#rindexes({ allowStale: true })) {\n if (this.#isStale(i)) {\n this.#delete(this.#keyList[i], 'expire');\n deleted = true;\n }\n }\n return deleted;\n }\n /**\n * Get the extended info about a given entry, to get its value, size, and\n * TTL info simultaneously. Returns `undefined` if the key is not present.\n *\n * Unlike {@link LRUCache#dump}, which is designed to be portable and survive\n * serialization, the `start` value is always the current timestamp, and the\n * `ttl` is a calculated remaining time to live (negative if expired).\n *\n * Always returns stale values, if their info is found in the cache, so be\n * sure to check for expirations (ie, a negative {@link LRUCache.Entry#ttl})\n * if relevant.\n */\n info(key) {\n const i = this.#keyMap.get(key);\n if (i === undefined)\n return undefined;\n const v = this.#valList[i];\n const value = this.#isBackgroundFetch(v)\n ? v.__staleWhileFetching\n : v;\n if (value === undefined)\n return undefined;\n const entry = { value };\n if (this.#ttls && this.#starts) {\n const ttl = this.#ttls[i];\n const start = this.#starts[i];\n if (ttl && start) {\n const remain = ttl - (perf.now() - start);\n entry.ttl = remain;\n entry.start = Date.now();\n }\n }\n if (this.#sizes) {\n entry.size = this.#sizes[i];\n }\n return entry;\n }\n /**\n * Return an array of [key, {@link LRUCache.Entry}] tuples which can be\n * passed to {@link LRLUCache#load}.\n *\n * The `start` fields are calculated relative to a portable `Date.now()`\n * timestamp, even if `performance.now()` is available.\n *\n * Stale entries are always included in the `dump`, even if\n * {@link LRUCache.OptionsBase.allowStale} is false.\n *\n * Note: this returns an actual array, not a generator, so it can be more\n * easily passed around.\n */\n dump() {\n const arr = [];\n for (const i of this.#indexes({ allowStale: true })) {\n const key = this.#keyList[i];\n const v = this.#valList[i];\n const value = this.#isBackgroundFetch(v)\n ? v.__staleWhileFetching\n : v;\n if (value === undefined || key === undefined)\n continue;\n const entry = { value };\n if (this.#ttls && this.#starts) {\n entry.ttl = this.#ttls[i];\n // always dump the start relative to a portable timestamp\n // it's ok for this to be a bit slow, it's a rare operation.\n const age = perf.now() - this.#starts[i];\n entry.start = Math.floor(Date.now() - age);\n }\n if (this.#sizes) {\n entry.size = this.#sizes[i];\n }\n arr.unshift([key, entry]);\n }\n return arr;\n }\n /**\n * Reset the cache and load in the items in entries in the order listed.\n *\n * The shape of the resulting cache may be different if the same options are\n * not used in both caches.\n *\n * The `start` fields are assumed to be calculated relative to a portable\n * `Date.now()` timestamp, even if `performance.now()` is available.\n */\n load(arr) {\n this.clear();\n for (const [key, entry] of arr) {\n if (entry.start) {\n // entry.start is a portable timestamp, but we may be using\n // node's performance.now(), so calculate the offset, so that\n // we get the intended remaining TTL, no matter how long it's\n // been on ice.\n //\n // it's ok for this to be a bit slow, it's a rare operation.\n const age = Date.now() - entry.start;\n entry.start = perf.now() - age;\n }\n this.set(key, entry.value, entry);\n }\n }\n /**\n * Add a value to the cache.\n *\n * Note: if `undefined` is specified as a value, this is an alias for\n * {@link LRUCache#delete}\n *\n * Fields on the {@link LRUCache.SetOptions} options param will override\n * their corresponding values in the constructor options for the scope\n * of this single `set()` operation.\n *\n * If `start` is provided, then that will set the effective start\n * time for the TTL calculation. Note that this must be a previous\n * value of `performance.now()` if supported, or a previous value of\n * `Date.now()` if not.\n *\n * Options object may also include `size`, which will prevent\n * calling the `sizeCalculation` function and just use the specified\n * number if it is a positive integer, and `noDisposeOnSet` which\n * will prevent calling a `dispose` function in the case of\n * overwrites.\n *\n * If the `size` (or return value of `sizeCalculation`) for a given\n * entry is greater than `maxEntrySize`, then the item will not be\n * added to the cache.\n *\n * Will update the recency of the entry.\n *\n * If the value is `undefined`, then this is an alias for\n * `cache.delete(key)`. `undefined` is never stored in the cache.\n */\n set(k, v, setOptions = {}) {\n if (v === undefined) {\n this.delete(k);\n return this;\n }\n const { ttl = this.ttl, start, noDisposeOnSet = this.noDisposeOnSet, sizeCalculation = this.sizeCalculation, status, } = setOptions;\n let { noUpdateTTL = this.noUpdateTTL } = setOptions;\n const size = this.#requireSize(k, v, setOptions.size || 0, sizeCalculation);\n // if the item doesn't fit, don't do anything\n // NB: maxEntrySize set to maxSize by default\n if (this.maxEntrySize && size > this.maxEntrySize) {\n if (status) {\n status.set = 'miss';\n status.maxEntrySizeExceeded = true;\n }\n // have to delete, in case something is there already.\n this.#delete(k, 'set');\n return this;\n }\n let index = this.#size === 0 ? undefined : this.#keyMap.get(k);\n if (index === undefined) {\n // addition\n index = (this.#size === 0\n ? this.#tail\n : this.#free.length !== 0\n ? this.#free.pop()\n : this.#size === this.#max\n ? this.#evict(false)\n : this.#size);\n this.#keyList[index] = k;\n this.#valList[index] = v;\n this.#keyMap.set(k, index);\n this.#next[this.#tail] = index;\n this.#prev[index] = this.#tail;\n this.#tail = index;\n this.#size++;\n this.#addItemSize(index, size, status);\n if (status)\n status.set = 'add';\n noUpdateTTL = false;\n }\n else {\n // update\n this.#moveToTail(index);\n const oldVal = this.#valList[index];\n if (v !== oldVal) {\n if (this.#hasFetchMethod && this.#isBackgroundFetch(oldVal)) {\n oldVal.__abortController.abort(new Error('replaced'));\n const { __staleWhileFetching: s } = oldVal;\n if (s !== undefined && !noDisposeOnSet) {\n if (this.#hasDispose) {\n this.#dispose?.(s, k, 'set');\n }\n if (this.#hasDisposeAfter) {\n this.#disposed?.push([s, k, 'set']);\n }\n }\n }\n else if (!noDisposeOnSet) {\n if (this.#hasDispose) {\n this.#dispose?.(oldVal, k, 'set');\n }\n if (this.#hasDisposeAfter) {\n this.#disposed?.push([oldVal, k, 'set']);\n }\n }\n this.#removeItemSize(index);\n this.#addItemSize(index, size, status);\n this.#valList[index] = v;\n if (status) {\n status.set = 'replace';\n const oldValue = oldVal && this.#isBackgroundFetch(oldVal)\n ? oldVal.__staleWhileFetching\n : oldVal;\n if (oldValue !== undefined)\n status.oldValue = oldValue;\n }\n }\n else if (status) {\n status.set = 'update';\n }\n }\n if (ttl !== 0 && !this.#ttls) {\n this.#initializeTTLTracking();\n }\n if (this.#ttls) {\n if (!noUpdateTTL) {\n this.#setItemTTL(index, ttl, start);\n }\n if (status)\n this.#statusTTL(status, index);\n }\n if (!noDisposeOnSet && this.#hasDisposeAfter && this.#disposed) {\n const dt = this.#disposed;\n let task;\n while ((task = dt?.shift())) {\n this.#disposeAfter?.(...task);\n }\n }\n return this;\n }\n /**\n * Evict the least recently used item, returning its value or\n * `undefined` if cache is empty.\n */\n pop() {\n try {\n while (this.#size) {\n const val = this.#valList[this.#head];\n this.#evict(true);\n if (this.#isBackgroundFetch(val)) {\n if (val.__staleWhileFetching) {\n return val.__staleWhileFetching;\n }\n }\n else if (val !== undefined) {\n return val;\n }\n }\n }\n finally {\n if (this.#hasDisposeAfter && this.#disposed) {\n const dt = this.#disposed;\n let task;\n while ((task = dt?.shift())) {\n this.#disposeAfter?.(...task);\n }\n }\n }\n }\n #evict(free) {\n const head = this.#head;\n const k = this.#keyList[head];\n const v = this.#valList[head];\n if (this.#hasFetchMethod && this.#isBackgroundFetch(v)) {\n v.__abortController.abort(new Error('evicted'));\n }\n else if (this.#hasDispose || this.#hasDisposeAfter) {\n if (this.#hasDispose) {\n this.#dispose?.(v, k, 'evict');\n }\n if (this.#hasDisposeAfter) {\n this.#disposed?.push([v, k, 'evict']);\n }\n }\n this.#removeItemSize(head);\n // if we aren't about to use the index, then null these out\n if (free) {\n this.#keyList[head] = undefined;\n this.#valList[head] = undefined;\n this.#free.push(head);\n }\n if (this.#size === 1) {\n this.#head = this.#tail = 0;\n this.#free.length = 0;\n }\n else {\n this.#head = this.#next[head];\n }\n this.#keyMap.delete(k);\n this.#size--;\n return head;\n }\n /**\n * Check if a key is in the cache, without updating the recency of use.\n * Will return false if the item is stale, even though it is technically\n * in the cache.\n *\n * Check if a key is in the cache, without updating the recency of\n * use. Age is updated if {@link LRUCache.OptionsBase.updateAgeOnHas} is set\n * to `true` in either the options or the constructor.\n *\n * Will return `false` if the item is stale, even though it is technically in\n * the cache. The difference can be determined (if it matters) by using a\n * `status` argument, and inspecting the `has` field.\n *\n * Will not update item age unless\n * {@link LRUCache.OptionsBase.updateAgeOnHas} is set.\n */\n has(k, hasOptions = {}) {\n const { updateAgeOnHas = this.updateAgeOnHas, status } = hasOptions;\n const index = this.#keyMap.get(k);\n if (index !== undefined) {\n const v = this.#valList[index];\n if (this.#isBackgroundFetch(v) &&\n v.__staleWhileFetching === undefined) {\n return false;\n }\n if (!this.#isStale(index)) {\n if (updateAgeOnHas) {\n this.#updateItemAge(index);\n }\n if (status) {\n status.has = 'hit';\n this.#statusTTL(status, index);\n }\n return true;\n }\n else if (status) {\n status.has = 'stale';\n this.#statusTTL(status, index);\n }\n }\n else if (status) {\n status.has = 'miss';\n }\n return false;\n }\n /**\n * Like {@link LRUCache#get} but doesn't update recency or delete stale\n * items.\n *\n * Returns `undefined` if the item is stale, unless\n * {@link LRUCache.OptionsBase.allowStale} is set.\n */\n peek(k, peekOptions = {}) {\n const { allowStale = this.allowStale } = peekOptions;\n const index = this.#keyMap.get(k);\n if (index === undefined ||\n (!allowStale && this.#isStale(index))) {\n return;\n }\n const v = this.#valList[index];\n // either stale and allowed, or forcing a refresh of non-stale value\n return this.#isBackgroundFetch(v) ? v.__staleWhileFetching : v;\n }\n #backgroundFetch(k, index, options, context) {\n const v = index === undefined ? undefined : this.#valList[index];\n if (this.#isBackgroundFetch(v)) {\n return v;\n }\n const ac = new AC();\n const { signal } = options;\n // when/if our AC signals, then stop listening to theirs.\n signal?.addEventListener('abort', () => ac.abort(signal.reason), {\n signal: ac.signal,\n });\n const fetchOpts = {\n signal: ac.signal,\n options,\n context,\n };\n const cb = (v, updateCache = false) => {\n const { aborted } = ac.signal;\n const ignoreAbort = options.ignoreFetchAbort && v !== undefined;\n if (options.status) {\n if (aborted && !updateCache) {\n options.status.fetchAborted = true;\n options.status.fetchError = ac.signal.reason;\n if (ignoreAbort)\n options.status.fetchAbortIgnored = true;\n }\n else {\n options.status.fetchResolved = true;\n }\n }\n if (aborted && !ignoreAbort && !updateCache) {\n return fetchFail(ac.signal.reason);\n }\n // either we didn't abort, and are still here, or we did, and ignored\n const bf = p;\n if (this.#valList[index] === p) {\n if (v === undefined) {\n if (bf.__staleWhileFetching) {\n this.#valList[index] = bf.__staleWhileFetching;\n }\n else {\n this.#delete(k, 'fetch');\n }\n }\n else {\n if (options.status)\n options.status.fetchUpdated = true;\n this.set(k, v, fetchOpts.options);\n }\n }\n return v;\n };\n const eb = (er) => {\n if (options.status) {\n options.status.fetchRejected = true;\n options.status.fetchError = er;\n }\n return fetchFail(er);\n };\n const fetchFail = (er) => {\n const { aborted } = ac.signal;\n const allowStaleAborted = aborted && options.allowStaleOnFetchAbort;\n const allowStale = allowStaleAborted || options.allowStaleOnFetchRejection;\n const noDelete = allowStale || options.noDeleteOnFetchRejection;\n const bf = p;\n if (this.#valList[index] === p) {\n // if we allow stale on fetch rejections, then we need to ensure that\n // the stale value is not removed from the cache when the fetch fails.\n const del = !noDelete || bf.__staleWhileFetching === undefined;\n if (del) {\n this.#delete(k, 'fetch');\n }\n else if (!allowStaleAborted) {\n // still replace the *promise* with the stale value,\n // since we are done with the promise at this point.\n // leave it untouched if we're still waiting for an\n // aborted background fetch that hasn't yet returned.\n this.#valList[index] = bf.__staleWhileFetching;\n }\n }\n if (allowStale) {\n if (options.status && bf.__staleWhileFetching !== undefined) {\n options.status.returnedStale = true;\n }\n return bf.__staleWhileFetching;\n }\n else if (bf.__returned === bf) {\n throw er;\n }\n };\n const pcall = (res, rej) => {\n const fmp = this.#fetchMethod?.(k, v, fetchOpts);\n if (fmp && fmp instanceof Promise) {\n fmp.then(v => res(v === undefined ? undefined : v), rej);\n }\n // ignored, we go until we finish, regardless.\n // defer check until we are actually aborting,\n // so fetchMethod can override.\n ac.signal.addEventListener('abort', () => {\n if (!options.ignoreFetchAbort ||\n options.allowStaleOnFetchAbort) {\n res(undefined);\n // when it eventually resolves, update the cache.\n if (options.allowStaleOnFetchAbort) {\n res = v => cb(v, true);\n }\n }\n });\n };\n if (options.status)\n options.status.fetchDispatched = true;\n const p = new Promise(pcall).then(cb, eb);\n const bf = Object.assign(p, {\n __abortController: ac,\n __staleWhileFetching: v,\n __returned: undefined,\n });\n if (index === undefined) {\n // internal, don't expose status.\n this.set(k, bf, { ...fetchOpts.options, status: undefined });\n index = this.#keyMap.get(k);\n }\n else {\n this.#valList[index] = bf;\n }\n return bf;\n }\n #isBackgroundFetch(p) {\n if (!this.#hasFetchMethod)\n return false;\n const b = p;\n return (!!b &&\n b instanceof Promise &&\n b.hasOwnProperty('__staleWhileFetching') &&\n b.__abortController instanceof AC);\n }\n async fetch(k, fetchOptions = {}) {\n const { \n // get options\n allowStale = this.allowStale, updateAgeOnGet = this.updateAgeOnGet, noDeleteOnStaleGet = this.noDeleteOnStaleGet, \n // set options\n ttl = this.ttl, noDisposeOnSet = this.noDisposeOnSet, size = 0, sizeCalculation = this.sizeCalculation, noUpdateTTL = this.noUpdateTTL, \n // fetch exclusive options\n noDeleteOnFetchRejection = this.noDeleteOnFetchRejection, allowStaleOnFetchRejection = this.allowStaleOnFetchRejection, ignoreFetchAbort = this.ignoreFetchAbort, allowStaleOnFetchAbort = this.allowStaleOnFetchAbort, context, forceRefresh = false, status, signal, } = fetchOptions;\n if (!this.#hasFetchMethod) {\n if (status)\n status.fetch = 'get';\n return this.get(k, {\n allowStale,\n updateAgeOnGet,\n noDeleteOnStaleGet,\n status,\n });\n }\n const options = {\n allowStale,\n updateAgeOnGet,\n noDeleteOnStaleGet,\n ttl,\n noDisposeOnSet,\n size,\n sizeCalculation,\n noUpdateTTL,\n noDeleteOnFetchRejection,\n allowStaleOnFetchRejection,\n allowStaleOnFetchAbort,\n ignoreFetchAbort,\n status,\n signal,\n };\n let index = this.#keyMap.get(k);\n if (index === undefined) {\n if (status)\n status.fetch = 'miss';\n const p = this.#backgroundFetch(k, index, options, context);\n return (p.__returned = p);\n }\n else {\n // in cache, maybe already fetching\n const v = this.#valList[index];\n if (this.#isBackgroundFetch(v)) {\n const stale = allowStale && v.__staleWhileFetching !== undefined;\n if (status) {\n status.fetch = 'inflight';\n if (stale)\n status.returnedStale = true;\n }\n return stale ? v.__staleWhileFetching : (v.__returned = v);\n }\n // if we force a refresh, that means do NOT serve the cached value,\n // unless we are already in the process of refreshing the cache.\n const isStale = this.#isStale(index);\n if (!forceRefresh && !isStale) {\n if (status)\n status.fetch = 'hit';\n this.#moveToTail(index);\n if (updateAgeOnGet) {\n this.#updateItemAge(index);\n }\n if (status)\n this.#statusTTL(status, index);\n return v;\n }\n // ok, it is stale or a forced refresh, and not already fetching.\n // refresh the cache.\n const p = this.#backgroundFetch(k, index, options, context);\n const hasStale = p.__staleWhileFetching !== undefined;\n const staleVal = hasStale && allowStale;\n if (status) {\n status.fetch = isStale ? 'stale' : 'refresh';\n if (staleVal && isStale)\n status.returnedStale = true;\n }\n return staleVal ? p.__staleWhileFetching : (p.__returned = p);\n }\n }\n async forceFetch(k, fetchOptions = {}) {\n const v = await this.fetch(k, fetchOptions);\n if (v === undefined)\n throw new Error('fetch() returned undefined');\n return v;\n }\n memo(k, memoOptions = {}) {\n const memoMethod = this.#memoMethod;\n if (!memoMethod) {\n throw new Error('no memoMethod provided to constructor');\n }\n const { context, forceRefresh, ...options } = memoOptions;\n const v = this.get(k, options);\n if (!forceRefresh && v !== undefined)\n return v;\n const vv = memoMethod(k, v, {\n options,\n context,\n });\n this.set(k, vv, options);\n return vv;\n }\n /**\n * Return a value from the cache. Will update the recency of the cache\n * entry found.\n *\n * If the key is not found, get() will return `undefined`.\n */\n get(k, getOptions = {}) {\n const { allowStale = this.allowStale, updateAgeOnGet = this.updateAgeOnGet, noDeleteOnStaleGet = this.noDeleteOnStaleGet, status, } = getOptions;\n const index = this.#keyMap.get(k);\n if (index !== undefined) {\n const value = this.#valList[index];\n const fetching = this.#isBackgroundFetch(value);\n if (status)\n this.#statusTTL(status, index);\n if (this.#isStale(index)) {\n if (status)\n status.get = 'stale';\n // delete only if not an in-flight background fetch\n if (!fetching) {\n if (!noDeleteOnStaleGet) {\n this.#delete(k, 'expire');\n }\n if (status && allowStale)\n status.returnedStale = true;\n return allowStale ? value : undefined;\n }\n else {\n if (status &&\n allowStale &&\n value.__staleWhileFetching !== undefined) {\n status.returnedStale = true;\n }\n return allowStale ? value.__staleWhileFetching : undefined;\n }\n }\n else {\n if (status)\n status.get = 'hit';\n // if we're currently fetching it, we don't actually have it yet\n // it's not stale, which means this isn't a staleWhileRefetching.\n // If it's not stale, and fetching, AND has a __staleWhileFetching\n // value, then that means the user fetched with {forceRefresh:true},\n // so it's safe to return that value.\n if (fetching) {\n return value.__staleWhileFetching;\n }\n this.#moveToTail(index);\n if (updateAgeOnGet) {\n this.#updateItemAge(index);\n }\n return value;\n }\n }\n else if (status) {\n status.get = 'miss';\n }\n }\n #connect(p, n) {\n this.#prev[n] = p;\n this.#next[p] = n;\n }\n #moveToTail(index) {\n // if tail already, nothing to do\n // if head, move head to next[index]\n // else\n // move next[prev[index]] to next[index] (head has no prev)\n // move prev[next[index]] to prev[index]\n // prev[index] = tail\n // next[tail] = index\n // tail = index\n if (index !== this.#tail) {\n if (index === this.#head) {\n this.#head = this.#next[index];\n }\n else {\n this.#connect(this.#prev[index], this.#next[index]);\n }\n this.#connect(this.#tail, index);\n this.#tail = index;\n }\n }\n /**\n * Deletes a key out of the cache.\n *\n * Returns true if the key was deleted, false otherwise.\n */\n delete(k) {\n return this.#delete(k, 'delete');\n }\n #delete(k, reason) {\n let deleted = false;\n if (this.#size !== 0) {\n const index = this.#keyMap.get(k);\n if (index !== undefined) {\n deleted = true;\n if (this.#size === 1) {\n this.#clear(reason);\n }\n else {\n this.#removeItemSize(index);\n const v = this.#valList[index];\n if (this.#isBackgroundFetch(v)) {\n v.__abortController.abort(new Error('deleted'));\n }\n else if (this.#hasDispose || this.#hasDisposeAfter) {\n if (this.#hasDispose) {\n this.#dispose?.(v, k, reason);\n }\n if (this.#hasDisposeAfter) {\n this.#disposed?.push([v, k, reason]);\n }\n }\n this.#keyMap.delete(k);\n this.#keyList[index] = undefined;\n this.#valList[index] = undefined;\n if (index === this.#tail) {\n this.#tail = this.#prev[index];\n }\n else if (index === this.#head) {\n this.#head = this.#next[index];\n }\n else {\n const pi = this.#prev[index];\n this.#next[pi] = this.#next[index];\n const ni = this.#next[index];\n this.#prev[ni] = this.#prev[index];\n }\n this.#size--;\n this.#free.push(index);\n }\n }\n }\n if (this.#hasDisposeAfter && this.#disposed?.length) {\n const dt = this.#disposed;\n let task;\n while ((task = dt?.shift())) {\n this.#disposeAfter?.(...task);\n }\n }\n return deleted;\n }\n /**\n * Clear the cache entirely, throwing away all values.\n */\n clear() {\n return this.#clear('delete');\n }\n #clear(reason) {\n for (const index of this.#rindexes({ allowStale: true })) {\n const v = this.#valList[index];\n if (this.#isBackgroundFetch(v)) {\n v.__abortController.abort(new Error('deleted'));\n }\n else {\n const k = this.#keyList[index];\n if (this.#hasDispose) {\n this.#dispose?.(v, k, reason);\n }\n if (this.#hasDisposeAfter) {\n this.#disposed?.push([v, k, reason]);\n }\n }\n }\n this.#keyMap.clear();\n this.#valList.fill(undefined);\n this.#keyList.fill(undefined);\n if (this.#ttls && this.#starts) {\n this.#ttls.fill(0);\n this.#starts.fill(0);\n }\n if (this.#sizes) {\n this.#sizes.fill(0);\n }\n this.#head = 0;\n this.#tail = 0;\n this.#free.length = 0;\n this.#calculatedSize = 0;\n this.#size = 0;\n if (this.#hasDisposeAfter && this.#disposed) {\n const dt = this.#disposed;\n let task;\n while ((task = dt?.shift())) {\n this.#disposeAfter?.(...task);\n }\n }\n }\n}\n//# sourceMappingURL=index.js.map","import {LRUCache}from'lru-cache';var P=class extends Error{constructor(e,t,n){super(t),this.name=\"HwError\",this.code=e,n!==void 0&&(this.context=Object.freeze({...n})),Object.setPrototypeOf(this,new.target.prototype),typeof Error.captureStackTrace==\"function\"&&Error.captureStackTrace(this,new.target);}},F=class extends P{constructor(e,t,n){super(e,t,n?.context),this.name=\"HelmParseError\",n?.span!==void 0&&(this.span={...n.span}),Object.setPrototypeOf(this,new.target.prototype);}},Ze=class extends P{constructor(e,t){let n=Object.freeze([...e]),o=t??Zi(n);super(\"helm-validation-failed\",o),this.name=\"HelmValidationError\",this.diagnostics=n,Object.setPrototypeOf(this,new.target.prototype);}};function Zi(i){if(i.length===0)return \"HELM validation failed\";let t=i[0],n=i.length>1?` (+${i.length-1} more)`:\"\";return `HELM validation failed: ${t.code} \\u2014 ${t.message}${n}`}var j=class extends P{constructor(e,t,n){super(e,t??`HELM operation not supported: ${e}`,n),this.name=\"HelmNotSupportedError\",Object.setPrototypeOf(this,new.target.prototype);}},rn=class extends P{constructor(e,t){super(\"monomer-not-found\",`Monomer not found in library: ${e}/${t}`,{polymerType:e,symbol:t}),this.name=\"MonomerNotFoundError\",this.polymerType=e,this.symbol=t,Object.setPrototypeOf(this,new.target.prototype);}};var Ee=class{constructor(e){if(!Number.isInteger(e.max)||e.max<=0)throw new RangeError(`LruCache: max must be a positive integer (got ${e.max})`);let t=e.onEvict;this._cache=t===void 0?new LRUCache({max:e.max}):new LRUCache({max:e.max,dispose:(n,o,r)=>{t(o,n);}});}get(e){return this._cache.get(e)}set(e,t){this._cache.set(e,t);}has(e){return this._cache.has(e)}delete(e){return this._cache.delete(e)}clear(){this._cache.clear();}get size(){return this._cache.size}keys(){return this._cache.keys()}entries(){return this._cache.entries()}};var Ce=class{debug(e,t){}info(e,t){}warn(e,t){}error(e,t){}};function sn(i){return i>=65&&i<=90||i>=97&&i<=122}function Qe(i){return i>=48&&i<=57}function Qi(i){return i===32||i===9||i===10||i===13}var an=class{constructor(e){this.src=e,this.len=e.length,this.pos=0,this.tokens=[];}tokenize(){for(;this.pos<this.len;){let e=this.pos,t=this.src.charCodeAt(this.pos);if(Qi(t))throw new F(\"unexpected-whitespace\",`Unexpected whitespace at offset ${e}`,{span:{start:e,end:e+1}});if(t===91){this.scanBracket(e);continue}if(t===34){this.scanQuote(e);continue}if(sn(t)){this.scanIdentifier(e);continue}if(Qe(t)){this.scanNumber(e);continue}let n=er.get(t);if(n!==void 0){this.pos+=1,this.push(n,this.src.charAt(e),e,this.pos);continue}throw new F(\"unexpected-char\",`Unexpected character ${JSON.stringify(this.src.charAt(e))} at offset ${e}`,{span:{start:e,end:e+1}})}return this.push(\"eof\",\"\",this.len,this.len),{tokens:this.tokens,source:this.src}}scanBracket(e){let t=1,n=false,o=false,r=e+1;for(;r<this.len;){let s=this.src.charCodeAt(r);if(n){if(s===92&&r+1<this.len){r+=2;continue}if(s===34){n=false,r+=1;continue}if(s===10||s===13)throw new F(\"unexpected-newline\",`Newline inside bracket at offset ${r}`,{span:{start:r,end:r+1}});r+=1;continue}if(o){if(s===36&&r+1<this.len){let a=this.src.charCodeAt(r+1);if(a===124){o=false,r+=2;continue}if(a===93){o=false,r+=1;continue}}if(s===10||s===13)throw new F(\"unexpected-newline\",`Newline inside bracket at offset ${r}`,{span:{start:r,end:r+1}});r+=1;continue}if(s===10||s===13)throw new F(\"unexpected-newline\",`Newline inside bracket at offset ${r}`,{span:{start:r,end:r+1}});if(s===34){n=true,r+=1;continue}if(s===124&&r+1<this.len&&this.src.charCodeAt(r+1)===36){o=true,r+=2;continue}if(s===91){t+=1,r+=1;continue}if(s===93){if(t-=1,t===0){let a=r+1,d=this.src.slice(e+1,r);this.pos=a,this.push(\"inline-smiles\",d,e,a);return}r+=1;continue}r+=1;}throw new F(\"unterminated-bracket\",`Unterminated '[' starting at offset ${e}`,{span:{start:e,end:this.len}})}scanQuote(e){let t=[],n=e+1;for(;n<this.len;){let o=this.src.charCodeAt(n);if(o===34){let r=n+1;this.pos=r,this.push(\"quote-string\",t.join(\"\"),e,r);return}if(o===92&&n+1<this.len){let r=this.src.charCodeAt(n+1);r===34?t.push('\"'):r===92?t.push(\"\\\\\"):r===110?t.push(`\n`):r===114?t.push(\"\\r\"):r===116?t.push(\"\t\"):(t.push(\"\\\\\"),t.push(this.src.charAt(n+1))),n+=2;continue}if(o===10||o===13)throw new F(\"unexpected-newline\",`Newline inside quote at offset ${n}`,{span:{start:n,end:n+1}});t.push(this.src.charAt(n)),n+=1;}throw new F(\"unterminated-quote\",`Unterminated '\"' starting at offset ${e}`,{span:{start:e,end:this.len}})}scanIdentifier(e){let t=e+1;for(;t<this.len;){let o=this.src.charCodeAt(t);if(sn(o)||Qe(o)||o===95){t+=1;continue}if(o===45&&t+1<this.len&&sn(this.src.charCodeAt(t+1))){t+=2;continue}break}let n=this.src.slice(e,t);this.pos=t,this.push(\"identifier\",n,e,t);}scanNumber(e){let t=e+1;for(;t<this.len&&Qe(this.src.charCodeAt(t));)t+=1;if(t+1<this.len&&this.src.charCodeAt(t)===46&&Qe(this.src.charCodeAt(t+1))){for(t+=2;t<this.len&&Qe(this.src.charCodeAt(t));)t+=1;let o=this.src.slice(e,t);this.pos=t,this.push(\"decimal\",o,e,t);return}let n=this.src.slice(e,t);this.pos=t,this.push(\"integer\",n,e,t);}push(e,t,n,o){this.tokens.push({kind:e,value:t,span:{start:n,end:o}});}},er=new Map([[123,\"lbrace\"],[125,\"rbrace\"],[40,\"lparen\"],[41,\"rparen\"],[93,\"rbracket\"],[124,\"pipe\"],[46,\"dot\"],[44,\"comma\"],[43,\"plus\"],[58,\"colon\"],[45,\"dash\"],[36,\"dollar\"],[62,\"gt\"],[63,\"question\"],[42,\"asterisk\"],[95,\"underscore\"],[39,\"apos\"]]);function to(i){let e=new an(i).tokenize();return tr(e),e}function tr(i){let e=null;for(let t of i.tokens)if(t.kind===\"apos\")e=e===null?t.span:null;else if(t.kind===\"eof\"&&e!==null)throw new F(\"unterminated-apostrophe\",`Unterminated apostrophe block starting at offset ${e.start}`,{span:{start:e.start,end:i.source.length}})}var nr={perPolymer:new Map,version:\"\"};function me(){return {atoms:[],bonds:[],chains:[],groups:[],annotations:nr}}function J(i,e){for(let t of i.atoms)if(t.id===e)return t}function xt(i,e){for(let t of i.bonds)if(t.id===e)return t}function le(i,e){if(e===void 0)return i.bio.positionInChain;let t=0;for(let n=0;n<e.backboneAtoms.length;n++){let o=e.backboneAtoms[n];if(o!==void 0&&(t+=1,o.id===i.id||o.branchAtom!==void 0&&(t+=1,o.branchAtom.id===i.id)))return t}return 0}var g={AA:\"HELM_AA\",SUGAR:\"HELM_SUGAR\",BASE:\"HELM_BASE\",LINKER:\"HELM_LINKER\",CHEM:\"HELM_CHEM\",BLOB:\"HELM_BLOB\",NUCLEOTIDE:\"HELM_NUCLEOTIDE\"},x={PEPTIDE:\"PEPTIDE\",RNA:\"RNA\",CHEM:\"CHEM\",BLOB:\"BLOB\",G:\"G\"},or={BACKBONE:\"Backbone\",BRANCH:\"Branch\",TERMINAL:\"Terminal\",UNDEFINED:\"Undefined\"};var ve=class{constructor(){this._counter=0;}next(){return this._counter+=1,this._counter}reset(){this._counter=0;}get current(){return this._counter}};function Le(i){let e=new Map,t=0;for(let n of i.chains)for(let o of n.backboneAtoms)t+=1,e.set(o.id,t),o.branchAtom!==void 0&&(t+=1,e.set(o.branchAtom.id,t));return e}function Be(i){let e=i.trim();if(/^\\[[a-zA-Z_][a-zA-Z0-9_]*\\]$/.test(e))return false;for(let t=0;t<e.length;t++){let n=e.charCodeAt(t);if(n===40||n===91||n===61||n===47||n===92||n===42)return true}return false}function ir(i){let e=new Map,t=/\\[R(\\d{1,2})\\]/g,n;for(;(n=t.exec(i))!==null;){let o=parseInt(n[1],10);o>=1&&o<=10&&!e.has(o)&&e.set(o,n.index);}return e}function rr(i){let e=new Map,n=/\\s*\\|\\$([^$]*)\\$\\|/.exec(i);if(n===null)return e;let o=n[1].split(\";\"),r=n.index+n[0].indexOf(\"$\")+1,s=0;for(let a of o){let d=/^_R(\\d{1,2})$/.exec(a);if(d!==null){let l=parseInt(d[1],10);l>=1&&l<=10&&!e.has(l)&&e.set(l,r+s);}s+=a.length+1;}return e}function sr(i){let e=new Map,t=/\\[\\*:(\\d{1,2})\\]/g,n;for(;(n=t.exec(i))!==null;){let o=parseInt(n[1],10);o>=1&&o<=10&&!e.has(o)&&e.set(o,n.index);}return e}function no(i){let e=i.trim();if(e.length===0)return {ok:false,reason:\"empty-smiles\"};let t=ir(e);if(t.size>0)return {ok:true,canonicalSmiles:e,info:{rs:t.size,rgroupPositions:t,flavor:\"jsdraw\"}};let n=rr(e);if(n.size>0)return {ok:true,canonicalSmiles:e,info:{rs:n.size,rgroupPositions:n,flavor:\"chemaxon\"}};let o=sr(e);return o.size>0?{ok:true,canonicalSmiles:e,info:{rs:o.size,rgroupPositions:o,flavor:\"opensmiles\"}}:{ok:false,reason:\"no-rgroups-found\"}}var Z=class{constructor(){this._listeners=new Set;this._completed=false;}subscribe(e){return this._completed?()=>{}:(this._listeners.add(e),()=>{this._listeners.delete(e);})}next(e){if(!this._completed)for(let t of [...this._listeners])t(e);}complete(){this._completed=true,this._listeners.clear();}get observerCount(){return this._listeners.size}};function L(i){return {line:\"#202020\",text:\"#000000\",background:i}}function ar(i){return {line:\"#e0e0e0\",text:\"#ffffff\",background:cn(i,.25)}}function Re(i){let e=/^#([0-9a-fA-F]{6})$/.exec(i),t=/^#([0-9a-fA-F]{3})$/.exec(i);if(e!==null){let n=e[1];return [parseInt(n.slice(0,2),16),parseInt(n.slice(2,4),16),parseInt(n.slice(4,6),16)]}if(t!==null){let n=t[1];return [parseInt(n[0]+n[0],16),parseInt(n[1]+n[1],16),parseInt(n[2]+n[2],16)]}return null}function ln(i){return i.toString(16).padStart(2,\"0\")}function un(i,e,t){return `#${ln(i)}${ln(e)}${ln(t)}`}function mn(i,e,t){let n=i/255,o=e/255,r=t/255,s=Math.max(n,o,r),a=Math.min(n,o,r),d=(s+a)/2;if(s===a)return [0,0,d];let l=s-a,u=d>.5?l/(2-s-a):l/(s+a),c;return s===n?c=((o-r)/l+(o<r?6:0))*60:s===o?c=((r-n)/l+2)*60:c=((n-o)/l+4)*60,[c,u,d]}function dn(i,e,t){let n=t;return n<0&&(n+=1),n>1&&(n-=1),n<1/6?i+(e-i)*6*n:n<1/2?e:n<2/3?i+(e-i)*(2/3-n)*6:i}function io(i,e,t){if(e===0){let s=Math.round(t*255);return [s,s,s]}let n=t<.5?t*(1+e):t+e-t*e,o=2*t-n,r=i/360;return [Math.round(dn(o,n,r+1/3)*255),Math.round(dn(o,n,r)*255),Math.round(dn(o,n,r-1/3)*255)]}function At(i,e=.3,t=.1){let n=Re(i);if(n===null)return i;let[o,r,s]=mn(n[0],n[1],n[2]),a=Math.max(0,Math.min(1,r*(1-e))),d=Math.max(0,Math.min(.95,s+t*(1-s))),[l,u,c]=io(o,a,d);return un(l,u,c)}function oo(i){let e=Re(i);if(e===null)return 0;let t=n=>{let o=n/255;return o<=.03928?o/12.92:Math.pow((o+.055)/1.055,2.4)};return .2126*t(e[0])+.7152*t(e[1])+.0722*t(e[2])}function ro(i,e){let t=oo(i),n=oo(e),o=Math.max(t,n),r=Math.min(t,n);return (o+.05)/(r+.05)}function so(i){let e=Re(i);if(e===null)return {h:0,s:0,l:0};let[t,n,o]=mn(e[0],e[1],e[2]);return {h:t,s:n,l:o}}function lr(i){let e=(i.h%360+360)%360,t=Math.max(0,Math.min(1,i.s)),n=Math.max(0,Math.min(1,i.l)),[o,r,s]=io(e,t,n);return un(o,r,s)}function wt(i){let e=Re(i);if(e===null)return \"#1f2937\";let[t,n,o]=mn(e[0],e[1],e[2]);if(o>.85||n<.15&&o>.7)return \"#1f2937\";let r=Math.max(.08,o-.3),s=Math.min(1,n+.1);return lr({h:t,s,l:r})}function dr(i){let e=Re(i);return e===null?null:{r:e[0]/255,g:e[1]/255,b:e[2]/255}}function kt(i){let e=dr(i);if(e===null)return \"#1f2937\";let t=s=>s<=.03928?s/12.92:Math.pow((s+.055)/1.055,2.4),n=.2126*t(e.r)+.7152*t(e.g)+.0722*t(e.b),o=(n+.05)/(0+.05);return (1+.05)/(n+.05)>o?\"#ffffff\":\"#1f2937\"}function cn(i,e){let t=Re(i);if(t===null)return i;let n=1-e,o=Math.max(0,Math.min(255,Math.round(t[0]*n))),r=Math.max(0,Math.min(255,Math.round(t[1]*n))),s=Math.max(0,Math.min(255,Math.round(t[2]*n)));return un(o,r,s)}var ao={A:L(\"#A0A0FF\"),G:L(\"#FF7070\"),T:L(\"#A0FFA0\"),C:L(\"#FF8C4B\"),U:L(\"#FF8080\")},lo={R:L(\"#7a85c1\"),r:L(\"#7a85c1\")},co={P:L(\"#9aa5e1\"),p:L(\"#9aa5e1\")},uo={A:L(\"#C8C8C8\"),R:L(\"#145AFF\"),N:L(\"#00DCDC\"),D:L(\"#E60A0A\"),C:L(\"#E6E600\"),E:L(\"#00DCDC\"),Q:L(\"#E60A0A\"),G:L(\"#EBEBEB\"),H:L(\"#8282D2\"),I:L(\"#0F820F\"),L:L(\"#0F820F\"),K:L(\"#145AFF\"),M:L(\"#E6E600\"),F:L(\"#3232AA\"),P:L(\"#DC9682\"),S:L(\"#FA9600\"),T:L(\"#FA9600\"),W:L(\"#B45AB4\"),Y:L(\"#3232AA\"),V:L(\"#0F820F\")},mo={R:L(\"#eeeeee\")},po={B:L(\"#999999\"),G:L(\"#e2e2e2\")},ho={P:L(\"#9aa5e1\")},we={name:\"light\",fallback:{line:\"#202020\",text:\"#000000\",background:\"#eeeeee\"},errorTriple:{line:\"#cc0000\",text:\"#000000\",background:\"#FFFF00\"},palette:{[g.BASE]:ao,[g.SUGAR]:lo,[g.LINKER]:co,[g.AA]:uo,[g.CHEM]:mo,[g.BLOB]:po,[g.NUCLEOTIDE]:ho}};function xe(i){let e={};for(let[t,n]of Object.entries(i))e[t]=ar(n.background);return e}var Ie={name:\"dark\",fallback:{line:\"#e0e0e0\",text:\"#ffffff\",background:cn(\"#eeeeee\",.5)},errorTriple:{line:\"#ff5050\",text:\"#ffffff\",background:cn(\"#FFFF00\",.4)},palette:{[g.BASE]:xe(ao),[g.SUGAR]:xe(lo),[g.LINKER]:xe(co),[g.AA]:xe(uo),[g.CHEM]:xe(mo),[g.BLOB]:xe(po),[g.NUCLEOTIDE]:xe(ho)}};function D(i,e,t=we){if(i===null)return {...t.errorTriple};let n=i.meta?.colors;if(n!==void 0){let r=t.name===\"light\"?n.light:t.name===\"dark\"?n.dark:void 0;if(r!==void 0)return {...r,line:wt(r.background)};if(n.default!==void 0)return {...n.default,line:wt(n.default.background)}}let o=i.naturalAnalog;if(o!==void 0&&o!==\"\"){let r=t.palette[e];if(r!==void 0){let s=r[o];if(s!==void 0)return {...s,line:wt(s.background),text:kt(s.background)}}}return {...t.fallback,line:wt(t.fallback.background),text:kt(t.fallback.background)}}function et(i){for(let e in i)if(Object.prototype.hasOwnProperty.call(i,e)&&e.toLowerCase()===\"capgroupsmiles\"){let t=i[e];if(typeof t==\"string\")return t}}function fo(i){let e=false,t=i.rgroups.map(n=>{let o=et(n);return o!==void 0&&n.capGroupSMILES!==o?(e=true,{...n,capGroupSMILES:o}):n});return e?{...i,rgroups:t}:i}var cr=new Set([\"PEPTIDE\",\"RNA\",\"CHEM\",\"BLOB\"]),ur=new Set([\"Backbone\",\"Branch\",\"Terminal\",\"Undefined\"]),mr=/^R[1-9][0-9]*$/;function Mt(i){let e=[];if(!Array.isArray(i))return {ok:false,errors:[{path:\"$\",message:`Expected a JSON array of monomers, got ${G(i)}`}]};for(let t=0;t<i.length;t++)pr(i[t],`$.${t}`,e);return e.length>0?{ok:false,errors:e}:{ok:true,data:i}}function pr(i,e,t){if(!nt(i)){t.push({path:e,message:`Expected an object, got ${G(i)}`});return}pn(i,\"symbol\",e,t,{minLength:1}),pn(i,\"molfile\",e,t);let n=i.polymerType;n===void 0?t.push({path:`${e}.polymerType`,message:\"Required property missing\"}):typeof n!=\"string\"?t.push({path:`${e}.polymerType`,message:`Expected string, got ${G(n)}`}):cr.has(n)||t.push({path:`${e}.polymerType`,message:`Expected one of PEPTIDE|RNA|CHEM|BLOB, got '${n}'`});let o=i.monomerType;o===void 0?t.push({path:`${e}.monomerType`,message:\"Required property missing\"}):typeof o!=\"string\"?t.push({path:`${e}.monomerType`,message:`Expected string, got ${G(o)}`}):ur.has(o)||t.push({path:`${e}.monomerType`,message:`Expected one of Backbone|Branch|Terminal|Undefined, got '${o}'`});let r=i.rgroups;if(r===void 0)t.push({path:`${e}.rgroups`,message:\"Required property missing\"});else if(!Array.isArray(r))t.push({path:`${e}.rgroups`,message:`Expected array, got ${G(r)}`});else {let s=new Set;for(let a=0;a<r.length;a++)hr(r[a],`${e}.rgroups[${a}]`,t,s);}if(tt(i,\"name\",e,t),tt(i,\"smiles\",e,t),tt(i,\"naturalAnalog\",e,t),tt(i,\"author\",e,t),\"createDate\"in i&&i.createDate!==void 0&&i.createDate!==null&&typeof i.createDate!=\"string\"&&t.push({path:`${e}.createDate`,message:`Expected string or null, got ${G(i.createDate)}`}),\"id\"in i&&i.id!==void 0){let s=i.id;typeof s==\"string\"||typeof s==\"number\"&&Number.isInteger(s)||t.push({path:`${e}.id`,message:`Expected integer or string, got ${G(s)}`});}if(\"meta\"in i&&i.meta!==void 0){let s=i.meta;nt(s)?s.colors!==void 0&&fr(s.colors,`${e}.meta.colors`,t):t.push({path:`${e}.meta`,message:`Expected object, got ${G(s)}`});}}function hr(i,e,t,n){if(!nt(i)){t.push({path:e,message:`Expected an object, got ${G(i)}`});return}let o=i.label;if(o===void 0?t.push({path:`${e}.label`,message:\"Required property missing\"}):typeof o!=\"string\"?t.push({path:`${e}.label`,message:`Expected string, got ${G(o)}`}):mr.test(o)?n.has(o)?t.push({path:`${e}.label`,message:`Duplicate R-group label '${o}'`}):n.add(o):t.push({path:`${e}.label`,message:`Expected pattern /^R[1-9][0-9]*$/, got '${o}'`}),pn(i,\"capGroupName\",e,t),et(i)===void 0){let r=Object.keys(i).some(s=>s.toLowerCase()===\"capgroupsmiles\");t.push({path:`${e}.capGroupSMILES`,message:r?\"Expected string\":\"Required property missing\"});}tt(i,\"alternateId\",e,t),\"id\"in i&&i.id!==void 0&&(typeof i.id!=\"number\"||!Number.isInteger(i.id))&&t.push({path:`${e}.id`,message:`Expected integer, got ${G(i.id)}`});}function fr(i,e,t){if(!nt(i)){t.push({path:e,message:`Expected object, got ${G(i)}`});return}for(let n of [\"default\",\"light\",\"dark\"])i[n]!==void 0&&br(i[n],`${e}.${n}`,t);}function br(i,e,t){if(!nt(i)){t.push({path:e,message:`Expected object, got ${G(i)}`});return}for(let n of [\"line\",\"text\",\"background\"])i[n]===void 0?t.push({path:`${e}.${n}`,message:\"Required property missing\"}):typeof i[n]!=\"string\"&&t.push({path:`${e}.${n}`,message:`Expected string, got ${G(i[n])}`});}function pn(i,e,t,n,o){let r=i[e],s=`${t}.${e}`;if(r===void 0){n.push({path:s,message:\"Required property missing\"});return}if(typeof r!=\"string\"){n.push({path:s,message:`Expected string, got ${G(r)}`});return}o?.minLength!==void 0&&r.length<o.minLength&&n.push({path:s,message:`Expected string of length >= ${o.minLength}, got ${r.length}`});}function tt(i,e,t,n){let o=i[e];o!==void 0&&typeof o!=\"string\"&&n.push({path:`${t}.${e}`,message:`Expected string, got ${G(o)}`});}function nt(i){return typeof i==\"object\"&&i!==null&&!Array.isArray(i)}function G(i){return i===null?\"null\":Array.isArray(i)?\"array\":typeof i}var yr=/^R([1-9][0-9]*)$/;function te(i){switch(i.polymerType){case x.PEPTIDE:return g.AA;case x.CHEM:return g.CHEM;case x.BLOB:return g.BLOB;case x.RNA:{if(i.monomerType===\"Branch\")return g.BASE;if(i.monomerType===\"Backbone\"){let e=i.naturalAnalog;return e===\"P\"||e===\"p\"?g.LINKER:g.SUGAR}return null}default:return null}}function gr(i){let e=new Map;for(let t of i.rgroups){let n=yr.exec(t.label);n!==null&&e.set(parseInt(n[1],10),t);}return Object.assign({},i,{rs:i.rgroups.length,rgroupMap:e})}var hn=class i{constructor(e){this._version=0;this._byPolymerSymbol=new Map;this._byBiotypeSymbol=new Map;this._byNaturalAnalog=new Map;this._resolved=new WeakMap;this._inlineSmilesCounter=0;this.source=e,this.onChanged=new Z;}static empty(e=\"empty\"){return new i(e)}static fromJSON(e,t=\"inline\",n){let o=new i(t);for(let r=0;r<e.length;r++){let s=e[r],a=Mt([s]);if(!a.ok){n!==void 0?n.skipped.push({index:r,errors:a.errors}):console.warn(`MonomerLib.fromJSON: skipping invalid entry at index ${r}`,a.errors);continue}o._addNoFire(s);}return o}static fromText(e,t=\"inline\"){let n;try{n=JSON.parse(e);}catch(r){let s=r instanceof Error?r.message:String(r);throw new P(\"invalid-monomer-lib\",`MonomerLib.fromText: JSON.parse failed \\u2014 ${s}`)}let o=Mt(n);if(!o.ok)throw new P(\"invalid-monomer-lib\",`MonomerLib.fromText: schema validation failed (${o.errors.length} errors)`,{errors:o.errors});return i.fromJSON(o.data,t)}static async fromUrl(e,t){let n=t??globalThis.fetch;if(n===void 0)throw new P(\"fetch-unavailable\",\"MonomerLib.fromUrl: no fetch implementation available \\u2014 pass `fetchImpl` or run in a fetch-capable environment.\",{url:e});let o=await n(e);if(!o.ok)throw new P(\"monomer-lib-fetch-failed\",`MonomerLib.fromUrl: HTTP ${o.status} fetching ${e}`,{url:e,status:o.status});let r=await o.text();return i.fromText(r,e)}static merge(...e){let t=e.map(o=>o.source).join(\"+\")||\"empty\",n=new i(t);for(let o of e)for(let r of o.getPolymerTypes())for(let s of o.getMonomerSymbolsByType(r)){let a=o.getMonomer(r,s);a!==null&&n._addNoFire(a);}return n}get isEmpty(){for(let e of this._byPolymerSymbol.values())if(e.size>0)return false;return true}get version(){return this._version}getMonomer(e,t){let n=this._byPolymerSymbol.get(e);return n===void 0?null:n.get(t)??null}getMonomerSet(e){let t=this._byBiotypeSymbol.get(e);return t===void 0?new Map:new Map(t)}getMonomerSymbolsByType(e){let t=this._byPolymerSymbol.get(e);return t===void 0?[]:Array.from(t.keys())}getByNaturalAnalog(e,t){let n=this._byNaturalAnalog.get(e);if(n===void 0)return [];let o=n.get(t);return o===void 0?[]:o.slice()}getPolymerTypes(){let e=[];for(let[t,n]of this._byPolymerSymbol.entries())n.size>0&&e.push(t);return e}getColors(e,t){let n=_r(t),o=e===null?g.AA:te(e)??g.AA;return D(e,o,n)}getResolved(e){return this._resolved.get(e)}addMonomer(e){let t=Mt([e]);if(!t.ok)throw new P(\"invalid-monomer\",\"MonomerLib.addMonomer: schema validation failed\",{errors:t.errors});let n=this._addNoFire(e);this._bumpVersion(),this.onChanged.next({type:n?\"update\":\"add\",affectedSymbols:[e.symbol]});}addMonomers(e){let t=[],n=false;for(let o of e)this._addNoFire(o)&&(n=true),t.push(o.symbol);t.length!==0&&(this._bumpVersion(),this.onChanged.next({type:n?\"update\":\"add\",affectedSymbols:t}));}removeMonomer(e,t){let n=this._byPolymerSymbol.get(e);if(n===void 0)return false;let o=n.get(t);if(o===void 0)return false;n.delete(t);let r=te(o);if(r!==null){let a=this._byBiotypeSymbol.get(r);a!==void 0&&a.delete(t);}let s=o.naturalAnalog;if(s!==void 0&&s!==\"\"){let d=this._byNaturalAnalog.get(e)?.get(s);if(d!==void 0){let l=d.indexOf(o);l>=0&&d.splice(l,1);}}return this._bumpVersion(),this.onChanged.next({type:\"remove\",affectedSymbols:[t]}),true}setMonomerColors(e,t,n){let o=this.getMonomer(e,t);if(o===null)throw new P(\"monomer-not-found\",`MonomerLib.setMonomerColors: ${e}/${t} not found`,{polymerType:e,symbol:t});let r=o.meta??{},s=r.colors??{},a=Object.assign({},r,{colors:Object.assign({},s,n)}),d=Object.assign({},o,{meta:a});this._addNoFire(d),this._bumpVersion(),this.onChanged.next({type:\"update\",affectedSymbols:[t]});}merge(e){for(let t of e.getPolymerTypes())for(let n of e.getMonomerSymbolsByType(t)){let o=e.getMonomer(t,n);o!==null&&this._addNoFire(o);}this._bumpVersion(),this.onChanged.next({type:\"reload\"});}registerInlineSmilesMonomer(e,t,n){let o=no(t);if(!o.ok)throw new P(\"inline-smiles-without-r-groups\",`MonomerLib.registerInlineSmilesMonomer: ${o.reason}`,{smiles:t});this._inlineSmilesCounter+=1;let r=`#${this._inlineSmilesCounter}`,s=[],a=Array.from(o.info.rgroupPositions.keys()).sort((u,c)=>u-c);for(let u of a)s.push({label:`R${u}`,capGroupName:\"H\",capGroupSMILES:\"\"});let d=n?.symbolHint!==void 0?{smilesHint:n.symbolHint}:void 0,l={symbol:r,polymerType:e,monomerType:\"Undefined\",molfile:\"\",smiles:o.canonicalSmiles,rgroups:s,...d!==void 0?{meta:d}:{}};return this._addNoFire(l),this._bumpVersion(),this.onChanged.next({type:\"add\",affectedSymbols:[r]}),l}toJSON(){let e=[];for(let t of this._byPolymerSymbol.values())for(let n of t.values())e.push(n);return e}_addNoFire(e){e=fo(e);let t=e.polymerType,n=this._byPolymerSymbol.get(t);n===void 0&&(n=new Map,this._byPolymerSymbol.set(t,n));let o=n.get(e.symbol);if(n.set(e.symbol,e),o!==void 0){let a=te(o);if(a!==null){let l=this._byBiotypeSymbol.get(a);l!==void 0&&l.delete(o.symbol);}let d=o.naturalAnalog;if(d!==void 0&&d!==\"\"){let l=this._byNaturalAnalog.get(t)?.get(d);if(l!==void 0){let u=l.indexOf(o);u>=0&&l.splice(u,1);}}this._resolved.delete(o);}let r=te(e);if(r!==null){let a=this._byBiotypeSymbol.get(r);a===void 0&&(a=new Map,this._byBiotypeSymbol.set(r,a)),a.set(e.symbol,e);}let s=e.naturalAnalog;if(s!==void 0&&s!==\"\"){let a=this._byNaturalAnalog.get(t);a===void 0&&(a=new Map,this._byNaturalAnalog.set(t,a));let d=a.get(s);d===void 0&&(d=[],a.set(s,d)),d.push(e);}return this._resolved.set(e,gr(e)),o!==void 0}_bumpVersion(){this._version+=1;}};function _r(i){return i===\"dark\"?Ie:we}function ke(i,e,t){return new fn(i,e,t??{}).run()}var vr=new Set([\"?\",\"*\",\"_\",\"X\",\"N\"]),xr=/^R([1-9][0-9]*)$/;function wr(i){return typeof i.registerInlineSmilesMonomer==\"function\"}var fn=class{constructor(e,t,n){this.diagnostics=[];this.oldToNew=new Map;this.placeholderCache=new Map;this.mol=e,this.lib=t,this.options=n;}run(){let e=new Map;for(let a of this.mol.chains)e.set(a.id,a.polymerType);for(let a of this.mol.atoms){let d=e.get(a.bio.chainId)??null,l=this.resolveAtom(a,d);this.oldToNew.set(a.id,l);}for(let a of this.mol.atoms){let d=this.oldToNew.get(a.id);if(d===void 0||a.branchAtom===void 0)continue;let l=this.oldToNew.get(a.branchAtom.id);l!==void 0&&(d.branchAtom=l);}let t=[];for(let a of this.mol.bonds){let d=this.oldToNew.get(a.a1.id),l=this.oldToNew.get(a.a2.id);d===void 0||l===void 0||t.push({...a,a1:d,a2:l});}let n=new Map;for(let a of t)n.set(a.id,a);let o=[];for(let a of this.mol.chains){let d=[];for(let u of a.backboneAtoms){let c=this.oldToNew.get(u.id);c!==void 0&&d.push(c);}let l=[];for(let u of a.bonds){let c=n.get(u.id);c!==void 0&&l.push(c);}o.push({id:a.id,polymerType:a.polymerType,backboneAtoms:d,bonds:l,...a.annotation!==void 0?{annotation:a.annotation}:{},...a.strandType!==void 0?{strandType:a.strandType}:{}});}return {mol:{atoms:this.mol.atoms.map(a=>this.oldToNew.get(a.id)),bonds:t,chains:o,groups:this.mol.groups,annotations:this.mol.annotations},diagnostics:this.diagnostics}}resolveAtom(e,t){let n=null,o=e.biotype;if(t!==null){let r=this.lib.getMonomer(t,e.symbol);if(r!==null)n=this.toResolved(r),o=te(r)??e.biotype;else if(this.isAmbiguitySymbol(e))n=this.synthesizeAmbiguity(t,e),this.emit(\"info\",\"ambiguous-monomer\",`Ambiguous monomer '${e.symbol}' on chain '${e.bio.chainId}'`,e);else if(Be(e.symbol))n=this.registerInlineSmilesFallback(t,e);else if(this.options.legacyCaseFallback===true&&t===\"RNA\"){let s=this.findCaseInsensitiveMatch(t,e.symbol);s!==null&&(n=this.toResolved(s),o=te(s)??e.biotype,this.emit(\"info\",\"case-mismatch\",`Symbol '${e.symbol}' matched library entry '${s.symbol}' only after case fold`,e));}n===null&&(n=this.synthesizeMissing(t,e),this.emit(\"warning\",\"unresolved-monomer\",`Monomer '${e.symbol}' not found in library for ${t}`,e));}return {...e,monomer:n,biotype:o}}toResolved(e){let t=this.lib.getResolved?.(e);if(t!==void 0)return t;let n=new Map;for(let o of e.rgroups){let r=xr.exec(o.label);r!==null&&n.set(parseInt(r[1],10),o);}return Object.assign({},e,{rs:e.rgroups.length,rgroupMap:n})}isAmbiguitySymbol(e){return !!(vr.has(e.symbol)||e.bio.ambiguity!==void 0)}synthesizeAmbiguity(e,t){let n=`ambig:${e}:${t.symbol}`,o=this.placeholderCache.get(n);return o===void 0&&(o={symbol:t.symbol,polymerType:e,monomerType:\"Undefined\",molfile:\"\",rgroups:[{label:\"R1\",capGroupName:\"H\",capGroupSMILES:\"\"},{label:\"R2\",capGroupName:\"H\",capGroupSMILES:\"\"}],meta:{ambiguous:true}},this.placeholderCache.set(n,o)),this.toResolved(o)}synthesizeMissing(e,t){let n=`missing:${e}:${t.symbol}`,o=this.placeholderCache.get(n);return o===void 0&&(o={symbol:t.symbol,polymerType:e,monomerType:\"Undefined\",molfile:\"\",rgroups:[{label:\"R1\",capGroupName:\"H\",capGroupSMILES:\"\"},{label:\"R2\",capGroupName:\"H\",capGroupSMILES:\"\"}],meta:{missing:true}},this.placeholderCache.set(n,o)),this.toResolved(o)}registerInlineSmilesFallback(e,t){if(wr(this.lib))try{let n=this.lib.registerInlineSmilesMonomer(e,t.symbol);return this.toResolved(n)}catch{this.emit(\"warning\",\"inline-smiles-without-r-groups\",`Inline SMILES '${kr(t.symbol,40)}' has no detectable R-groups`,t);}else this.emit(\"warning\",\"inline-smiles-without-r-groups\",\"Inline SMILES seen but lib has no registerInlineSmilesMonomer\",t);return this.synthesizeMissing(e,t)}findCaseInsensitiveMatch(e,t){let n=t.toLowerCase();for(let o of this.lib.getMonomerSymbolsByType(e))if(o.toLowerCase()===n&&o!==t){let r=this.lib.getMonomer(e,o);if(r!==null)return r}return null}emit(e,t,n,o){let r={chainId:o.bio.chainId,atomId:o.id,symbol:o.symbol};this.diagnostics.push({severity:e,code:t,message:n,context:r});}};function kr(i,e){return i.length<=e?i:i.slice(0,e-1)+\"\\u2026\"}function ot(i,e,t){let n=t?.mode??\"lenient\",o;try{o=to(i);}catch(r){if(r instanceof F){if(n===\"strict\")throw r;let s={severity:\"error\",code:r.code,message:r.message,...r.span!==void 0?{span:{start:r.span.start,end:r.span.end}}:{}};return {mol:me(),diagnostics:[s]}}throw r}return yo(o,e,t)}function yo(i,e,t){let o=new yn(i,e,t?.mode??\"lenient\").parseDocument();if(e===null||t?.resolveMonomers===false)return o;let r=ke(o.mol,e,{mode:t?.mode??\"lenient\",...t?.legacyCaseFallback===true?{legacyCaseFallback:true}:{}});return {mol:r.mol,diagnostics:[...o.diagnostics,...r.diagnostics]}}var bn=class{constructor(e){this.tokens=e.tokens,this.len=e.tokens.length,this.eof=e.tokens[e.tokens.length-1],this.idx=0;}peek(e=0){let t=this.idx+e;return t>=this.len?this.eof:this.tokens[t]}advance(){let e=this.idx<this.len?this.tokens[this.idx]:this.eof;return e.kind!==\"eof\"&&(this.idx+=1),e}optional(e){let t=this.idx<this.len?this.tokens[this.idx]:this.eof;return t.kind===e?(t.kind!==\"eof\"&&(this.idx+=1),t):null}at(e){return (this.idx<this.len?this.tokens[this.idx]:this.eof).kind===e}at2(e,t){let o=(this.idx<this.len?this.tokens[this.idx]:this.eof).kind;return o===e||o===t}at3(e,t,n){let r=(this.idx<this.len?this.tokens[this.idx]:this.eof).kind;return r===e||r===t||r===n}currentSpan(){return (this.idx<this.len?this.tokens[this.idx]:this.eof).span}position(){return this.idx}setPosition(e){this.idx=e;}isAtEnd(){return (this.idx<this.len?this.tokens[this.idx]:this.eof).kind===\"eof\"}},Ar=/^(PEPTIDE|RNA|DNA|CHEM|BLOB|G)([0-9]+)$/;function bo(i){let e=Ar.exec(i);if(e===null)return null;let t=e[1],n=parseInt(e[2],10);switch(t){case \"PEPTIDE\":return {rawTypeName:\"PEPTIDE\",polymerType:x.PEPTIDE,number:n,isDnaShim:false,isGroup:false};case \"RNA\":return {rawTypeName:\"RNA\",polymerType:x.RNA,number:n,isDnaShim:false,isGroup:false};case \"DNA\":return {rawTypeName:\"DNA\",polymerType:x.RNA,number:n,isDnaShim:true,isGroup:false};case \"CHEM\":return {rawTypeName:\"CHEM\",polymerType:x.CHEM,number:n,isDnaShim:false,isGroup:false};case \"BLOB\":return {rawTypeName:\"BLOB\",polymerType:x.BLOB,number:n,isDnaShim:false,isGroup:false};case \"G\":return {rawTypeName:\"G\",polymerType:x.PEPTIDE,number:n,isDnaShim:false,isGroup:true};default:return null}}var yn=class{constructor(e,t,n){this.diagnostics=[];this.chains=[];this.chainById=new Map;this.pendingBonds=[];this.groups=[];this.atomIds=new ve;this.bondIds=new ve;this.cursor=new bn(e),this.source=e.source,this.lib=t,this.mode=n,this.annotations={perPolymer:new Map,version:\"\"};}parseDocument(){if(this.cursor.isAtEnd())return this.emit(\"warning\",\"empty-helm\",\"Empty HELM string\"),{mol:me(),diagnostics:this.diagnostics};if(this.parseSimplePolymers(),this.expectDollarSeparator(1),this.parseConnections(),this.expectDollarSeparator(2),this.parseGroupsSection(),this.expectDollarSeparator(3),this.parseAnnotationsSection(),this.cursor.at(\"dollar\")&&(this.cursor.advance(),this.parseVersionTrailer()),!this.cursor.isAtEnd())for(this.emit(\"warning\",\"extra-section-separator\",\"Unexpected trailing tokens after HELM document\",this.cursor.currentSpan());!this.cursor.isAtEnd();)this.cursor.advance();return {mol:this.finalize(),diagnostics:this.diagnostics}}expectDollarSeparator(e){if(this.cursor.at(\"dollar\")){this.cursor.advance();return}this.emit(\"error\",\"missing-section-separator\",`Expected '$' separator before section ${e+1}`,this.cursor.currentSpan());}parseSimplePolymers(){if(!(this.cursor.at(\"dollar\")||this.cursor.isAtEnd()))for(this.parsePolymer();this.cursor.at(\"pipe\");){if(this.cursor.advance(),this.cursor.at(\"dollar\")||this.cursor.isAtEnd()){this.emit(\"warning\",\"empty-polymer-body\",\"Empty polymer after '|'\",this.cursor.currentSpan());return}this.parsePolymer();}}parsePolymer(){let e=this.cursor.currentSpan(),t=this.cursor.optional(\"identifier\");if(t===null){this.emit(\"error\",\"unexpected-token\",`Expected polymer id, got '${this.cursor.peek().value}'`,this.cursor.currentSpan()),this.skipUntil([\"pipe\",\"dollar\",\"eof\"]);return}let n=bo(t.value);if(n===null){this.emit(\"error\",\"unknown-polymer-type\",`Unknown polymer type '${t.value}'`,t.span),this.skipUntil([\"pipe\",\"dollar\",\"eof\"]);return}if(this.chainById.has(t.value)&&this.emit(\"warning\",\"duplicate-polymer-id\",`Duplicate polymer id '${t.value}'`,t.span),this.cursor.optional(\"lbrace\")===null){this.emit(\"error\",\"unexpected-token\",`Expected '{' after polymer id '${t.value}'`,this.cursor.currentSpan());return}let o={id:t.value,polymerType:n.polymerType,rawTypeName:n.rawTypeName,rawNumber:n.number,backboneAtoms:[],allAtoms:[],bonds:[],span:{start:e.start,end:e.end}};if(this.chains.push(o),this.chainById.set(o.id,o),this.cursor.at(\"rbrace\"))this.emit(\"warning\",\"empty-polymer-body\",`Empty body for polymer '${o.id}'`,this.cursor.currentSpan());else if(n.isGroup)this.parseGroupBody(o);else switch(n.polymerType){case x.PEPTIDE:this.parsePeptideBody(o);break;case x.RNA:this.parseRnaBody(o,n.isDnaShim),n.isDnaShim&&this.emit(\"info\",\"dna-emitted-as-rna\",`DNA polymer '${o.id}' will be emitted as RNA on canonicalize`,t.span);break;case x.CHEM:this.parseChemBody(o);break;case x.BLOB:this.parseBlobBody(o);break;}if(this.cursor.optional(\"rbrace\")===null){this.emit(\"error\",\"unterminated-brace\",`Expected '}' to close polymer '${o.id}'`,this.cursor.currentSpan()),this.skipUntil([\"pipe\",\"dollar\",\"eof\"]);return}let r=this.cursor.optional(\"quote-string\");r!==null&&(o.annotation=r.value);}parsePeptideBody(e){for(this.parsePeptideItem(e);this.cursor.at(\"dot\")&&(this.cursor.advance(),!(this.cursor.at(\"rbrace\")||this.cursor.at(\"gt\")));)this.parsePeptideItem(e);if(this.cursor.at(\"gt\")){let t=this.cursor.currentSpan();this.cursor.advance(),this.emit(\"warning\",\"peptide-cyclic-without-closure\",`Peptide '${e.id}' marked cyclic with '>' \\u2014 no explicit closure connection emitted`,t);}}parsePeptideItem(e){if(this.cursor.at(\"lparen\"))this.parsePeptideAlternation(e);else {let t=this.parsePeptideAtom(e);this.maybeRepeatBracket(e,[t]);}this.maybeAttachAnnotation(e);}parsePeptideAtom(e){let t=this.consumeMonomerSymbol(false),{symbol:n,annotation:o,ambiguity:r,ambiguityKind:s,isInlineSmiles:a,rawPayload:d,inlineSource:l,span:u}=t,c=this.makeAtom(e,g.AA,n);o!==void 0&&(c.tag=o),r!==void 0&&(c.bio.ambiguity=r),s!==void 0&&(c.bio.ambiguityKind=s),l!==void 0&&(c.inlineSource=l),a&&this.registerInlineSmiles(d,u,x.PEPTIDE),this.addToChain(e,c,true);let m=e.backboneAtoms[e.backboneAtoms.length-2];return m!==void 0&&this.addBond(e,m,c,\"backbone\",{kind:\"numeric\",r:2},{kind:\"numeric\",r:1}),c}parsePeptideAlternation(e){let t=this.cursor.currentSpan();if(this.cursor.advance(),this.peptideContentIsSubsequence()){let l=e.backboneAtoms.length;for(this.parsePeptideItem(e);this.cursor.at(\"dot\")&&(this.cursor.advance(),!(this.cursor.at(\"rparen\")||this.cursor.isAtEnd()));)this.parsePeptideItem(e);this.cursor.optional(\"rparen\")===null&&this.emit(\"error\",\"unterminated-paren\",\"Expected ')' to close repeat sub-sequence\",this.cursor.currentSpan());let u=e.backboneAtoms.slice(l);this.maybeRepeatBracket(e,u),this.maybeAttachAnnotation(e);return}let n=[],o=null;for(;!this.cursor.at(\"rparen\")&&!this.cursor.isAtEnd();){let l=this.parseAlternationCandidate(x.PEPTIDE);if(n.push(l),this.cursor.at(\"comma\"))o===\"and\"&&this.emit(\"warning\",\"mixed-separator-in-alternation\",\"Mixed ',' and '+' separators in alternation\",this.cursor.currentSpan()),o=\"or\",this.cursor.advance();else if(this.cursor.at(\"plus\"))o===\"or\"&&this.emit(\"warning\",\"mixed-separator-in-alternation\",\"Mixed ',' and '+' separators in alternation\",this.cursor.currentSpan()),o=\"and\",this.cursor.advance();else break}this.cursor.optional(\"rparen\")===null&&this.emit(\"error\",\"unterminated-paren\",\"Expected ')' to close alternation\",this.cursor.currentSpan());let r=o===\"and\"?\"+\":\",\",s=`(${n.map(l=>l.symbol+(l.ratio!==void 0?`:${String(l.ratio)}`:\"\")).join(r)})`,a=this.makeAtom(e,g.AA,\"?\");a.bio.ambiguity=s,a.bio.ambiguityKind=o===\"and\"?\"and\":\"or\",this.addToChain(e,a,true);let d=e.backboneAtoms[e.backboneAtoms.length-2];if(d!==void 0&&this.addBond(e,d,a,\"backbone\",{kind:\"numeric\",r:2},{kind:\"numeric\",r:1}),o===\"and\")for(let l of n)typeof l.ratio==\"number\"&&l.ratio<0&&this.emit(\"error\",\"ratio-and-negative\",`Negative ratio ${l.ratio} in AND mixture`,t);this.maybeRepeatBracket(e,[a]),this.maybeAttachAnnotation(e);}peptideContentIsSubsequence(){let e=1,t=0;for(;;){let n=this.cursor.peek(t);if(n.kind===\"eof\")return false;if(n.kind===\"lparen\"){e+=1,t+=1;continue}if(n.kind===\"rparen\"){if(e-=1,e===0)return true;t+=1;continue}if(e===1){if(n.kind===\"dot\")return true;if(n.kind===\"comma\"||n.kind===\"plus\"||n.kind===\"colon\")return false}if(t+=1,t>1024)return false}}parseAlternationCandidate(e){let{symbol:t,isInlineSmiles:n,rawPayload:o,span:r}=this.consumeMonomerSymbol(true);n&&this.registerInlineSmiles(o,r,e);let s;if(this.cursor.optional(\"colon\")!==null){let a=this.cursor.peek();a.kind===\"integer\"||a.kind===\"decimal\"?(this.cursor.advance(),s=parseFloat(a.value)):a.kind===\"question\"?(this.cursor.advance(),s=\"?\"):this.emit(\"error\",\"unexpected-token\",\"Expected ratio after ':' in alternation\",a.span);}return s===void 0?{symbol:t}:{symbol:t,ratio:s}}parseRnaBody(e,t){for(this.parseRnaItem(e,t);this.cursor.at(\"dot\")&&(this.cursor.advance(),!(this.cursor.at(\"rbrace\")||this.cursor.at(\"dollar\")||this.cursor.isAtEnd()));)this.parseRnaItem(e,t);}parseRnaItem(e,t){if(this.cursor.at(\"lparen\")){this.parseRnaAlternation(e,t);return}if(this.cursor.at(\"asterisk\")){this.cursor.currentSpan();this.cursor.advance();let l=this.makeAtom(e,g.NUCLEOTIDE,\"*\");this.addToChain(e,l,true);let u=e.backboneAtoms[e.backboneAtoms.length-2];u!==void 0&&this.addBond(e,u,l,\"backbone\",{kind:\"numeric\",r:2},{kind:\"numeric\",r:1}),this.maybeRepeatBracket(e,[l]),this.maybeAttachAnnotation(e);return}let n=this.parseRnaSugar(e,t);this.maybeAttachAnnotation(e);let o;this.cursor.at(\"lparen\")&&(this.cursor.advance(),this.cursor.at(\"rparen\")||(o=this.parseRnaBaseSymbol(e),this.maybeAttachAnnotationTo(o)),this.cursor.optional(\"rparen\")===null&&this.emit(\"error\",\"unterminated-paren\",\"Expected ')' after RNA base\",this.cursor.currentSpan()),o!==void 0&&(this.addBond(e,n,o,\"branch\",{kind:\"numeric\",r:3},{kind:\"numeric\",r:1}),n.branchAtom=o));let r;this.canStartRnaLinker()&&(r=this.parseRnaLinker(e),this.maybeAttachAnnotationTo(r)),r!==void 0&&this.addBond(e,n,r,\"backbone\",{kind:\"numeric\",r:2},{kind:\"numeric\",r:1});let s=e.backboneAtoms.indexOf(n);if(s>0){let d=e.backboneAtoms[s-1];this.addBond(e,d,n,\"backbone\",{kind:\"numeric\",r:2},{kind:\"numeric\",r:1});}let a=[n];o!==void 0&&a.push(o),r!==void 0&&a.push(r),this.maybeRepeatBracket(e,a);}canStartRnaLinker(){let e=this.cursor.peek().kind;return e===\"identifier\"||e===\"inline-smiles\"||e===\"asterisk\"}parseRnaSugar(e,t){let{symbol:n,isInlineSmiles:o,rawPayload:r,inlineSource:s,span:a}=this.consumeMonomerSymbol(false),d=this.makeAtom(e,g.SUGAR,n);return s!==void 0&&(d.inlineSource=s),o&&this.registerInlineSmiles(r,a,x.RNA),this.addToChain(e,d,true),d}parseRnaBaseSymbol(e){let{symbol:t,isInlineSmiles:n,rawPayload:o,inlineSource:r,span:s}=this.consumeMonomerSymbol(false),a=this.makeAtom(e,g.BASE,t);return r!==void 0&&(a.inlineSource=r),n&&this.registerInlineSmiles(o,s,x.RNA),this.addToChain(e,a,false),a}parseRnaLinker(e){if(this.cursor.at(\"asterisk\")){this.cursor.currentSpan();this.cursor.advance();let l=this.makeAtom(e,g.LINKER,\"*\");return this.addToChain(e,l,true),l}let{symbol:t,isInlineSmiles:n,rawPayload:o,inlineSource:r,span:s}=this.consumeMonomerSymbol(false),a=this.makeAtom(e,g.LINKER,t);return r!==void 0&&(a.inlineSource=r),n&&this.registerInlineSmiles(o,s,x.RNA),this.addToChain(e,a,true),a}parseRnaAlternation(e,t){let n=e.backboneAtoms.length;if(this.cursor.advance(),this.looksLikeFlatAlternation()){let r=[],s=null;for(;!this.cursor.at(\"rparen\")&&!this.cursor.isAtEnd();)if(r.push(this.parseAlternationCandidate(x.RNA)),this.cursor.at(\"comma\"))s=\"or\",this.cursor.advance();else if(this.cursor.at(\"plus\"))s=\"and\",this.cursor.advance();else break;this.cursor.optional(\"rparen\")===null&&this.emit(\"error\",\"unterminated-paren\",\"Expected ')' in RNA alternation\",this.cursor.currentSpan());let a=s===\"and\"?\"+\":\",\",d=`(${r.map(c=>c.symbol+(c.ratio!==void 0?`:${String(c.ratio)}`:\"\")).join(a)})`,l=this.makeAtom(e,g.BASE,\"?\");l.bio.ambiguity=d,l.bio.ambiguityKind=s===\"and\"?\"and\":\"or\",this.addToChain(e,l,true);let u=e.backboneAtoms[e.backboneAtoms.length-2];u!==void 0&&this.addBond(e,u,l,\"backbone\",{kind:\"numeric\",r:2},{kind:\"numeric\",r:1}),this.maybeRepeatBracket(e,[l]),this.maybeAttachAnnotation(e);return}for(this.parseRnaItem(e,t);this.cursor.at(\"dot\")&&(this.cursor.advance(),!(this.cursor.at(\"rparen\")||this.cursor.isAtEnd()));)this.parseRnaItem(e,t);this.cursor.optional(\"rparen\")===null&&this.emit(\"error\",\"unterminated-paren\",\"Expected ')' in RNA repeat\",this.cursor.currentSpan());let o=e.backboneAtoms.slice(n);this.maybeRepeatBracket(e,o),this.maybeAttachAnnotation(e);}looksLikeFlatAlternation(){let e=1,t=0,n=false;for(;;){let o=this.cursor.peek(t);if(o.kind===\"eof\")return n;if(o.kind===\"rparen\"){if(e-=1,e===0)return n}else {if(o.kind===\"lparen\")return false;if(o.kind===\"dot\")return false;e===1&&(o.kind===\"comma\"||o.kind===\"plus\")&&(n=true);}if(t+=1,t>256)return n}}parseChemBody(e){let t;if(this.cursor.at(\"asterisk\"))this.cursor.advance(),t=this.makeAtom(e,g.CHEM,\"*\"),this.addToChain(e,t,true);else {let{symbol:n,isInlineSmiles:o,rawPayload:r,inlineSource:s,span:a}=this.consumeMonomerSymbol(false);t=this.makeAtom(e,g.CHEM,n),s!==void 0&&(t.inlineSource=s),o&&this.registerInlineSmiles(r,a,x.CHEM),this.addToChain(e,t,true);}this.maybeAttachAnnotation(e),this.cursor.at(\"apos\")&&this.maybeRepeatBracket(e,[t]),this.cursor.at(\"rbrace\")||(this.emit(\"error\",\"chem-multiple-monomers\",`CHEM polymer '${e.id}' must contain exactly one monomer`,this.cursor.currentSpan()),this.skipUntil([\"rbrace\",\"eof\"]));}parseBlobBody(e){let t,n,o=false,r=\"\",s,a=this.cursor.currentSpan();if(this.cursor.at(\"inline-smiles\")){let l=this.cursor.advance();o=Be(l.value),r=l.value,t=l.value,n=l.value,s=l.value,a=l.span;}else if(this.cursor.at(\"identifier\")){let l=this.cursor.advance();t=l.value,n=l.value,a=l.span;}else this.emit(\"error\",\"unknown-blobtype\",\"Expected BLOB identifier\",this.cursor.currentSpan()),t=\"?\",n=\"?\";let d=this.makeAtom(e,g.BLOB,t);d.bio.blobtype=n,s!==void 0&&(d.inlineSource=s),o&&this.registerInlineSmiles(r,a,x.BLOB),this.addToChain(e,d,true),this.maybeAttachAnnotation(e);}parseGroupBody(e){let t=0;for(;;){let n=this.cursor.peek();if(n.kind===\"eof\"||t===0&&n.kind===\"rbrace\")break;n.kind===\"lbrace\"&&(t+=1),n.kind===\"rbrace\"&&(t-=1),this.cursor.advance();}}parseConnections(){if(!(this.cursor.at(\"dollar\")||this.cursor.isAtEnd()))for(this.parseConnection();this.cursor.at(\"pipe\")&&(this.cursor.advance(),!(this.cursor.at(\"dollar\")||this.cursor.isAtEnd()));)this.parseConnection();}parseConnection(){let e=this.cursor.currentSpan(),t=this.cursor.optional(\"identifier\");if(t===null){this.emit(\"error\",\"unexpected-token\",\"Expected chain id in connection\",this.cursor.currentSpan()),this.skipUntil([\"pipe\",\"dollar\",\"eof\"]);return}if(this.cursor.optional(\"comma\")===null){this.emit(\"error\",\"unexpected-token\",\"Expected ',' in connection\",this.cursor.currentSpan()),this.skipUntil([\"pipe\",\"dollar\",\"eof\"]);return}let n=this.cursor.optional(\"identifier\");if(n===null){this.emit(\"error\",\"unexpected-token\",\"Expected second chain id in connection\",this.cursor.currentSpan()),this.skipUntil([\"pipe\",\"dollar\",\"eof\"]);return}if(this.cursor.optional(\"comma\")===null){this.emit(\"error\",\"unexpected-token\",\"Expected ',' before connection position\",this.cursor.currentSpan()),this.skipUntil([\"pipe\",\"dollar\",\"eof\"]);return}let o=this.parsePosition();if(this.cursor.optional(\"colon\")===null){this.emit(\"error\",\"unexpected-token\",\"Expected ':' between position and R-group\",this.cursor.currentSpan()),this.skipUntil([\"pipe\",\"dollar\",\"eof\"]);return}let r=this.parseRGroupSpec();if(this.cursor.optional(\"dash\")===null){this.emit(\"error\",\"unexpected-token\",\"Expected '-' between connection endpoints\",this.cursor.currentSpan()),this.skipUntil([\"pipe\",\"dollar\",\"eof\"]);return}let s=this.parsePosition();if(this.cursor.optional(\"colon\")===null){this.emit(\"error\",\"unexpected-token\",\"Expected ':' before second R-group\",this.cursor.currentSpan()),this.skipUntil([\"pipe\",\"dollar\",\"eof\"]);return}let a=this.parseRGroupSpec(),d=this.cursor.optional(\"quote-string\"),l=r.kind===\"pair\"&&a.kind===\"pair\"?\"hbond\":\"cross-polymer\",u={chain1:t.value,pos1:o,r1:r,chain2:n.value,pos2:s,r2:a,kind:l,span:{start:e.start,end:d?.span.end??this.cursor.peek().span.start},...d!==null?{tag:d.value}:{}};this.pendingBonds.push(u);}parsePosition(){let e=this.cursor.peek();return e.kind===\"integer\"?(this.cursor.advance(),{kind:\"index\",value:parseInt(e.value,10)}):e.kind===\"question\"?(this.cursor.advance(),{kind:\"any\"}):e.kind===\"identifier\"?(this.cursor.advance(),this.emit(\"info\",\"symbol-position-reference\",`Connection position uses monomer symbol '${e.value}' as chain-level ambiguity`,e.span),{kind:\"symbol\",value:e.value}):(this.emit(\"error\",\"invalid-position\",`Expected position (integer, '?', or symbol), got '${e.value}'`,e.span),{kind:\"any\"})}parseRGroupSpec(){let e=this.cursor.peek();if(e.kind===\"question\")return this.cursor.advance(),{kind:\"unspecified\"};if(e.kind===\"asterisk\")return this.cursor.advance(),{kind:\"wildcard\"};if(e.kind===\"identifier\"){if(this.cursor.advance(),e.value===\"pair\")return {kind:\"pair\"};let t=/^R([1-9][0-9]*)$/.exec(e.value);return t===null?(this.emit(\"error\",\"invalid-rgroup\",`Expected R-group label, got '${e.value}'`,e.span),{kind:\"unspecified\"}):{kind:\"numeric\",r:parseInt(t[1],10)}}return this.emit(\"error\",\"invalid-rgroup\",`Expected R-group label, got '${e.value}'`,e.span),{kind:\"unspecified\"}}parseGroupsSection(){if(!(this.cursor.at(\"dollar\")||this.cursor.isAtEnd()))for(this.parseGroupOrBondRatio();this.cursor.at(\"pipe\")&&(this.cursor.advance(),!(this.cursor.at(\"dollar\")||this.cursor.isAtEnd()));)this.parseGroupOrBondRatio();}parseGroupOrBondRatio(){let e=this.cursor.optional(\"identifier\");if(e===null){this.emit(\"error\",\"unexpected-token\",\"Expected group or bond-ratio identifier\",this.cursor.currentSpan()),this.skipUntil([\"pipe\",\"dollar\",\"eof\"]);return}this.cursor.at(\"lparen\")?this.parseGroupAfterId(e):this.cursor.at(\"plus\")?this.parseBondRatioAfterId(e):(this.emit(\"warning\",\"unexpected-token\",`Expected '(' or '+' after id '${e.value}' in section 3`,this.cursor.currentSpan()),this.skipUntil([\"pipe\",\"dollar\",\"eof\"]));}parseGroupAfterId(e){let t=bo(e.value);(t===null||!t.isGroup)&&this.emit(\"error\",\"unknown-group-reference\",`Group id must be 'G<n>', got '${e.value}'`,e.span),this.cursor.advance();let n=[],o=\"or\",r=null;for(;!this.cursor.at(\"rparen\")&&!this.cursor.isAtEnd();){let s=this.parseGroupMember();if(s!==null&&n.push(s),this.cursor.at(\"comma\"))r===null&&(r=\"or\",o=\"or\"),this.cursor.advance();else if(this.cursor.at(\"plus\"))r===null&&(r=\"and\",o=\"and\"),this.cursor.advance();else break}this.cursor.optional(\"rparen\")===null&&this.emit(\"error\",\"unterminated-paren\",\"Expected ')' to close group\",this.cursor.currentSpan()),this.groups.push({id:e.value,kind:o,members:n});}parseGroupMember(){let e=this.cursor.optional(\"identifier\");if(e===null)return this.emit(\"error\",\"unexpected-token\",\"Expected group member id\",this.cursor.currentSpan()),null;let t;return this.cursor.optional(\"colon\")!==null&&(t=this.parseRatio()),t===void 0?{target:e.value}:{target:e.value,ratio:t}}parseRatio(){let e=this.cursor.peek();if(e.kind===\"integer\"||e.kind===\"decimal\"){this.cursor.advance();let t=parseFloat(e.value);if(this.cursor.at(\"dash\")){this.cursor.peek();if(this.cursor.peek(1).kind===\"integer\"){this.cursor.advance();let o=this.cursor.advance();this.emit(\"info\",\"ratio-range\",`Ratio range ${e.value}-${o.value}; using lower bound`,{start:e.span.start,end:o.span.end});}}return t}return e.kind===\"question\"?(this.cursor.advance(),\"?\"):(this.emit(\"error\",\"unexpected-token\",`Expected ratio after ':', got '${e.value}'`,e.span),0)}parseBondRatioAfterId(e){this.cursor.advance();let t=this.cursor.optional(\"identifier\");if(t===null){this.emit(\"error\",\"unexpected-token\",\"Expected second chain id in bond-ratio\",this.cursor.currentSpan());return}let n;if(this.cursor.optional(\"colon\")!==null){let r=this.parseRatio();typeof r==\"number\"&&(n=r);}let o=this.pendingBonds.find(r=>r.chain1===e.value&&r.chain2===t.value||r.chain1===t.value&&r.chain2===e.value);if(o===void 0){this.emit(\"warning\",\"bond-ratio-no-matching-bond\",`Bond-ratio for ${e.value}+${t.value} has no matching cross-polymer bond`,e.span);return}n!==void 0&&(o.ratio={numerator:n});}parseAnnotationsSection(){if(this.cursor.at(\"dollar\")||this.cursor.isAtEnd())return;this.cursor.position();if(this.cursor.at(\"lbrace\")){this.parseAnnotation20(),this.cursor.at(\"pipe\")&&(this.emit(\"info\",\"annotation-mixed-versions\",\"Mixed HELM 2.0 JSON and HELM 1.0 pipe annotations\",this.cursor.currentSpan()),this.cursor.advance(),this.parseAnnotation10Entries());return}this.parseAnnotation10Entries();}parseAnnotation20(){let e=this.cursor.currentSpan(),t=0,n=e.end;for(;!this.cursor.isAtEnd();){let s=this.cursor.peek();if(s.kind===\"lbrace\")t+=1;else if(s.kind===\"rbrace\"&&(t-=1,t===0)){n=s.span.end,this.cursor.advance();break}this.cursor.advance();}let o=this.source.slice(e.start,n),r=null;try{r=JSON.parse(o);}catch{this.emit(\"warning\",\"annotation-malformed-json\",\"Annotation block is not valid JSON\",{start:e.start,end:n}),this.annotations={perPolymer:this.annotations.perPolymer,version:this.annotations.version,raw:o};return}if(r!==null&&typeof r==\"object\"&&!Array.isArray(r)){let s=new Map(this.annotations.perPolymer);for(let[a,d]of Object.entries(r))d!==null&&typeof d==\"object\"&&!Array.isArray(d)?(s.set(a,{...d}),this.chainById.has(a)||this.emit(\"warning\",\"annotation-unknown-polymer\",`Annotation references unknown polymer '${a}'`,e)):s.set(a,{value:d});this.annotations={perPolymer:s,version:this.annotations.version};}else this.emit(\"warning\",\"annotation-malformed-json\",\"Annotation block parsed but is not an object\",{start:e.start,end:n}),this.annotations={perPolymer:this.annotations.perPolymer,version:this.annotations.version,raw:o};}parseAnnotation10Entries(){for(this.parseAnnotation10One();this.cursor.at(\"pipe\")&&(this.cursor.advance(),!(this.cursor.at(\"dollar\")||this.cursor.isAtEnd()));)this.parseAnnotation10One();}parseAnnotation10One(){let e=this.cursor.optional(\"identifier\");if(e===null){this.emit(\"warning\",\"annotation-malformed-json\",\"Expected polymer-id in HELM 1.0 annotation\",this.cursor.currentSpan()),this.skipUntil([\"pipe\",\"dollar\",\"eof\"]);return}if(this.cursor.optional(\"lbrace\")===null){this.emit(\"warning\",\"annotation-malformed-json\",\"Expected '{' after polymer-id\",this.cursor.currentSpan()),this.skipUntil([\"pipe\",\"dollar\",\"eof\"]);return}let t=[];for(;!this.cursor.at(\"rbrace\")&&!this.cursor.isAtEnd();)t.push(this.cursor.advance().value);if(this.cursor.optional(\"rbrace\")===null){this.emit(\"error\",\"unterminated-brace\",\"Expected '}' to close annotation\",this.cursor.currentSpan());return}let n=t.join(\"\").trim(),o=new Map(this.annotations.perPolymer),r=o.get(e.value)??{};n===\"ss\"||n===\"as\"?o.set(e.value,{...r,strandtype:n}):o.set(e.value,{...r,[n]:true}),this.chainById.has(e.value)||this.emit(\"warning\",\"annotation-unknown-polymer\",`Annotation references unknown polymer '${e.value}'`,e.span),this.annotations={perPolymer:o,version:this.annotations.version};}parseVersionTrailer(){let e=this.cursor.optional(\"identifier\");if(e===null){this.annotations={...this.annotations,version:\"\"};return}let t=e.value;if(this.cursor.at(\"dot\")&&this.cursor.peek(1).kind===\"integer\"){this.cursor.advance();let n=this.cursor.advance();t=`${e.value}.${n.value}`;}this.annotations={...this.annotations,version:t};}skipUntil(e){for(;!this.cursor.isAtEnd();){if(e.includes(this.cursor.peek().kind))return;this.cursor.advance();}}consumeMonomerSymbol(e){let t=this.cursor.peek();if(t.kind===\"inline-smiles\"){this.cursor.advance();let n=Be(t.value);return {symbol:t.value,isInlineSmiles:n,rawPayload:t.value,inlineSource:t.value,span:t.span}}if(t.kind===\"identifier\"){this.cursor.advance();let n=t.value,o=t.span;for(;this.cursor.peek().kind===\"dash\"&&this.cursor.peek(1).kind===\"integer\"&&(this.cursor.peek(2).kind===\"identifier\"||this.cursor.peek(2).kind===\"dash\");){this.cursor.advance();let s=this.cursor.advance();if(n=`${n}-${s.value}`,o=s.span,this.cursor.peek().kind===\"identifier\"){let a=this.cursor.advance();n=`${n}${a.value}`,o=a.span;}}return {symbol:n,isInlineSmiles:false,rawPayload:n,span:{start:t.span.start,end:o.end}}}if(t.kind===\"asterisk\"||t.kind===\"underscore\"||t.kind===\"question\")return this.cursor.advance(),{symbol:t.value,isInlineSmiles:false,rawPayload:t.value,span:t.span};if(t.kind===\"integer\"&&this.cursor.peek(1).kind===\"identifier\"){let n=this.cursor.advance(),o=this.cursor.advance(),r=`${n.value}${o.value}`;return {symbol:r,isInlineSmiles:false,rawPayload:r,span:{start:n.span.start,end:o.span.end}}}return this.emit(\"error\",\"unexpected-token\",`Expected monomer symbol, got '${t.value}'`,t.span),{symbol:\"?\",isInlineSmiles:false,rawPayload:\"\",span:t.span}}maybeRepeatBracket(e,t){if(!this.cursor.at(\"apos\"))return;let n=this.cursor.currentSpan();this.cursor.advance();let o=this.cursor.optional(\"integer\");if(o===null){this.emit(\"error\",\"unexpected-token\",\"Expected integer in repeat bracket\",this.cursor.currentSpan()),this.cursor.optional(\"apos\");return}let r=parseInt(o.value,10),s=r;if(this.cursor.at(\"dash\")){this.cursor.advance();let a=this.cursor.optional(\"integer\");a===null?this.emit(\"error\",\"unexpected-token\",\"Expected integer after '-' in repeat bracket\",this.cursor.currentSpan()):s=parseInt(a.value,10);}if(this.cursor.optional(\"apos\")===null&&this.emit(\"error\",\"unterminated-apostrophe\",\"Expected closing apostrophe\",this.cursor.currentSpan()),t.length===0){this.emit(\"warning\",\"repeat-on-empty-bracket\",\"Repeat bracket applied to empty content\",n);return}if(s<r){this.emit(\"warning\",\"repeat-range-inverted\",`Repeat range ${r}-${s} has max < min; swapping`,n);let a=r;r=s,s=a;}if(r===0&&s===0){this.emit(\"warning\",\"repeat-zero-count\",\"Repeat bracket with zero count\",n);return}s>1e4&&this.emit(\"warning\",\"bracket-repeat-too-large\",`Repeat range upper bound ${s} > 10000`,n),e.polymerType===x.CHEM&&this.emit(\"error\",\"repeat-on-non-iterable-polymer\",`Repeat bracket not allowed on CHEM polymer '${e.id}'`,n),this.groups.push({id:`${e.id}/bracket@${t[0]?.id??0}`,kind:\"bracket\",members:t.map(a=>({target:String(a.id)})),repeat:{min:r,max:s}});}maybeAttachAnnotation(e){let t=e.backboneAtoms[e.backboneAtoms.length-1];t!==void 0&&this.maybeAttachAnnotationTo(t);}maybeAttachAnnotationTo(e){if(e===void 0)return;let t=this.cursor.optional(\"quote-string\");t!==null&&(e.tag=t.value);}registerInlineSmiles(e,t,n){if(Be(e)){if(this.lib===null){this.emit(\"info\",\"inline-smiles-no-lib\",\"Inline SMILES seen but no monomer library available for registration\",t);return}try{this.lib.addMonomer;let o=this.lib.registerInlineSmilesMonomer;typeof o==\"function\"&&o.call(this.lib,n,e);}catch(o){let r=o instanceof Error?o.message:String(o);this.emit(\"warning\",\"inline-smiles-without-r-groups\",`Inline SMILES registration failed: ${r}`,t);}}}makeAtom(e,t,n){return {id:this.atomIds.next(),p:{x:0,y:0},biotype:t,symbol:n,monomer:null,bio:{chainId:e.id,positionInChain:0,continuousId:0},hidden:false,selected:false,highlighted:false}}addToChain(e,t,n){e.allAtoms.push(t),n&&(e.backboneAtoms.push(t),t.bio.positionInChain=e.backboneAtoms.length);}addBond(e,t,n,o,r,s){let a=this.bondIds.next();e.bonds.push({id:a,a1:t,a2:n,kind:o,r1:r,r2:s});}finalize(){let e=[];for(let a of this.pendingBonds){let d=this.chainById.get(a.chain1),l=this.chainById.get(a.chain2);if(d===void 0){this.emit(\"error\",\"unknown-chain-reference\",`Connection references unknown chain '${a.chain1}'`,a.span);continue}if(l===void 0){this.emit(\"error\",\"unknown-chain-reference\",`Connection references unknown chain '${a.chain2}'`,a.span);continue}let u=this.resolveAtomByPosition(d,a.pos1,a.span),c=this.resolveAtomByPosition(l,a.pos2,a.span);if(u===null||c===null)continue;a.r1.kind===\"pair\"&&u.branchAtom!==void 0&&(u=u.branchAtom),a.r2.kind===\"pair\"&&c.branchAtom!==void 0&&(c=c.branchAtom);let p={id:this.bondIds.next(),a1:u,a2:c,kind:a.kind,r1:a.r1,r2:a.r2,...a.tag!==void 0?{tag:a.tag}:{},...a.ratio!==void 0?{ratio:a.ratio}:{}};e.push(p);}let t=[],n=[],o=[];for(let a of this.chains){for(let c of a.allAtoms)t.push(c);for(let c of a.bonds)n.push(c);let d=this.annotations.perPolymer.get(a.id),l=d===void 0?void 0:d.strandtype,u=l===\"ss\"||l===\"as\"?l:void 0;o.push({id:a.id,polymerType:a.polymerType,backboneAtoms:a.backboneAtoms,bonds:a.bonds,...a.annotation!==void 0?{annotation:a.annotation}:{},...u!==void 0?{strandType:u}:{}});}for(let a of e)n.push(a);let r=0;for(let a of this.chains)for(let d of a.backboneAtoms)r+=1,d.bio.continuousId=r,d.branchAtom!==void 0&&(r+=1,d.branchAtom.bio.continuousId=r);let s=[];for(let a of this.groups)s.push({id:a.id,kind:a.kind,members:a.members,...a.repeat!==void 0?{repeat:a.repeat}:{}});return {atoms:t,bonds:n,chains:o,groups:s,annotations:this.annotations}}sourceOrderAtoms(e){let t=[];for(let n of e.backboneAtoms)t.push(n),n.branchAtom!==void 0&&t.push(n.branchAtom);return t}resolveAtomByPosition(e,t,n){if(t.kind===\"any\")return e.backboneAtoms[0]??null;if(t.kind===\"symbol\"){let s=e.backboneAtoms.find(a=>a.symbol===t.value);if(s===void 0){let a=e.allAtoms.find(d=>d.symbol===t.value);return a===void 0?(this.emit(\"warning\",\"position-out-of-range\",`Chain '${e.id}' has no monomer with symbol '${t.value}'`,n),e.backboneAtoms[0]??null):a}return s}let o=this.sourceOrderAtoms(e),r=t.value;return r<1||r>o.length?(this.emit(\"error\",\"position-out-of-range\",`Position ${r} out of range for chain '${e.id}' (length ${o.length})`,n),e.backboneAtoms[0]??null):o[r-1]}emit(e,t,n,o){let r={severity:e,code:t,message:n,...o!==void 0?{span:{start:o.start,end:o.end}}:{}};if(this.diagnostics.push(r),this.mode===\"strict\"&&e===\"error\")throw new F(t,n,{...o!==void 0?{span:{start:o.start,end:o.end}}:{}})}};function Mr(i,e,t){for(let n of t){if(n.kind!==\"backbone\"||n.r1.kind!==\"numeric\"||n.r2.kind!==\"numeric\")continue;let o=n.a1.id===i.id&&n.a2.id===e.id&&n.r1.r===2&&n.r2.r===1,r=n.a1.id===e.id&&n.a2.id===i.id&&n.r1.r===2&&n.r2.r===1;if(o||r)return true}return false}function Tr(i){let e=(c,m)=>c.polymerType===x.CHEM||c.polymerType===x.BLOB?true:!Mr(c.backboneAtoms[m],c.backboneAtoms[m+1],i.bonds),t=false;for(let c of i.chains){for(let m=0;m<c.backboneAtoms.length-1;m++)if(e(c,m)){t=true;break}if(t)break}if(!t)return i;let n=new Set(i.chains.map(c=>c.id)),o=c=>{let m=1;for(;n.has(`${c}${m}`);)m+=1;let p=`${c}${m}`;return n.add(p),p},r=[];for(let c of i.chains){let m=[[]],p=m[0];for(let h=0;h<c.backboneAtoms.length;h++){let y=c.backboneAtoms[h];p.push(y),h<c.backboneAtoms.length-1&&e(c,h)&&(p=[],m.push(p));}for(let h=0;h<m.length;h++){let f={id:h===0?c.id:o(c.polymerType),polymerType:c.polymerType,atoms:m[h]};h===0&&c.annotation!==void 0&&(f.annotation=c.annotation),r.push(f);}}let s=new Map;for(let c of r)for(let m=0;m<c.atoms.length;m++){let p=c.atoms[m];s.set(p.id,{chainId:c.id,pos:m+1}),p.branchAtom!==void 0&&s.set(p.branchAtom.id,{chainId:c.id,pos:m+1});}let a=new Map;for(let c of i.atoms){let m=s.get(c.id);if(m===void 0){a.set(c.id,c);continue}if(c.bio.chainId===m.chainId&&c.bio.positionInChain===m.pos){a.set(c.id,c);continue}a.set(c.id,{...c,bio:{...c.bio,chainId:m.chainId,positionInChain:m.pos}});}for(let c of i.atoms){if(c.branchAtom===void 0)continue;let m=a.get(c.id),p=a.get(c.branchAtom.id);m===void 0||p===void 0||(m.branchAtom=p);}let d=i.bonds.map(c=>{let m=a.get(c.a1.id)??c.a1,p=a.get(c.a2.id)??c.a2;return m===c.a1&&p===c.a2?c:{...c,a1:m,a2:p}}),l=r.map(c=>{let m=c.atoms.map(f=>a.get(f.id)??f),p=new Set;for(let f of c.atoms)p.add(f.id),f.branchAtom!==void 0&&p.add(f.branchAtom.id);let h=[];for(let f of d)p.has(f.a1.id)&&p.has(f.a2.id)&&h.push(f);return {id:c.id,polymerType:c.polymerType,backboneAtoms:m,bonds:h,...c.annotation!==void 0?{annotation:c.annotation}:{}}});return {atoms:i.atoms.map(c=>a.get(c.id)??c),bonds:d,chains:l,groups:i.groups,annotations:i.annotations}}function Pe(i,e){let t=Tr(i);return new gn(t,e??{}).emit()}var gn=class{constructor(e,t){this.mol=e,this.options=t;}emit(){let t=this.orderedChains().map(a=>this.emitPolymer(a)).join(\"|\"),n=this.emitConnections(),o=this.emitGroupsAndBondRatios(),r=this.emitAnnotations(),s=this.versionTrailer();return `${t}$${n}$${o}$${r}${s}`}orderedChains(){if(this.options.canonicalize!==true)return this.mol.chains;let e=this.mol.chains.slice();return e.sort((t,n)=>t.polymerType!==n.polymerType?t.polymerType<n.polymerType?-1:1:t.id<n.id?-1:t.id>n.id?1:0),e}emitPolymer(e){let t=this.emitChainBody(e),n=e.annotation!==void 0?`\"${ne(e.annotation)}\"`:\"\";return `${e.id}{${t}}${n}`}emitChainBody(e){switch(e.polymerType){case \"PEPTIDE\":return this.emitPeptideBody(e);case \"RNA\":return this.emitRnaBody(e);case \"CHEM\":return this.emitChemBody(e);case \"BLOB\":return this.emitBlobBody(e);default:return \"\"}}emitPeptideBody(e){let t=this.bracketsForChain(e.id),n=[],o=0,r=0,s=null;for(;o<e.backboneAtoms.length;){let a=e.backboneAtoms[o],d=t.find(u=>u.startAtomId===a.id);d!==void 0&&s===null&&(n.push(\"(\"),s=d,r+=1),n.push(this.emitMonomerToken(a));let l=a.tag!==void 0?`\"${ne(a.tag)}\"`:\"\";n.push(l),s!==null&&s.endAtomId===a.id&&(n.push(`)${go(s.min,s.max)}`),s=null,r-=1),o+=1,o<e.backboneAtoms.length&&n.push(\".\");}return n.join(\"\")}emitRnaBody(e){let t=this.bracketsForChain(e.id),n=[],o=0,r=true,s=null,a=l=>{s!==null&&s.endAtomId===l&&(n.push(`)${go(s.min,s.max)}`),s=null);},d=l=>{let u=t.find(c=>c.startAtomId===l);u!==void 0&&s===null&&(n.push(\"(\"),s=u);};for(;o<e.backboneAtoms.length;){let l=e.backboneAtoms[o];if(r||n.push(\".\"),r=false,l.biotype===g.NUCLEOTIDE){d(l.id),n.push(this.emitMonomerToken(l)),l.tag!==void 0&&n.push(`\"${ne(l.tag)}\"`),a(l.id),o+=1;continue}if(l.biotype===g.SUGAR){d(l.id),n.push(this.emitMonomerToken(l)),l.tag!==void 0&&n.push(`\"${ne(l.tag)}\"`),l.branchAtom!==void 0&&(n.push(\"(\"),n.push(this.emitMonomerToken(l.branchAtom)),l.branchAtom.tag!==void 0&&n.push(`\"${ne(l.branchAtom.tag)}\"`),n.push(\")\"));let u=e.backboneAtoms[o+1];u!==void 0&&u.biotype===g.LINKER?(n.push(this.emitMonomerToken(u)),u.tag!==void 0&&n.push(`\"${ne(u.tag)}\"`),a(u.id),o+=2):(a(l.id),o+=1);continue}d(l.id),n.push(this.emitMonomerToken(l)),l.tag!==void 0&&n.push(`\"${ne(l.tag)}\"`),a(l.id),o+=1;}return n.join(\"\")}emitChemBody(e){let t=e.backboneAtoms[0];if(t===void 0)return \"\";let n=t.tag!==void 0?`\"${ne(t.tag)}\"`:\"\";return `${this.emitMonomerToken(t)}${n}`}emitBlobBody(e){let t=e.backboneAtoms[0];if(t===void 0)return \"\";let n=t.tag!==void 0?`\"${ne(t.tag)}\"`:\"\";return `${this.emitMonomerToken(t)}${n}`}emitMonomerToken(e){let t;return e.inlineSource!==void 0?t=`[${e.inlineSource}]`:e.bio.ambiguity!==void 0&&(e.symbol===\"?\"||e.bio.ambiguity.startsWith(\"(\"))?t=e.bio.ambiguity:t=e.symbol,this.options.includeHighlights===true&&e.selected?`<span style='background:#bbf;'>${t}</span>`:t}emitConnections(){let e=[];for(let t of this.crossPolymerBonds())e.push(this.emitConnection(t));return e.join(\"|\")}*crossPolymerBonds(){let e=new Map;for(let t of this.mol.chains){let n=new Map;for(let o=0;o<t.backboneAtoms.length;o++)n.set(t.backboneAtoms[o].id,o);e.set(t.id,n);}for(let t of this.mol.bonds){if(t.kind===\"backbone\"){if(t.a1.bio.chainId===t.a2.bio.chainId){let n=e.get(t.a1.bio.chainId);if(n!==void 0){let o=n.get(t.a1.id),r=n.get(t.a2.id);if(o!==void 0&&r!==void 0&&Math.abs(o-r)===1)continue}}yield t;continue}if(t.kind===\"branch\"){if(t.a1.branchAtom!==void 0&&t.a1.branchAtom.id===t.a2.id||t.a2.branchAtom!==void 0&&t.a2.branchAtom.id===t.a1.id)continue;yield t;continue}yield t;}}emitConnection(e){let t=_o(e.r1,e.kind),n=_o(e.r2,e.kind),o=e.tag!==void 0?`\"${ne(e.tag)}\"`:\"\",r=String(this.connectionPosition(e.a1)),s=String(this.connectionPosition(e.a2));return `${e.a1.bio.chainId},${e.a2.bio.chainId},${r}:${t}-${s}:${n}${o}`}connectionPosition(e){return le(e,this.mol.chains.find(t=>t.id===e.bio.chainId))}emitGroupsAndBondRatios(){let e=[];for(let t of this.mol.groups)t.kind!==\"bracket\"&&e.push(this.emitGroup(t));for(let t of this.mol.bonds){if(t.kind!==\"cross-polymer\"||t.ratio===void 0)continue;let n=t.ratio.denominator!==void 0?`${t.ratio.numerator}/${t.ratio.denominator}`:`${t.ratio.numerator}`;e.push(`${t.a1.bio.chainId}+${t.a2.bio.chainId}:${n}`);}return e.join(\"|\")}emitGroup(e){let t=e.kind===\"and\"?\"+\":\",\",n=e.members.map(o=>Sr(o)).join(t);return `${e.id}(${n})`}emitAnnotations(){let e=this.mol.annotations.perPolymer;if(e.size===0)return \"\";let t={};for(let[n,o]of e)t[n]=o;return JSON.stringify(t)}versionTrailer(){let e=this.options.version??\"V2.0\";if(e===\"none\")return \"\";if(e===\"preserve\"){let t=this.mol.annotations.version;return t===\"\"?\"\":`$${t}`}return `$${e}`}bracketsForChain(e){let t=[],n=new Map;for(let o of this.mol.atoms)n.set(o.id,o.bio.chainId);for(let o of this.mol.groups){if(o.kind!==\"bracket\")continue;let r=[];for(let d of o.members){let l=parseInt(d.target,10);Number.isFinite(l)&&r.push(l);}if(r.length===0)continue;let s=new Set;for(let d of r){let l=n.get(d);l!==void 0&&s.add(l);}if(!s.has(e)||s.size>1)continue;let a=o.repeat??{min:1,max:1};t.push({members:r,min:a.min,max:a.max,set:new Set(r),startAtomId:r[0],endAtomId:r[r.length-1]});}return t}};function ne(i){let e=\"\";for(let t=0;t<i.length;t++){let n=i.charCodeAt(t);if(n===34){e+='\\\\\"';continue}if(n===92){e+=\"\\\\\\\\\";continue}if(n===10){e+=\"\\\\n\";continue}if(n===13){e+=\"\\\\r\";continue}if(n===9){e+=\"\\\\t\";continue}e+=i.charAt(t);}return e}function go(i,e){return i===e?`'${i}'`:`'${i}-${e}'`}function _o(i,e){switch(i.kind){case \"numeric\":return `R${i.r}`;case \"unspecified\":return \"?\";case \"wildcard\":return \"*\";case \"pair\":return \"pair\";case \"positional\":return `${i.position}:R${i.r}`;default:return \"?\"}}function Sr(i){return i.ratio===void 0?i.target:`${i.target}:${i.ratio}`}function vn(i){return new _n(i).run()}var _n=class{constructor(e){this.chainIdMap=new Map;this.mol=e;}run(){let e=this.mol.chains.slice().sort((m,p)=>m.polymerType!==p.polymerType?m.polymerType<p.polymerType?-1:1:xo(m.id,p.id)),t={},n=[];for(let m of e){let p=Er(m.polymerType);t[p]=(t[p]??0)+1;let h=`${p}${t[p]}`;this.chainIdMap.set(m.id,h),n.push(m);}let o=new Map;for(let m of this.mol.atoms){let p=this.chainIdMap.get(m.bio.chainId)??m.bio.chainId;o.set(m.id,{...m,bio:{...m.bio,chainId:p}});}for(let m of this.mol.atoms){if(m.branchAtom===void 0)continue;let p=o.get(m.id),h=o.get(m.branchAtom.id);p!==void 0&&h!==void 0&&(p.branchAtom=h);}let r=this.mol.bonds.map(m=>({...m,a1:o.get(m.a1.id)??m.a1,a2:o.get(m.a2.id)??m.a2})),s=new Map;for(let m of r)s.set(m.id,m);let a=n.map(m=>{let p=this.chainIdMap.get(m.id)??m.id,h=[];for(let f of m.backboneAtoms){let _=o.get(f.id);_!==void 0&&h.push(_);}let y=[];for(let f of m.bonds){let _=s.get(f.id);_!==void 0&&y.push(_);}return {id:p,polymerType:m.polymerType,backboneAtoms:h,bonds:y,...m.annotation!==void 0&&m.annotation.length>0?{annotation:m.annotation}:{}}}),d=new Map;for(let m of a)d.set(m.id,m);r.sort((m,p)=>{let h=vo(m.kind),y=vo(p.kind);if(h&&!y)return 1;if(!h&&y)return -1;if(!h&&!y)return m.id-p.id;let f=m.a1.bio.chainId,_=p.a1.bio.chainId;if(f!==_)return f<_?-1:1;let b=m.a2.bio.chainId,A=p.a2.bio.chainId;if(b!==A)return b<A?-1:1;let w=le(m.a1,d.get(m.a1.bio.chainId)),k=le(p.a1,d.get(p.a1.bio.chainId));if(w!==k)return w-k;let C=le(m.a2,d.get(m.a2.bio.chainId)),I=le(p.a2,d.get(p.a2.bio.chainId));return C-I});let l=this.renumberGroups(this.mol.groups),u=this.rekeyAnnotations(this.mol.annotations);return {atoms:this.mol.atoms.map(m=>o.get(m.id)),bonds:r,chains:a,groups:l,annotations:u}}renumberGroups(e){let t=[],n=[];for(let r of e)r.kind===\"bracket\"?t.push(this.rekeyBracket(r)):n.push(r);n.sort((r,s)=>xo(r.id,s.id));let o={G:0};return n.map(r=>{o.G+=1;let s=`G${o.G}`;return {...r,id:s,members:r.members.map(a=>this.rekeyMember(a))}}).concat(t)}rekeyBracket(e){return e}rekeyMember(e){let t=this.chainIdMap.get(e.target);return t===void 0?e:e.ratio===void 0?{target:t}:{target:t,ratio:e.ratio}}rekeyAnnotations(e){let t=new Map;for(let[n,o]of e.perPolymer){let r=this.chainIdMap.get(n)??n;Object.keys(o).length!==0&&t.set(r,o);}return {perPolymer:t,version:e.version}}};function Er(i){switch(i){case \"PEPTIDE\":return \"PEPTIDE\";case \"RNA\":return \"RNA\";case \"CHEM\":return \"CHEM\";case \"BLOB\":return \"BLOB\";default:return \"BLOB\"}}function vo(i){return i===\"cross-polymer\"||i===\"hbond\"}function xo(i,e){let t=/^([A-Z]+)([0-9]+)$/.exec(i),n=/^([A-Z]+)([0-9]+)$/.exec(e);return t===null||n===null?i<e?-1:i>e?1:0:t[1]!==n[1]?t[1]<n[1]?-1:1:parseInt(t[2],10)-parseInt(n[2],10)}function wo(i){let e=Le(i),t=new Map;for(let a of i.atoms){let d=e.get(a.id);if(d===void 0||d===a.bio.continuousId){t.set(a.id,a);continue}t.set(a.id,{...a,bio:{...a.bio,continuousId:d}});}for(let a of i.atoms){if(a.branchAtom===void 0)continue;let d=t.get(a.id),l=t.get(a.branchAtom.id);d===void 0||l===void 0||(d.branchAtom=l);}let n=i.bonds.map(a=>{let d=t.get(a.a1.id),l=t.get(a.a2.id);return d===void 0||l===void 0||d===a.a1&&l===a.a2?a:{...a,a1:d,a2:l}}),o=new Map;for(let a of n)o.set(a.id,a);let r=i.chains.map(a=>{let d=[];for(let u of a.backboneAtoms){let c=t.get(u.id);d.push(c??u);}let l=[];for(let u of a.bonds){let c=o.get(u.id);l.push(c??u);}return {id:a.id,polymerType:a.polymerType,backboneAtoms:d,bonds:l,...a.annotation!==void 0?{annotation:a.annotation}:{}}});return {atoms:i.atoms.map(a=>t.get(a.id)??a),bonds:n,chains:r,groups:i.groups,annotations:i.annotations}}function xn(i,e){let n=ot(i,e??null,{mode:\"lenient\",resolveMonomers:false}),o=Cr(n.mol),r=wo(o.mol),s=new Map;for(let l of r.atoms)s.set(l.id,l.bio.continuousId);let a=new Map;for(let[l,u]of o.survivorByOldContinuousId){let c=s.get(u);c!==void 0&&a.set(l,c);}let d=Pe(r,{version:\"V2.0\"});return {srcHelm:i,resHelm:d,monomerMap:a}}function Cr(i){let e=new Map;for(let c of i.atoms)e.set(c.bio.continuousId,c.id);let t=new Set;for(let c of i.atoms)c.symbol===\"*\"&&t.add(c.id);if(t.size===0)return {mol:i,survivorByOldContinuousId:e};let n=new Map;for(let c of i.atoms)n.set(c.id,[]);for(let c of i.bonds)n.get(c.a1.id)?.push(c),n.get(c.a2.id)?.push(c);for(let c of t){let m=n.get(c)??[];if(m.some(y=>y.kind===\"cross-polymer\"||y.kind===\"hbond\"))throw new j(\"gap-at-complex-junction\",`Gap atom ${c} participates in a cross-polymer/hbond bond`,{atomId:c});let h=m.filter(y=>y.kind===\"backbone\");if(h.length>2)throw new j(\"gap-at-complex-junction\",`Gap atom ${c} has ${h.length} backbone bonds (max 2 allowed)`,{atomId:c,bondCount:h.length})}let o=i.atoms.filter(c=>!t.has(c.id)),r=[],s=[];for(let c of i.chains){let m=c.backboneAtoms.filter(y=>!t.has(y.id)),p=(()=>{let y=0;for(let f of i.bonds)f.id>y&&(y=f.id);return y+1})(),h=[];for(let y of c.bonds)t.has(y.a1.id)||t.has(y.a2.id)||h.push(y);for(let y=0;y<c.backboneAtoms.length;y++){let f=c.backboneAtoms[y];if(!t.has(f.id))continue;let _=Lr(c.backboneAtoms,y,t),b=Br(c.backboneAtoms,y,t);if(_===null||b===null)continue;let A={id:p++,a1:_,a2:b,kind:\"backbone\",r1:{kind:\"numeric\",r:2},r2:{kind:\"numeric\",r:1}};h.find(k=>k.a1.id===_.id&&k.a2.id===b.id)===void 0&&h.push(A);}for(let y of h)s.push(y);r.push({id:c.id,polymerType:c.polymerType,backboneAtoms:m,bonds:h,...c.annotation!==void 0?{annotation:c.annotation}:{}});}for(let c of i.bonds)c.kind!==\"cross-polymer\"&&c.kind!==\"hbond\"||t.has(c.a1.id)||t.has(c.a2.id)||s.push(c);let a=new Map;for(let c of r){let m=0;for(let p of c.backboneAtoms)m+=1,a.set(p.id,{...p,bio:{...p.bio,positionInChain:m}});}for(let c of o)a.has(c.id)||a.set(c.id,c);let d=r.map(c=>{let m=c.backboneAtoms.map(h=>a.get(h.id)),p=c.bonds.map(h=>({...h,a1:a.get(h.a1.id),a2:a.get(h.a2.id)}));return {id:c.id,polymerType:c.polymerType,backboneAtoms:m,bonds:p,...c.annotation!==void 0?{annotation:c.annotation}:{}}}),l=s.map(c=>({...c,a1:a.get(c.a1.id),a2:a.get(c.a2.id)}));return {mol:{atoms:o.map(c=>a.get(c.id)),bonds:l,chains:d,groups:i.groups,annotations:i.annotations},survivorByOldContinuousId:e}}function Lr(i,e,t){for(let n=e-1;n>=0;n--){let o=i[n];if(o!==void 0&&!t.has(o.id))return o}return null}function Br(i,e,t){for(let n=e+1;n<i.length;n++){let o=i[n];if(o!==void 0&&!t.has(o.id))return o}return null}function wn(i,e,t){let n=t?.mode??\"lenient\",o=[];for(let s of Rr)o.push(...s(i,e));let r=n===\"pedantic\"?o.map(s=>s.severity===\"warning\"?{...s,severity:\"error\"}:s):o;if(n===\"strict\"||n===\"pedantic\"){let s=r.filter(a=>a.severity===\"error\");if(s.length>0)throw new Ze(s)}return r}var Rr=[Ir,Pr,Hr,$r,Dr,Nr,Fr,Gr];function Ir(i,e){let t=[],n=new Set(i.chains.map(s=>s.id));for(let s of i.bonds)s.kind!==\"cross-polymer\"&&s.kind!==\"hbond\"||(n.has(s.a1.bio.chainId)||t.push({severity:\"error\",code:\"unknown-chain-reference\",message:`Connection references unknown chain '${s.a1.bio.chainId}'`,context:{chainId:s.a1.bio.chainId,bondId:s.id}}),n.has(s.a2.bio.chainId)||t.push({severity:\"error\",code:\"unknown-chain-reference\",message:`Connection references unknown chain '${s.a2.bio.chainId}'`,context:{chainId:s.a2.bio.chainId,bondId:s.id}}));for(let s of i.chains)for(let a of i.bonds){if(a.kind!==\"cross-polymer\"&&a.kind!==\"hbond\")continue;let d=0;for(let l of s.backboneAtoms)d+=l.branchAtom!==void 0?2:1;for(let l of [a.a1,a.a2]){if(l.bio.chainId!==s.id)continue;let u=le(l,s);(u<1||u>d)&&t.push({severity:\"error\",code:\"position-out-of-range\",message:`Position ${u} out of range for chain '${s.id}' (length ${d})`,context:{chainId:s.id,atomId:l.id,found:u}});}}let o=new Set;for(let s of i.groups)s.kind!==\"bracket\"&&o.add(s.id);for(let s of i.groups)if(s.kind!==\"bracket\")for(let a of s.members)n.has(a.target)||o.has(a.target)||t.push({severity:\"error\",code:\"unknown-group-reference\",message:`Group '${s.id}' references unknown id '${a.target}'`,context:{found:a.target}});let r=new Map;for(let s of i.groups){if(s.kind===\"bracket\")continue;let a=[];for(let d of s.members)o.has(d.target)&&a.push(d.target);r.set(s.id,a);}for(let s of r.keys()){let a=new Set,d=[s];for(;d.length>0;){let l=d.pop();if(a.has(l))continue;a.add(l);let u=r.get(l)??[];for(let c of u)c===s?t.push({severity:\"error\",code:\"group-cycle\",message:`Group cycle detected involving '${s}'`,context:{found:s}}):a.has(c)||d.push(c);}}return t}function Pr(i,e){let t=[];if(e===null)return t;let n=new Map;for(let o of i.chains)n.set(o.id,o.polymerType);for(let o of i.atoms){let r=n.get(o.bio.chainId);if(r===void 0)continue;let s=o.monomer,a=s?.meta;if(s===null||a?.missing===true){t.push({severity:\"warning\",code:\"unresolved-monomer\",message:`Monomer '${o.symbol}' not found in library for ${r}`,context:{chainId:o.bio.chainId,atomId:o.id,found:o.symbol}});continue}a?.ambiguous!==true&&s.smiles!==void 0&&s.smiles.length>0&&(s.rgroups.length===0?t.push({severity:\"warning\",code:\"inline-smiles-without-r-groups\",message:`Inline-SMILES monomer '${s.symbol}' has no R-groups`,context:{atomId:o.id,found:s.symbol}}):s.rgroups.length>4&&t.push({severity:\"warning\",code:\"inline-smiles-too-many-rs\",message:`Inline-SMILES monomer '${s.symbol}' has ${s.rgroups.length} R-groups (max 4 expected)`,context:{atomId:o.id,found:s.rgroups.length}}));}for(let o of i.atoms){let r=n.get(o.bio.chainId);if(!(r===void 0||e.getMonomer(r,o.symbol)!==null)){for(let a of e.getMonomerSymbolsByType(r))if(a!==o.symbol&&a.toLowerCase()===o.symbol.toLowerCase()){t.push({severity:\"info\",code:\"case-mismatch\",message:`Symbol '${o.symbol}' differs from library entry '${a}' only in case`,context:{atomId:o.id,found:o.symbol,expected:a}});break}}}return t}function Hr(i,e){let t=[],n=new Map;for(let o of i.bonds)for(let[r,s]of [[o.a1,o.r1],[o.a2,o.r2]]){if(s.kind!==\"numeric\")continue;let a=n.get(r.id)??new Set;a.has(s.r)&&t.push({severity:\"error\",code:\"rgroup-already-bonded\",message:`R-group R${s.r} on atom ${r.id} already bonded`,context:{atomId:r.id,bondId:o.id,found:s.r}}),a.add(s.r),n.set(r.id,a);}for(let o of i.bonds){for(let[r,s]of [[o.a1,o.r1],[o.a2,o.r2]]){if(s.kind!==\"numeric\"||r.monomer===null)continue;let a=r.monomer.rs;(s.r<1||s.r>a)&&t.push({severity:\"error\",code:\"rgroup-not-on-monomer\",message:`R-group R${s.r} not defined on monomer '${r.symbol}' (rs=${a})`,context:{atomId:r.id,bondId:o.id,found:s.r,expected:`R1..R${a}`}});}o.kind===\"backbone\"&&o.r1.kind===\"numeric\"&&o.r2.kind===\"numeric\"&&(o.r1.r===2&&o.r2.r===1||t.push({severity:\"warning\",code:\"backbone-rgroup-misaligned\",message:`Backbone bond uses R${o.r1.r}->R${o.r2.r} (expected R2->R1)`,context:{bondId:o.id,found:`R${o.r1.r}->R${o.r2.r}`}})),o.kind===\"branch\"&&o.r1.kind===\"numeric\"&&o.r1.r!==3&&t.push({severity:\"warning\",code:\"branch-rgroup-misaligned\",message:`Branch bond uses R${o.r1.r} (expected R3 on parent)`,context:{bondId:o.id,found:`R${o.r1.r}`}});}for(let o of i.atoms){if(o.monomer===null)continue;let s=n.get(o.id)?.size??0;if(o.monomer.rs>s){let a=o.monomer.rs-s;a>0&&o.monomer.rs>0&&t.push({severity:\"info\",code:\"unmatched-r-group\",message:`Monomer '${o.symbol}' on atom ${o.id} has ${a} unused R-group(s); default cap applied`,context:{atomId:o.id,found:a}});}}return t}function $r(i,e){let t=[];for(let n of i.chains){if(n.polymerType===\"CHEM\"&&n.backboneAtoms.length>1&&t.push({severity:\"error\",code:\"chem-multiple-monomers\",message:`CHEM polymer '${n.id}' has ${n.backboneAtoms.length} monomers (expected 1)`,context:{chainId:n.id,found:n.backboneAtoms.length}}),n.polymerType===\"BLOB\")for(let o of n.backboneAtoms)o.bio.blobtype===void 0&&o.symbol!==\"Bead\"&&o.symbol!==\"Group\"&&t.push({severity:\"error\",code:\"blob-non-blob-symbol\",message:`BLOB '${n.id}' contains non-blob symbol '${o.symbol}'`,context:{chainId:n.id,atomId:o.id,found:o.symbol}});if(n.polymerType===\"RNA\"){let o=false;for(let r=0;r<n.backboneAtoms.length;r++){let s=n.backboneAtoms[r];s.biotype===g.BASE&&!o&&t.push({severity:\"error\",code:\"rna-bare-base\",message:`Bare base '${s.symbol}' without parent sugar in '${n.id}'`,context:{chainId:n.id,atomId:s.id}}),s.biotype===g.LINKER&&(n.backboneAtoms.slice(0,r).some(d=>d.biotype===g.SUGAR)||t.push({severity:\"warning\",code:\"rna-bare-linker\",message:`Bare linker '${s.symbol}' before any sugar in '${n.id}'`,context:{chainId:n.id,atomId:s.id}})),o=s.biotype===g.SUGAR||s.biotype===g.LINKER;}}}return t}function Dr(i,e){let t=[],n=new Map;for(let r of i.chains)n.set(r.id,r.polymerType);let o=new Map;for(let r of i.bonds){if(r.kind!==\"hbond\")continue;o.set(r.a1.id,(o.get(r.a1.id)??0)+1),o.set(r.a2.id,(o.get(r.a2.id)??0)+1);let s=n.get(r.a1.bio.chainId),a=n.get(r.a2.bio.chainId);(s!==\"RNA\"||a!==\"RNA\")&&t.push({severity:\"error\",code:\"pair-non-rna\",message:`Hydrogen-bond connects non-RNA chains (${s}/${a})`,context:{bondId:r.id}}),(r.a1.biotype!==g.BASE||r.a2.biotype!==g.BASE)&&t.push({severity:\"warning\",code:\"pair-position-not-base\",message:\"Hydrogen-bond endpoints are not both bases\",context:{bondId:r.id,found:`${r.a1.biotype}/${r.a2.biotype}`}}),Or(r.a1.symbol,r.a2.symbol)||t.push({severity:\"warning\",code:\"pair-non-canonical\",message:`Non-canonical pair ${r.a1.symbol}-${r.a2.symbol}`,context:{bondId:r.id,found:`${r.a1.symbol}-${r.a2.symbol}`}});}for(let[r,s]of o)s>1&&t.push({severity:\"warning\",code:\"pair-already-paired\",message:`Base atom ${r} participates in ${s} pair bonds`,context:{atomId:r,found:s}});return t}function Or(i,e){let t=i.toUpperCase(),n=e.toUpperCase();return new Set([\"A:T\",\"T:A\",\"A:U\",\"U:A\",\"G:C\",\"C:G\"]).has(`${t}:${n}`)}function Nr(i,e){let t=[];for(let n of i.atoms){let o=n.bio.ambiguity;if(o!==void 0){if(n.bio.ambiguityKind===\"and\"){let r=ko(o,\"+\");for(let s of r)s.ratio!==void 0&&s.ratio<0&&t.push({severity:\"error\",code:\"ratio-and-negative\",message:`AND ratio for '${s.symbol}' is negative (${s.ratio})`,context:{atomId:n.id,found:s.ratio}});}else if(n.bio.ambiguityKind===\"or\"){let r=ko(o,\",\"),s=0,a=false;for(let d of r)typeof d.ratio==\"number\"&&(s+=d.ratio,a=true);a&&Math.abs(s-1)>.001&&Math.abs(s-100)>.5&&t.push({severity:\"info\",code:\"ratio-doesnt-sum-to-1\",message:`OR ratios sum to ${s} (expected 1.0 or 100)`,context:{atomId:n.id,found:s}});}}}return t}function ko(i,e){let t=i.trim();t.startsWith(\"(\")&&t.endsWith(\")\")&&(t=t.slice(1,-1));let n=t.split(e),o=[];for(let r of n){let s=r.trim();if(s.length===0)continue;let a=s.indexOf(\":\");if(a<0){o.push({symbol:s});continue}let d=s.slice(0,a),l=s.slice(a+1),u=parseFloat(l);Number.isFinite(u)?o.push({symbol:d,ratio:u}):o.push({symbol:d});}return o}function Fr(i,e){let t=[],n=new Set(i.chains.map(o=>o.id));for(let o of i.annotations.perPolymer.keys())n.has(o)||t.push({severity:\"warning\",code:\"annotation-unknown-polymer\",message:`Annotation references unknown polymer '${o}'`,context:{found:o}});return t}function Gr(i,e){let t=[];for(let o of i.chains)o.backboneAtoms.length>1e4&&t.push({severity:\"info\",code:\"polymer-too-long\",message:`Polymer '${o.id}' has ${o.backboneAtoms.length} atoms (> 10000); renderer may switch to rows layout`,context:{chainId:o.id,found:o.backboneAtoms.length}});let n=0;for(let o of i.bonds)(o.kind===\"cross-polymer\"||o.kind===\"hbond\")&&(n+=1);n>1e3&&t.push({severity:\"info\",code:\"connection-count-high\",message:`${n} cross-polymer/hbond connections (> 1000); rendering may be slow`,context:{found:n}});for(let o of i.groups)o.kind===\"bracket\"&&o.repeat!==void 0&&o.repeat.max>1e4&&t.push({severity:\"warning\",code:\"bracket-repeat-too-large\",message:`Bracket repeat upper bound ${o.repeat.max} > 10000`,context:{found:o.repeat.max}});return t}function Ao(i){let e=[];for(let s of i.chains){let a=jr(s.polymerType),d=s.backboneAtoms,l=[],u=[],c=[];for(let m of s.bonds)m.kind===\"backbone\"&&c.push(m);for(let m of d){if(m.biotype!==g.SUGAR){l.push(null),u.push(null);continue}let p=null,h=null;for(let y of s.bonds){if(y.kind!==\"branch\")continue;let f=y.a1.id===m.id?y.a2:y.a2.id===m.id?y.a1:null;if(f!==null&&f.biotype===g.BASE){p=f,h=y;break}}l.push(p),u.push(h);}e.push({id:s.id,polymerType:a,backbone:d,bases:l,backboneBonds:c,baseBonds:u,...s.strandType!==void 0?{strandType:s.strandType}:{}});}let t=zr(e,i),n=new Set,o=t.map(s=>{let a=s[0].id;for(let d=2;n.has(a);d++)a=`${s[0].id}#${d}`;return n.add(a),a}),r=new Map;return t.forEach((s,a)=>{for(let d of s)for(let l of d.backbone)r.set(l.id,o[a]),l.branchAtom!==void 0&&r.set(l.branchAtom.id,o[a]);}),t.map((s,a)=>Vr(s,o[a],i,r))}function Vr(i,e,t,n){let o=[],r=[],s=[],a=[];for(let l of i)o.push(...l.backbone),r.push(...l.bases),s.push(...l.backboneBonds),a.push(...l.baseBonds);let d=i.find(l=>l.strandType!==void 0)?.strandType;return {id:e,polymerType:Ur(i),segments:i.map(l=>l.id),backbone:o,bases:r,backboneBonds:s,baseBonds:a,isCyclic:qr(t,e,o,n),...d!==void 0?{strandType:d}:{}}}function Ur(i){let e=new Map;for(let o of i)e.set(o.polymerType,(e.get(o.polymerType)??0)+o.backbone.length);let t=i[0].polymerType,n=-1;for(let o of i){let r=e.get(o.polymerType);r>n&&(t=o.polymerType,n=r);}return t}function zr(i,e){let t=new Map;i.forEach((l,u)=>{for(let c of l.backbone)t.set(c.id,u);});let n=new Map,o=new Map;for(let l of e.bonds){if(l.kind!==\"cross-polymer\")continue;let u=Kr(l,i,t);if(u===null)continue;let{tail:c,head:m}=u;c!==m&&(n.has(c)||o.has(m)||Wr(n,m,c)||(n.set(c,m),o.set(m,c)));}let r=[],s=new Set;for(let l=0;l<i.length;l++){if(s.has(l)||o.has(l))continue;let u=[],c=l;for(;c!==void 0&&!s.has(c);)s.add(c),u.push(i[c]),c=n.get(c);r.push(u);}for(let l=0;l<i.length;l++)s.has(l)||(s.add(l),r.push([i[l]]));let a=new Map;i.forEach((l,u)=>a.set(l,u));let d=l=>Math.min(...l.map(u=>a.get(u)));return r.sort((l,u)=>d(l)-d(u))}function Kr(i,e,t){let n=(r,s)=>r.kind===\"numeric\"&&r.r===s,o=[[i.a1,i.r1,i.a2,i.r2],[i.a2,i.r2,i.a1,i.r1]];for(let[r,s,a,d]of o){if(!n(s,2)||!n(d,1))continue;let l=t.get(r.id),u=t.get(a.id);if(l===void 0||u===void 0)continue;let c=e[l],m=e[u];if(c.backbone[c.backbone.length-1].id===r.id&&m.backbone[0].id===a.id)return {tail:l,head:u}}return null}function Wr(i,e,t){let n=new Set,o=e;for(;o!==void 0&&!n.has(o);){if(o===t)return true;n.add(o),o=i.get(o);}return false}function jr(i){switch(i){case x.PEPTIDE:return \"PEPTIDE\";case x.RNA:return \"RNA\";case x.CHEM:return \"CHEM\";case x.BLOB:return \"BLOB\";default:return \"BLOB\"}}function qr(i,e,t,n){if(t.length<2)return false;let o=t[0],r=t[t.length-1];for(let s of i.bonds){if(s.kind===\"backbone\"||s.kind===\"branch\")continue;let a=n.get(s.a1.id),d=n.get(s.a2.id);if(a!==e||d!==e||!(s.a1.id===r.id&&s.a2.id===o.id||s.a2.id===r.id&&s.a1.id===o.id))continue;let u=s.a1.id===o.id?s.r1:s.r2,c=s.a1.id===r.id?s.r1:s.r2,m=u.kind===\"numeric\"&&u.r===1,p=c.kind===\"numeric\"&&c.r===2;if(m&&p)return true}return false}var kn=44.800000000000004,Mo=1.5*28,Tt=1.5*28/kn,An=1.5*28/kn,Mn=1.5*28/kn;function Ae(i,e){let t=e?.bondLength??28,n=e?.origin??{x:0,y:0},o=1.6*t,r=new Map;for(let s=0;s<i.backbone.length;s++){let a=i.backbone[s];r.set(a.id,{x:n.x+s*o,y:n.y});}return r}var Yr=Math.PI/180;function St(i,e){let t=i.backbone.length;if(t<=2){let l={};return e?.bondLength!==void 0&&(l.bondLength=e.bondLength),e?.origin!==void 0&&(l.origin=e.origin),Ae(i,l)}let n=e?.bondLength??28,o=e?.origin??{x:0,y:0},r=e?.startDegrees??-90,a=1.6*n/(2*Math.sin(Math.PI/t)),d=new Map;for(let l=0;l<t;l++){let u=i.backbone[l],m=(r+l*360/t)*Yr;d.set(u.id,{x:o.x+a*Math.cos(m),y:o.y+a*Math.sin(m)});}return d}var Xr=10,Jr=1.5/1.6;function To(i,e){let t=e?.bondLength??28,n=e?.origin??{x:0,y:0},o=Math.max(1,e?.perRow??Xr),r=e?.rowSpacing??Jr,s=1.6*t,a=r*s,d=new Map;for(let l=0;l<i.backbone.length;l++){let u=i.backbone[l],c=Math.floor(l/o),m=l%o,p=c%2===0?n.x+m*s:n.x+(o-1-m)*s,h=n.y+c*a;d.set(u.id,{x:p,y:h});}return d}function So(i,e){let t=new Map;for(let r=0;r<i.backbone.length;r++)t.set(i.backbone[r].id,r);let n=i.backbone.length-1,o=[];for(let r of e.bonds){if(r.kind===\"backbone\"||r.kind===\"branch\")continue;let s=t.get(r.a1.id),a=t.get(r.a2.id);if(s===void 0||a===void 0)continue;let d=Math.min(s,a),l=Math.max(s,a);l-d<2||d===0&&l===n&&Zr(r)||o.push({lo:d,hi:l});}return o}function Zr(i){let t=[i.r1,i.r2].filter(n=>n.kind===\"numeric\").map(n=>n.r);return t.length===2&&t.includes(1)&&t.includes(2)}function Eo(i,e){return e===null?false:So(i,e).length>0}function Tn(i,e,t){if(e===null)return Ae(i,t);let n=t?.bondLength??28,o=t?.origin??{x:0,y:0},r=1.6*n,s=So(i,e);if(s.length===0)return Ae(i,t);let a=s[0].lo,d=s[0].hi;for(let E of s)E.lo<a&&(a=E.lo),E.hi>d&&(d=E.hi);let l=i.backbone.slice(a,d+1),u=l.length,c=r/(2*Math.sin(Math.PI/u)),m={id:i.id,polymerType:i.polymerType,segments:i.segments,backbone:l,bases:new Array(u).fill(null),baseBonds:new Array(u).fill(null)},p=a,h={x:o.x+p*r+c,y:o.y},y=St(m,{bondLength:n,origin:h,startDegrees:180}),f=new Map;for(let E=0;E<a;E++){let H=i.backbone[E];f.set(H.id,{x:o.x+E*r,y:o.y});}for(let[E,H]of y)f.set(E,H);let _=l[u-1],b=y.get(_.id)??h,A=b.x-h.x,w=b.y-h.y,k=Math.hypot(A,w);k<1e-6&&(A=0,w=1,k=1);let C=A/k,I=w/k,T={x:b.x+C*r,y:b.y+I*r},B=Math.sign(b.x-h.x);if(B===0&&u>=2){let E=y.get(l[u-2].id);E!==void 0&&(B=Math.sign(b.x-E.x));}B===0&&(B=1);for(let E=d+1;E<i.backbone.length;E++){let H=i.backbone[E],_e=E-(d+1);f.set(H.id,_e===0?T:{x:T.x+B*r*_e,y:T.y});}return f}function Lo(i){let e=new Map,t=new Map;for(let n=0;n<i.backbone.length;n++){e.set(i.backbone[n].id,n);let o=i.bases[n];o!=null&&t.set(o.id,n);}return {sugarToIdx:e,baseToIdx:t}}function Co(i,e,t){let n=e.get(i);if(n!==void 0)return n;let o=t.get(i);return o!==void 0?o:null}function Bo(i,e,t){let n=i.kind===\"hbond\",o=i.kind===\"cross-polymer\"&&typeof i.r1==\"object\"&&i.r1!==null&&i.r1.kind===\"pair\"&&typeof i.r2==\"object\"&&i.r2!==null&&i.r2.kind===\"pair\";if(!n&&!o)return null;let r=Co(i.a1.id,e,t),s=Co(i.a2.id,e,t);return r===null||s===null||r===s?null:{lo:Math.min(r,s),hi:Math.max(r,s)}}function Ro(i,e){if(i.polymerType!==\"RNA\"||i.backbone.length===0)return false;let{sugarToIdx:t,baseToIdx:n}=Lo(i);for(let o of e.bonds)if(Bo(o,t,n)!==null)return true;return false}function Qr(i,e){let t=i.backbone.length,n=new Int32Array(t).fill(-1);if(t===0)return n;let{sugarToIdx:o,baseToIdx:r}=Lo(i),s=[];for(let d of e.bonds){let l=Bo(d,o,r);l!==null&&s.push([l.lo,l.hi]);}s.sort((d,l)=>d[0]-l[0]||l[1]-d[1]);let a=[];for(let d of s){let[l,u]=d,c=false;for(let[m,p]of a){let h=u<m||l>p,y=l>m&&u<p||l<m&&u>p;if(!h&&!y){c=true;break}}c||n[l]!==-1||n[u]!==-1||(n[l]=u,n[u]=l,a.push(d));}return n}function es(i){return e(0,i.length-1,null);function e(t,n,o){let r=[],s=-1,a=t;for(;a<=n;){let d=i[a];if(d>a&&d<=n){s!==-1&&(r.push({kind:\"unpaired\",from:s,to:a-1}),s=-1);let l=1;for(;a+2*l<d-2*l&&i[a+2*l]===d-2*l&&i[a+2*l-1]===-1&&i[d-2*l+1]===-1;)l+=1;let u=a+2*(l-1),c=d-2*(l-1),m=[u,c],p=e(u+1,c-1,m);r.push({kind:\"stem\",fromIdx:a,toIdx:d,numPairs:l,child:p}),a=d+1;}else s===-1&&(s=a),a+=1;}return s!==-1&&r.push({kind:\"unpaired\",from:s,to:n}),{kind:\"loop\",nodes:r,closingPair:o}}}function Et(i){let e=Math.hypot(i.x,i.y);return e===0?{x:1,y:0}:{x:i.x/e,y:i.y/e}}function ts(i){return {x:-i.y,y:i.x}}function Sn(i,e,t){return {x:i.x+e*Math.cos(t),y:i.y+e*Math.sin(t)}}function ns(i,e,t,n){let o=t+n+1;if(o<=0)return Math.max(i/2+1,e);let r=n+1,s=o*e,a=Math.max(s/(2*Math.PI),i/2+1);for(let d=0;d<64;d++){let l=i/(2*a),c=2*Math.asin(Math.min(.9999,Math.max(-0.9999,l))),m=(2*Math.PI-r*c)*a-s,p=l,h=Math.sqrt(Math.max(1e-12,1-p*p)),f=2*(-i/(2*a*a)/h),_=2*Math.PI-r*c-r*a*f;if(!Number.isFinite(_)||Math.abs(_)<1e-12)break;let b=m/_,A=a-b;if(!Number.isFinite(A)||A<i/2+.001){a=i/2+.001;break}if(a=A,Math.abs(b)<1e-9)break}return Math.max(a,i/2+.001)}function Ct(i,e,t,n,o){let r=o.chain.bases[i];r!=null&&o.out.set(r.id,{x:e.x+n*t.x,y:e.y+n*t.y});}function Io(i,e,t){let{chain:n,step:o,rail:r,baseInwardHang:s,out:a}=t,d=2*i.numPairs-1,l={x:e.normal.x,y:e.normal.y},u={x:-e.normal.x,y:-e.normal.y};for(let m=0;m<d;m++){let p=n.backbone[i.fromIdx+m],h=n.backbone[i.toIdx-m],y=m*o,f={x:e.origin.x+y*e.tangent.x,y:e.origin.y+y*e.tangent.y},_={x:e.origin.x+y*e.tangent.x+r*e.normal.x,y:e.origin.y+y*e.tangent.y+r*e.normal.y};a.set(p.id,f),a.set(h.id,_),Ct(i.fromIdx+m,f,l,s,t),Ct(i.toIdx-m,_,u,s,t);}let c=(d-1)*o;return {origin:{x:e.origin.x+c*e.tangent.x,y:e.origin.y+c*e.tangent.y},tangent:e.tangent,normal:e.normal}}function Po(i,e,t,n){if(i.closingPair===null)return;let{step:o,rail:r,out:s}=t,a=0,d=0;for(let C of i.nodes)C.kind===\"unpaired\"?a+=C.to-C.from+1:d+=1;let l=ns(r,o,a,d),u=s.get(t.chain.backbone[i.closingPair[0]].id),c=s.get(t.chain.backbone[i.closingPair[1]].id),m={x:(u.x+c.x)/2,y:(u.y+c.y)/2},p=Math.sqrt(Math.max(0,l*l-r/2*(r/2))),h={x:m.x+p*e.tangent.x,y:m.y+p*e.tangent.y},y=Math.atan2(u.y-h.y,u.x-h.x),_=Math.atan2(c.y-h.y,c.x-h.x)-y;for(;_>Math.PI;)_-=2*Math.PI;for(;_<=-Math.PI;)_+=2*Math.PI;let b=_>0?-1:1,A=2*Math.asin(Math.min(.9999,Math.max(-0.9999,r/(2*l)))),w=o/l,k=y;for(let C of i.nodes)if(C.kind===\"unpaired\")for(let I=C.from;I<=C.to;I++){k=k+b*w;let T=Sn(h,l,k);s.set(t.chain.backbone[I].id,T);let B=Et({x:T.x-h.x,y:T.y-h.y});Ct(I,T,B,t.step,t);}else {k=k+b*w;let I=Sn(h,l,k);k=k+b*A;let T=Sn(h,l,k);s.set(t.chain.backbone[C.fromIdx].id,I),s.set(t.chain.backbone[C.toIdx].id,T);let B=Et({x:(I.x+T.x)/2-h.x,y:(I.y+T.y)/2-h.y}),E=Et({x:T.x-I.x,y:T.y-I.y}),_e=Io(C,{origin:I,tangent:B,normal:E},t);Po(C.child,_e,t);}}function os(i,e,t){let{step:n,rail:o,out:r}=t,s={x:e.origin.x,y:e.origin.y},a={x:e.tangent.x,y:e.tangent.y},d={x:-e.normal.x,y:-e.normal.y};for(let l of i.nodes)if(l.kind===\"unpaired\")for(let u=l.from;u<=l.to;u++){let c={x:s.x,y:s.y};r.set(t.chain.backbone[u].id,c),Ct(u,c,{x:e.normal.x,y:e.normal.y},t.step,t),s={x:s.x+n*a.x,y:s.y+n*a.y};}else {let u={origin:{x:s.x,y:s.y},tangent:d,normal:a},c=Io(l,u,t);Po(l.child,c,t),s={x:s.x+(o+n)*a.x,y:s.y+(o+n)*a.y};}}function Ho(i,e,t){let n=t?.bondLength??28,o=1.6*n,r=o/2,a=Mo*(n/28)+2*r,d=t?.origin??{x:0,y:0},l=Et(t?.rootDirection??{x:1,y:0}),u=ts(l),c=new Map;if(i.backbone.length===0)return c;let m=Qr(i,e),p=es(m);os(p,{origin:d,tangent:l,normal:u},{chain:i,step:o,rail:a,baseInwardHang:r,out:c});for(let f of i.backbone)c.has(f.id)||c.set(f.id,{x:d.x,y:d.y});return c}function $o(i,e,t){let n=t?.bondLength??28,o=1.6*n;for(let r=0;r<i.backbone.length;r++){let s=i.bases[r];if(s==null||e.has(s.id))continue;let a=i.backbone[r],d=e.get(a.id);if(d===void 0)continue;let l=is(i,r,e);e.set(s.id,{x:d.x+o*l.x,y:d.y+o*l.y});}return e}function is(i,e,t){let n=i.backbone[e],o=t.get(n.id);if(o===void 0)return {x:0,y:1};let r=e>0?i.backbone[e-1]:void 0,s=e<i.backbone.length-1?i.backbone[e+1]:void 0,a=r!==void 0?t.get(r.id):void 0,d=s!==void 0?t.get(s.id):void 0,l=y=>{let f=y.x-o.x,_=y.y-o.y,b=Math.hypot(f,_);return b<1e-9?null:{x:f/b,y:_/b}},u=a!==void 0?l(a):null,c=d!==void 0?l(d):null;if(u!==null&&c!==null){let y=u.x+c.x,f=u.y+c.y,_=Math.hypot(y,f);if(_>.05)return {x:-y/_,y:-f/_}}let m=c??u;if(m===null)return {x:0,y:1};let p={x:m.y,y:-m.x},h={x:-m.y,y:m.x};return p.y>=h.y?p:h}var rs=.72,ss=.45;function Go(i,e,t,n){let o=n?.bondLength??28,r=1.6*o,s=new Map,a=new Map;for(let f of i){let _=new Set;for(let b of f.backbone)_.add(b.id);for(let b of f.bases)b!==null&&_.add(b.id);a.set(f.id,{chain:f,atomIds:_});for(let b of _)s.set(b,f);}let d=new Map;for(let f of t.bonds)for(let _ of [f.a1,f.a2]){let b=d.get(_.id);b===void 0?d.set(_.id,[f]):b.push(f);}let l=new Set;if(i.length>0){let f=i.find(_=>_.strandType===\"ss\");l.add((f??i[0]).id);}let u=new Map;for(let f of i)u.set(f.id,f.id);let c=f=>{let _=f;for(;u.get(_)!==_;)_=u.get(_);let b=f;for(;u.get(b)!==_;){let A=u.get(b);u.set(b,_),b=A;}return _},m=(f,_)=>{u.set(c(f),c(_));},p=f=>{let _=c(f),b=0;for(let A of u.keys())c(A)===_&&(b+=1);return b},h=f=>{let _=s.get(f),b=_===void 0?void 0:c(_.id);return A=>{let w=s.get(A);return w!==void 0&&b!==void 0&&c(w.id)===b}},y=f=>{let _=c(f),b=new Set;for(let[A,w]of a)if(c(A)===_)for(let k of w.atomIds)b.add(k);return b};for(let f of t.bonds){if(f.kind===\"backbone\"||f.kind===\"branch\")continue;let _=s.get(f.a1.id),b=s.get(f.a2.id);if(_===void 0||b===void 0||_.id===b.id)continue;if(f.kind===\"hbond\"&&(_.strandType===\"as\"&&b.strandType===\"ss\"?l.add(b.id):b.strandType===\"as\"&&_.strandType===\"ss\"?l.add(_.id):_.strandType===\"as\"&&!l.has(b.id)?l.add(b.id):b.strandType===\"as\"&&!l.has(_.id)&&l.add(_.id)),f.kind===\"cross-polymer\"){let T=l.has(_.id)!==l.has(b.id)?l.has(_.id)?_:b:void 0,B=T===void 0?void 0:T===_?b:_;T!==void 0&&B!==void 0&&p(T.id)===1&&B.backbone.length>T.backbone.length&&(l.delete(T.id),l.add(B.id));}let A=b,w=f.a1,k=f.a2;if(l.has(b.id)&&!l.has(_.id))A=_,w=f.a2,k=f.a1;else if(!l.has(_.id)&&!l.has(b.id)){if(l.size>0){let T=Uo(En(l,a),e),B=a.get(_.id),E=Vo(B.atomIds,e);if(T!==null&&E!==null){let H=T+r*Tt-E;H>0&&He(B.atomIds,e,0,H);}}l.add(_.id),A=b,w=f.a1,k=f.a2;}else if(l.has(_.id)&&l.has(b.id)){if(c(_.id)===c(b.id)||f.kind!==\"cross-polymer\")continue;let T=y(_.id),B=y(b.id),E=T.size<=B.size,H=E?T:B,_e=E?B:T,Se=E?f.a1:f.a2,ee=E?f.a2:f.a1,nn=e.get(Se.id),on=e.get(ee.id);if(nn!==void 0&&on!==void 0){let Zn={fixedAtomId:ee.id,fixedPos:on,movingAtomId:Se.id},Qn=En(l,a),Ji=Fo(H,Zn,t,Qn,e,h(ee.id));No(H,nn,ee,Zn,Ji,d,Qn,r,e)||ds(H,nn,_e,on,r,e);}m(_.id,b.id);continue}let C=e.get(w.id),I=e.get(k.id);if(!(C===void 0||I===void 0)){if(f.kind===\"hbond\"){let T=a.get(A.id);as(T.atomIds,e),ls(T.atomIds,e);let B=e.get(k.id),E=C.x-B.x,H=C.y+r*An-B.y;H=Do(H,T,l,a,e,r*An),He(T.atomIds,e,E,H);}else {let T=a.get(A.id),B=En(l,a),E={fixedAtomId:w.id,fixedPos:C,movingAtomId:k.id},H=Fo(T.atomIds,E,t,B,e,h(w.id));if(A.isCyclic&&A.backbone.length>=3&&H.length===1){let Se=A.id===_.id?b:_,ee=a.get(Se.id);_s(T.atomIds,I,ee.atomIds,C,r,e),l.add(A.id),m(_.id,b.id);continue}if(!No(T.atomIds,I,w,E,H,d,B,r,e)){let Se=C.x-I.x,ee=C.y+r*Mn-I.y;ee=Do(ee,T,l,a,e,r*Mn),He(T.atomIds,e,Se,ee);}}l.add(A.id),m(_.id,b.id);}}return l}function Do(i,e,t,n,o,r){let s=Vo(e.atomIds,o);if(s===null)return i;let a=null;for(let u of t){let c=n.get(u);if(c===void 0)continue;let m=Uo(c.atomIds,o);m!==null&&(a===null||m>a)&&(a=m);}if(a===null)return i;let d=s+i,l=a+r;return d<l?l-s:i}function En(i,e){let t=new Set;for(let n of i){let o=e.get(n);if(o!==void 0)for(let r of o.atomIds)t.add(r);}return t}function Vo(i,e){let t=null;for(let n of i){let o=e.get(n);o!==void 0&&(t===null||o.y<t)&&(t=o.y);}return t}function Uo(i,e){let t=null;for(let n of i){let o=e.get(n);o!==void 0&&(t===null||o.y>t)&&(t=o.y);}return t}function He(i,e,t,n){for(let o of i){let r=e.get(o);r!==void 0&&e.set(o,{x:r.x+t,y:r.y+n});}}function as(i,e){let t=0,n=0;for(let r of i){let s=e.get(r);s!==void 0&&(t+=s.x,n+=1);}if(n===0)return;let o=t/n;for(let r of i){let s=e.get(r);s!==void 0&&e.set(r,{x:2*o-s.x,y:s.y});}}function ls(i,e){let t=0,n=0;for(let r of i){let s=e.get(r);s!==void 0&&(t+=s.y,n+=1);}if(n===0)return;let o=t/n;for(let r of i){let s=e.get(r);s!==void 0&&e.set(r,{x:s.x,y:2*o-s.y});}}function Lt(i,e){let t=0,n=0,o=0;for(let r of i){let s=e.get(r);s!==void 0&&(t+=s.x,n+=s.y,o+=1);}return o===0?{x:0,y:0}:{x:t/o,y:n/o}}function ds(i,e,t,n,o,r){let s=Lt(t,r),a=n.x-s.x,d=n.y-s.y,l=Math.hypot(a,d);l<1e-6&&(a=0,d=1,l=1);let u=a/l,c=d/l,m=n.x+u*o,p=n.y+c*o;He(i,r,m-e.x,p-e.y);}function cs(i,e){let t=[],n=o=>{let r=Math.hypot(o.x,o.y);if(r<1e-6)return;let s={x:o.x/r,y:o.y/r};for(let a of t)if(Math.hypot(a.x-s.x,a.y-s.y)<.001)return;t.push(s);};if(e.length>1){let o=0,r=0;for(let a of e)o+=a.x,r+=a.y;o/=e.length,r/=e.length;let s={x:i.x-o,y:i.y-r};Math.hypot(s.x,s.y)>.05&&n(s);}if(e.length>0){let o={x:e[0].x-i.x,y:e[0].y-i.y},r={x:o.y,y:-o.x},s={x:-o.y,y:o.x};n(r.y>=s.y?r:s),n(r.y>=s.y?s:r);}n({x:0,y:1}),n({x:0,y:-1});for(let[o,r]of [[1,1],[-1,1],[1,-1],[-1,-1],[1,0],[-1,0]])n({x:o,y:r});return t}function us(i){let e=[...i];for(let t=0;t<24;t++){let n=t*Math.PI*2/24,o={x:Math.cos(n),y:Math.sin(n)};e.some(r=>Math.hypot(r.x-o.x,r.y-o.y)<.001)||e.push(o);}return e}function ms(i,e,t,n){let o=[];for(let r of t.get(i.id)??[]){if(r.kind===\"hbond\")continue;let s=r.a1.id===i.id?r.a2:r.a1;if(s.id===i.id||s.id===e)continue;let a=n.get(s.id);a!==void 0&&o.push(a);}return o}function ps(i,e,t,n,o){let r=Math.cos(n),s=Math.sin(n),a=new Map;for(let d of i){let l=o.get(d);if(l===void 0)continue;let u=l.x-e.x,c=l.y-e.y;a.set(d,{x:t.x+u*r-c*s,y:t.y+u*s+c*r});}return a}function hs(i,e,t,n,o,r){let s=rs*r,a=ss*r,d=t.map(l=>({a:l,end:e.get(l.movingAtomId)})).filter(l=>l.end!==void 0);for(let l of n){if(i.has(l))continue;let u=o.get(l);if(u!==void 0){for(let c of e.values())if(Math.hypot(c.x-u.x,c.y-u.y)<s)return false;for(let c of d)if(l!==c.a.fixedAtomId&&Oo(u,c.a.fixedPos,c.end)<a)return false}}for(let[l,u]of e)for(let c of d)if(l!==c.a.movingAtomId&&Oo(u,c.a.fixedPos,c.end)<a)return false;return true}function fs(i,e){let t=0;for(let n of i){let o=e.get(n.movingAtomId);o!==void 0&&(t+=Math.hypot(o.x-n.fixedPos.x,o.y-n.fixedPos.y));}return t}function Oo(i,e,t){let n=t.x-e.x,o=t.y-e.y,r=n*n+o*o;if(r===0)return Math.hypot(i.x-e.x,i.y-e.y);let s=((i.x-e.x)*n+(i.y-e.y)*o)/r;return s=Math.max(0,Math.min(1,s)),Math.hypot(i.x-(e.x+s*n),i.y-(e.y+s*o))}function No(i,e,t,n,o,r,s,a,d){let l=ms(t,n.movingAtomId,r,d),u=cs(n.fixedPos,l),c=ys(i,e,d),m=[n.fixedPos];if(o.length>1){let y=0,f=0;for(let _ of o)y+=_.fixedPos.x,f+=_.fixedPos.y;m.unshift({x:y/o.length,y:f/o.length});}let p=c===null?[0]:[0,1],h=us(u);for(let y of [a,2*a,3*a,4*a]){let f=bs(y===a?u:h,y,m,p,c,i,e,o,s,d,a);if(f!==null)return gs(i,e,f.target,f.angle,d),true}return false}function bs(i,e,t,n,o,r,s,a,d,l,u){let c=null;for(let m of n)for(let p of t)for(let h of i){let y={x:p.x+h.x*e,y:p.y+h.y*e},f=m===0||o===null?0:Math.atan2(h.y,h.x)-Math.atan2(o.y,o.x),_=ps(r,s,y,f,l);if(!hs(r,_,a,d,l,u))continue;let b=fs(a,_);if(a.length===1)return {target:y,angle:f,cost:b};(c===null||b<c.cost)&&(c={target:y,angle:f,cost:b});}return c}function Fo(i,e,t,n,o,r){let s=[e];for(let a of t.bonds)if(a.kind===\"cross-polymer\")for(let[d,l]of [[a.a1,a.a2],[a.a2,a.a1]]){if(!i.has(d.id)||i.has(l.id)||!n.has(l.id)||l.id===e.fixedAtomId&&d.id===e.movingAtomId||!r(l.id))continue;let u=o.get(l.id);u!==void 0&&s.push({fixedAtomId:l.id,fixedPos:u,movingAtomId:d.id});}return s}function ys(i,e,t){if(i.size<2)return null;let n=Lt(i,t),o=n.x-e.x,r=n.y-e.y;if(Math.hypot(o,r)<.001){let a=0;for(let d of i){let l=t.get(d);if(l===void 0)continue;let u=Math.hypot(l.x-e.x,l.y-e.y);u>a&&(a=u,o=l.x-e.x,r=l.y-e.y);}}let s=Math.hypot(o,r);return s<1e-6?null:{x:o/s,y:r/s}}function gs(i,e,t,n,o){n!==0&&zo(i,o,e,n),He(i,o,t.x-e.x,t.y-e.y);}function zo(i,e,t,n){let o=Math.cos(n),r=Math.sin(n);for(let s of i){let a=e.get(s);if(a===void 0)continue;let d=a.x-t.x,l=a.y-t.y;e.set(s,{x:t.x+d*o-l*r,y:t.y+d*r+l*o});}}function _s(i,e,t,n,o,r){let s=Lt(t,r),a=n.x-s.x,d=n.y-s.y,l=Math.hypot(a,d);l<1e-6&&(a=1,d=0,l=1);let u=a/l,c=d/l,m=Lt(i,r),p=Math.hypot(e.x-m.x,e.y-m.y),h=Math.atan2(e.y-m.y,e.x-m.x),y=Math.atan2(-c,-u);zo(i,r,m,y-h);let f=n.x+u*(o+p),_=n.y+c*(o+p);He(i,r,f-m.x,_-m.y);}function Ko(i,e,t,n){let o=n?.bondLength??28,r=n?.gap??Tt,s=1.6*o,a=r*s,d=0,l=false;for(let c of i)if(t.has(c.id)){for(let m of c.backbone){let p=e.get(m.id);p!==void 0&&(l?p.y>d&&(d=p.y):(d=p.y,l=true));}for(let m of c.bases){if(m===null)continue;let p=e.get(m.id);p!==void 0&&p.y>d&&(d=p.y);}}l||(d=0);let u=d+a;for(let c of i){if(t.has(c.id))continue;let m=Number.POSITIVE_INFINITY,p=Number.NEGATIVE_INFINITY;for(let y of c.backbone){let f=e.get(y.id);f!==void 0&&(f.y<m&&(m=f.y),f.y>p&&(p=f.y));}for(let y of c.bases){if(y===null)continue;let f=e.get(y.id);f!==void 0&&(f.y<m&&(m=f.y),f.y>p&&(p=f.y));}if(m===Number.POSITIVE_INFINITY){t.add(c.id);continue}let h=u-m;for(let y of c.backbone){let f=e.get(y.id);f!==void 0&&e.set(y.id,{x:f.x,y:f.y+h});}for(let y of c.bases){if(y===null)continue;let f=e.get(y.id);f!==void 0&&e.set(y.id,{x:f.x,y:f.y+h});}u=p+h+a,t.add(c.id);}}var vs=20,xs=40,ws=250,ks=4;function As(i,e){let t=1,n=ws;for(;e>n;)t*=2,n*=ks;return i*t}function oe(i,e){let t=e?.bondLength??28,n=e?.perRow,o=e?.rowsThreshold,r=e?.circleThreshold??50,s=Ao(i),a=new Map;for(let l of s){let u=Ms(l,i,t,n,o,r);for(let[c,m]of u)a.set(c,m);$o(l,a,{bondLength:t});}let d=Go(s,a,i,{bondLength:t});Ko(s,a,d,{bondLength:t});for(let l of i.atoms)a.has(l.id)||a.set(l.id,{x:0,y:0});return Ts(i,a)}function Ms(i,e,t,n,o,r){let s=i.backbone.length;if(s===0)return new Map;let a=i.polymerType===\"RNA\"||i.bases.some(c=>c!==null),l=n??As(a?xs:vs,s),u=o??l;if(i.polymerType===\"RNA\"&&Ro(i,e))return Ho(i,e,{bondLength:t});if(i.isCyclic&&s<=r)return St(i,{bondLength:t});if(!i.isCyclic&&Eo(i,e))return Tn(i,e,{bondLength:t});if(s>u){let c=a?2:void 0;return To(i,c!==void 0?{bondLength:t,perRow:l,rowSpacing:c}:{bondLength:t,perRow:l})}return i.isCyclic?Ae(i,{bondLength:t}):Tn(i,e,{bondLength:t})}function Ts(i,e){let t=new Map,n=[];for(let s of i.atoms){let a=e.get(s.id)??s.p,d={...s,p:{x:a.x,y:a.y}};t.set(s.id,d),n.push(d);}for(let s=0;s<n.length;s++){let a=i.atoms[s];if(a.branchAtom!==void 0){let d=t.get(a.branchAtom.id);d!==void 0&&(n[s]={...n[s],branchAtom:d}),t.set(n[s].id,n[s]);}}let o=[];for(let s of i.bonds){let a=t.get(s.a1.id),d=t.get(s.a2.id);a===void 0||d===void 0||o.push({...s,a1:a,a2:d});}let r=[];for(let s of i.chains){let a=s.backboneAtoms.map(l=>t.get(l.id)??l),d=s.bonds.map(l=>{let u=t.get(l.a1.id)??l.a1,c=t.get(l.a2.id)??l.a2;return {...l,a1:u,a2:c}});r.push({id:s.id,polymerType:s.polymerType,backboneAtoms:a,bonds:d,...s.annotation!==void 0?{annotation:s.annotation}:{},...s.strandType!==void 0?{strandType:s.strandType}:{}});}return {atoms:n,bonds:o,chains:r,groups:i.groups,annotations:i.annotations}}function Bt(i,e){let t=Math.min(i.x,e.x),n=Math.min(i.y,e.y),o=Math.max(i.x+i.width,e.x+e.width),r=Math.max(i.y+i.height,e.y+e.height);return {x:t,y:n,width:o-t,height:r-n}}function M(i){if(Number.isInteger(i))return i===0?\"0\":i.toString();if(!Number.isFinite(i)||Object.is(i,-0))return \"0\";let e=Math.round(i*1e3)/1e3;return e===0?\"0\":e.toString()}function Cn(i){if(i.length===0)return \"\";let e=i[0],t=`M ${M(e.x)} ${M(e.y)}`;for(let n=1;n<i.length;n++){let o=i[n];t+=` L ${M(o.x)} ${M(o.y)}`;}return t+=` L ${M(e.x)} ${M(e.y)} Z`,t}function Wo(i,e,t,n){let o=[],r=360/e;for(let s=0;s<e;s++){let a=(n+s*r)*Math.PI/180;o.push({x:i.x+t*Math.cos(a),y:i.y+t*Math.sin(a)});}return o}function jo(i,e,t=-30){return Cn(Wo(i,6,e,t))}function qo(i,e){let t=[{x:i.x,y:i.y-e},{x:i.x+e,y:i.y},{x:i.x,y:i.y+e},{x:i.x-e,y:i.y}];return Cn(t)}function Yo(i,e,t=-90){return Cn(Wo(i,5,e,t))}function Ln(i,e,t,n){let o=Math.abs(e)/2,r=Math.abs(t)/2,s=Math.max(0,Math.min(n,o,r)),a=i.x-o,d=i.y-r,l=a+o*2,u=d+r*2,c=`M ${M(a+s)} ${M(d)}`;return c+=` L ${M(l-s)} ${M(d)}`,c+=` A ${M(s)} ${M(s)} 0 0 1 ${M(l)} ${M(d+s)}`,c+=` L ${M(l)} ${M(u-s)}`,c+=` A ${M(s)} ${M(s)} 0 0 1 ${M(l-s)} ${M(u)}`,c+=` L ${M(a+s)} ${M(u)}`,c+=` A ${M(s)} ${M(s)} 0 0 1 ${M(a)} ${M(u-s)}`,c+=` L ${M(a)} ${M(d+s)}`,c+=` A ${M(s)} ${M(s)} 0 0 1 ${M(a+s)} ${M(d)}`,c+=\" Z\",c}function Bn(i,e,t){let n=Math.abs(e),o=Math.abs(t);return `M ${M(i.x-n)} ${M(i.y)} A ${M(n)} ${M(o)} 0 1 0 ${M(i.x+n)} ${M(i.y)} A ${M(n)} ${M(o)} 0 1 0 ${M(i.x-n)} ${M(i.y)} Z`}function Xo(i,e,t,n){return Ln(i,e,t,n)}function Jo(i,e){return Bn(i,e,e)}function Zo(i,e){return `M ${M(i.x)} ${M(i.y)} L ${M(e.x)} ${M(e.y)}`}function Qo(i,e,t=6){let n=e.x-i.x,o=e.y-i.y,r=Math.sqrt(n*n+o*o);if(r===0)return `M ${M(i.x)} ${M(i.y)} L ${M(i.x)} ${M(i.y)}`;let s=n/r,a=o/r,d=-a,l=s,u=(i.x+e.x)/2,c=(i.y+e.y)/2,m=t/2,p=Math.min(t*.6,r*.25),h=u-s*p,y=c-a*p,f=u+s*p,_=c+a*p;return `M ${M(h-d*m)} ${M(y-l*m)} L ${M(h+d*m)} ${M(y+l*m)} M ${M(f-d*m)} ${M(_-l*m)} L ${M(f+d*m)} ${M(_+l*m)}`}function Rn(i,e,t,n){switch(i){case \"hexagon\":{let o=t*Math.sqrt(3)/2,r=t;return {x:e.x-o,y:e.y-r,width:o*2,height:r*2}}case \"diamond\":return {x:e.x-t,y:e.y-t,width:t*2,height:t*2};case \"pentagon\":{let o=Math.cos(18*Math.PI/180)*t,r=-t,s=Math.sin(54*Math.PI/180)*t;return {x:e.x-o,y:e.y+r,width:o*2,height:s-r}}case \"rounded-rect\":case \"blob\":{let o=n??t,r=Math.abs(t)/2,s=Math.abs(o)/2;return {x:e.x-r,y:e.y-s,width:r*2,height:s*2}}case \"ellipse\":{let o=Math.abs(t),r=Math.abs(n??t);return {x:e.x-o,y:e.y-r,width:o*2,height:r*2}}case \"circle\":{let o=Math.abs(t);return {x:e.x-o,y:e.y-o,width:o*2,height:o*2}}}}var Rt=14,ei='\"Helvetica Neue\", Helvetica, Arial, sans-serif';function ti(i){return {aa:{size:i*.72,strokeWidth:5},sugar:{size:i*1.39,strokeWidth:5,cornerRadius:i*.3},base:{size:i*.88,strokeWidth:5},linker:{size:i*.63,strokeWidth:5},chem:{size:i*1.49,strokeWidth:5,cornerRadius:i*.5},blob:{size:i*1.64,strokeWidth:5,cornerRadius:i*.8},nucleotide:{size:i*.98,strokeWidth:5}}}var $={name:\"light\",background:\"#ffffff\",defaultStroke:\"#202020\",defaultFill:\"#ffffff\",selectionColor:\"#FFC107\",highlightColor:\"#A4E2DC\",errorColor:\"#cc0000\",fontSize:Rt,fontFamily:ei,bondLength:28,textColor:\"#000000\",idColor:\"#00aa00\",annotationColor:\"#FFA500\",tagDotColor:\"#dd2222\",hbondColor:\"#888888\",nonCanonicalHbondColor:\"#cc8800\",crossPolymerBondColor:\"#1f5fcd\",colorTheme:we,palette:{softenCanvas:false},shapes:ti(Rt)},In={name:\"dark\",background:\"#1a1d23\",defaultStroke:\"#e0e0e0\",defaultFill:\"#2b2f37\",selectionColor:\"#FFD54F\",highlightColor:\"#7DD8CC\",errorColor:\"#ff5050\",fontSize:Rt,fontFamily:ei,bondLength:28,textColor:\"#ffffff\",idColor:\"#33ff33\",annotationColor:\"#FFB84D\",tagDotColor:\"#ff6464\",hbondColor:\"#aaaaaa\",nonCanonicalHbondColor:\"#ffaa44\",crossPolymerBondColor:\"#6699ff\",colorTheme:Ie,palette:{softenCanvas:false},shapes:ti(Rt)};function Ss(i,e){let t=e.shapes===void 0?i.shapes:{...i.shapes,...e.shapes};return {...i,...e,shapes:t}}function it(i,e){switch(e){case g.AA:return i.shapes.aa;case g.SUGAR:return i.shapes.sugar;case g.BASE:return i.shapes.base;case g.LINKER:return i.shapes.linker;case g.CHEM:return i.shapes.chem;case g.BLOB:return i.shapes.blob;case g.NUCLEOTIDE:return i.shapes.nucleotide}}var ni=\"*\";function It(i){switch(i){case g.AA:return \"hexagon\";case g.SUGAR:return \"rounded-rect\";case g.BASE:return \"diamond\";case g.LINKER:return \"circle\";case g.CHEM:return \"rounded-rect\";case g.BLOB:return \"blob\";case g.NUCLEOTIDE:return \"pentagon\"}}function $e(i,e,t=0){let n=it(e,i.biotype);if(i.symbol===ni)return Jo(i.p,n.size+t);switch(It(i.biotype)){case \"hexagon\":{let r=t===0?0:t/Math.cos(Math.PI/6);return jo(i.p,n.size+r)}case \"diamond\":{let r=t===0?0:t/Math.cos(Math.PI/4);return qo(i.p,n.size+r)}case \"pentagon\":{let r=t===0?0:t/Math.cos(Math.PI/5);return Yo(i.p,n.size+r)}case \"rounded-rect\":return Ln(i.p,n.size+2*t,n.size+2*t,(n.cornerRadius??0)+t);case \"blob\":return Xo(i.p,n.size+2*t,n.size+2*t,(n.cornerRadius??0)+t);case \"circle\":return Bn(i.p,n.size+t,n.size+t)}}function pe(i,e){let t=it(e,i.biotype),n=i.symbol===ni?\"circle\":It(i.biotype),o;switch(n){case \"hexagon\":case \"diamond\":case \"pentagon\":case \"circle\":o=Rn(n,i.p,t.size);break;case \"rounded-rect\":case \"blob\":o=Rn(n,i.p,t.size,t.size);break}let r=t.strokeWidth/2;return {x:o.x-r,y:o.y-r,width:o.width+2*r,height:o.height+2*r}}function oi(i,e){return it(e,i.biotype).size}function he(i,e){return it(e,i.biotype)}var Es=/[&\"'<>]/,Cs=/[&<>]/;function Ls(i){return Es.test(i)?i.replace(/&/g,\"&amp;\").replace(/\"/g,\"&quot;\").replace(/'/g,\"&apos;\").replace(/</g,\"&lt;\").replace(/>/g,\"&gt;\"):i}function de(i){return Cs.test(i)?i.replace(/&/g,\"&amp;\").replace(/</g,\"&lt;\").replace(/>/g,\"&gt;\"):i}function Me(i){if(Number.isInteger(i))return i===0?\"0\":i.toString();if(!Number.isFinite(i)||Object.is(i,-0))return \"0\";let e=Math.round(i*1e3)/1e3;return e===0?\"0\":e.toString()}function R(i,e,t){let n=`<${i}`;if(e!==void 0)for(let o in e){let r=e[o];if(!(r===void 0||r===false)){if(r===true){n+=` ${o}`;continue}typeof r==\"number\"?n+=` ${o}=\"${Me(r)}\"`:n+=` ${o}=\"${Ls(r)}\"`;}}return t===void 0?`${n}/>`:typeof t==\"string\"?`${n}>${t}</${i}>`:`${n}>${t.join(\"\")}</${i}>`}var Bs=\"http://www.w3.org/2000/svg\",Pn=.525,Hn=.8,$n=1.125,Rs=\".hw-atom{transition:stroke-width 120ms,filter 120ms;}.hw-atom:focus{outline:none;}.hw-atom__shape{shape-rendering:geometricPrecision;}.hw-bond__stroke{stroke-linecap:round;}\",Is=[[\"A\",\"T\"],[\"A\",\"U\"],[\"G\",\"C\"]];function Ht(i,e={}){let t=e.theme??$,n=e.width??400,o=e.height??100,r=e.padding??16,s=e.backColor??t.background,a=e.showIds??false,d=e.showAnnotations??true,l=e.fontSize??t.fontSize,u=e.selectedAtomIds??new Set,c=e.highlightedAtomIds??new Set;e.documentImpl??(typeof globalThis<\"u\"&&typeof globalThis.document<\"u\"?globalThis.document:void 0);let p=e.fixedModelBbox??Dn(i,t),h=Ps(p,n,o,r,e.maxScale??1),y=h.x-p.x*h.scale,f=h.y-p.y*h.scale,_=On(i,t,c),b=Nn(i,t,u),A=Hs(i,t),w=Gs(i,t,l,a,e.bondLength??t.bondLength),k=d?zs(i,t,l):\"\",C=`translate(${Me(y)} ${Me(f)}) scale(${Me(h.scale)})`,I=R(\"g\",{class:\"hw-content\",transform:C},[A,w,k,_,b].join(\"\")),T=R(\"defs\",void 0,`<style>${Rs}</style>`),B=R(\"rect\",{class:\"hw-bg\",x:0,y:0,width:n,height:o,fill:s});return {svg:R(\"svg\",{xmlns:Bs,viewBox:`0 0 ${Me(n)} ${Me(o)}`,width:n,height:o,\"data-hw-theme\":t.name},[T,B,I].join(\"\")),bbox:{x:p.x,y:p.y,width:p.width,height:p.height},drawBox:{x:h.x,y:h.y,width:h.width,height:h.height,scale:h.scale}}}function Dn(i,e=$){if(i.atoms.length===0)return {x:0,y:0,width:0,height:0};let t=pe(i.atoms[0],e);for(let n=1;n<i.atoms.length;n++)t=Bt(t,pe(i.atoms[n],e));return t}function Ps(i,e,t,n,o=1){let r=Math.max(0,e-2*n),s=Math.max(0,t-2*n),a=1;if(i.width>0||i.height>0){let u=i.width>0?r/i.width:Number.POSITIVE_INFINITY,c=i.height>0?s/i.height:Number.POSITIVE_INFINITY;a=Math.min(u,c,o),(!Number.isFinite(a)||a<=0)&&(a=1);}let d=i.width*a,l=i.height*a;return {x:(e-d)/2,y:(t-l)/2,width:d,height:l,scale:a}}var Pt=3;function On(i,e,t){if(t.size===0)return R(\"g\",{class:\"hw-layer hw-highlights\"},\"\");let n=[];for(let o of i.atoms){if(!t.has(o.id))continue;let s=(he(o,e).strokeWidth+Pt)/2,a=$e(o,e,s);n.push(R(\"path\",{d:a,class:\"hw-highlight\",fill:\"none\",stroke:e.highlightColor,\"stroke-width\":Pt,\"stroke-linejoin\":\"round\",\"stroke-linecap\":\"round\",\"data-symbol\":o.symbol,\"data-ring-atom-id\":o.id,\"data-testid\":`highlight-ring-${o.id}`}));}return R(\"g\",{class:\"hw-layer hw-highlights\"},n.join(\"\"))}function Nn(i,e,t){if(t.size===0)return R(\"g\",{class:\"hw-layer hw-selections\"},\"\");let n=[];for(let o of i.atoms){if(!t.has(o.id))continue;let s=(he(o,e).strokeWidth+Pt)/2,a=$e(o,e,s);n.push(R(\"path\",{d:a,class:\"hw-selection\",fill:\"none\",stroke:e.selectionColor,\"stroke-width\":Pt,\"stroke-linejoin\":\"round\",\"stroke-linecap\":\"round\",\"data-symbol\":o.symbol,\"data-ring-atom-id\":o.id,\"data-testid\":`selection-ring-${o.id}`}));}return R(\"g\",{class:\"hw-layer hw-selections\"},n.join(\"\"))}function Hs(i,e){let t=[];for(let n of i.bonds)t.push($s(n,e));return R(\"g\",{class:\"hw-layer hw-bonds\"},t.join(\"\"))}function $s(i,e){let t=i.a1.p,n=i.a2.p,o=Ds(i,e),r=Os(i),s=Ns(),d={d:Zo(t,n),class:\"hw-bond__stroke\",fill:\"none\",stroke:o,\"stroke-width\":s};r!==void 0&&(d[\"stroke-dasharray\"]=r);let l=[R(\"path\",d)];return i.kind===\"hbond\"&&l.push(R(\"path\",{d:Qo(t,n,e.fontSize*.6),class:\"hw-bond__hash\",fill:\"none\",stroke:o,\"stroke-width\":s})),R(\"g\",{class:`hw-bond hw-bond--${i.kind}`,\"data-bond-id\":i.id,\"data-kind\":i.kind,\"data-testid\":`canvas-bond-${i.id}`},l.join(\"\"))}function Ds(i,e){switch(i.kind){case \"backbone\":case \"branch\":return e.defaultStroke;case \"cross-polymer\":return e.crossPolymerBondColor;case \"hbond\":return Fs(i)?e.hbondColor:e.nonCanonicalHbondColor;case \"group\":return e.defaultStroke}}function Os(i){if(i.kind===\"hbond\")return \"4 3\"}function Ns(i){return $n}function Fs(i){if(i.a1.biotype!==g.BASE||i.a2.biotype!==g.BASE)return false;let e=ii(i.a1),t=ii(i.a2);for(let[n,o]of Is)if(e===n&&t===o||e===o&&t===n)return true;return false}function ii(i){let e=i.monomer?.naturalAnalog,t=e!==void 0&&e!==\"\"?e:i.symbol;return t.length===0?\"\":t.charAt(0).toUpperCase()}function Gs(i,e,t,n,o=e.bondLength){let r=[];for(let s of i.atoms)s.hidden||r.push(Vs(s,e,t,n,o));return R(\"g\",{class:\"hw-layer hw-atoms\"},r.join(\"\"))}function Vs(i,e,t,n,o=e.bondLength){let r=he(i,e),s=$e(i,e),a=D(i.monomer,i.biotype,e.colorTheme),d=a.background,l=a.text,u=i.symbol===\"*\"?\"3 3\":void 0,c={d:s,class:\"hw-atom__shape\",fill:d,stroke:d,\"stroke-width\":r.strokeWidth,\"stroke-linejoin\":\"round\",\"stroke-linecap\":\"round\"};u!==void 0&&(c[\"stroke-dasharray\"]=u);let m=[R(\"path\",c)],p=i.monomer?.symbol??i.symbol;if(p!==\"\"){let y=p.length<=1?1:Math.min(1,2/p.length),f=t*y;m.push(R(\"text\",{class:\"hw-atom__label\",x:i.p.x,y:i.p.y+f*.35,\"text-anchor\":\"middle\",\"font-size\":f,\"font-family\":e.fontFamily,fill:l},de(p)));}if(i.bio.ambiguity!==void 0&&i.bio.ambiguity!==\"\"&&m.push(R(\"text\",{class:\"hw-atom__ambiguity\",x:i.p.x,y:i.p.y+r.size+t*.7,\"text-anchor\":\"middle\",\"font-size\":t*.7,\"font-family\":e.fontFamily,fill:l},de(i.bio.ambiguity))),n){let y=o*Pn;m.push(R(\"text\",{class:\"hw-atom__id\",x:i.p.x-y,y:i.p.y-y,\"font-size\":t*Hn,\"font-family\":e.fontFamily,fill:e.idColor},de(String(i.bio.continuousId))));}i.tag!==void 0&&i.tag!==\"\"&&m.push(R(\"circle\",{class:\"hw-atom__tag-dot\",cx:i.p.x+r.size*.7,cy:i.p.y-r.size*.7,r:Math.max(2,t*.18),fill:e.tagDotColor}));let h=Us(i);return R(\"g\",{class:\"hw-atom\",\"data-atom-id\":i.id,\"data-symbol\":i.symbol,\"data-chain-id\":i.bio.chainId,\"data-biotype\":i.biotype,\"data-testid\":`canvas-atom-${i.id}`,tabindex:0,role:\"button\",\"aria-label\":h},m.join(\"\"))}function Us(i){let e=i.symbol===\"\"?\"?\":i.symbol,t=i.bio.chainId===\"\"?\"unknown chain\":i.bio.chainId,n=i.bio.positionInChain;return `${e} at position ${n} of ${t}`}function zs(i,e,t){let n=[];for(let o of i.bonds){if(o.ratio===void 0)continue;let r=(o.a1.p.x+o.a2.p.x)/2,s=(o.a1.p.y+o.a2.p.y)/2,a=o.ratio.denominator!==void 0?`${o.ratio.numerator}/${o.ratio.denominator}`:`${o.ratio.numerator}`;n.push(R(\"text\",{class:\"hw-annotation hw-annotation--bond-ratio\",x:r,y:s-t*.4,\"text-anchor\":\"middle\",\"font-size\":t*.7,\"font-family\":e.fontFamily,fill:e.annotationColor},de(a)));}for(let o of i.atoms){let r=o.bio.annotation;if(r===void 0||r===\"\")continue;let s=he(o,e);n.push(R(\"text\",{class:\"hw-annotation hw-annotation--atom\",x:o.p.x+s.size+2,y:o.p.y-s.size,\"font-size\":t*.7,\"font-family\":e.fontFamily,fill:e.annotationColor},de(r)));}for(let o of i.chains){if(o.annotation===void 0||o.annotation===\"\")continue;let r=o.backboneAtoms[0];r!==void 0&&n.push(R(\"text\",{class:\"hw-annotation hw-annotation--chain\",x:r.p.x,y:r.p.y-e.fontSize*1.4,\"font-size\":t*.8,\"font-family\":e.fontFamily,fill:e.annotationColor},de(o.annotation)));}for(let o of i.chains){if(o.polymerType!==\"RNA\")continue;let r=o.backboneAtoms;if(r.length<2)continue;let s=r[0],a=r[r.length-1],d=r.length>=2?r[1]:null,l=r.length>=2?r[r.length-2]:null,u=e.fontSize*1.4,c=ri(s.p,d?.p??null,u),m=ri(a.p,l?.p??null,u),p=o.strandType!==void 0?`5'${o.strandType}`:\"5'\",h=o.strandType!==void 0?`3'${o.strandType}`:\"3'\";n.push(R(\"text\",{class:\"hw-annotation hw-annotation--prime hw-annotation--prime-5\",\"data-testid\":`prime-5-${o.id}`,x:c.x,y:c.y,\"text-anchor\":\"middle\",\"dominant-baseline\":\"central\",\"font-size\":t*.85,\"font-family\":e.fontFamily,\"font-weight\":\"bold\",fill:e.annotationColor},de(p))),n.push(R(\"text\",{class:\"hw-annotation hw-annotation--prime hw-annotation--prime-3\",\"data-testid\":`prime-3-${o.id}`,x:m.x,y:m.y,\"text-anchor\":\"middle\",\"dominant-baseline\":\"central\",\"font-size\":t*.85,\"font-family\":e.fontFamily,\"font-weight\":\"bold\",fill:e.annotationColor},de(h)));}return R(\"g\",{class:\"hw-layer hw-annotations\"},n.join(\"\"))}function ri(i,e,t){if(e===null)return {x:i.x-t,y:i.y};let n=i.x-e.x,o=i.y-e.y,r=Math.hypot(n,o);return r===0?{x:i.x-t,y:i.y}:{x:i.x+t*(n/r),y:i.y+t*(o/r)}}function $t(i,e,t,n={}){let o=n.theme??$,r=n.padding??16,s=Ws(e,o),a=js(s,t.width,t.height,r,n.maxScale??1),d=t.x+a.x,l=t.y+a.y;return i.save(),i.beginPath(),i.rect(t.x,t.y,t.width,t.height),i.clip(),n.backColor!==void 0&&(i.fillStyle=n.backColor,i.fillRect(t.x,t.y,t.width,t.height)),i.translate(d,l),i.scale(a.scale,a.scale),i.translate(-s.x,-s.y),qs(i,e,o),Xs(i,e,o,n.fontSize??o.fontSize,n.showIds??false,n.bondLength??o.bondLength),n.showAnnotations!==false&&Ys(i,e,o,n.fontSize??o.fontSize),i.restore(),{bbox:{x:s.x,y:s.y,width:s.width,height:s.height},drawBox:{x:d,y:l,width:a.width,height:a.height}}}async function di(i,e={}){let t=Ks();if(t===null&&e.canvas===void 0)throw new Error(\"renderToPng: OffscreenCanvas is not available in this environment\");let n=e.theme??$,o=e.width??400,r=e.height??100,s=e.pixelRatio??1,a=e.canvas??new t(Math.max(1,Math.round(o*s)),Math.max(1,Math.round(r*s))),d=a.getContext(\"2d\");if(d===null)throw new Error(\"renderToPng: failed to acquire 2D context\");d.save(),d.scale(s,s),$t(d,i,{x:0,y:0,width:o,height:r},{...e,backColor:e.backColor??n.background}),d.restore();let l=a;if(typeof l.convertToBlob!=\"function\")throw new Error(\"renderToPng: canvas.convertToBlob is not available\");let c=await(await l.convertToBlob({type:\"image/png\"})).arrayBuffer();return new Uint8Array(c)}function Ks(){let i=globalThis;return typeof i.OffscreenCanvas==\"function\"?i.OffscreenCanvas:null}function Ws(i,e){if(i.atoms.length===0)return {x:0,y:0,width:0,height:0};let t=pe(i.atoms[0],e);for(let n=1;n<i.atoms.length;n++)t=Bt(t,pe(i.atoms[n],e));return t}function js(i,e,t,n,o=1){let r=Math.max(0,e-2*n),s=Math.max(0,t-2*n),a=1;if(i.width>0||i.height>0){let u=i.width>0?r/i.width:Number.POSITIVE_INFINITY,c=i.height>0?s/i.height:Number.POSITIVE_INFINITY;a=Math.min(u,c,o),(!Number.isFinite(a)||a<=0)&&(a=1);}let d=i.width*a,l=i.height*a;return {x:(e-d)/2,y:(t-l)/2,width:d,height:l,scale:a}}function qs(i,e,t){for(let n of e.bonds)i.save(),i.strokeStyle=Zs(n,t),i.lineWidth=Qs(),n.kind===\"hbond\"?i.setLineDash([4,3]):i.setLineDash([]),i.beginPath(),i.moveTo(n.a1.p.x,n.a1.p.y),i.lineTo(n.a2.p.x,n.a2.p.y),i.stroke(),i.restore();}function Ys(i,e,t,n){i.save(),i.fillStyle=t.annotationColor,i.font=`${n*.7}px ${t.fontFamily}`,i.textAlign=\"left\",i.textBaseline=\"alphabetic\";for(let r of e.atoms){let s=r.bio.annotation;if(s===void 0||s===\"\")continue;let a=he(r,t);i.fillText(s,r.p.x+a.size+2,r.p.y-a.size);}i.font=`${n*.8}px ${t.fontFamily}`;for(let r of e.chains){if(r.annotation===void 0||r.annotation===\"\")continue;let s=r.backboneAtoms[0];s!==void 0&&i.fillText(r.annotation,s.p.x,s.p.y-t.fontSize*1.4);}i.font=`bold ${n*.85}px ${t.fontFamily}`,i.textAlign=\"center\",i.textBaseline=\"middle\";let o=t.fontSize*1.4;for(let r of e.chains){if(r.polymerType!==\"RNA\")continue;let s=r.backboneAtoms;if(s.length<2)continue;let a=s[0],d=s[s.length-1],l=s.length>=2?s[1]:null,u=s.length>=2?s[s.length-2]:null,c=si(a.p,l?.p??null,o),m=si(d.p,u?.p??null,o),p=r.strandType!==void 0?`5'${r.strandType}`:\"5'\",h=r.strandType!==void 0?`3'${r.strandType}`:\"3'\";i.fillText(p,c.x,c.y),i.fillText(h,m.x,m.y);}i.restore();}function si(i,e,t){if(e===null)return {x:i.x-t,y:i.y};let n=i.x-e.x,o=i.y-e.y,r=Math.hypot(n,o);return r===0?{x:i.x-t,y:i.y}:{x:i.x+t*(n/r),y:i.y+t*(o/r)}}function Xs(i,e,t,n,o=false,r=t.bondLength){for(let s of e.atoms){if(s.hidden)continue;let a=he(s,t),d=D(s.monomer,s.biotype,t.colorTheme);i.save(),i.fillStyle=d.background,i.strokeStyle=d.background,i.lineWidth=a.strokeWidth,i.lineJoin=\"round\",i.lineCap=\"round\",s.symbol===\"*\"?i.setLineDash([3,3]):i.setLineDash([]),Js(i,s,a.size,a.cornerRadius??0),i.fill(),i.stroke(),i.restore();let l=s.monomer?.symbol??s.symbol;if(l!==\"\"){let u=l.length<=1?1:Math.min(1,2/l.length),c=n*u;i.save(),i.fillStyle=d.text,i.font=`${c}px ${t.fontFamily}`,i.textAlign=\"center\",i.textBaseline=\"middle\",i.fillText(l,s.p.x,s.p.y),i.restore();}if(o){let u=r*Pn;i.save(),i.fillStyle=t.idColor,i.font=`${n*Hn}px ${t.fontFamily}`,i.textAlign=\"right\",i.textBaseline=\"bottom\",i.fillText(String(s.bio.continuousId),s.p.x-u,s.p.y-u),i.restore();}}}function Js(i,e,t,n){let o=e.p,r=e.symbol===\"*\"?\"circle\":It(e.biotype);switch(i.beginPath(),r){case \"hexagon\":ai(i,o,6,t,-30);break;case \"diamond\":i.moveTo(o.x,o.y-t),i.lineTo(o.x+t,o.y),i.lineTo(o.x,o.y+t),i.lineTo(o.x-t,o.y),i.closePath();break;case \"pentagon\":ai(i,o,5,t,-90);break;case \"rounded-rect\":case \"blob\":{let s=t/2,a=Math.max(0,Math.min(n,s)),d=o.x-s,l=o.y-s,u=s*2,c=s*2;i.moveTo(d+a,l),i.lineTo(d+u-a,l),i.quadraticCurveTo(d+u,l,d+u,l+a),i.lineTo(d+u,l+c-a),i.quadraticCurveTo(d+u,l+c,d+u-a,l+c),i.lineTo(d+a,l+c),i.quadraticCurveTo(d,l+c,d,l+c-a),i.lineTo(d,l+a),i.quadraticCurveTo(d,l,d+a,l),i.closePath();break}case \"circle\":i.ellipse(o.x,o.y,t,t,0,0,Math.PI*2);break}}function ai(i,e,t,n,o){let r=360/t;for(let s=0;s<t;s++){let a=(o+s*r)*Math.PI/180,d=e.x+n*Math.cos(a),l=e.y+n*Math.sin(a);s===0?i.moveTo(d,l):i.lineTo(d,l);}i.closePath();}function Zs(i,e){switch(i.kind){case \"backbone\":case \"branch\":return e.defaultStroke;case \"cross-polymer\":return e.crossPolymerBondColor;case \"hbond\":return ta(i)?e.hbondColor:e.nonCanonicalHbondColor;case \"group\":return e.defaultStroke}}function Qs(i){return $n}var ea=[[\"A\",\"T\"],[\"A\",\"U\"],[\"G\",\"C\"]];function ta(i){if(i.a1.biotype!==g.BASE||i.a2.biotype!==g.BASE)return false;let e=li(i.a1),t=li(i.a2);for(let[n,o]of ea)if(e===n&&t===o||e===o&&t===n)return true;return false}function li(i){let e=i.monomer?.naturalAnalog,t=e!==void 0&&e!==\"\"?e:i.symbol;return t.length===0?\"\":t.charAt(0).toUpperCase()}function fe(i){let e=new Map,t=new Map;for(let o of i.bonds){let r=o.a1.id,s=o.a2.id,a=t.get(r);a===void 0&&(a=[],t.set(r,a)),a.push(o);let d=t.get(s);d===void 0&&(d=[],t.set(s,d)),d.push(o);}for(let o of i.atoms)ci(e,o,t.get(o.id)??[]);for(let o of i.groups){if(o.kind!==\"bracket\")continue;let r=o.repeat?.min??1;if(r===1)continue;let s=new Set(o.members.map(d=>d.target)),a=new Map;for(let d of i.atoms){if(!s.has(d.bio.chainId))continue;let l=new Map;ci(l,d,t.get(d.id)??[]);for(let[u,c]of l)a.set(u,(a.get(u)??0)+c*(r-1));}for(let[d,l]of a)e.set(d,(e.get(d)??0)+l);}for(let[o,r]of [...e])r===0&&e.delete(o);let n=ia(e);return {elements:e,mw:n}}var na={H:1.008,C:12.011,N:14.007,O:15.999,F:18.998,Na:22.99,Mg:24.305,P:30.974,S:32.06,Cl:35.45,K:39.098,Ca:40.078,Br:79.904,I:126.904,Fe:55.845,Zn:65.38,Cu:63.546},oa={C:4,N:3,O:2,S:2,P:3,F:1,Cl:1,Br:1,I:1,H:1};function ia(i){let e=0;for(let[t,n]of i){let o=na[t];o!==void 0&&(e+=o*n);}return Math.round(e*1e3)/1e3}function ci(i,e,t){if(e.monomer===null)return;let n=sa(e.monomer);for(let[o,r]of n.elements)i.set(o,(i.get(o)??0)+r);for(let o of t){if(o.kind===\"hbond\"||o.kind===\"group\")continue;let r=o.a1.id===e.id?o.r1:o.r2,s=ra(e.monomer,r);if(s===void 0)continue;let a=mi(s);for(let[d,l]of a)i.set(d,(i.get(d)??0)-l);}}function ra(i,e){if(e.kind!==\"numeric\"&&e.kind!==\"positional\")return;let t=(e.kind===\"numeric\",e.r);for(let n of i.rgroups){let o=/^R([1-9][0-9]*)$/.exec(n.label);if(o!==null&&parseInt(o[1],10)===t)return n.capGroupName}}function mi(i){let e=new Map;switch(i){case \"H\":e.set(\"H\",1);break;case \"OH\":e.set(\"H\",1),e.set(\"O\",1);break;}return e}var ui=new WeakMap;function sa(i){let e=ui.get(i);if(e!==void 0)return e;let t=aa(i);return ui.set(i,t),t}function aa(i){let e=new Map;if(i.molfile===void 0||i.molfile===\"\")return {elements:e};let t=la(i.molfile);if(t===null)return {elements:e};let{atoms:n,bondOrders:o}=t;for(let r=0;r<n.length;r++){let s=n[r];if(s===\"R\"||s===\"R#\"||s===\"*\")continue;e.set(s,(e.get(s)??0)+1);let a=oa[s];if(a===void 0)continue;let d=o[r]??0,l=a-d;l>0&&e.set(\"H\",(e.get(\"H\")??0)+l);}for(let r of i.rgroups){let s=r.capGroupName;if(s===void 0)continue;let a=mi(s);for(let[d,l]of a)e.set(d,(e.get(d)??0)+l);}return {elements:e}}function la(i){let e=i.split(/\\r\\n|\\n|\\r/);if(e.length<5)return null;let t=e[3];if(t===void 0||t.length<6)return null;let n=parseInt(t.slice(0,3),10),o=parseInt(t.slice(3,6),10);if(!Number.isFinite(n)||!Number.isFinite(o)||e.length<4+n+o)return null;let r=[];for(let a=0;a<n;a++){let d=e[4+a];if(d===void 0)return null;let l=d.slice(31,34).trim();r.push(l);}let s=new Array(n).fill(0);for(let a=0;a<o;a++){let d=e[4+n+a];if(d===void 0)return null;let l=parseInt(d.slice(0,3),10),u=parseInt(d.slice(3,6),10),c=parseInt(d.slice(6,9),10);if(!Number.isFinite(l)||!Number.isFinite(u)||!Number.isFinite(c))continue;let m=c===4?1:c;l>=1&&l<=n&&(s[l-1]=(s[l-1]??0)+m),u>=1&&u<=n&&(s[u-1]=(s[u-1]??0)+m);}return {atoms:r,bondOrders:s}}function De(i){return fe(i).mw}var Fn={W:5.5,Y:1.49,C:.0625},da={AA:13.65,AC:10.67,AG:12.79,AU:12.14,CA:10.67,CC:7.52,CG:9.39,CU:8.37,GA:12.79,GC:9.39,GG:11.77,GU:10.21,UA:12.14,UC:8.37,UG:10.21,UU:8.99},pi={A:15.4,C:7.4,G:11.7,U:10,T:8.8};function Oe(i){let e=0;for(let t of i.chains)t.polymerType===\"PEPTIDE\"?e+=ca(t.backboneAtoms):t.polymerType===\"RNA\"&&(e+=ua(t.backboneAtoms));return Math.round(e*1e4)/1e4}function ca(i){let e=0,t=0,n=0;for(let o of i){let r=hi(o);r===\"W\"?e++:r===\"Y\"?t++:r===\"C\"&&n++;}return Fn.W*e+Fn.Y*t+Fn.C*n}function ua(i){let e=[];for(let o of i)if(o.branchAtom!==void 0&&o.branchAtom.biotype===g.BASE){let r=hi(o.branchAtom);r===\"T\"&&(r=\"U\"),r!==\"\"&&e.push(r);}if(e.length===0)return 0;if(e.length===1){let o=e[0];return pi[o]??0}let t=0;for(let o=0;o<e.length-1;o++){let r=e[o],s=e[o+1],a=da[r+s];a!==void 0&&(t+=a);}let n=0;for(let o=1;o<e.length-1;o++){let r=e[o];n+=pi[r]??0;}return 2*t-n}function hi(i){let e=i.monomer;return e!==null&&e.naturalAnalog!==void 0&&e.naturalAnalog!==\"\"?e.naturalAnalog.charAt(0).toUpperCase():i.symbol===\"\"?\"\":i.symbol.charAt(0).toUpperCase()}function Dt(i){let e=[];e.push(\"HWE pseudo-molfile\"),e.push(\" HWE 2D\"),e.push(\"\");let t=i.atoms.length,n=i.bonds.length;e.push(ma(t,n));for(let r of i.atoms)e.push(pa(r));let o=new Map;for(let r=0;r<i.atoms.length;r++)o.set(i.atoms[r].id,r+1);for(let r of i.bonds){let s=o.get(r.a1.id),a=o.get(r.a2.id);s===void 0||a===void 0||e.push(ha(s,a));}return e.push(\"M END\"),e.join(`\n`)+`\n`}function ma(i,e){return Ne(i)+Ne(e)+\" 0 0 0 0 0 0 0 0999 V2000\"}function pa(i){let e=fa(i);return Gn(i.p.x)+Gn(i.p.y)+Gn(0)+\" \"+ba(e,3)+\" 0 0 0 0 0 0 0 0 0 0 0 0\"}function ha(i,e){return Ne(i)+Ne(e)+Ne(1)+Ne(0)}function fa(i){let e=i.monomer;return e!==null&&e.symbol!==\"\"?e.symbol:i.symbol!==\"\"?i.symbol:e!==null&&e.naturalAnalog!==void 0&&e.naturalAnalog!==\"\"?e.naturalAnalog:\"X\"}function Ne(i){let e=String(i);return e.length>=3?e:\" \".repeat(3-e.length)+e}function ba(i,e){return i.length>=e?i:i+\" \".repeat(e-i.length)}function Gn(i){let e=i.toFixed(4);return e.length>=10?e.slice(0,10):\" \".repeat(10-e.length)+e}var ya=new Map;function ga(i){return `${i.mode}|${i.resolveMonomers?1:0}|${i.helm}`}function _a(i){let e=i.chains.map(o=>`${o.id}:${o.polymerType}:${o.backboneAtoms.length}`).join(\",\"),t=i.atoms.map(o=>`${o.id}@${o.symbol}@${o.bio.chainId}`).join(\";\"),n=i.bonds.map(o=>`${o.id}:${o.a1.id}-${o.a2.id}:${o.kind}`).join(\";\");return `${e}#${t}#${n}`}var va=256,Vn=class{constructor(e){this._destroyed=false;this._parseHits=0;this._parseMisses=0;this._layoutHits=0;this._layoutMisses=0;this._renderHits=0;this._renderMisses=0;if(e.monomerLib===void 0||e.monomerLib===null)throw new TypeError(\"HelmService: options.monomerLib is required\");this.monomerLib=e.monomerLib,this.theme=e.theme??$,this.logger=e.logger??new Ce,this.options=Object.freeze({...e});let t=e.cacheSize??va;this._parseCache=new Ee({max:t}),this._layoutCache=new Ee({max:t}),this._renderCache=new Ee({max:t}),this._libUnsub=this.monomerLib.onChanged.subscribe(()=>{this.clearCaches();});}parse(e,t){this._ensureLive(),e=this._normalizeHelm(e);let n=t?.mode??\"lenient\",o=t?.resolveMonomers!==false,r=ga({mode:n,resolveMonomers:o,helm:e}),s=this._parseCache.get(r);if(s!==void 0)return this._parseHits+=1,s;this._parseMisses+=1;let a={mode:n,resolveMonomers:o},d=ot(e,this.monomerLib,a),l={mol:d.mol,diagnostics:Object.freeze([...d.diagnostics])};return this._parseCache.set(r,l),l}serialize(e,t){this._ensureLive();let n={...t?.canonicalize!==void 0?{canonicalize:t.canonicalize}:{},...t?.includeHighlights!==void 0?{includeHighlights:t.includeHighlights}:{},...t?.version!==void 0?{version:t.version}:{}};return Pe(e,n)}validate(e,t){this._ensureLive(),e=this._normalizeHelm(e);let{mol:n,diagnostics:o}=this.parse(e,{mode:\"lenient\"}),r=t?.mode!==void 0?{mode:t.mode}:{},s=wn(n,this.monomerLib,r);return [...o,...s]}canonicalize(e){this._ensureLive(),e=this._normalizeHelm(e);let{mol:t}=this.parse(e,{mode:\"lenient\"}),n=vn(t);return Pe(n,{canonicalize:true,version:\"V2.0\"})}removeGaps(e){return this._ensureLive(),xn(this._normalizeHelm(e),this.monomerLib)}renderToSvg(e,t){this._ensureLive(),e=this._normalizeHelm(e);let n=this._resolveRenderOptions(t),o=this._renderKey(e,n),r=this._renderCache.get(o);if(r!==void 0)return this._renderHits+=1,r;this._renderMisses+=1;let{mol:s}=this.parse(e,{mode:\"lenient\"}),a=this._layout(s,n.bondLength),{svg:d}=Ht(a,n);return this._renderCache.set(o,d),d}renderMol(e,t){this._ensureLive();let n=this._resolveRenderOptions(t),{svg:o}=Ht(e,n);return o}renderMolResult(e,t){this._ensureLive();let n=this._resolveRenderOptions(t);return Ht(e,n)}async renderToPng(e,t){if(this._ensureLive(),e=this._normalizeHelm(e),typeof globalThis.OffscreenCanvas!=\"function\")throw new j(\"png-rendering-requires-browser\",\"HelmService.renderToPng requires OffscreenCanvas (browser-only).\");let n=this._resolveRenderOptions(t),{mol:o}=this.parse(e,{mode:\"lenient\"}),r=this._layout(o,n.bondLength);return di(r,n)}renderToCanvas(e,t,n,o){this._ensureLive(),t=this._normalizeHelm(t);let r=this._resolveRenderOptions(o),{mol:s}=this.parse(t,{mode:\"lenient\"}),a=this._layout(s,r.bondLength),{bbox:d,drawBox:l}=$t(e,a,n,r);return {mol:a,bbox:d,drawBox:l}}renderMolToCanvas(e,t,n,o){this._ensureLive();let r=this._resolveRenderOptions(o),{bbox:s,drawBox:a}=$t(e,t,n,r);return {mol:t,bbox:s,drawBox:a}}*renderMany(e,t){for(let n of e??[]){let o=this.renderToSvg(n.helm,t);yield {id:n.id,svg:o};}}getFormula(e){this._ensureLive();let{mol:t}=this.parse(this._normalizeHelm(e),{mode:\"lenient\"});return fe(t)}getMolWeight(e){this._ensureLive();let{mol:t}=this.parse(this._normalizeHelm(e),{mode:\"lenient\"});return De(t)}getExtinctionCoefficient(e){this._ensureLive();let{mol:t}=this.parse(this._normalizeHelm(e),{mode:\"lenient\"});return Oe(t)}getMolfile(e){this._ensureLive();let{mol:t}=this.parse(this._normalizeHelm(e),{mode:\"lenient\"});return Dt(t)}hasAtomicMolfileProvider(){return typeof this.options.atomicMolfileProvider==\"function\"}async getAtomicMolfile(e){this._ensureLive(),e=this._normalizeHelm(e);let t=this.options.atomicMolfileProvider;if(typeof t!=\"function\")throw new j(\"atomic-molfile-not-configured\",\"Set HelmServiceOptions.atomicMolfileProvider to enable atomic-level expansion.\");return await t(e,this.monomerLib)}hasExtraPanes(){let e=this.options.extraPanes;return e!==void 0&&e.size>0}getExtraPanes(){return this.options.extraPanes??ya}invalidate(e){if(e===void 0){this.clearCaches();return}for(let t of [this._parseCache,this._layoutCache,this._renderCache]){let n=[];for(let o of t.keys())e(o)&&n.push(o);for(let o of n)t.delete(o);}}clearCaches(){this._parseCache.clear(),this._layoutCache.clear(),this._renderCache.clear(),this._parseHits=0,this._parseMisses=0,this._layoutHits=0,this._layoutMisses=0,this._renderHits=0,this._renderMisses=0;}destroy(){this._destroyed||(this._destroyed=true,this._libUnsub(),this.clearCaches());}_ensureLive(){if(this._destroyed)throw new j(\"service-destroyed\",\"HelmService instance has been destroyed.\")}_normalizeHelm(e){return e==null?\"\":typeof e==\"string\"?e:String(e)}_resolveRenderOptions(e){let t={},n=e?.theme??this.theme;return t.theme=n,e?.width!==void 0&&(t.width=e.width),e?.height!==void 0&&(t.height=e.height),e?.backColor!==void 0&&(t.backColor=e.backColor),e?.padding!==void 0&&(t.padding=e.padding),e?.showIds!==void 0&&(t.showIds=e.showIds),e?.showAnnotations!==void 0&&(t.showAnnotations=e.showAnnotations),e?.bondLength!==void 0&&(t.bondLength=e.bondLength),e?.fontSize!==void 0&&(t.fontSize=e.fontSize),e?.maxScale!==void 0&&(t.maxScale=e.maxScale),e?.showRGroupLabels!==void 0&&(t.showRGroupLabels=e.showRGroupLabels),e?.selectedAtomIds!==void 0&&(t.selectedAtomIds=e.selectedAtomIds),e?.highlightedAtomIds!==void 0&&(t.highlightedAtomIds=e.highlightedAtomIds),e?.fixedModelBbox!==void 0&&(t.fixedModelBbox=e.fixedModelBbox),t}_renderKey(e,t){let o=(t.theme??this.theme).name,r=this._libCacheTag(),s=t.width??0,a=t.height??0,d=t.padding??-1,l=t.bondLength??-1,u=t.backColor??\"\",c=t.showIds===true?1:0,m=t.showAnnotations===false?0:1,p=t.maxScale??1;return `${r}|${o}|${s}x${a}|p${d}|b${l}|bg${u}|i${c}a${m}|s${p}|${e}`}_layout(e,t){let n=_a(e),o=`${this._libCacheTag()}|${t??\"d\"}|${n}`,r=this._layoutCache.get(o);if(r!==void 0)return this._layoutHits+=1,r;this._layoutMisses+=1;let s=t!==void 0?oe(e,{bondLength:t}):oe(e);return this._layoutCache.set(o,s),s}get stats(){return {parseHits:this._parseHits,parseMisses:this._parseMisses,layoutHits:this._layoutHits,layoutMisses:this._layoutMisses,renderHits:this._renderHits,renderMisses:this._renderMisses}}_libCacheTag(){let e=this.monomerLib,t=typeof e.version==\"number\"?e.version:0;return `${this.monomerLib.source}@${t}`}};var Q=class{constructor(e,t){this.atoms=e,this.bonds=t,this.isEmpty=e.size===0&&t.size===0,Object.freeze(this);}},fi=new Q(new Set,new Set),V={empty(){return fi},fromAtoms(i){return new Q(new Set(i),new Set)},fromBonds(i){return new Q(new Set,new Set(i))},fromAtomsAndBonds(i,e){return new Q(new Set(i),new Set(e))},union(...i){if(i.length===0)return fi;let e=new Set,t=new Set;for(let n of i){for(let o of n.atoms)e.add(o);for(let o of n.bonds)t.add(o);}return new Q(e,t)},difference(i,e){let t=new Set,n=new Set;for(let o of i.atoms)e.atoms.has(o)||t.add(o);for(let o of i.bonds)e.bonds.has(o)||n.add(o);return new Q(t,n)},intersect(i,e){let t=new Set,n=new Set;for(let o of i.atoms)e.atoms.has(o)&&t.add(o);for(let o of i.bonds)e.bonds.has(o)&&n.add(o);return new Q(t,n)},toggle(i,e){if(e.kind===\"atom\"){let n=new Set(i.atoms);return n.has(e.id)?n.delete(e.id):n.add(e.id),new Q(n,new Set(i.bonds))}let t=new Set(i.bonds);return t.has(e.id)?t.delete(e.id):t.add(e.id),new Q(new Set(i.atoms),t)},hasAtom(i,e){return i.atoms.has(e)},hasBond(i,e){return i.bonds.has(e)},equals(i,e){if(i===e)return true;if(i.atoms.size!==e.atoms.size||i.bonds.size!==e.bonds.size)return false;for(let t of i.atoms)if(!e.atoms.has(t))return false;for(let t of i.bonds)if(!e.bonds.has(t))return false;return true}};function be(i){let e=i.monomer;return e===null?0:e.rgroups.length}function bi(i,e){let t=new Set;for(let r of e)r.a1.id===i.id&&r.r1.kind===\"numeric\"&&t.add(r.r1.r),r.a2.id===i.id&&r.r2.kind===\"numeric\"&&t.add(r.r2.r);let n=[],o=Array.from(t).sort((r,s)=>r-s);for(let r of o)n.push(r);return n}function W(i,e){let t=be(i);if(t===0)return [];let n=new Set(bi(i,e)),o=[];for(let r=1;r<=t;r++)n.has(r)||o.push(r);return o}function xa(i,e){return W(i,e).length>0}function Ot(i,e){let t=[];for(let n of e)if(n.a1.id===i.id){let o=n.r1.kind===\"numeric\"?n.r1.r:0;t.push({bond:n,side:\"r1\",rNumber:o});}else if(n.a2.id===i.id){let o=n.r2.kind===\"numeric\"?n.r2.r:0;t.push({bond:n,side:\"r2\",rNumber:o});}return t}function wa(i){switch(i){case g.AA:return x.PEPTIDE;case g.SUGAR:case g.BASE:case g.LINKER:case g.NUCLEOTIDE:return x.RNA;case g.CHEM:return x.CHEM;case g.BLOB:return x.BLOB}}function ka(i){switch(i){case x.PEPTIDE:return \"PEPTIDE\";case x.RNA:return \"RNA\";case x.CHEM:return \"CHEM\";case x.BLOB:return \"BLOB\";case x.G:return \"G\"}}function Aa(i){let e=0;for(let t of i.atoms)t.id>e&&(e=t.id);for(let t of i.bonds)t.id>e&&(e=t.id);return e}function Nt(i,e){return i.kind!==e.kind?false:i.kind===\"numeric\"&&e.kind===\"numeric\"?i.r===e.r:i.kind===\"positional\"&&e.kind===\"positional\"?i.position===e.position&&i.r===e.r:true}var N=class{constructor(e){this._atoms=new Map;this._atomOrder=[];this._bonds=new Map;this._bondOrder=[];this._chains=new Map;this._chainOrder=[];this._addedAtoms=new Set;this._removedAtoms=new Set;this._modifiedAtoms=new Set;this._addedBonds=new Set;this._removedBonds=new Set;this._modifiedBonds=new Set;this._topologyDirty=false;this._idgen=new ve;let t=Aa(e);for(let n=0;n<t;n++)this._idgen.next();for(let n of e.chains)this._chains.set(n.id,{id:n.id,polymerType:n.polymerType,backboneAtomIds:n.backboneAtoms.map(o=>o.id),bondIds:n.bonds.map(o=>o.id),annotation:n.annotation}),this._chainOrder.push(n.id);for(let n of e.atoms)this._atoms.set(n.id,{id:n.id,p:{x:n.p.x,y:n.p.y},biotype:n.biotype,symbol:n.symbol,monomer:n.monomer,bio:{...n.bio},hidden:n.hidden,selected:n.selected,highlighted:n.highlighted,tag:n.tag,branchAtomId:n.branchAtom?.id,inlineSource:n.inlineSource}),this._atomOrder.push(n.id);for(let n of e.bonds)this._bonds.set(n.id,{id:n.id,a1Id:n.a1.id,a2Id:n.a2.id,kind:n.kind,r1:n.r1,r2:n.r2,ratio:n.ratio,tag:n.tag}),this._bondOrder.push(n.id);this._groups=[...e.groups],this._annotations=e.annotations;}addAtom(e){let t=this._idgen.next(),n=wa(e.biotype),o=e.chainId??this._pickChainId(n),r=this._chains.get(o);r===void 0&&(r={id:o,polymerType:n,backboneAtomIds:[],bondIds:[],annotation:void 0},this._chains.set(o,r),this._chainOrder.push(o));let s=e.positionInChain??r.backboneAtomIds.length+1,a={id:t,p:{x:e.p.x,y:e.p.y},biotype:e.biotype,symbol:e.symbol,monomer:null,bio:{chainId:o,positionInChain:s,continuousId:0},hidden:false,selected:false,highlighted:false,tag:void 0,branchAtomId:void 0,inlineSource:void 0};this._atoms.set(t,a),this._atomOrder.push(t);let d=Math.max(0,Math.min(s-1,r.backboneAtomIds.length));return r.backboneAtomIds.splice(d,0,t),this._addedAtoms.add(t),this._topologyDirty=true,t}removeAtom(e){let t=this._atoms.get(e);if(t===void 0)return;let n=[];for(let s of this._bonds.values())(s.a1Id===e||s.a2Id===e)&&n.push(s.id);for(let s of n)this._removeBondInternal(s);for(let s of this._atoms.values())s.branchAtomId===e&&(s.branchAtomId=void 0);let o=this._chains.get(t.bio.chainId);if(o!==void 0){let s=o.backboneAtomIds.indexOf(e);s>=0&&o.backboneAtomIds.splice(s,1);}this._atoms.delete(e);let r=this._atomOrder.indexOf(e);r>=0&&this._atomOrder.splice(r,1),this._addedAtoms.has(e)?this._addedAtoms.delete(e):this._removedAtoms.add(e),this._modifiedAtoms.delete(e),this._topologyDirty=true;}updateAtom(e,t){let n=this._atoms.get(e);n!==void 0&&(t.p!==void 0&&(n.p={x:t.p.x,y:t.p.y}),t.symbol!==void 0&&(n.symbol=t.symbol),t.selected!==void 0&&(n.selected=t.selected),t.highlighted!==void 0&&(n.highlighted=t.highlighted),\"tag\"in t&&(n.tag=t.tag),t.hidden!==void 0&&(n.hidden=t.hidden),this._addedAtoms.has(e)||this._modifiedAtoms.add(e));}addBond(e){if(!this._atoms.has(e.a1))throw new Error(`Transaction.addBond: atom ${e.a1} does not exist`);if(!this._atoms.has(e.a2))throw new Error(`Transaction.addBond: atom ${e.a2} does not exist`);for(let r of this._bonds.values()){let s=r.a1Id===e.a1&&r.a2Id===e.a2&&Nt(r.r1,e.r1)&&Nt(r.r2,e.r2),a=r.a1Id===e.a2&&r.a2Id===e.a1&&Nt(r.r1,e.r2)&&Nt(r.r2,e.r1);if(s||a)throw new Error(`Transaction.addBond: duplicate bond ${e.a1}:${yi(e.r1)}-${e.a2}:${yi(e.r2)}`)}let t=this._idgen.next();this._bonds.set(t,{id:t,a1Id:e.a1,a2Id:e.a2,kind:e.kind,r1:e.r1,r2:e.r2,ratio:void 0,tag:void 0}),this._bondOrder.push(t);let n=this._atoms.get(e.a1),o=this._atoms.get(e.a2);if(n!==void 0&&o!==void 0&&n.bio.chainId===o.bio.chainId){let r=this._chains.get(n.bio.chainId);r!==void 0&&r.bondIds.push(t);}return this._addedBonds.add(t),this._topologyDirty=true,t}removeBond(e){this._bonds.has(e)&&(this._removeBondInternal(e),this._topologyDirty=true);}updateBond(e,t){let n=this._bonds.get(e);n!==void 0&&(\"tag\"in t&&(n.tag=t.tag),\"ratio\"in t&&(n.ratio=t.ratio),this._addedBonds.has(e)||this._modifiedBonds.add(e));}commit(){let e=new Map;for(let d of this._atomOrder){let l=this._atoms.get(d);if(l===void 0)continue;let u={id:l.id,p:{x:l.p.x,y:l.p.y},biotype:l.biotype,symbol:l.symbol,monomer:l.monomer,bio:{...l.bio},hidden:l.hidden,selected:l.selected,highlighted:l.highlighted,...l.tag!==void 0?{tag:l.tag}:{},...l.inlineSource!==void 0?{inlineSource:l.inlineSource}:{}};e.set(d,u);}for(let d of this._atomOrder){let l=this._atoms.get(d);if(l===void 0||l.branchAtomId===void 0)continue;let u=e.get(d),c=e.get(l.branchAtomId);u===void 0||c===void 0||(u.branchAtom=c);}let t=new Map;for(let d of this._bondOrder){let l=this._bonds.get(d);if(l===void 0)continue;let u=e.get(l.a1Id),c=e.get(l.a2Id);if(u===void 0||c===void 0)continue;let m={id:l.id,a1:u,a2:c,kind:l.kind,r1:l.r1,r2:l.r2,...l.ratio!==void 0?{ratio:{...l.ratio}}:{},...l.tag!==void 0?{tag:l.tag}:{}};t.set(d,m);}let n=[];for(let d of this._chainOrder){let l=this._chains.get(d);if(l===void 0||l.backboneAtomIds.length===0&&l.bondIds.length===0)continue;let u=[];for(let m of l.backboneAtomIds){let p=e.get(m);p!==void 0&&u.push(p);}let c=[];for(let m of l.bondIds){let p=t.get(m);p!==void 0&&c.push(p);}n.push({id:l.id,polymerType:l.polymerType,backboneAtoms:u,bonds:c,...l.annotation!==void 0?{annotation:l.annotation}:{}});}let o=this._atomOrder.map(d=>e.get(d)).filter(d=>d!==void 0),r=this._bondOrder.map(d=>t.get(d)).filter(d=>d!==void 0),s={atoms:o,bonds:r,chains:n,groups:[...this._groups],annotations:this._annotations};this._topologyDirty&&(s=Ma(s));let a=Object.freeze({addedAtomIds:new Set(this._addedAtoms),removedAtomIds:new Set(this._removedAtoms),addedBondIds:new Set(this._addedBonds),removedBondIds:new Set(this._removedBonds),modifiedAtomIds:new Set(this._modifiedAtoms),modifiedBondIds:new Set(this._modifiedBonds)});return this._addedAtoms.clear(),this._removedAtoms.clear(),this._modifiedAtoms.clear(),this._addedBonds.clear(),this._removedBonds.clear(),this._modifiedBonds.clear(),this._topologyDirty=false,{mol:s,changes:a}}_removeBondInternal(e){if(this._bonds.get(e)===void 0)return;this._bonds.delete(e);let n=this._bondOrder.indexOf(e);n>=0&&this._bondOrder.splice(n,1);for(let o of this._chains.values()){let r=o.bondIds.indexOf(e);r>=0&&o.bondIds.splice(r,1);}this._addedBonds.has(e)?this._addedBonds.delete(e):this._removedBonds.add(e),this._modifiedBonds.delete(e);}_pickChainId(e){let t=ka(e),n=1;for(;this._chains.has(`${t}${n}`);)n+=1;return `${t}${n}`}};function yi(i){switch(i.kind){case \"numeric\":return `R${i.r}`;case \"unspecified\":return \"?\";case \"wildcard\":return \"*\";case \"pair\":return \"pair\";case \"positional\":return `${i.position}pos:R${i.r}`}}function Ma(i){let e=Le(i),t=new Map;for(let a of i.atoms){let d=e.get(a.id);if(d===void 0||d===a.bio.continuousId){t.set(a.id,a);continue}t.set(a.id,{...a,bio:{...a.bio,continuousId:d}});}for(let a of i.atoms){if(a.branchAtom===void 0)continue;let d=t.get(a.id),l=t.get(a.branchAtom.id);d===void 0||l===void 0||(d.branchAtom=l);}let n=i.bonds.map(a=>{let d=t.get(a.a1.id),l=t.get(a.a2.id);return d===void 0||l===void 0||d===a.a1&&l===a.a2?a:{...a,a1:d,a2:l}}),o=new Map;for(let a of n)o.set(a.id,a);let r=i.chains.map(a=>{let d=[];for(let u of a.backboneAtoms)d.push(t.get(u.id)??u);let l=[];for(let u of a.bonds)l.push(o.get(u.id)??u);return {id:a.id,polymerType:a.polymerType,backboneAtoms:d,bonds:l,...a.annotation!==void 0?{annotation:a.annotation}:{}}});return {atoms:i.atoms.map(a=>t.get(a.id)??a),bonds:n,chains:r,groups:i.groups,annotations:i.annotations}}var q=class{constructor(e,t,n){this.atoms=[];this.bonds=[];this.bondHitWidth=n?.bondHitWidth??4,this.rebuild(e,t);}rebuild(e,t){let n=[];for(let r of e.atoms)r.hidden||n.push({atom:r,bbox:pe(r,t),hitRadius:oi(r,t)});let o=[];for(let r of e.bonds)o.push({bond:r,a:r.a1.p,b:r.a2.p});this.atoms=n,this.bonds=o;}test(e){let t=null,n=null;for(let r of this.atoms){if(!Ft(e,r.bbox))continue;let s=e.x-r.atom.p.x,a=e.y-r.atom.p.y,d=Math.sqrt(s*s+a*a);d>r.hitRadius||(t===null||d<t.d?(n=t,t={entry:r,d}):(n===null||d<n.d)&&(n={entry:r,d}));}if(t!==null)return {atom:t.entry.atom};let o=null;for(let r of this.bonds){let s=Ta(e,r.a,r.b);s>this.bondHitWidth||(o===null||s<o.d)&&(o={entry:r,d:s});}return o!==null?{bond:o.entry.bond}:null}testRect(e){let t=[];for(let o of this.atoms)Ft(o.atom.p,e)&&t.push(o.atom);let n=[];for(let o of this.bonds)Ft(o.a,e)&&Ft(o.b,e)&&n.push(o.bond);return {atoms:t,bonds:n}}atomCount(){return this.atoms.length}bondCount(){return this.bonds.length}};function Ft(i,e){return i.x>=e.x&&i.x<=e.x+e.width&&i.y>=e.y&&i.y<=e.y+e.height}function Ta(i,e,t){let n=t.x-e.x,o=t.y-e.y,r=n*n+o*o;if(r===0){let c=i.x-e.x,m=i.y-e.y;return Math.sqrt(c*c+m*m)}let s=((i.x-e.x)*n+(i.y-e.y)*o)/r;s<0?s=0:s>1&&(s=1);let a=e.x+s*n,d=e.y+s*o,l=i.x-a,u=i.y-d;return Math.sqrt(l*l+u*u)}var Fe=class{constructor(){this._handlers=new Map;}on(e,t){let n=this._handlers.get(e);n===void 0&&(n=new Set,this._handlers.set(e,n));let o=t;return n.add(o),()=>{let r=this._handlers.get(e);r!==void 0&&r.delete(o);}}off(e,t){let n=this._handlers.get(e);n!==void 0&&n.delete(t);}fire(e,t){let n=this._handlers.get(e);if(n===void 0||n.size===0)return;let o=[...n];for(let r of o)r(t);}clear(){this._handlers.clear();}observerCount(e){if(e===void 0){let t=0;for(let n of this._handlers.values())t+=n.size;return t}return this._handlers.get(e)?.size??0}};var Ge=class{constructor(e){this._entries=[];this._idx=-1;let t=e?.maxEntries??100;if(t<=0)throw new RangeError(\"HistoryStack: maxEntries must be > 0\");this._max=t;}push(e){for(this._idx<this._entries.length-1&&(this._entries=this._entries.slice(0,this._idx+1)),this._entries.push(e),this._idx=this._entries.length-1;this._entries.length>this._max;)this._entries.shift(),this._idx-=1;}canUndo(){return this._idx>0}canRedo(){return this._idx>=0&&this._idx<this._entries.length-1}undo(){return this.canUndo()?(this._idx-=1,this._entries[this._idx]??null):null}redo(){return this.canRedo()?(this._idx+=1,this._entries[this._idx]??null):null}clear(){this._entries=[],this._idx=-1;}get size(){return this._entries.length}current(){return this._idx<0?null:this._entries[this._idx]??null}};function gi(i,e={}){let t=e.theme??$,n=e.selectedAtomIds??new Set,o=e.highlightedAtomIds??new Set;return {highlightLayer:On(i,t,o),selectionLayer:Nn(i,t,n)}}function S(i){let e=i.ownerDocument;if(e!=null)return e;let t=globalThis;if(t.document!==void 0)return t.document;throw new Error(\"EditorView: no Document available (host.ownerDocument is null).\")}function v(i,e,t,n){let o=i.createElement(e);if(t!==void 0)for(let r of Object.keys(t)){let s=t[r];s===false||s===void 0||o.setAttribute(r,s===true?\"\":String(s));}if(n!==void 0)for(let r of n)typeof r==\"string\"?o.appendChild(i.createTextNode(r)):o.appendChild(r);return o}function _i(i){let e=S(i);if(e.querySelector(\"style[data-hw-editor-view-styles]\")!==null)return;let n=e.createElement(\"style\");n.setAttribute(\"data-hw-editor-view-styles\",\"\"),n.textContent=\".hw-editor-view{position:relative;display:block;overflow:hidden;outline:none;}.hw-editor-view svg{display:block;user-select:none;}.hw-editor-view.hw-view-only{cursor:default;}\";let o=e.head??e.documentElement;o!==null&&o.appendChild(n);}function vi(i,e){let t=S(i),n=i.querySelector(\".hw-editor-view\");if(n===null)throw new Error(\"EditorView.replaceSvg: missing .hw-editor-view wrapper.\");let o=t.createElement(\"div\");o.innerHTML=e;let r=o.querySelector(\"svg\");if(r===null)throw new Error(\"EditorView.replaceSvg: rendered output contained no <svg>.\");for(;n.firstChild!==null;)n.removeChild(n.firstChild);return n.appendChild(r),r}function ye(i,e,t=220,n=140){if(i==null||e===\"\")return null;try{let o=i.get_mol(e);if(o===null)return null;let r=o.get_svg(t,n);return o.delete(),r}catch{return null}}function ie(i,e,t){let n=\"data-testid\";for(let r=0;r<i.body.children.length;r++){let s=i.body.children[r];if(s!==void 0&&s.getAttribute(n)===e)return s}let o=v(i,\"div\",{class:t,[n]:e});return o.style.display=\"none\",i.body.appendChild(o),o}function Te(i,e,t){for(;e.firstChild!==null;)e.removeChild(e.firstChild);if(e.appendChild(v(i,\"div\",{class:\"hw-tooltip__symbol\"},[t.symbol])),t.name!==void 0&&t.name!==\"\"&&t.name!==t.symbol&&e.appendChild(v(i,\"div\",{class:\"hw-tooltip__name\"},[t.name])),t.rdkitSvg!==void 0&&t.rdkitSvg!==null&&t.rdkitSvg!==\"\"){let n={class:\"hw-tooltip__rdkit\"};t.rdkitTestid!==void 0&&(n[\"data-testid\"]=t.rdkitTestid);let o=v(i,\"div\",n);o.innerHTML=t.rdkitSvg,e.appendChild(o);}t.hint!==void 0&&t.hint!==\"\"&&e.appendChild(v(i,\"div\",{class:\"hw-tooltip__hint\"},[t.hint]));}function xi(i,e,t){for(;e.firstChild!==null;)e.removeChild(e.firstChild);e.appendChild(v(i,\"div\",{class:\"hw-tooltip__symbol\"},[t.title]));let n=v(i,\"div\",{class:\"hw-tooltip__triplet\"});for(let o of t.parts){let r=v(i,\"div\",{class:\"hw-tooltip__triplet-part\"});if(r.appendChild(v(i,\"div\",{class:\"hw-tooltip__triplet-role\"},[`${o.role}: ${o.symbol}`])),o.name!==void 0&&o.name!==\"\"&&o.name!==o.symbol&&r.appendChild(v(i,\"div\",{class:\"hw-tooltip__name\"},[o.name])),o.rdkitSvg!==void 0&&o.rdkitSvg!==null&&o.rdkitSvg!==\"\"){let s={class:\"hw-tooltip__rdkit\"};t.rdkitTestid!==void 0&&(s[\"data-testid\"]=t.rdkitTestid);let a=v(i,\"div\",s);a.innerHTML=o.rdkitSvg,r.appendChild(a);}n.appendChild(r);}e.appendChild(n),t.hint!==void 0&&t.hint!==\"\"&&e.appendChild(v(i,\"div\",{class:\"hw-tooltip__hint\"},[t.hint]));}function Y(i,e,t){let n=i.style;n.display=\"block\",n.left=`${e+12}px`,n.top=`${t+12}px`;}function U(i){i!==null&&(i.style.display=\"none\");}function Gt(i){let e=i.body;if(e==null)return;let t=\"data-testid\";for(let n=0;n<e.children.length;n++){let o=e.children[n];if(o===void 0)continue;let r=o.getAttribute===void 0?null:o.getAttribute(t);r!=null&&r.endsWith(\"-tooltip\")&&U(o);}}var Ut=class Ut{constructor(e,t,n){this._baseTransform=\"\";this._viewport={scale:1,offset:{x:0,y:0}};this._pinnedBbox=null;this._tooltip=null;this._bondTooltip=null;this._rdkitSvgCache=new Map;this._unsubs=[];this._destroyed=false;this.host=e,this._editor=t,this._doc=n?.documentImpl??S(e),this._width=n?.width??400,this._height=n?.height??200,_i(e);let o=this._doc.createElement(\"div\");o.setAttribute(\"class\",\"hw-editor-view\"),e.appendChild(o),this._tooltip=ie(this._doc,\"atom-tooltip\",\"hw-atom-tooltip\"),this._bondTooltip=ie(this._doc,\"bond-tooltip\",\"hw-bond-tooltip\"),this._svgRoot=this._renderFresh(),this._unsubs.push(t.on(\"mol:changed\",r=>{this._hideTooltip(),this._hideBondTooltip(),(r.reason===\"setHelm\"||r.reason===\"cleanLayout\"||r.reason===\"initial\")&&(this._pinnedBbox=null),this._renderFresh();})),this._unsubs.push(t.on(\"selection:change\",r=>{this._refreshOverlays(r);})),this._unsubs.push(t.on(\"highlight:change\",r=>{this._refreshOverlays(r);})),this._unsubs.push(t.on(\"theme:change\",()=>{this._renderFresh();})),this._unsubs.push(t.on(\"view:resize\",r=>{this._applyResize(r.width,r.height);})),this._unsubs.push(t.on(\"view:viewport-change\",r=>{this._viewport=r.viewport,this._applyViewport(r.viewport);})),this._unsubs.push(t.on(\"view:fit-to-content\",()=>{this._pinnedBbox=null,this._renderFresh();})),this._unsubs.push(t.on(\"monomer:hover\",r=>{this._showTooltip(r.atom,r.clientX,r.clientY);})),this._unsubs.push(t.on(\"monomer:hover-end\",()=>{this._hideTooltip();})),this._unsubs.push(t.on(\"bond:hover\",r=>{this._showBondTooltip(r.bond,r.clientX,r.clientY);})),this._unsubs.push(t.on(\"bond:hover-end\",()=>{this._hideBondTooltip();})),this._unsubs.push(t.on(\"bond:preview\",r=>{this._paintBondPreview(r.start.p,r.cursor,r.candidate!==null);})),this._unsubs.push(t.on(\"bond:preview-end\",()=>{this._clearBondPreview();})),this._unsubs.push(t.on(\"bond:cancel\",()=>{this._clearBondPreview();})),this._unsubs.push(t.on(\"selection:rectangle-start\",r=>{this._paintSelectionRect(r.origin,r.origin);})),this._unsubs.push(t.on(\"selection:rectangle-update\",r=>{this._paintSelectionRectFromRect(r.rect);})),this._unsubs.push(t.on(\"selection:rectangle-end\",()=>{this._clearSelectionRect();}));}get svgRoot(){return this._svgRoot}get width(){return this._width}get height(){return this._height}resize(e,t){this._destroyed||(this._width=e,this._height=t,this._renderFresh());}redraw(){this._destroyed||this._renderFresh();}destroy(){if(this._destroyed)return;this._destroyed=true;for(let t of this._unsubs)t();this._unsubs.length=0;let e=this.host.querySelector(\".hw-editor-view\");e!==null&&e.parentNode!==null&&e.parentNode.removeChild(e),U(this._tooltip),U(this._bondTooltip),this._tooltip=null,this._bondTooltip=null;}_renderFresh(){let e=this._editor.getService(),t=this._currentTheme(),n=this._editor.getMol();this._pinnedBbox===null&&(this._pinnedBbox=Dn(n,t));let o=e.renderMol(n,{width:this._width,height:this._height,theme:t,fixedModelBbox:this._pinnedBbox});this._svgRoot=vi(this.host,o);let r=this._svgRoot.querySelector(\".hw-content\");return this._baseTransform=r!==null?r.getAttribute(\"transform\")??\"\":\"\",this._svgRoot.setAttribute(\"data-testid\",\"editor-svg\"),this._applyOverlaysToCurrent(),(this._viewport.scale!==1||this._viewport.offset.x!==0||this._viewport.offset.y!==0)&&this._applyViewport(this._viewport),this._svgRoot}_refreshOverlays(e){this._applyOverlaysToCurrent();}_applyOverlaysToCurrent(){let e=this._editor.getMol(),t=this._editor.getSelection(),n=gi(e,{theme:this._currentTheme(),selectedAtomIds:t.atoms,highlightedAtomIds:this._editorHighlights()});this._spliceLayer(\"hw-highlights\",n.highlightLayer),this._spliceLayer(\"hw-selections\",n.selectionLayer);}_spliceLayer(e,t){let n=this._svgRoot.querySelector(`.${e}`);if(n===null||n.parentNode===null)return;let o=this._doc.createElementNS(\"http://www.w3.org/2000/svg\",\"svg\");o.innerHTML=t;let r=o.querySelector(`.${e}`);r!==null&&n.parentNode.replaceChild(r,n);}_editorHighlights(){let e=this._editor;return typeof e._currentHighlights==\"function\"?e._currentHighlights():new Set}_currentTheme(){let e=this._editor;return typeof e._currentTheme==\"function\"?e._currentTheme():this._editor.getService().theme}_applyResize(e,t){this._width=e,this._height=t,this._pinnedBbox=null,this._renderFresh();}_applyViewport(e){let n=this._svgRoot.querySelector(\".hw-content\");if(n===null)return;let o=`translate(${e.offset.x} ${e.offset.y}) scale(${e.scale})`,r=this._baseTransform===\"\"?o:`${o} ${this._baseTransform}`;n.setAttribute(\"transform\",r);}_showTooltip(e,t,n){let o=this._tooltip;if(o===null)return;let r=e.symbol===\"\"?\"?\":e.symbol,s=e.monomer?.name??\"\",a=e.bio.positionInChain,d=e.bio.chainId===\"\"?\"?\":e.bio.chainId,l=s!==\"\"&&s!==r?`${s} @ ${d}:${a}`:`${r} @ ${d}:${a}`,u=this._renderRdkitTooltipSvg(e);Te(this._doc,o,{symbol:r,name:l,rdkitSvg:u,rdkitTestid:\"atom-tooltip-rdkit-svg\"});let c=s!==\"\"&&s!==r?`${r} \\u2014 ${s} @ ${d}:${a}`:`${r} @ ${d}:${a}`,m=this._doc.createElement(\"div\");m.setAttribute(\"class\",\"hw-atom-tooltip__text\"),m.style.display=\"none\",m.appendChild(this._doc.createTextNode(c)),o.appendChild(m),Y(o,t,n);}_renderRdkitTooltipSvg(e){let n=this._editor.getService().options.rdkitModule;if(n==null)return null;let o=e.monomer;if(o===null)return null;let r=o.smiles;if(r===void 0||r===\"\")return null;let s=`${o.polymerType}:${o.symbol}`;if(this._rdkitSvgCache.has(s))return this._rdkitSvgCache.get(s)??null;let a=ye(n,r,220,140);if(this._rdkitSvgCache.size>=Ut._RDKIT_CACHE_LIMIT){let d=this._rdkitSvgCache.keys().next().value;d!==void 0&&this._rdkitSvgCache.delete(d);}return this._rdkitSvgCache.set(s,a),a}_hideTooltip(){U(this._tooltip);}_showBondTooltip(e,t,n){let o=this._bondTooltip;if(o===null)return;let r=wi(e.r1),s=wi(e.r2),a=`${e.a1.symbol}@${e.a1.bio.chainId}:${e.a1.bio.positionInChain}`,d=`${e.a2.symbol}@${e.a2.bio.chainId}:${e.a2.bio.positionInChain}`;Te(this._doc,o,{symbol:`${r}-${s} (${e.kind})`,name:`${a} \\u2194 ${d}`}),Y(o,t,n);}_hideBondTooltip(){U(this._bondTooltip);}_paintBondPreview(e,t,n){let o=\"http://www.w3.org/2000/svg\",r=this._svgRoot.querySelector(\".hw-content\");if(r===null)return;let s=r.querySelector(\".hw-bond-preview\");s===null&&(s=this._doc.createElementNS(o,\"line\"),s.setAttribute(\"class\",\"hw-bond-preview\"),s.setAttribute(\"data-testid\",\"bond-preview\"),s.setAttribute(\"stroke-dasharray\",\"6 4\"),s.setAttribute(\"stroke-width\",\"2\"),s.setAttribute(\"fill\",\"none\"),s.setAttribute(\"pointer-events\",\"none\"),r.appendChild(s)),s.setAttribute(\"x1\",String(e.x)),s.setAttribute(\"y1\",String(e.y)),s.setAttribute(\"x2\",String(t.x)),s.setAttribute(\"y2\",String(t.y)),s.setAttribute(\"stroke\",n?\"#1f5fcd\":\"#999999\");}_clearBondPreview(){let e=this._svgRoot.querySelector(\".hw-bond-preview\");e!==null&&e.parentNode!==null&&e.parentNode.removeChild(e);}_paintSelectionRect(e,t){let n=Math.min(e.x,t.x),o=Math.min(e.y,t.y),r=Math.abs(e.x-t.x),s=Math.abs(e.y-t.y);this._paintSelectionRectAt(n,o,r,s);}_paintSelectionRectFromRect(e){this._paintSelectionRectAt(e.x,e.y,e.width,e.height);}_paintSelectionRectAt(e,t,n,o){let r=\"http://www.w3.org/2000/svg\",s=this._svgRoot.querySelector(\".hw-content\");if(s===null)return;let a=s.querySelector(\".hw-selection-rect\");a===null&&(a=this._doc.createElementNS(r,\"rect\"),a.setAttribute(\"class\",\"hw-selection-rect\"),a.setAttribute(\"data-testid\",\"selection-rect\"),a.setAttribute(\"fill\",\"rgba(31, 95, 205, 0.08)\"),a.setAttribute(\"stroke\",\"#1f5fcd\"),a.setAttribute(\"stroke-width\",\"1\"),a.setAttribute(\"stroke-dasharray\",\"4 3\"),a.setAttribute(\"pointer-events\",\"none\"),s.appendChild(a)),a.setAttribute(\"x\",String(e)),a.setAttribute(\"y\",String(t)),a.setAttribute(\"width\",String(n)),a.setAttribute(\"height\",String(o));}_clearSelectionRect(){let e=this._svgRoot.querySelector(\".hw-selection-rect\");e!==null&&e.parentNode!==null&&e.parentNode.removeChild(e);}};Ut._RDKIT_CACHE_LIMIT=256;var Vt=Ut;function wi(i){switch(i.kind){case \"numeric\":return `R${i.r}`;case \"unspecified\":return \"?\";case \"wildcard\":return \"*\";case \"pair\":return \"pair\";case \"positional\":return `${i.position}pos:R${i.r}`}}var re=class re{constructor(e,t){this._onClose=null;this._primaryAction=null;this._host=e,this._doc=t.documentImpl??S(e);let n=this._doc,o={class:\"hw-modal-backdrop\",role:\"presentation\"};t.testId!==void 0&&(o[\"data-testid\"]=`dialog-${t.testId}`);let r=v(n,\"div\",o),s={class:\"hw-modal\",role:\"dialog\",\"aria-modal\":\"true\",\"aria-label\":t.title};t.testId!==void 0&&(s[\"data-testid\"]=`dialog-${t.testId}-frame`);let a=v(n,\"div\",s),d=v(n,\"div\",{class:\"hw-modal__header\"},[t.title]),l=v(n,\"div\",{class:\"hw-modal__body\"});a.appendChild(d),a.appendChild(l),r.appendChild(a);let u=c=>{c.stopPropagation();};for(let c of [\"mousedown\",\"mousemove\",\"mouseup\",\"mouseover\",\"mouseenter\",\"mouseleave\",\"wheel\",\"contextmenu\",\"dblclick\",\"keydown\",\"keyup\",\"keypress\"])r.addEventListener(c,u);a.addEventListener(\"keydown\",c=>{let m=c;if(m.key!==\"Enter\"||m.target?.tagName===\"TEXTAREA\")return;let p=this._primaryAction;p!==null&&(m.preventDefault?.(),m.stopImmediatePropagation?.(),p());}),r.addEventListener(\"click\",c=>{if(c.target===r){this.close();return}c.stopPropagation();}),this.root=r,this.body=l;}static anyOpen(){return re._openStack.length>0}static closeTopmost(){let e=re._openStack[re._openStack.length-1];return e===void 0?false:(e.close(),true)}open(e){this._onClose=e??null,this.root.parentNode===null&&this._host.appendChild(this.root),re._openStack.includes(this)||re._openStack.push(this),Gt(this._doc);}close(){let e=re._openStack.indexOf(this);e>=0&&re._openStack.splice(e,1),this.root.parentNode!==null&&this.root.parentNode.removeChild(this.root);let t=this._onClose;this._onClose=null,t!==null&&t();}setPrimaryAction(e){this._primaryAction=e;}get isOpen(){return this.root.parentNode!==null}};re._openStack=[];var X=re;function Ve(i,e,t,n){let o=`hw-input-${Math.random().toString(36).slice(2,9)}`,r=v(i,\"label\",{for:o,class:\"hw-modal__label\"},[e]),s=i.createElement(\"input\");return s.setAttribute(\"id\",o),s.setAttribute(\"type\",\"text\"),s.setAttribute(\"class\",\"hw-modal__input\"),n!==void 0&&s.setAttribute(\"data-testid\",n),s.value=t,{row:v(i,\"div\",{class:\"hw-modal__row\"},[r,s]),input:s}}function Ue(i,e,t,n,o){let r=`hw-sel-${Math.random().toString(36).slice(2,9)}`,s=v(i,\"label\",{for:r,class:\"hw-modal__label\"},[e]),a=i.createElement(\"select\");a.setAttribute(\"id\",r),a.setAttribute(\"class\",\"hw-modal__select\"),o!==void 0&&a.setAttribute(\"data-testid\",o);for(let l of t){let u=i.createElement(\"option\");u.setAttribute(\"value\",l.value),l.value===n&&u.setAttribute(\"selected\",\"\"),u.appendChild(i.createTextNode(l.label)),a.appendChild(u);}return {row:v(i,\"div\",{class:\"hw-modal__row\"},[s,a]),select:a}}function ze(i,e){let t=i.createElement(\"button\");t.setAttribute(\"class\",\"hw-modal__ok\"),t.setAttribute(\"type\",\"button\"),e!==void 0&&t.setAttribute(\"data-testid\",`${e}-ok`),t.appendChild(i.createTextNode(\"OK\"));let n=i.createElement(\"button\");return n.setAttribute(\"class\",\"hw-modal__cancel\"),n.setAttribute(\"type\",\"button\"),e!==void 0&&n.setAttribute(\"data-testid\",`${e}-cancel`),n.appendChild(i.createTextNode(\"Cancel\")),{row:v(i,\"div\",{class:\"hw-modal__actions\"},[t,n]),ok:t,cancel:n}}var Ke=class{constructor(e,t){this._modal=null;this._editor=e;let n=e._getHost();if(n===null)throw new Error(\"ChooseRDialog: editor has no host element.\");this._doc=t?.documentImpl??S(n);}open(e,t,n){this.close();let o=this._editor._getHost();if(o===null)return Promise.resolve(null);let r=new X(o,{documentImpl:this._doc,title:\"Choose R-Groups\",testId:\"choose-r\"});this._modal=r;let s=Ai(e,n?.freeR1,n?.currentR1,this._editor),a=Ai(t,n?.freeR2,n?.currentR2,this._editor),d=v(this._doc,\"div\",{class:\"hw-modal__info\"},[`${e.symbol} (${e.bio.chainId})`]),l=n?.currentR1!==void 0?String(n.currentR1):s[0]?.value??\"1\",u=n?.currentR2!==void 0?String(n.currentR2):a[0]?.value??\"1\",c=Ue(this._doc,\"R-group on side A\",s,l,\"choose-r-r1\"),m=v(this._doc,\"div\",{class:\"hw-modal__info\"},[`${t.symbol} (${t.bio.chainId})`]),p=Ue(this._doc,\"R-group on side B\",a,u,\"choose-r-r2\"),h=ze(this._doc,\"choose-r\"),y=[];return s.length===0&&y.push(v(this._doc,\"div\",{class:\"hw-modal__info hw-modal__note-fully-booked\"},[`All R-groups on ${e.symbol} are in use.`])),a.length===0&&y.push(v(this._doc,\"div\",{class:\"hw-modal__info hw-modal__note-fully-booked\"},[`All R-groups on ${t.symbol} are in use.`])),new Promise(f=>{let _=false,b=k=>{_||(_=true,f(k));},A=k=>{b(k),this.close();},w=()=>A({r1:ki(c.select),r2:ki(p.select)});h.ok.addEventListener(\"click\",w),h.cancel.addEventListener(\"click\",()=>A(null)),r.setPrimaryAction(w),r.body.appendChild(d),r.body.appendChild(c.row),r.body.appendChild(m),r.body.appendChild(p.row);for(let k of y)r.body.appendChild(k);r.body.appendChild(h.row),r.open(()=>b(null));})}get isOpen(){return this._modal!==null&&this._modal.isOpen}close(){this._modal!==null&&(this._modal.close(),this._modal=null);}};function ki(i){let e=i.value;if(typeof e==\"string\"&&e.length>0){let o=Number(e);if(Number.isFinite(o)&&o>=1)return o}let t=i.querySelectorAll(\"option\");for(let o of Array.from(t))if(o.getAttribute(\"selected\")!==null){let r=o.getAttribute(\"value\")??\"\",s=Number(r);if(Number.isFinite(s)&&s>=1)return s}let n=t[0];if(n!==void 0){let o=n.getAttribute(\"value\")??\"\",r=Number(o);if(Number.isFinite(r)&&r>=1)return r}return 1}function Ai(i,e,t,n){let o=i.monomer?.rgroups;if(o===void 0||o.length===0)return [{value:\"1\",label:\"R1\"},{value:\"2\",label:\"R2\"},{value:\"3\",label:\"R3\"}];let r;if(e!==void 0)r=new Set(e);else if(r=new Set(W(i,n.getMol().bonds)),r.size===0)for(let d=1;d<=o.length;d++)r.add(d);t!==void 0&&t>=1&&t<=o.length&&r.add(t);let s=[],a=Array.from(r).sort((d,l)=>d-l);for(let d of a){let l=o[d-1];if(l===void 0)continue;let u=l.capGroupName!==void 0&&l.capGroupName!==\"\"?` (${l.capGroupName})`:\"\";s.push({value:String(d),label:`${l.label}${u}`});}return s}var Mi=\"next-add-cursor\",rt=28,zt=rt*2;function Ti(i){let e=\"data-testid\";for(let n=0;n<i.body.children.length;n++){let o=i.body.children[n];if(o!==void 0&&o.getAttribute(e)===Mi)return o}let t=i.createElement(\"div\");return t.className=\"hw-next-add-cursor\",t.setAttribute(e,Mi),t.style.display=\"none\",i.body.appendChild(t),t}function Si(i,e,t,n,o,r,s){let d=$e({p:{x:0,y:0},biotype:t,symbol:e},o),u=D(n,t,o.colorTheme).background,c=kt(u),m=e.length,p=m<=1?1:Math.min(1,2/m),h=o.fontSize*p,y=`<svg xmlns=\"http://www.w3.org/2000/svg\" viewBox=\"${-rt} ${-rt} ${zt} ${zt}\" width=\"${zt}\" height=\"${zt}\" class=\"hw-next-add-cursor__svg\" aria-hidden=\"true\"><path d=\"${d}\" fill=\"${u}\" stroke=\"${u}\" stroke-width=\"5\" stroke-linejoin=\"round\" stroke-linecap=\"round\"/><text x=\"0\" y=\"0\" text-anchor=\"middle\" dominant-baseline=\"central\" font-family=\"Helvetica Neue, Helvetica, Arial, sans-serif\" font-size=\"${h}\" fill=\"${c}\">${Sa(e)}</text></svg>`;i.innerHTML=y;let f=i.style;f.left=`${r-rt}px`,f.top=`${s-rt}px`,f.display=\"block\";}function st(i){i!==null&&(i.style.display=\"none\");}function Sa(i){let e=\"\";for(let t=0;t<i.length;t++){let n=i.charAt(t);n===\"<\"?e+=\"&lt;\":n===\">\"?e+=\"&gt;\":n===\"&\"?e+=\"&amp;\":e+=n;}return e}var Kt=class{constructor(e,t,n){this._hoverAtom=null;this._hoverBond=null;this._dragOrigin=null;this._bondStart=null;this._bondDragMoved=false;this._rectDragHappened=false;this._chooseRDialog=null;this._panStart=null;this._atomDragState=null;this._panMoved=false;this._atomDragMoved=false;this._nextAddCursorEl=null;this._destroyed=false;this._unsubs=[];this._host=e,this._editor=t,this._enableContextMenu=n?.enableContextMenu??true,this._tester=new q(t.getMol(),t._currentTheme()),this._unsubs.push(t.on(\"mol:changed\",()=>{this._tester=new q(this._editor.getMol(),this._editor._currentTheme()),this._hoverAtom=null,this._hoverBond=null;})),this._unsubs.push(t.on(\"option:change\",o=>{(o.key===\"mode\"||o.key===\"nextAdd\")&&st(this._nextAddCursorEl);})),this._onMove=o=>this._handleMove(o),this._onClick=o=>this._handleClick(o),this._onDblClick=o=>this._handleDblClick(o),this._onContextMenu=o=>this._handleContextMenu(o),this._onMouseDown=o=>this._handleMouseDown(o),this._onMouseUp=o=>this._handleMouseUp(o),this._onMouseLeave=o=>this._handleMouseLeave(o),this._onWheel=o=>this._handleWheel(o),e.addEventListener(\"mousemove\",this._onMove),e.addEventListener(\"click\",this._onClick),e.addEventListener(\"dblclick\",this._onDblClick),e.addEventListener(\"contextmenu\",this._onContextMenu),e.addEventListener(\"mousedown\",this._onMouseDown),e.addEventListener(\"mouseup\",this._onMouseUp),e.addEventListener(\"mouseleave\",this._onMouseLeave),e.addEventListener(\"wheel\",this._onWheel,{passive:false});}destroy(){if(!this._destroyed){this._destroyed=true;for(let e of this._unsubs)e();this._host.removeEventListener(\"mousemove\",this._onMove),this._host.removeEventListener(\"click\",this._onClick),this._host.removeEventListener(\"dblclick\",this._onDblClick),this._host.removeEventListener(\"contextmenu\",this._onContextMenu),this._host.removeEventListener(\"mousedown\",this._onMouseDown),this._host.removeEventListener(\"mouseup\",this._onMouseUp),this._host.removeEventListener(\"mouseleave\",this._onMouseLeave),this._host.removeEventListener(\"wheel\",this._onWheel),this._chooseRDialog!==null&&(this._chooseRDialog.close(),this._chooseRDialog=null),st(this._nextAddCursorEl),this._nextAddCursorEl=null;}}_handleMove(e){if(this._panStart!==null){let s=this._toViewBox({clientX:e.clientX,clientY:e.clientY}),a=s.x-this._panStart.origin.x,d=s.y-this._panStart.origin.y;this._editor.panTo({x:this._panStart.initialOffset.x+a,y:this._panStart.initialOffset.y+d}),this._panMoved=true;return}if(this._atomDragState!==null){let s=this._toModel(e),a=s.x-this._atomDragState.pointerDownModel.x,d=s.y-this._atomDragState.pointerDownModel.y,l=[];for(let u of this._atomDragState.atomIds){let c=this._atomDragState.initialPositions.get(u);c!==void 0&&l.push({atomId:u,p:{x:c.x+a,y:c.y+d}});}this._editor.moveAtoms(l),this._atomDragMoved=true;return}let t=this._toModel(e),n=this._tester.test(t),o=n?.atom??null,r=n?.bond??null;if(this._bondStart!==null){this._bondDragMoved=true;let s=o!==null&&o.id!==this._bondStart.id?o:null;this._editor.fire(\"bond:preview\",{start:this._bondStart,cursor:t,candidate:s,kind:this._editor.getMode()===\"hbond\"?\"hbond\":\"backbone\"});}if(this._hoverAtom!==null&&(o===null||o.id!==this._hoverAtom.id)&&(this._editor.fire(\"monomer:hover-end\",{atom:this._hoverAtom}),this._hoverAtom=null),o!==null&&(this._hoverAtom===null||this._hoverAtom.id!==o.id)&&(this._hoverAtom=o,this._editor.fire(\"monomer:hover\",{atom:o,clientX:e.clientX,clientY:e.clientY,modelX:t.x,modelY:t.y})),this._hoverBond!==null&&(r===null||r.id!==this._hoverBond.id)&&(this._editor.fire(\"bond:hover-end\",{bond:this._hoverBond}),this._hoverBond=null),r!==null&&(this._hoverBond===null||this._hoverBond.id!==r.id)&&(this._hoverBond=r,this._editor.fire(\"bond:hover\",{bond:r,clientX:e.clientX,clientY:e.clientY})),this._dragOrigin!==null){let s=Ri(this._dragOrigin,t);this._editor.fire(\"selection:rectangle-update\",{rect:s});}this._updateNextAddCursor(e);}_handleClick(e){if(this._bondDragMoved){this._bondDragMoved=false;return}if(this._rectDragHappened){this._rectDragHappened=false;return}if(this._panMoved){this._panMoved=false;return}if(this._atomDragMoved){this._atomDragMoved=false;return}let t=this._toModel(e),n=this._tester.test(t),o=Bi(e),r=this._editor.getMode();if(r===\"eraser\"){if(n?.atom!==void 0){this._editor.removeAtom(n.atom);return}if(n?.bond!==void 0){this._editor.removeBond(n.bond);return}return}if(n?.atom!==void 0){if(r===\"select\"&&!o.ctrl&&!o.shift&&!o.meta){let s=this._editor.getNextAddSymbol();if(s!==null){if(n.atom.biotype===s.biotype){this._editor.replaceMonomer(n.atom,s.symbol);return}this._editor.fire(\"editor:status\",{message:`Cannot replace: ${n.atom.biotype} is incompatible with ${s.biotype}`,severity:\"warn\",durationMs:3e3});return}}this._editor.fire(\"monomer:click\",{atom:n.atom,modifiers:o,clientX:e.clientX,clientY:e.clientY});return}if(n?.bond!==void 0){this._editor.fire(\"bond:click\",{bond:n.bond,modifiers:o});return}if(this._addsEnabled()){let s=this._editor.getNextAddSymbol();if(s!==null){this._editor.addAtom(t,s.biotype,s.symbol);return}}!o.shift&&!o.ctrl&&!o.meta&&this._editor.clearSelection();}_handleDblClick(e){let t=this._toModel(e),n=this._tester.test(t),o=Bi(e);if(n?.atom!==void 0){this._editor.fire(\"monomer:dblclick\",{atom:n.atom,modifiers:o});return}n===null&&this._editor.fitToContent();}_handleContextMenu(e){this._enableContextMenu||e.preventDefault();let t=this._toModel(e),n=this._tester.test(t),r=()=>{e.preventDefault();};n?.atom!==void 0?this._editor.fire(\"monomer:contextmenu\",{atom:n.atom,clientX:e.clientX,clientY:e.clientY,preventDefault:r}):n?.bond!==void 0&&this._editor.fire(\"bond:contextmenu\",{bond:n.bond,clientX:e.clientX,clientY:e.clientY,preventDefault:r});}_handleMouseDown(e){if(e.button!==0)return;let t=this._toModel(e),n=this._tester.test(t),o=this._editor.getMode(),r=e.ctrlKey===true||e.metaKey===true,s=e.shiftKey===true;if(n?.atom!==void 0){if(o===\"move\"||o===\"select\"&&r){let a=this._editor.getSelection(),l=a.atoms.has(n.atom.id)?Array.from(a.atoms):[n.atom.id],u=this._editor.getMol(),c=new Map;for(let m of l){let p=u.atoms.find(h=>h.id===m);p!==void 0&&c.set(m,{x:p.p.x,y:p.p.y});}this._atomDragState={atomIds:l,pointerDownModel:{x:t.x,y:t.y},initialPositions:c},this._atomDragMoved=false;return}this._bondStart=n.atom,this._bondDragMoved=false;return}if(n===null){if(o===\"move\"||o===\"select\"&&!s){let a=this._editor.getViewport();this._panStart={origin:this._toViewBox({clientX:e.clientX,clientY:e.clientY}),initialOffset:{x:a.offset.x,y:a.offset.y}},this._panMoved=false;return}o===\"select\"&&s&&(this._dragOrigin=t,this._editor.fire(\"selection:rectangle-start\",{origin:t}));}}_handleMouseUp(e){if(this._panStart!==null){this._panStart=null;return}if(this._atomDragState!==null){this._atomDragState=null;return}if(this._bondStart!==null){let a=this._bondStart,d=this._bondDragMoved;this._bondStart=null;let l=this._toModel(e),c=this._tester.test(l)?.atom;if(d&&c!==void 0&&c.id!==a.id){if(this._editor.fire(\"bond:preview-end\",{start:a}),this._editor.getMode()===\"hbond\"){try{this._editor.addHydrogenBond(a,c);}catch{this._editor.fire(\"bond:cancel\",{start:a});}return}let m=a.bio.chainId===c.bio.chainId&&Li(a,c,this._editor.getMol())?\"backbone\":\"cross-polymer\",p=Ei(a,c,this._editor.getMol().bonds,m);if(p.mode===\"fail\"){this._editor.fire(\"bond:cancel\",{start:a}),this._editor.fire(\"editor:status\",{message:p.reason,severity:\"error\",durationMs:3e3});return}if(p.mode===\"auto\"){try{this._editor.addBond(a,c,p.r1,p.r2,p.kind);}catch{this._editor.fire(\"bond:cancel\",{start:a});}return}this._openChooseR(a,c,m,p.freeR1,p.freeR2);return}if(d){let m=this._addsEnabled()?this._editor.getNextAddSymbol():null;if(m!==null){let p;try{p=this._editor.addAtom(l,m.biotype,m.symbol);}catch{this._editor.fire(\"bond:cancel\",{start:a}),this._editor.fire(\"bond:preview-end\",{start:a});return}let h=this._editor.getMol().atoms.find(A=>A.id===a.id);if(h===void 0){this._editor.fire(\"bond:cancel\",{start:a}),this._editor.fire(\"bond:preview-end\",{start:a});return}let y=h.bio.chainId===p.bio.chainId&&Li(h,p,this._editor.getMol())?\"backbone\":\"cross-polymer\",f=W(h,this._editor.getMol().bonds),_=W(p,this._editor.getMol().bonds);if(f.includes(2)&&_.includes(1)){try{this._editor.addBond(h,p,2,1,y);}catch{this._editor.fire(\"bond:cancel\",{start:a});}this._editor.fire(\"bond:preview-end\",{start:a});return}let b=Ei(h,p,this._editor.getMol().bonds,y);if(b.mode===\"fail\"){this._editor.fire(\"bond:cancel\",{start:a}),this._editor.fire(\"editor:status\",{message:b.reason,severity:\"error\",durationMs:3e3}),this._editor.fire(\"bond:preview-end\",{start:a});return}if(b.mode===\"auto\"){try{this._editor.addBond(h,p,b.r1,b.r2,b.kind);}catch{this._editor.fire(\"bond:cancel\",{start:a});}this._editor.fire(\"bond:preview-end\",{start:a});return}this._editor.fire(\"bond:preview-end\",{start:a}),this._openChooseR(h,p,y,b.freeR1,b.freeR2);return}this._editor.fire(\"bond:cancel\",{start:a}),this._editor.fire(\"bond:preview-end\",{start:a});return}return}if(this._dragOrigin===null)return;let t=this._toModel(e),n=Ri(this._dragOrigin,t);this._dragOrigin=null;let o=this._tester.testRect(n),r=V.fromAtomsAndBonds(o.atoms.map(a=>a.id),o.bonds.map(a=>a.id)),s=V.union(this._editor.getSelection(),r);this._editor.setSelection(s),this._editor.fire(\"selection:rectangle-end\",{rect:n,selection:s}),this._rectDragHappened=true,s.atoms.size>0&&this._editor.getMode()===\"select\"&&this._editor.setMode(\"move\");}_handleMouseLeave(e){this._hoverAtom!==null&&(this._editor.fire(\"monomer:hover-end\",{atom:this._hoverAtom}),this._hoverAtom=null),this._hoverBond!==null&&(this._editor.fire(\"bond:hover-end\",{bond:this._hoverBond}),this._hoverBond=null),this._bondStart!==null&&(this._editor.fire(\"bond:cancel\",{start:this._bondStart}),this._editor.fire(\"bond:preview-end\",{start:this._bondStart}),this._bondStart=null,this._bondDragMoved=false),this._dragOrigin=null,this._panStart=null,this._atomDragState=null,this._panMoved=false,this._atomDragMoved=false,st(this._nextAddCursorEl);}_openChooseR(e,t,n,o,r){this._chooseRDialog===null&&(this._chooseRDialog=new Ke(this._editor)),this._chooseRDialog.open(e,t,{freeR1:o,freeR2:r}).then(a=>{if(!this._destroyed){if(a===null){this._editor.fire(\"bond:cancel\",{start:e});return}try{this._editor.addBond(e,t,a.r1,a.r2,n);}catch{this._editor.fire(\"bond:cancel\",{start:e});}}});}_updateNextAddCursor(e){let t=this._editor.getNextAddSymbol(),n=this._editor.getMode(),o=this._hoverAtom!==null,r=this._bondStart!==null||this._dragOrigin!==null||this._panStart!==null||this._atomDragState!==null;if(!(n===\"select\"&&t!==null&&!o&&!r)){this._nextAddCursorEl!==null&&st(this._nextAddCursorEl);return}let a=this._host.ownerDocument;if(a===null)return;this._nextAddCursorEl===null&&(this._nextAddCursorEl=Ti(a));let d=this._editor.getService().monomerLib,l=null;for(let u of d.getPolymerTypes()){let c=d.getMonomer(u,t.symbol);if(c!==null){l=c;break}}Si(this._nextAddCursorEl,t.symbol,t.biotype,l,this._editor._currentTheme(),e.clientX,e.clientY);}_addsEnabled(){return this._editor.getMode()===\"select\"}_handleWheel(e){let t=e.ctrlKey===true||e.metaKey===true;if(e.preventDefault(),t){this._wheelPan(e);return}let n=e.deltaY<0?1.1:1/1.1,o=this._toViewBox({clientX:e.clientX,clientY:e.clientY}),r=this._editor.getViewport(),s=r.scale===0?o:{x:(o.x-r.offset.x)/r.scale,y:(o.y-r.offset.y)/r.scale};this._editor.zoom(n,s);}_wheelPan(e){let t=e.deltaX??0,n=e.deltaY??0;if(t===0&&n===0)return;let o=this._toViewBox({clientX:e.clientX,clientY:e.clientY}),r=this._toViewBox({clientX:e.clientX+t,clientY:e.clientY+n}),s=r.x-o.x,a=r.y-o.y,d=this._editor.getViewport();this._editor.panTo({x:d.offset.x-s,y:d.offset.y-a});}_toModel(e){let t=this._host.querySelector(\"svg\"),n=t!==null?t.querySelector(\".hw-content\"):null;if(t!==null&&n!==null){let r=Ci(n,e.clientX,e.clientY);if(r!==null)return r;let s=this._host.getBoundingClientRect(),a=e.clientX-s.left,d=e.clientY-s.top,l=Ca(n.getAttribute(\"transform\")??\"\");return l!==null?{x:(a-l.tx)/(l.scale===0?1:l.scale),y:(d-l.ty)/(l.scale===0?1:l.scale)}:{x:a,y:d}}let o=this._host.getBoundingClientRect();return {x:e.clientX-o.left,y:e.clientY-o.top}}_toViewBox(e){let t=this._host.querySelector(\"svg\");if(t!==null){let o=Ci(t,e.clientX,e.clientY);if(o!==null)return o;let r=this._host.getBoundingClientRect(),s=e.clientX-r.left,a=e.clientY-r.top,d=Ea(t.getAttribute(\"viewBox\"));return d!==null&&r.width>0&&r.height>0?{x:s*(d.w/r.width),y:a*(d.h/r.height)}:{x:s,y:a}}let n=this._host.getBoundingClientRect();return {x:e.clientX-n.left,y:e.clientY-n.top}}};function Ei(i,e,t,n){let o=be(i),r=be(e);if(o===0||r===0)return {mode:\"auto\",r1:2,r2:1,kind:n};let s=W(i,t),a=W(e,t);if(s.length===0)return {mode:\"fail\",reason:`${i.symbol} has no free R-groups (max ${o}).`};if(a.length===0)return {mode:\"fail\",reason:`${e.symbol} has no free R-groups (max ${r}).`};if(s.includes(2)&&a.includes(1)&&(s.length===1||a.length===1))return {mode:\"auto\",r1:2,r2:1,kind:n};if(s.length===1&&a.length===1){let d=s[0],l=a[0];return {mode:\"auto\",r1:d,r2:l,kind:n}}return {mode:\"choose\",freeR1:s,freeR2:a}}function Ci(i,e,t){let n=i;if(typeof n.getScreenCTM!=\"function\")return null;let o=n.getScreenCTM();if(o===null)return null;let r=null;try{let d=o;typeof d.inverse==\"function\"&&(r=d.inverse());}catch{return null}if(r===null)return null;let s=n.ownerSVGElement;if(s!=null&&typeof s.createSVGPoint==\"function\"){let d=s.createSVGPoint();d.x=e,d.y=t;let l=d.matrixTransform(r);return {x:l.x,y:l.y}}let a=r;return {x:a.a*e+a.c*t+a.e,y:a.b*e+a.d*t+a.f}}function Ea(i){if(i===null||i===\"\")return null;let e=i.split(/[,\\s]+/).map(o=>Number(o)).filter(o=>Number.isFinite(o));if(e.length<4)return null;let t=e[2],n=e[3];return t<=0||n<=0?null:{w:t,h:n}}function Ca(i){if(i===\"\")return null;let e=0,t=0,n=1,o=/(translate|scale)\\(([^)]+)\\)/g,r,s=false;for(;(r=o.exec(i))!==null;){s=true;let a=r[1],d=(r[2]??\"\").split(/[,\\s]+/).map(l=>Number(l)).filter(l=>Number.isFinite(l));if(a===\"translate\"){let l=d[0]??0,u=d[1]??0;e=e+n*l,t=t+n*u;}else if(a===\"scale\"){let l=d[0]??1;n=n*l;}}return s?{tx:e,ty:t,scale:n}:null}function Li(i,e,t){if(i.bio.chainId!==e.bio.chainId)return false;let n=t.chains.find(s=>s.id===i.bio.chainId);if(n===void 0)return false;let o=-1,r=-1;for(let s=0;s<n.backboneAtoms.length;s++){let a=n.backboneAtoms[s];a.id===i.id&&(o=s),a.id===e.id&&(r=s);}return o<0||r<0?false:Math.abs(o-r)===1}function Bi(i){return {shift:i.shiftKey===true,alt:i.altKey===true,ctrl:i.ctrlKey===true,meta:i.metaKey===true}}function Ri(i,e){let t=Math.min(i.x,e.x),n=Math.min(i.y,e.y);return {x:t,y:n,width:Math.abs(i.x-e.x),height:Math.abs(i.y-e.y)}}var Wt=class{constructor(e,t,n){this._destroyed=false;this._host=e,this._editor=t,this._enabled=n?.enableKeyboard!==false,this._enabled&&e.getAttribute(\"tabindex\")===null&&e.setAttribute(\"tabindex\",\"0\"),this._onKey=o=>this._handleKey(o),e.addEventListener(\"keydown\",this._onKey);}destroy(){this._destroyed||(this._destroyed=true,this._host.removeEventListener(\"keydown\",this._onKey));}_handleKey(e){if(!this._enabled)return;let t=this._classify(e),n=La(e);if(t===null){this._editor.fire(\"key:unhandled\",{key:e.key,modifiers:n,preventDefault:()=>e.preventDefault()});return}let o=false,r=()=>{o=true,e.preventDefault();};this._editor.fire(\"key:command\",{command:t,preventDefault:r}),!o&&(e.preventDefault(),t!==\"clearSelection\"&&(e.stopPropagation(),e.stopImmediatePropagation?.()),this._execute(t));}_classify(e){let t=e.key,n=e.ctrlKey||e.metaKey;return t===\"Delete\"||t===\"Backspace\"?\"delete\":n&&(t===\"z\"||t===\"Z\")&&!e.shiftKey?\"undo\":n&&((t===\"z\"||t===\"Z\")&&e.shiftKey||t===\"y\"||t===\"Y\")?\"redo\":n&&(t===\"a\"||t===\"A\")?\"selectAll\":n&&(t===\"c\"||t===\"C\")?\"copy\":n&&(t===\"v\"||t===\"V\")?\"paste\":n&&(t===\"x\"||t===\"X\")?\"cut\":t===\"Escape\"?\"clearSelection\":t===\"+\"||t===\"=\"?\"zoomIn\":t===\"-\"||t===\"_\"?\"zoomOut\":t===\"0\"?\"fitToContent\":t===\"ArrowUp\"?\"nudgeUp\":t===\"ArrowDown\"?\"nudgeDown\":t===\"ArrowLeft\"?\"nudgeLeft\":t===\"ArrowRight\"?\"nudgeRight\":null}_execute(e){switch(e){case \"delete\":this._editor.deleteSelection();return;case \"undo\":this._editor.undo();return;case \"redo\":this._editor.redo();return;case \"selectAll\":this._editor.selectAll();return;case \"clearSelection\":this._editor.clearSelection();return;case \"zoomIn\":this._editor.zoom(1.1);return;case \"zoomOut\":this._editor.zoom(1/1.1);return;case \"fitToContent\":this._editor.fitToContent();return;case \"nudgeUp\":this._editor.nudgeSelection(0,-5);return;case \"nudgeDown\":this._editor.nudgeSelection(0,5);return;case \"nudgeLeft\":this._editor.nudgeSelection(-5,0);return;case \"nudgeRight\":this._editor.nudgeSelection(5,0);return;case \"copy\":{let t=this._editor.getHelm();this._editor.fire(\"clipboard:copy\",{format:\"helm\",payload:t});return}case \"cut\":{let t=this._editor.getHelm();this._editor.fire(\"clipboard:copy\",{format:\"helm\",payload:t}),this._editor.deleteSelection();return}case \"paste\":this._editor.fire(\"clipboard:paste\",{format:\"helm\"});return;default:return}}};function La(i){return {shift:i.shiftKey===true,alt:i.altKey===true,ctrl:i.ctrlKey===true,meta:i.metaKey===true}}var Ba=\"application/x-hwe-monomer\",jt=class{constructor(e,t){this._currentPaletteSymbol=null;this._currentPaletteBiotype=null;this._destroyed=false;this._unsubs=[];this._host=e,this._editor=t,this._tester=new q(t.getMol(),t._currentTheme()),this._unsubs.push(t.on(\"mol:changed\",()=>{this._tester=new q(this._editor.getMol(),this._editor._currentTheme());})),this._onDragOver=n=>this._handleDragOver(n),this._onDrop=n=>this._handleDrop(n),this._onDragStart=n=>this._handleDragStart(n),this._onDragEnd=n=>this._handleDragEnd(n),this._onDragEnter=n=>this._handleDragEnter(n),this._onDragLeave=n=>this._handleDragLeave(n),e.addEventListener(\"dragover\",this._onDragOver),e.addEventListener(\"drop\",this._onDrop),e.addEventListener(\"dragstart\",this._onDragStart),e.addEventListener(\"dragend\",this._onDragEnd),e.addEventListener(\"dragenter\",this._onDragEnter),e.addEventListener(\"dragleave\",this._onDragLeave);}startPaletteDrag(e,t){this._currentPaletteSymbol=e,this._currentPaletteBiotype=t,this._editor.fire(\"dnd:start\",{source:\"palette\",symbol:e});}cancelPaletteDrag(){this._currentPaletteSymbol!==null&&(this._currentPaletteSymbol=null,this._currentPaletteBiotype=null,this._editor.fire(\"dnd:cancel\",{source:\"palette\"}));}destroy(){if(!this._destroyed){this._destroyed=true;for(let e of this._unsubs)e();this._host.removeEventListener(\"dragover\",this._onDragOver),this._host.removeEventListener(\"drop\",this._onDrop),this._host.removeEventListener(\"dragstart\",this._onDragStart),this._host.removeEventListener(\"dragend\",this._onDragEnd),this._host.removeEventListener(\"dragenter\",this._onDragEnter),this._host.removeEventListener(\"dragleave\",this._onDragLeave);}}_activePaletteSymbol(e){if(this._currentPaletteSymbol!==null&&this._currentPaletteBiotype!==null)return {symbol:this._currentPaletteSymbol,biotype:this._currentPaletteBiotype};let t=e.dataTransfer;if(t==null)return null;try{let n=typeof t.getData==\"function\"?t.getData(Ba):\"\";if(n===\"\")return null;let o=JSON.parse(n);return typeof o.symbol!=\"string\"||typeof o.biotype!=\"string\"?null:{symbol:o.symbol,biotype:o.biotype}}catch{return null}}_handleDragEnter(e){if(this._activePaletteSymbol(e)!==null&&(e.preventDefault(),e.dataTransfer!==null&&e.dataTransfer!==void 0))try{e.dataTransfer.dropEffect=\"copy\";}catch{}}_handleDragLeave(e){}_handleDragOver(e){if(this._activePaletteSymbol(e)===null)return;if(e.preventDefault(),e.dataTransfer!==null&&e.dataTransfer!==void 0)try{e.dataTransfer.dropEffect=\"copy\";}catch{}let n=this._toModel(e),o=this._tester.test(n),r=o?.atom!==void 0?o.atom:o?.bond!==void 0?o.bond:void 0,s={clientX:e.clientX,clientY:e.clientY};r!==void 0&&(s.target=r),this._editor.fire(\"dnd:over\",s);}_handleDrop(e){let t=this._activePaletteSymbol(e);if(t===null)return;e.preventDefault();let{symbol:n,biotype:o}=t,r=this._toModel(e),s=this._tester.test(r),a=s?.atom!==void 0?s.atom:s?.bond!==void 0?s.bond:void 0,d={symbol:n,biotype:o,clientX:e.clientX,clientY:e.clientY};a!==void 0&&(d.target=a),this._editor.fire(\"dnd:drop\",d),s?.atom!==void 0?this._editor.replaceMonomer(s.atom,n):this._editor.addAtom(r,o,n),this._currentPaletteSymbol=null,this._currentPaletteBiotype=null;}_handleDragStart(e){this._editor.fire(\"dnd:start\",{source:\"canvas\"});}_handleDragEnd(e){this._currentPaletteSymbol!==null&&(this._currentPaletteSymbol=null,this._currentPaletteBiotype=null,this._editor.fire(\"dnd:cancel\",{source:\"palette\"}));}_toModel(e){let t=this._host.querySelector(\"svg\"),n=t!==null?t.querySelector(\".hw-content\"):null;if(t!==null&&n!==null){let r=Ra(n,e.clientX,e.clientY);if(r!==null)return r;let s=this._host.getBoundingClientRect(),a=e.clientX-s.left,d=e.clientY-s.top,l=Ia(n.getAttribute(\"transform\")??\"\");return l!==null?{x:(a-l.tx)/(l.scale===0?1:l.scale),y:(d-l.ty)/(l.scale===0?1:l.scale)}:{x:a,y:d}}let o=this._host.getBoundingClientRect();return {x:e.clientX-o.left,y:e.clientY-o.top}}};function Ra(i,e,t){let n=i;if(typeof n.getScreenCTM!=\"function\")return null;let o=n.getScreenCTM();if(o===null)return null;let r=null;try{let d=o;typeof d.inverse==\"function\"&&(r=d.inverse());}catch{return null}if(r===null)return null;let s=n.ownerSVGElement;if(s!=null&&typeof s.createSVGPoint==\"function\"){let d=s.createSVGPoint();d.x=e,d.y=t;let l=d.matrixTransform(r);return {x:l.x,y:l.y}}let a=r;return {x:a.a*e+a.c*t+a.e,y:a.b*e+a.d*t+a.f}}function Ia(i){if(i===\"\")return null;let e=0,t=0,n=1,o=/(translate|scale)\\(([^)]+)\\)/g,r,s=false;for(;(r=o.exec(i))!==null;){s=true;let a=r[1],d=(r[2]??\"\").split(/[,\\s]+/).map(l=>Number(l)).filter(l=>Number.isFinite(l));if(a===\"translate\"){let l=d[0]??0,u=d[1]??0;e=e+n*l,t=t+n*u;}else if(a===\"scale\"){let l=d[0]??1;n=n*l;}}return s?{tx:e,ty:t,scale:n}:null}var We=class{constructor(e,t){this._modal=null;this._atom=null;this._editor=e;let n=e._getHost();if(n===null)throw new Error(\"AtomPropsDialog: editor has no host element.\");this._doc=t?.documentImpl??S(n);}get isOpen(){return this._modal!==null&&this._modal.isOpen}open(e){this.close(),this._atom=e;let t=this._editor._getHost();if(t===null)return;let n=new X(t,{documentImpl:this._doc,title:\"Monomer Properties\",testId:\"atom-props\"});this._modal=n;let o=v(this._doc,\"div\",{class:\"hw-modal__info\"},[`Position ${e.bio.continuousId} in ${e.bio.chainId}`]),r=Ve(this._doc,\"Symbol\",e.symbol,\"atom-props-symbol\"),s=Ve(this._doc,\"Annotation\",e.bio.annotation??\"\",\"atom-props-annotation\"),a=ze(this._doc,\"atom-props\"),d=()=>this._commit(r.input.value,s.input.value);a.ok.addEventListener(\"click\",d),a.cancel.addEventListener(\"click\",()=>this.close()),n.setPrimaryAction(d),n.body.appendChild(o),n.body.appendChild(r.row),n.body.appendChild(s.row),n.body.appendChild(a.row),n.open();}close(){this._modal!==null&&(this._modal.close(),this._modal=null),this._atom=null;}_commit(e,t){let n=this._atom;if(n===null){this.close();return}let o=e.trim(),r=(n.bio.annotation??\"\")!==t;if(o.length>0&&o!==n.symbol&&this._editor.replaceMonomer(n,o),r){let a=new N(this._editor.getMol()),d={};d.tag=t===\"\"?void 0:t,a.updateAtom(n.id,d);let{mol:l}=a.commit();this._editor.setMol(l);let u=l.atoms.find(c=>c.id===n.id);if(u!==void 0){let c={atom:u};n.bio.annotation!==void 0&&(c.oldAnnotation=n.bio.annotation),t!==\"\"&&(c.newAnnotation=t),this._editor.fire(\"monomer:annotate\",c);}}this.close();}};var je=class{constructor(e,t){this._modal=null;this._bond=null;this._editor=e;let n=e._getHost();if(n===null)throw new Error(\"BondPropsDialog: editor has no host element.\");this._doc=t?.documentImpl??S(n);}get isOpen(){return this._modal!==null&&this._modal.isOpen}open(e){this.close(),this._bond=e;let t=this._editor._getHost();if(t===null)return;let n=new X(t,{documentImpl:this._doc,title:\"Bond Properties\",testId:\"bond-props\"});this._modal=n;let o=v(this._doc,\"div\",{class:\"hw-modal__info\"},[`Kind: ${e.kind}`]),r=this._buildAtomsPreviewRow(e),s=e.r1.kind===\"numeric\",a=e.r2.kind===\"numeric\",d=s&&a,u=this._editor.getMol().bonds,c=d?Ii(e.r1,e.a1,u):[],m=d?Ii(e.r2,e.a2,u):[],p=null,h=null;if(d){let _=String(e.r1.r),b=String(e.r2.r);p=Ue(this._doc,`R-group on ${e.a1.symbol} (${e.a1.bio.chainId}:${e.a1.bio.positionInChain})`,c,_,\"bond-props-r1\"),h=Ue(this._doc,`R-group on ${e.a2.symbol} (${e.a2.bio.chainId}:${e.a2.bio.positionInChain})`,m,b,\"bond-props-r2\");}let y=ze(this._doc,\"bond-props\"),f=()=>{let _=p!==null?Number(Pi(p.select,e.r1.r)):null,b=h!==null?Number(Pi(h.select,e.r2.r)):null;this._commit(_,b);};y.ok.addEventListener(\"click\",f),y.cancel.addEventListener(\"click\",()=>this.close()),n.setPrimaryAction(f),n.body.appendChild(o),r!==null&&n.body.appendChild(r),p!==null&&n.body.appendChild(p.row),h!==null&&n.body.appendChild(h.row),n.body.appendChild(y.row),n.open();}_buildAtomsPreviewRow(e){let t=this._rdkit(),n=this._buildAtomCell(e.a1,t,\"bond-props-atom-a1\"),o=this._buildAtomCell(e.a2,t,\"bond-props-atom-a2\"),r=v(this._doc,\"div\",{class:\"hw-bond-props__bond-arrow\"},[\"\\u2194\"]);return v(this._doc,\"div\",{class:\"hw-bond-props__atoms\",\"data-testid\":\"bond-props-atoms\"},[n,r,o])}_buildAtomCell(e,t,n){let o=e.monomer?.name??e.symbol,r=e.symbol===o?e.symbol:`${e.symbol} \\u2014 ${o}`,s=v(this._doc,\"div\",{class:\"hw-bond-props__atom-label\"},[r]),a={class:\"hw-bond-props__atom-rdkit\",\"data-testid\":`${n}-rdkit`},d=v(this._doc,\"div\",a),l=e.monomer?.smiles;if(t!==null&&l!==void 0&&l!==\"\"){let u=ye(t,l,220,140);u!==null&&u!==\"\"&&(d.innerHTML=u);}return v(this._doc,\"div\",{class:\"hw-bond-props__atom\",\"data-testid\":n},[s,d])}_rdkit(){let t=this._editor.getService().options?.rdkitModule;return t??null}close(){this._modal!==null&&(this._modal.close(),this._modal=null),this._bond=null;}_commit(e,t){let n=this._bond;if(n===null){this.close();return}let o=n.r1.kind===\"numeric\"?n.r1.r:null,r=n.r2.kind===\"numeric\"?n.r2.r:null;if(!(e!==null&&t!==null&&(e!==o||t!==r))){this.close();return}if(e!==null&&t!==null){let a=n.kind,d=n.a1,l=n.a2;this._editor.removeBond(n);try{this._editor.addBond(d,l,e,t,a);}catch(u){if(o!==null&&r!==null)try{this._editor.addBond(d,l,o,r,n.kind);}catch{}}}this.close();}};function Ii(i,e,t){let n=e.monomer?.rgroups;if(n===void 0||n.length===0)return [{value:\"1\",label:\"R1\"},{value:\"2\",label:\"R2\"},{value:\"3\",label:\"R3\"}];let o=new Set(W(e,t));o.add(i.r);let r=Array.from(o).sort((a,d)=>a-d),s=[];for(let a of r){let d=n[a-1];if(d===void 0)continue;let l=d.capGroupName!==void 0&&d.capGroupName!==\"\"?` (${d.capGroupName})`:\"\";s.push({value:String(a),label:`${d.label}${l}`});}return s}function Pi(i,e){let t=i.value;if(typeof t==\"string\"&&t.length>0){let o=Number(t);if(Number.isFinite(o)&&o>=1)return o}let n=i.querySelectorAll(\"option\");for(let o of Array.from(n))if(o.getAttribute(\"selected\")!==null){let r=o.getAttribute(\"value\")??\"\",s=Number(r);if(Number.isFinite(s)&&s>=1)return s}return e}var qe=class{constructor(e,t){this._modal=null;this._result=null;this._findInput=null;this._replaceInput=null;this._matches=[];this._cursor=-1;this._editor=e;let n=e._getHost();if(n===null)throw new Error(\"FindReplaceDialog: editor has no host element.\");this._doc=t?.documentImpl??S(n);}get isOpen(){return this._modal!==null&&this._modal.isOpen}open(){this.close();let e=this._editor._getHost();if(e===null)return;let t=new X(e,{documentImpl:this._doc,title:\"Find / Replace\",testId:\"find-replace\"});this._modal=t;let n=Ve(this._doc,\"Find\",\"\",\"find-replace-find\"),o=Ve(this._doc,\"Replace with\",\"\",\"find-replace-replace\");this._findInput=n.input,this._replaceInput=o.input;let r=this._doc.createElement(\"button\");r.setAttribute(\"class\",\"hw-modal__find-next\"),r.setAttribute(\"type\",\"button\"),r.setAttribute(\"data-testid\",\"find-replace-next\"),r.appendChild(this._doc.createTextNode(\"Find Next\")),r.addEventListener(\"click\",()=>this._findNext());let s=this._doc.createElement(\"button\");s.setAttribute(\"class\",\"hw-modal__replace\"),s.setAttribute(\"type\",\"button\"),s.setAttribute(\"data-testid\",\"find-replace-replace-one\"),s.appendChild(this._doc.createTextNode(\"Replace\")),s.addEventListener(\"click\",()=>this._replaceOne());let a=this._doc.createElement(\"button\");a.setAttribute(\"class\",\"hw-modal__replace-all\"),a.setAttribute(\"type\",\"button\"),a.setAttribute(\"data-testid\",\"find-replace-replace-all\"),a.appendChild(this._doc.createTextNode(\"Replace All\")),a.addEventListener(\"click\",()=>this._replaceAll());let d=this._doc.createElement(\"button\");d.setAttribute(\"class\",\"hw-modal__cancel\"),d.setAttribute(\"type\",\"button\"),d.setAttribute(\"data-testid\",\"find-replace-close\"),d.appendChild(this._doc.createTextNode(\"Close\")),d.addEventListener(\"click\",()=>this.close());let l=v(this._doc,\"div\",{class:\"hw-modal__actions\"},[r,s,a,d]),u=v(this._doc,\"div\",{class:\"hw-modal__result\",\"data-testid\":\"find-replace-result\"},[\"0 matches\"]);this._result=u,t.setPrimaryAction(()=>this._findNext()),t.body.appendChild(n.row),t.body.appendChild(o.row),t.body.appendChild(l),t.body.appendChild(u),t.open();}close(){this._modal!==null&&(this._modal.close(),this._modal=null),this._result=null,this._findInput=null,this._replaceInput=null,this._matches=[],this._cursor=-1;}_findNext(){let e=this._findInput?.value.trim()??\"\";if(e===\"\"){this._setResultText(\"Enter a symbol to find\");return}let t=this._editor.findMonomers(e);if(this._matches=t.map(o=>o.id),this._matches.length===0){this._cursor=-1,this._editor.setHighlights([]),this._setResultText(\"No matches\");return}this._cursor=(this._cursor+1)%this._matches.length;let n=this._matches[this._cursor];n!==void 0&&this._editor.setHighlights([n]),this._setResultText(`${this._cursor+1} / ${this._matches.length} matches`);}_replaceOne(){let e=this._findInput?.value.trim()??\"\",t=this._replaceInput?.value.trim()??\"\";if(e===\"\"||t===\"\"){this._setResultText(\"Both Find and Replace fields are required\");return}if(this._matches.length===0||this._cursor<0){this._findNext();return}let n=this._matches[this._cursor];if(n===void 0)return;let o=this._editor.getMol().atoms.find(r=>r.id===n);if(o!==void 0)if(this._editor.replaceMonomer(o,t),this._matches.splice(this._cursor,1),this._matches.length===0)this._cursor=-1,this._editor.setHighlights([]),this._setResultText(\"Replaced; no further matches\");else {this._cursor=this._cursor%this._matches.length;let r=this._matches[this._cursor];r!==void 0&&this._editor.setHighlights([r]),this._setResultText(`${this._matches.length} matches remaining`);}}_replaceAll(){let e=this._findInput?.value.trim()??\"\",t=this._replaceInput?.value.trim()??\"\";if(e===\"\"||t===\"\"){this._setResultText(\"Both Find and Replace fields are required\");return}let n=this._editor.replaceMonomers(e,t);this._matches=[],this._cursor=-1,this._editor.setHighlights([]),this._setResultText(`${n} replacement${n===1?\"\":\"s\"} made`);}_setResultText(e){if(this._result!==null){for(;this._result.firstChild!==null;)this._result.removeChild(this._result.firstChild);this._result.appendChild(this._doc.createTextNode(e));}}};var ge=Object.freeze(new Set),Pa=.2,Ha=8,at=class{constructor(e,t){this._events=new Fe;this._destroyed=false;this._view=null;this._pointer=null;this._keyboard=null;this._dnd=null;this._atomDialog=null;this._bondDialog=null;this._findReplaceDialog=null;this._viewBootstrapped=false;this._mode=\"select\";this._nextAdd=null;this._lastAction=null;this._lastTripletSugarPos=null;if(t.service===void 0||t.service===null)throw new TypeError(\"HelmEditor: options.service is required\");this._host=e,this._service=t.service,this._options=Object.freeze({...t}),this._mol=me(),this._selection=V.empty(),this._highlights=ge,this._theme=t.service.theme??$,this._viewport={scale:1,offset:{x:0,y:0}},this._viewOnly=t.viewOnly??false,this._history=new Ge({maxEntries:100}),this._history.push({mol:this._mol,label:\"initial\"}),this._libUnsub=this._service.monomerLib.onChanged.subscribe(n=>{let o=this._service.monomerLib,r=typeof o.version==\"number\"?o.version:0,s=n.type===\"reload\"?\"replace\":\"update\";this._events.fire(\"monomer-lib:change\",{source:this._service.monomerLib.source,version:r,reason:s});}),t.initialHelm!==void 0&&this.setHelm(t.initialHelm),this._bootstrapWaveB();}_bootstrapWaveB(){if(this._viewBootstrapped||this._host===null)return;let e=this._resolveDocument(this._host);if(e===null)return;this._viewBootstrapped=true;let t={documentImpl:e};this._options.width!==void 0&&(t.width=this._options.width),this._options.height!==void 0&&(t.height=this._options.height),this._view=new Vt(this._host,this,t),this._viewOnly!==true&&(this._pointer=new Kt(this._host,this,{enableContextMenu:this._options.enableContextMenu??true})),this._options.enableKeyboard!==false&&(this._keyboard=new Wt(this._host,this,{enableKeyboard:true})),this._options.enableDragDrop!==false&&(this._dnd=new jt(this._host,this)),this._events.on(\"monomer:hover\",n=>{this.setHighlights([n.atom.id]);}),this._events.on(\"monomer:hover-end\",()=>{this.clearHighlights();}),this._events.on(\"monomer:click\",n=>{let o=n.modifiers;if(o.ctrl===true||o.meta===true){this.setSelection(V.toggle(this._selection,{kind:\"atom\",id:n.atom.id}));return}if(o.shift===true){this.setSelection(V.union(this._selection,V.fromAtoms([n.atom.id])));return}this.setSelection(V.fromAtoms([n.atom.id]));});}_resolveDocument(e){let t=e.ownerDocument;if(t!=null)return t;let n=globalThis;return n.document!==void 0?n.document:null}destroy(){this._destroyed||(this._destroyed=true,this._atomDialog!==null&&(this._atomDialog.close(),this._atomDialog=null),this._bondDialog!==null&&(this._bondDialog.close(),this._bondDialog=null),this._findReplaceDialog!==null&&(this._findReplaceDialog.close(),this._findReplaceDialog=null),this._dnd!==null&&(this._dnd.destroy(),this._dnd=null),this._keyboard!==null&&(this._keyboard.destroy(),this._keyboard=null),this._pointer!==null&&(this._pointer.destroy(),this._pointer=null),this._view!==null&&(this._view.destroy(),this._view=null),this._libUnsub(),this._events.clear(),this._history.clear());}resize(e,t){this._ensureLive(),this._view!==null&&this._view.resize(e,t),this._events.fire(\"view:resize\",{width:e,height:t});}redraw(){if(this._ensureLive(),this._view!==null){this._view.redraw();return}this._events.fire(\"render:skip\",{reason:\"no-view-mounted\"});}setHelm(e,t){this._ensureLive();let n=t?.canonicalize??this._options.canonicalize??false,o=this._service.parse(e,{mode:\"lenient\"}),r=o.diagnostics;r.filter(l=>l.severity===\"error\").length>0&&this._events.fire(\"helm:parse-error\",{helm:e,diagnostics:r});for(let l of r)l.severity===\"error\"?this._events.fire(\"validation:error\",{diagnostic:l}):l.severity===\"warning\"&&this._events.fire(\"validation:warning\",{diagnostic:l});let a=o.mol;if(n){let l=this._service.canonicalize(e);a=this._service.parse(l,{mode:\"lenient\"}).mol;}let d=oe(a,this._options.bondLength!==void 0?{bondLength:this._options.bondLength}:void 0);return this._replaceMol(d,\"setHelm\",\"api\"),{mol:d,diagnostics:r}}getHelm(e){this._ensureLive();let t={};return e?.canonicalize!==void 0&&(t.canonicalize=e.canonicalize),e?.includeHighlights!==void 0&&(t.includeHighlights=e.includeHighlights),this._service.serialize(this._mol,t)}setMol(e){this._ensureLive(),this._replaceMol(e,\"setMol\",\"api\");}getMol(){return this._mol}getService(){return this._service}getSelection(){return this._selection}setSelection(e){if(this._ensureLive(),V.equals(this._selection,e))return;let t=V.difference(e,this._selection),n=V.difference(this._selection,e);this._selection=e,this._events.fire(\"selection:change\",{selection:e,addedAtomIds:t.atoms,removedAtomIds:n.atoms,addedBondIds:t.bonds,removedBondIds:n.bonds});}selectAll(){this._ensureLive();let e=this._mol.atoms.map(n=>n.id),t=this._mol.bonds.map(n=>n.id);this.setSelection(V.fromAtomsAndBonds(e,t));}clearSelection(){this._ensureLive(),!this._selection.isEmpty&&this.setSelection(V.empty());}setHighlights(e){this._ensureLive();let t=new Set(e);this._highlights=t,this._events.fire(\"highlight:change\",{atomIds:t,bondIds:ge});}clearHighlights(){this._ensureLive(),this._highlights.size!==0&&(this._highlights=ge,this._events.fire(\"highlight:change\",{atomIds:ge,bondIds:ge}));}addAtom(e,t,n){this._ensureLive();let o=new N(this._mol),r=o.addAtom({p:e,biotype:t,symbol:n}),{mol:s}=o.commit(),a=ke(s,this._service.monomerLib,{mode:\"lenient\"}).mol;this._replaceMol(a,`addAtom:${n}`,\"api\");let d=J(a,r);if(d===void 0)throw new Error(\"HelmEditor.addAtom: lost atom after commit\");return this._events.fire(\"monomer:add\",{atom:d,source:\"api\"}),d}removeAtom(e){this._ensureLive();let t=typeof e==\"number\"?e:e.id,n=J(this._mol,t);if(n===void 0)return;let o=new N(this._mol);o.removeAtom(t);let{mol:r}=o.commit();this._replaceMol(r,`removeAtom:${n.symbol}`,\"api\"),this._events.fire(\"monomer:remove\",{atom:n,source:\"api\"});}addBond(e,t,n,o,r){this._ensureLive();let s,a;try{this._validateAddBondConstraints(e,t,n,o);let l=r??\"backbone\",u=this._maybeMergeForLinearExtend(e,t,n,o,l);if(u!==null)({id:s,mol:a}=u);else {let c=new N(this._mol);s=c.addBond({a1:e.id,a2:t.id,kind:r??\"backbone\",r1:{kind:\"numeric\",r:n},r2:{kind:\"numeric\",r:o}}),{mol:a}=c.commit();}}catch(l){let u=l instanceof P?l.message:this._friendlyBondError(l instanceof Error?l.message:String(l),e,t,n,o);throw this._events.fire(\"editor:status\",{message:`Could not add bond: ${u}`,severity:\"error\",durationMs:3e3}),l}this._replaceMol(a,\"addBond\",\"api\");let d=xt(a,s);if(d===void 0)throw new Error(\"HelmEditor.addBond: lost bond after commit\");return this._events.fire(\"bond:add\",{bond:d,source:\"api\"}),d}_maybeMergeForLinearExtend(e,t,n,o,r){if(e.bio.chainId===t.bio.chainId||r!==\"backbone\"&&r!==\"cross-polymer\")return null;let s=this._mol.chains.find(d=>d.id===e.bio.chainId),a=this._mol.chains.find(d=>d.id===t.bio.chainId);if(s===void 0||a===void 0||s.polymerType!==a.polymerType||s.polymerType===x.CHEM||s.polymerType===x.BLOB)return null;if(n===2&&o===1){let d=s.backboneAtoms[s.backboneAtoms.length-1],l=a.backboneAtoms[0];if(d!==void 0&&l!==void 0&&d.id===e.id&&l.id===t.id)return this._mergeChains(s,a,r)}if(n===1&&o===2){let d=s.backboneAtoms[0],l=a.backboneAtoms[a.backboneAtoms.length-1];if(d!==void 0&&l!==void 0&&d.id===e.id&&l.id===t.id)return this._mergeChains(a,s,r)}return null}_mergeChains(e,t,n){let o=e.backboneAtoms.length,r=new Set;for(let b of t.backboneAtoms)r.add(b.id),b.branchAtom!==void 0&&r.add(b.branchAtom.id);let s=new Map,a=o;for(let b of t.backboneAtoms){a+=1;let A={...b,bio:{...b.bio,chainId:e.id,positionInChain:a}};if(s.set(b.id,A),b.branchAtom!==void 0){let w=b.branchAtom,k={...w,bio:{...w.bio,chainId:e.id,positionInChain:a}};s.set(w.id,k);}}for(let b of t.backboneAtoms){let A=s.get(b.id);if(A===void 0||b.branchAtom===void 0)continue;let w=s.get(b.branchAtom.id);w!==void 0&&(A.branchAtom=w);}for(let b of this._mol.atoms)s.has(b.id)||s.set(b.id,b);let d=0;for(let b of this._mol.atoms)b.id>d&&(d=b.id);for(let b of this._mol.bonds)b.id>d&&(d=b.id);let l=d+1,u=s.get(e.backboneAtoms[e.backboneAtoms.length-1].id),c=s.get(t.backboneAtoms[0].id),m={id:l,a1:u,a2:c,kind:\"backbone\",r1:{kind:\"numeric\",r:2},r2:{kind:\"numeric\",r:1}},p=[];for(let b of this._mol.bonds){let A=s.get(b.a1.id)??b.a1,w=s.get(b.a2.id)??b.a2;A===b.a1&&w===b.a2?p.push(b):p.push({...b,a1:A,a2:w});}p.push(m);let h=[],y=[...e.backboneAtoms];for(let b of t.backboneAtoms)y.push(s.get(b.id));for(let b of this._mol.chains)if(b.id!==t.id)if(b.id===e.id){let A=b.bonds.map(w=>{let k=s.get(w.a1.id)??w.a1,C=s.get(w.a2.id)??w.a2;return k===w.a1&&C===w.a2?w:{...w,a1:k,a2:C}});for(let w of t.bonds){let k=s.get(w.a1.id)??w.a1,C=s.get(w.a2.id)??w.a2;A.push(k===w.a1&&C===w.a2?w:{...w,a1:k,a2:C});}A.push(m),h.push({id:b.id,polymerType:b.polymerType,backboneAtoms:y,bonds:A,...b.annotation!==void 0?{annotation:b.annotation}:{}});}else {let A=b.backboneAtoms.map(k=>s.get(k.id)??k),w=b.bonds.map(k=>{let C=s.get(k.a1.id)??k.a1,I=s.get(k.a2.id)??k.a2;return C===k.a1&&I===k.a2?k:{...k,a1:C,a2:I}});h.push({id:b.id,polymerType:b.polymerType,backboneAtoms:A,bonds:w,...b.annotation!==void 0?{annotation:b.annotation}:{}});}let _={atoms:this._mol.atoms.map(b=>s.get(b.id)??b),bonds:p,chains:h,groups:this._mol.groups,annotations:this._mol.annotations};return _=this._refreshContinuousIdsLocal(_),{id:l,mol:_}}_refreshContinuousIdsLocal(e){let t=Le(e),n=new Map;for(let d of e.atoms){let l=t.get(d.id);if(l===void 0||l===d.bio.continuousId){n.set(d.id,d);continue}n.set(d.id,{...d,bio:{...d.bio,continuousId:l}});}for(let d of e.atoms){if(d.branchAtom===void 0)continue;let l=n.get(d.id),u=n.get(d.branchAtom.id);l===void 0||u===void 0||(l.branchAtom=u);}let o=e.bonds.map(d=>{let l=n.get(d.a1.id)??d.a1,u=n.get(d.a2.id)??d.a2;return l===d.a1&&u===d.a2?d:{...d,a1:l,a2:u}}),r=new Map;for(let d of o)r.set(d.id,d);let s=e.chains.map(d=>{let l=d.backboneAtoms.map(c=>n.get(c.id)??c),u=d.bonds.map(c=>r.get(c.id)??c);return {id:d.id,polymerType:d.polymerType,backboneAtoms:l,bonds:u,...d.annotation!==void 0?{annotation:d.annotation}:{}}});return {atoms:e.atoms.map(d=>n.get(d.id)??d),bonds:o,chains:s,groups:e.groups,annotations:e.annotations}}_friendlyBondError(e,t,n,o,r){return e.includes(\"duplicate bond\")?`bond ${t.symbol}:R${o} \\u2194 ${n.symbol}:R${r} already exists`:e.includes(\"does not exist\")?\"one of the endpoint atoms is missing\":e}_validateAddBondConstraints(e,t,n,o){let r=this._mol.bonds,s=be(e);if(s>0&&(n<1||n>s))throw new P(\"rgroup-not-on-monomer\",`R-group R${n} is not defined on monomer '${e.symbol}' (has R1..R${s})`,{atomId:e.id,requested:n,total:s});let a=be(t);if(a>0&&(o<1||o>a))throw new P(\"rgroup-not-on-monomer\",`R-group R${o} is not defined on monomer '${t.symbol}' (has R1..R${a})`,{atomId:t.id,requested:o,total:a});if(s>0){let d=Ot(e,r).find(l=>l.rNumber===n);if(d!==void 0){let l=d.side===\"r1\"?d.bond.a2:d.bond.a1;throw new P(\"rgroup-already-bonded\",`R-group R${n} on '${e.symbol}' is already bonded to '${l.symbol}' (${l.bio.chainId}:${l.bio.positionInChain})`,{atomId:e.id,requested:n,conflictingBondId:d.bond.id})}}if(a>0){let d=Ot(t,r).find(l=>l.rNumber===o);if(d!==void 0){let l=d.side===\"r1\"?d.bond.a2:d.bond.a1;throw new P(\"rgroup-already-bonded\",`R-group R${o} on '${t.symbol}' is already bonded to '${l.symbol}' (${l.bio.chainId}:${l.bio.positionInChain})`,{atomId:t.id,requested:o,conflictingBondId:d.bond.id})}}for(let d of r){if(d.r1.kind!==\"numeric\"||d.r2.kind!==\"numeric\")continue;let l=d.a1.id===e.id&&d.a2.id===t.id&&d.r1.r===n&&d.r2.r===o,u=d.a1.id===t.id&&d.a2.id===e.id&&d.r1.r===o&&d.r2.r===n;if(l||u)throw new P(\"duplicate-bond\",`bond ${e.symbol}:R${n} \\u2194 ${t.symbol}:R${o} already exists`,{atomId:e.id,bondId:d.id})}}_freeRgroupsOn(e){return W(e,this._mol.bonds)}addHydrogenBond(e,t){this._ensureLive();let n=new N(this._mol),o={kind:\"pair\"},r=n.addBond({a1:e.id,a2:t.id,kind:\"hbond\",r1:o,r2:o}),{mol:s}=n.commit();this._replaceMol(s,\"addHydrogenBond\",\"api\");let a=xt(s,r);if(a===void 0)throw new Error(\"HelmEditor.addHydrogenBond: lost bond after commit\");return this._events.fire(\"bond:add\",{bond:a,source:\"api\"}),a}removeBond(e){this._ensureLive();let t=typeof e==\"number\"?e:e.id,n=xt(this._mol,t);if(n===void 0)return;let o=new N(this._mol);o.removeBond(t);let{mol:r}=o.commit();this._replaceMol(r,\"removeBond\",\"api\"),this._events.fire(\"bond:remove\",{bond:n,source:\"api\"});}replaceMonomer(e,t){this._ensureLive();let n=J(this._mol,e.id);if(n===void 0)return;let o=n.symbol;if(o===t)return;let r=new N(this._mol);r.updateAtom(e.id,{symbol:t});let{mol:s}=r.commit(),a=ke(s,this._service.monomerLib,{mode:\"lenient\"}).mol;this._replaceMol(a,`replaceMonomer:${o}->${t}`,\"api\");let d=J(a,e.id);d!==void 0&&this._events.fire(\"monomer:replace\",{atom:d,oldSymbol:o,newSymbol:t});}hitTest(e,t){this._ensureLive();let o=new q(this._mol,this._theme).test({x:e,y:t});return o===null?null:o.atom!==void 0?{atom:o.atom}:o.bond!==void 0?{bond:o.bond}:null}moveAtom(e,t){this._ensureLive();let n=J(this._mol,e);if(n===void 0||n.p.x===t.x&&n.p.y===t.y)return;let o=new N(this._mol);o.updateAtom(e,{p:{x:t.x,y:t.y}});let{mol:r}=o.commit();this._replaceMol(r,\"moveAtom\",\"user\");}moveAtoms(e){if(this._ensureLive(),e.length===0)return;let t=new N(this._mol),n=0;for(let r of e){let s=J(this._mol,r.atomId);s!==void 0&&(s.p.x===r.p.x&&s.p.y===r.p.y||(t.updateAtom(r.atomId,{p:{x:r.p.x,y:r.p.y}}),n+=1));}if(n===0)return;let{mol:o}=t.commit();this._replaceMol(o,\"moveAtom\",\"user\");}cleanLayout(e){this._ensureLive(),this._resetLastAction();let t=oe(this._mol,this._options.bondLength!==void 0?{bondLength:this._options.bondLength}:void 0);this._mol=t,this._history.push({mol:t,label:\"cleanLayout\"}),this._events.fire(\"layout:change\",{mol:t,strategy:\"auto\"}),this._events.fire(\"mol:changed\",{mol:t,changedAtomIds:new Set(t.atoms.map(n=>n.id)),changedBondIds:ge,reason:\"cleanLayout\"});}canUndo(){return this._history.canUndo()}canRedo(){return this._history.canRedo()}undo(){this._ensureLive();let e=this._history.undo();e!==null&&this._restoreFromHistory(e.mol,\"undo\");}redo(){this._ensureLive();let e=this._history.redo();e!==null&&this._restoreFromHistory(e.mol,\"redo\");}on(e,t){return this._events.on(e,t)}off(e,t){this._events.off(e,t);}fire(e,t){this._events.fire(e,t);}zoom(e,t){if(this._ensureLive(),!Number.isFinite(e)||e<=0)return;let n=this._viewport.scale,o=Math.min(Ha,Math.max(Pa,n*e));if(o===n)return;let r={...this._viewport.offset},s=r;t!==void 0&&(s={x:r.x+(n-o)*t.x,y:r.y+(n-o)*t.y});let a={scale:o,offset:s};this._viewport=a;let d=t??{x:0,y:0};this._events.fire(\"view:zoom\",{scale:o,center:d,previousScale:n}),this._events.fire(\"view:viewport-change\",{viewport:a});}panTo(e){this._ensureLive();let t={...this._viewport.offset},n={scale:this._viewport.scale,offset:{...e}};this._viewport=n,this._events.fire(\"view:pan\",{offset:n.offset,previousOffset:t}),this._events.fire(\"view:viewport-change\",{viewport:n});}getViewport(){return {scale:this._viewport.scale,offset:{...this._viewport.offset}}}fitToContent(e){this._ensureLive();let t=0,n=0,o=0,r=0,s=false;for(let c of this._mol.atoms){if(!s){t=o=c.p.x,n=r=c.p.y,s=true;continue}c.p.x<t&&(t=c.p.x),c.p.x>o&&(o=c.p.x),c.p.y<n&&(n=c.p.y),c.p.y>r&&(r=c.p.y);}let a=s?{x:t,y:n,width:o-t,height:r-n}:{x:0,y:0,width:0,height:0},d={...this._viewport.offset},l=this._viewport.scale,u={scale:1,offset:{x:0,y:0}};this._viewport=u,l!==1&&this._events.fire(\"view:zoom\",{scale:1,center:{x:0,y:0},previousScale:l}),(d.x!==0||d.y!==0)&&this._events.fire(\"view:pan\",{offset:u.offset,previousOffset:d}),this._events.fire(\"view:viewport-change\",{viewport:u}),this._events.fire(\"view:fit-to-content\",{bbox:a});}setViewOnly(e){this._ensureLive();let t=this._viewOnly;t!==e&&(this._viewOnly=e,this._events.fire(\"option:change\",{key:\"viewOnly\",oldValue:t,newValue:e}));}setTheme(e){this._ensureLive();let t=this._theme;t!==e&&(this._theme=e,this._events.fire(\"theme:change\",{theme:e,previousTheme:t}));}toSvg(e){this._ensureLive();let t=this.getHelm(),n={};return e?.width!==void 0&&(n.width=e.width),e?.height!==void 0&&(n.height=e.height),this._service.renderToSvg(t,n)}async toPng(e){this._ensureLive();let t=this.getHelm(),n={};return e?.width!==void 0&&(n.width=e.width),e?.height!==void 0&&(n.height=e.height),this._service.renderToPng(t,n)}_getHost(){return this._host}_observerCount(){return this._events.observerCount()}_currentHighlights(){return this._highlights}_currentTheme(){return this._theme}_getView(){return this._view}_getViewport(){return this._viewport}openAtomProps(e){this._ensureLive(),this._host!==null&&(this._atomDialog===null&&(this._atomDialog=new We(this)),this._atomDialog.open(e));}openBondProps(e){this._ensureLive(),this._host!==null&&(this._bondDialog===null&&(this._bondDialog=new je(this)),this._bondDialog.open(e));}openFindReplace(){this._ensureLive(),this._host!==null&&(this._findReplaceDialog===null&&(this._findReplaceDialog=new qe(this)),this._findReplaceDialog.open());}getMode(){return this._mode}setMode(e){this._ensureLive();let t=this._mode;t!==e&&(this._mode=e,this._events.fire(\"option:change\",{key:\"mode\",oldValue:t,newValue:e}));}getNextAddSymbol(){return this._nextAdd}setNextAddSymbol(e,t){this._ensureLive();let n=this._nextAdd;if(e===null)this._nextAdd=null;else {if(t===void 0)return;this._nextAdd={symbol:e,biotype:t};}this._events.fire(\"option:change\",{key:\"nextAdd\",oldValue:n,newValue:this._nextAdd});}startPaletteDrag(e,t){if(this._ensureLive(),this._dnd===null){this._events.fire(\"dnd:start\",{source:\"palette\",symbol:e});return}this._dnd.startPaletteDrag(e,t);}findMonomers(e){this._ensureLive();let t=[];for(let n of this._mol.atoms)n.symbol===e&&t.push(n);return t}replaceMonomers(e,t){this._ensureLive();let n,o;if(typeof e==\"string\"){let l=e,u=t;if(n=this.findMonomers(l),n.length===0)return 0;if(l===u)return n.length;o=`${l}->${u}`;}else {let l=t,u=new Set,c=[];for(let m of e){if(u.has(m.id))continue;u.add(m.id);let p=J(this._mol,m.id);p!==void 0&&p.symbol!==l&&c.push(p);}if(c.length===0)return 0;n=c,o=`atoms[${c.length}]->${l}`;}let r=t,s=new N(this._mol);for(let l of n)s.updateAtom(l.id,{symbol:r});let{mol:a}=s.commit(),d=ke(a,this._service.monomerLib,{mode:\"lenient\"}).mol;return this._replaceMol(d,`replaceMonomers:${o}`,\"api\"),n.length}nudgeSelection(e,t){this._ensureLive();let n=this._selection;if(n.atoms.size===0)return;let o=new N(this._mol);for(let s of n.atoms){let a=J(this._mol,s);a!==void 0&&o.updateAtom(s,{p:{x:a.p.x+e,y:a.p.y+t}});}let{mol:r}=o.commit();this._replaceMol(r,\"nudge\",\"user\");}deleteSelection(){this._ensureLive();let e=this._selection;if(e.atoms.size===0&&e.bonds.size===0)return;let t=new N(this._mol);for(let o of e.atoms)t.removeAtom(o);for(let o of e.bonds)t.removeBond(o);let{mol:n}=t.commit();this._selection=V.empty(),this._replaceMol(n,\"delete-selection\",\"user\"),this._events.fire(\"selection:change\",{selection:this._selection,addedAtomIds:ge,removedAtomIds:e.atoms,addedBondIds:ge,removedBondIds:e.bonds});}appendRnaTriplet(e,t,n){this._ensureLive();let o=Ye(e,t,n),r=this.getHelm(),s=Da(r,o);this.setHelm(s);}placeRnaTriplet(e,t,n){this._ensureLive();let o=1.6*(this._options.bondLength??28),r,s=this._mol.atoms;if(this._lastAction===\"add-triplet\"&&this._lastTripletSugarPos!==null)r={x:this._lastTripletSugarPos.x+o*2,y:this._lastTripletSugarPos.y};else if(s.length===0)r={x:0,y:0};else {let A=s[0].p.x,w=s[0].p.y;for(let k of s)k.p.x<A&&(A=k.p.x),k.p.y>w&&(w=k.p.y);r={x:A,y:w+o};}let a={x:r.x+o,y:r.y},d={x:r.x,y:r.y+o},l=new Set;for(let A of this._mol.chains)l.add(A.id);let u=1;for(;l.has(`RNA${u}`);)u+=1;let c=`RNA${u}`,m=new N(this._mol),p=m.addAtom({p:r,biotype:g.SUGAR,symbol:e,chainId:c,positionInChain:1}),h=m.addAtom({p:a,biotype:g.LINKER,symbol:n,chainId:c,positionInChain:2}),y=m.addAtom({p:d,biotype:g.BASE,symbol:t,chainId:c,positionInChain:0});m.addBond({a1:p,a2:y,kind:\"branch\",r1:{kind:\"numeric\",r:3},r2:{kind:\"numeric\",r:1}}),m.addBond({a1:p,a2:h,kind:\"backbone\",r1:{kind:\"numeric\",r:2},r2:{kind:\"numeric\",r:1}});let{mol:f}=m.commit(),_=this._postProcessTripletMol(f,p,y,c),b=ke(_,this._service.monomerLib,{mode:\"lenient\"}).mol;this._replaceMol(b,\"placeRnaTriplet\",\"user\"),this._lastAction=\"add-triplet\",this._lastTripletSugarPos=r;}_postProcessTripletMol(e,t,n,o){let r=new Map,s=J(e,n),a=J(e,t);if(s===void 0||a===void 0)return e;let d={...a,branchAtom:s};r.set(t,d);let l=e.bonds.map(h=>{let y=r.get(h.a1.id)??h.a1,f=r.get(h.a2.id)??h.a2;return y===h.a1&&f===h.a2?h:{...h,a1:y,a2:f}}),u=new Map;for(let h of l)u.set(h.id,h);let c=e.chains.map(h=>{let y=[];for(let _ of h.backboneAtoms)h.id===o&&_.id===n||y.push(r.get(_.id)??_);let f=h.bonds.map(_=>u.get(_.id)??_);return {id:h.id,polymerType:h.polymerType,backboneAtoms:y,bonds:f,...h.annotation!==void 0?{annotation:h.annotation}:{}}}),p={atoms:e.atoms.map(h=>r.get(h.id)??h),bonds:l,chains:c,groups:e.groups,annotations:e.annotations};return p=this._refreshContinuousIdsLocal(p),p}_resetLastAction(){this._lastAction=\"other\",this._lastTripletSugarPos=null;}_ensureLive(){if(this._destroyed)throw new Error(\"HelmEditor: this instance has been destroyed.\")}_replaceMol(e,t,n){let o=this._service.serialize(this._mol),r=this._service.serialize(e);this._mol=e,this._history.push({mol:e,label:t}),this._resetLastAction(),this._events.fire(\"mol:changed\",{mol:e,changedAtomIds:new Set(e.atoms.map(s=>s.id)),changedBondIds:new Set(e.bonds.map(s=>s.id)),reason:t}),o!==r&&this._events.fire(\"helm:changed\",{helm:r,mol:e,source:n});}_restoreFromHistory(e,t){let n=this._service.serialize(this._mol),o=this._service.serialize(e);this._mol=e,this._resetLastAction(),this._events.fire(\"mol:changed\",{mol:e,changedAtomIds:new Set(e.atoms.map(r=>r.id)),changedBondIds:new Set(e.bonds.map(r=>r.id)),reason:t}),n!==o&&this._events.fire(\"helm:changed\",{helm:o,mol:e,source:t});}};function Un(i){return i.startsWith(\"[\")&&i.endsWith(\"]\")||i.length===1&&/^[A-Za-z]$/.test(i)?i:`[${i}]`}function Ye(i,e,t){return `${Un(i)}(${Un(e)})${Un(t)}`}function Da(i,e){if(i===\"\")return `RNA1{${e}}$$$$V2.0`;let t=/(^|\\|)(RNA\\d+)\\{([^}]*)\\}/g,n=null,o;for(;(o=t.exec(i))!==null;)n={name:o[2],body:o[3],matchText:o[0]};if(n!==null){let h=n.body===\"\"?\"\":\".\",y=`${n.matchText.startsWith(\"|\")?\"|\":\"\"}${n.name}{${n.body}${h}${e}}`,f=i.lastIndexOf(n.matchText);return i.slice(0,f)+y+i.slice(f+n.matchText.length)}let r=new Set,s=/RNA(\\d+)\\{/g,a;for(;(a=s.exec(i))!==null;)r.add(Number(a[1]));let d=1;for(;r.has(d);)d+=1;let l=`RNA${d}{${e}}`,u=i.indexOf(\"$\");if(u<0)return `${i}|${l}$$$$V2.0`;let c=i.slice(0,u),m=i.slice(u);return `${c}${c===\"\"?\"\":\"|\"}${l}${m}`}var Oa=5,Na=3,Fa=14,Ga=11,Va=9,Ua=8,za=48,Ka=96;function Wa(i){return i<=Na?Fa:i<=6?Ga:i<=9?Va:Ua}function Hi(i,e){let t=D(e.monomer,e.biotype,e.theme.colorTheme),n=At(t.background),o=t.text,r=ro(o,n)<Oa,s=e.monomer.symbol,a=Wa(s.length),l=s.length>=10?\"line-height:1.1;letter-spacing:-0.02em;\":\"\",u=`font-size:${a}px;${l}white-space:nowrap;overflow:hidden;text-overflow:ellipsis;max-width:${Ka-16}px;display:inline-block;`,c=v(i,\"span\",{class:\"hw-palette__star\"},[e.favorite?\"\\u2605\":\"\\u2606\"]),m=v(i,\"span\",{class:\"hw-palette__label\",style:u},[s]),p=[\"hw-palette__tile\"];e.primed&&p.push(\"hw-palette__tile--primed\"),e.favorite&&p.push(\"hw-palette__tile--favorite\"),r&&p.push(\"hw-palette__tile--low-contrast\");let h=e.monomer.name!==void 0?`${s} \\u2014 ${e.monomer.name}`:s,y=`background:${n};color:${o};width:100%;min-width:${za}px;padding:4px 6px;height:40px;box-sizing:border-box;overflow:hidden;text-overflow:ellipsis;`;return {root:v(i,\"div\",{class:p.join(\" \"),draggable:\"true\",role:\"button\",\"aria-pressed\":e.primed?\"true\":\"false\",\"aria-label\":h,\"data-symbol\":s,\"data-biotype\":e.biotype,\"data-bg\":n,\"data-raw-bg\":t.background,\"data-testid\":`palette-tile-${s}`,title:h,style:y},[c,m]),star:c}}function $i(i,e){let t=e.showStar!==false,n=v(i,\"span\",{class:\"hw-triplet-chip__star\"},[e.favorite?\"\\u2605\":\"\\u2606\"]),o=v(i,\"span\",{class:\"hw-triplet-chip__label\"},[e.label]),r=[\"hw-triplet-chip\"];e.favorite&&r.push(\"hw-triplet-chip--favorite\");let s=t?[n,o]:[o];return {root:v(i,\"div\",{class:r.join(\" \"),role:\"button\",tabindex:\"0\",\"aria-label\":e.title,\"data-sugar\":e.sugar,\"data-base\":e.base,\"data-linker\":e.linker,\"data-triplet\":e.label,\"data-testid\":`palette-triplet-${e.label}`,title:e.title,style:`background:${e.background};color:${e.textColor};`},s),star:n}}var ce=\"http://www.w3.org/2000/svg\",Di={sugar:g.SUGAR,base:g.BASE,linker:g.LINKER},ja={sugar:[\"r\",\"R\"],base:[\"A\"],linker:[\"p\",\"P\"]},qa=200,Ya=180,lt={x:70,y:60},zn={x:140,y:60},Kn={x:70,y:130},Xe=18,Oi=18,dt=22,Yt=class Yt{constructor(e,t,n){this.onValueSet=new Z;this.onPickModeChange=new Z;this._slots=new Map;this._favStar=null;this._pickMode=null;this._destroyed=false;this._builderRdkitCache=new Map;this._editor=t,this._doc=n?.documentImpl??S(e),this._hooks=n?.paletteHooks??null,this._favHooks=n?.favoriteHooks??null,this.element=v(this._doc,\"div\",{class:\"hw-rna-builder\",\"data-testid\":\"rna-builder\"});let o=v(this._doc,\"div\",{class:\"hw-rna-builder__header\"});if(o.appendChild(v(this._doc,\"div\",{class:\"hw-rna-builder__title\"},[\"RNA builder\"])),this._favHooks!==null){let d=v(this._doc,\"span\",{class:\"hw-rna-builder__fav hw-rna-builder__fav--disabled\",role:\"button\",tabindex:\"0\",\"data-testid\":\"rna-builder-fav-star\",title:\"Favorite this triplet\",\"aria-pressed\":\"false\",\"aria-disabled\":\"true\"},[\"\\u2606\"]),l=u=>{u.stopPropagation();let c=this.getSelection();c.preview===\"\"||this._favHooks===null||this._favHooks.toggleFavoriteTriplet(c.sugar,c.base,c.linker);};d.addEventListener(\"click\",l),d.addEventListener(\"keydown\",u=>{let c=u;(c.key===\"Enter\"||c.key===\" \")&&l(u);}),this._favStar=d,o.appendChild(d);}this.element.appendChild(o),this._hintEl=v(this._doc,\"div\",{class:\"hw-rna-builder__hint\",\"data-testid\":\"rna-builder-hint\",hidden:true}),this.element.appendChild(this._hintEl);let r=this._buildSvg();this.element.appendChild(r),this._preview=v(this._doc,\"div\",{class:\"hw-rna-builder__preview\",\"data-testid\":\"rna-builder-preview\"}),this.element.appendChild(this._preview),this._addBtn=v(this._doc,\"button\",{class:\"hw-rna-builder__add\",type:\"button\",\"data-testid\":\"rna-builder-add-btn\"},[\"Add triplet\"]),this._addBtn.addEventListener(\"click\",()=>this._onAddClicked()),this.element.appendChild(this._addBtn),e.appendChild(this.element);let s=t.getService().monomerLib.onChanged.subscribe(()=>{this._destroyed||this.refresh();}),a=t.on(\"theme:change\",()=>{this._destroyed||this._repaintSlotColors();});this._libUnsub=()=>{try{s();}catch{}try{a();}catch{}},this._populateDefaults(),this._updatePreview(),this._repaintSlotColors();}refresh(){this._populateDefaults(),this._updatePreview(),this._repaintSlotColors();}getSelection(){let e=this._slots.get(\"sugar\")?.value??\"\",t=this._slots.get(\"base\")?.value??\"\",n=this._slots.get(\"linker\")?.value??\"\",o=e!==\"\"&&t!==\"\"&&n!==\"\"?Ye(e,t,n):\"\";return {sugar:e,base:t,linker:n,preview:o}}setField(e,t){let n=this._slots.get(e);n!==void 0&&(n.value=t,this._setLabelText(n.labelEl,t),this._repaintSlot(n),this._updatePreview(),this.onValueSet.next({field:e,symbol:t}));}startPickMode(e){if(this._pickMode===e){this.cancelPickMode();return}this._pickMode!==null&&this._setSlotPressed(this._pickMode,false),this._pickMode=e,this._setSlotPressed(e,true),this._setHintActive(e),this.onPickModeChange.next({field:e}),this._hooks!==null&&this._hooks.beginBiotypeFilter(Di[e],t=>{this.setField(e,t),this._exitPickMode();},()=>{this._exitPickMode();});}cancelPickMode(){this._pickMode!==null&&(this._hooks!==null&&this._hooks.endBiotypeFilter(),this._exitPickMode());}getPickMode(){return this._pickMode}triggerAdd(){this._onAddClicked();}destroy(){this._destroyed||(this._destroyed=true,this._pickMode!==null&&this._hooks!==null&&this._hooks.endBiotypeFilter(),this._libUnsub(),this.onValueSet.complete(),this.onPickModeChange.complete(),this.element.parentNode!==null&&this.element.parentNode.removeChild(this.element));}_buildSvg(){let e=this._doc.createElementNS(ce,\"svg\");e.setAttribute(\"class\",\"hw-rna-builder__triplet\"),e.setAttribute(\"viewBox\",`0 0 ${qa} ${Ya}`),e.setAttribute(\"data-testid\",\"rna-builder-triplet-svg\"),e.setAttribute(\"role\",\"group\"),e.setAttribute(\"aria-label\",\"Triplet preview\");let t=this._doc.createElementNS(ce,\"line\");t.setAttribute(\"class\",\"hw-rna-builder__bond\"),t.setAttribute(\"x1\",String(lt.x+Xe)),t.setAttribute(\"y1\",String(lt.y)),t.setAttribute(\"x2\",String(zn.x-Oi)),t.setAttribute(\"y2\",String(zn.y)),e.appendChild(t);let n=this._doc.createElementNS(ce,\"line\");n.setAttribute(\"class\",\"hw-rna-builder__bond\"),n.setAttribute(\"x1\",String(lt.x)),n.setAttribute(\"y1\",String(lt.y+Xe)),n.setAttribute(\"x2\",String(Kn.x)),n.setAttribute(\"y2\",String(Kn.y-dt)),e.appendChild(n);let o=this._doc.createElementNS(ce,\"rect\");o.setAttribute(\"class\",\"hw-rna-builder__slot-shape\"),o.setAttribute(\"x\",String(-Xe)),o.setAttribute(\"y\",String(-Xe)),o.setAttribute(\"width\",String(Xe*2)),o.setAttribute(\"height\",String(Xe*2)),o.setAttribute(\"rx\",\"8\"),o.setAttribute(\"ry\",\"8\");let r=this._buildSlot(\"sugar\",\"Pick sugar (backbone)\",lt,o),s=this._doc.createElementNS(ce,\"circle\");s.setAttribute(\"class\",\"hw-rna-builder__slot-shape\"),s.setAttribute(\"cx\",\"0\"),s.setAttribute(\"cy\",\"0\"),s.setAttribute(\"r\",String(Oi));let a=this._buildSlot(\"linker\",\"Pick linker\",zn,s),d=this._doc.createElementNS(ce,\"path\");d.setAttribute(\"class\",\"hw-rna-builder__slot-shape\"),d.setAttribute(\"d\",`M ${-dt} 0 L 0 ${-dt} L ${dt} 0 L 0 ${dt} Z`);let l=this._buildSlot(\"base\",\"Pick base\",Kn,d);return e.appendChild(a.groupEl),e.appendChild(r.groupEl),e.appendChild(l.groupEl),this._slots.set(\"sugar\",r),this._slots.set(\"linker\",a),this._slots.set(\"base\",l),e}_buildSlot(e,t,n,o){let r=this._doc.createElementNS(ce,\"g\");r.setAttribute(\"class\",\"hw-rna-builder__slot\"),r.setAttribute(\"data-slot\",e),r.setAttribute(\"data-testid\",`rna-builder-slot-${e}`),r.setAttribute(\"role\",\"button\"),r.setAttribute(\"tabindex\",\"0\"),r.setAttribute(\"aria-label\",t),r.setAttribute(\"aria-pressed\",\"false\"),r.setAttribute(\"transform\",`translate(${n.x} ${n.y})`),r.appendChild(o);let s=this._doc.createElementNS(ce,\"text\");s.setAttribute(\"class\",\"hw-rna-builder__slot-label\"),s.setAttribute(\"data-testid\",`rna-builder-${e}-value`),s.setAttribute(\"x\",\"0\"),s.setAttribute(\"y\",\"0\"),s.setAttribute(\"text-anchor\",\"middle\"),s.setAttribute(\"dominant-baseline\",\"central\"),r.appendChild(s);let a=d=>{d.stopPropagation(),this.startPickMode(e);};return r.addEventListener(\"click\",a),r.addEventListener(\"keydown\",d=>{let l=d;(l.key===\"Enter\"||l.key===\" \")&&a(d);}),r.addEventListener(\"mouseenter\",d=>this._showSlotTooltip(e,d)),r.addEventListener(\"mouseleave\",()=>this._hideSlotTooltip()),r.addEventListener(\"focus\",()=>this._showSlotTooltip(e,null)),r.addEventListener(\"blur\",()=>this._hideSlotTooltip()),{id:e,biotype:Di[e],groupEl:r,shapeEl:o,labelEl:s,value:\"\"}}_setLabelText(e,t){let n=[];for(let a=e.firstChild;a!==null;a=a.nextSibling)a.nodeName===\"title\"||a.nodeName===\"TITLE\"||n.push(a);for(let a of n)e.removeChild(a);let o=Xa(t);e.setAttribute(\"font-size\",String(o)),e.setAttribute(\"text-anchor\",\"middle\"),e.setAttribute(\"dominant-baseline\",\"central\");let r=t.length>10?`${t.slice(0,9)}\\u2026`:t;e.appendChild(this._doc.createTextNode(r));let s=e.parentNode;if(s!==null){let a=null;for(let d=s.firstChild;d!==null;d=d.nextSibling)if(d.nodeName===\"title\"||d.nodeName===\"TITLE\"){a=d;break}for(a===null&&(a=this._doc.createElementNS(ce,\"title\"),s.insertBefore(a,s.firstChild));a.firstChild!==null;)a.removeChild(a.firstChild);a.appendChild(this._doc.createTextNode(t));}}_repaintSlotColors(){for(let e of this._slots.values())this._repaintSlot(e);}_repaintSlot(e){let t=this._editor.getService().monomerLib,n=this._theme(),o=e.value===\"\"?null:Qa(t,e.biotype,e.value),r=D(o,e.biotype,n.colorTheme);e.shapeEl.style.fill=r.background,e.shapeEl.style.stroke=r.line,e.labelEl.style.fill=r.text;}_populateDefaults(){let e=this._editor.getService().monomerLib;for(let[t,n]of this._slots.entries()){let o=Ja(e,n.biotype),r=Za(o,ja[t]),s=n.value!==\"\"&&o.some(a=>a.symbol===n.value)?n.value:r??o[0]?.symbol??\"\";n.value=s,this._setLabelText(n.labelEl,s);}}_updatePreview(){let e=this.getSelection();for(;this._preview.firstChild!==null;)this._preview.removeChild(this._preview.firstChild);this._preview.appendChild(this._doc.createTextNode(e.preview===\"\"?\"-\":e.preview)),this._updateFavStar(e);}_updateFavStar(e){if(this._favStar===null||this._favHooks===null)return;let t=e.preview!==\"\",n=t&&this._favHooks.isFavoriteTriplet(e.sugar,e.base,e.linker);for(;this._favStar.firstChild!==null;)this._favStar.removeChild(this._favStar.firstChild);this._favStar.appendChild(this._doc.createTextNode(n?\"\\u2605\":\"\\u2606\")),this._favStar.setAttribute(\"aria-pressed\",n?\"true\":\"false\"),t?this._favStar.removeAttribute(\"aria-disabled\"):this._favStar.setAttribute(\"aria-disabled\",\"true\");let o=\"hw-rna-builder__fav\"+(n?\" hw-rna-builder__fav--active\":\"\")+(t?\"\":\" hw-rna-builder__fav--disabled\");this._favStar.setAttribute(\"class\",o);}_onAddClicked(){let e=this.getSelection();e.preview!==\"\"&&this._editor.placeRnaTriplet(e.sugar,e.base,e.linker);}_exitPickMode(){if(this._pickMode===null)return;let e=this._pickMode;this._setSlotPressed(e,false),this._pickMode=null,this._setHintActive(null),this.onPickModeChange.next({field:null});}_setHintActive(e){let t=this._hintEl;for(;t.firstChild!==null;)t.removeChild(t.firstChild);if(e===null){t.setAttribute(\"hidden\",\"\");return}t.removeAttribute(\"hidden\");let n=e===\"sugar\"?\"sugar\":e===\"base\"?\"base\":\"linker\";t.appendChild(this._doc.createTextNode(`Pick ${n} from palette`));}_setSlotPressed(e,t){let n=this._slots.get(e);if(n===void 0)return;n.groupEl.setAttribute(\"aria-pressed\",t?\"true\":\"false\");let r=(n.groupEl.getAttribute(\"class\")??\"\").split(/\\s+/).filter(s=>s!==\"hw-rna-builder__slot--active\").join(\" \");n.groupEl.setAttribute(\"class\",t?`${r} hw-rna-builder__slot--active`:r);}_theme(){let e=this._editor;return typeof e._currentTheme==\"function\"?e._currentTheme():this._editor.getService().theme}_rdkit(){let t=this._editor.getService().options?.rdkitModule;return t??null}_builderRdkitSvgFor(e){if(e===null)return null;let t=e.smiles;if(t===void 0||t===\"\")return null;let n=this._rdkit();if(n===null)return null;let o=`${e.polymerType}:${e.symbol}`;if(this._builderRdkitCache.has(o))return this._builderRdkitCache.get(o)??null;let r=ye(n,t,220,140);if(this._builderRdkitCache.size>=Yt._BUILDER_RDKIT_CACHE_LIMIT){let s=this._builderRdkitCache.keys().next().value;s!==void 0&&this._builderRdkitCache.delete(s);}return this._builderRdkitCache.set(o,r),r}_slotHint(e){switch(e){case \"sugar\":return \"Click to choose a different sugar\";case \"base\":return \"Click to choose a different base\";case \"linker\":return \"Click to choose a different linker\"}}_slotTitle(e,t){let n=t===\"\"?\"?\":t;switch(e){case \"sugar\":return `Sugar: ${n}`;case \"base\":return `Base: ${n}`;case \"linker\":return `Linker: ${n}`}}_showSlotTooltip(e,t){let n=this._slots.get(e);if(n===void 0)return;let r=this._editor.getService().monomerLib.getMonomerSet(n.biotype),s=n.value===\"\"?null:r.get(n.value)??null,a=ie(this._doc,\"builder-tooltip\",\"hw-builder-tooltip\");Te(this._doc,a,{symbol:this._slotTitle(e,n.value),name:s?.name??\"\",rdkitSvg:this._builderRdkitSvgFor(s),rdkitTestid:\"builder-tooltip-rdkit-svg\",hint:this._slotHint(e)});let d=t;if(d!==null&&typeof d.clientX==\"number\"&&typeof d.clientY==\"number\")Y(a,d.clientX,d.clientY);else {let l=n.groupEl,u=typeof l.getBoundingClientRect==\"function\"?l.getBoundingClientRect():null;u!==null?Y(a,u.left+u.width/2,u.top+u.height/2):Y(a,0,0);}}_hideSlotTooltip(){let e=this._doc.body.querySelector('[data-testid=\"builder-tooltip\"]');U(e);}};Yt._BUILDER_RDKIT_CACHE_LIMIT=256;var qt=Yt;function Xa(i){let e=i.length;return e<=2?16:e<=4?11:e<=7?8:e<=10?6:5}function Ja(i,e){let t=i.getMonomerSet(e),n=[];for(let o of t.values())n.push(o);return n.sort((o,r)=>o.symbol.localeCompare(r.symbol)),n}function Za(i,e){let t=new Set;for(let n of i)t.add(n.symbol);for(let n of e)if(t.has(n))return n;return null}function Qa(i,e,t){return i.getMonomerSet(e).get(t)??null}var ue=\"Favorites\",Wn={[ue]:\"\\u2605 Favorites\",[x.PEPTIDE]:\"Peptides\",[x.RNA]:\"RNA\",[x.CHEM]:\"CHEM\",[x.BLOB]:\"BLOB\",G:\"G\"},Xt=[ue,x.PEPTIDE,x.RNA,x.CHEM,x.BLOB,\"G\"],Ni=\"hwe:palette:favorites\",Fi=\"hwe:palette:active-tab\",el=\"hwe.palette.favorites\";function Jt(i){return `${i.sugar}|${i.base}|${i.linker}`}var Je=class Je{constructor(e,t,n){this.favoritesChanged=new Z;this._nextAddUnsub=()=>{};this._favorites=new Set;this._favoriteTriplets=[];this._pendingRnaSelection=null;this._visibleTabs=[ue];this._activeTab=ue;this._searchInput=null;this._filter=\"\";this._destroyed=false;this._rnaBuilder=null;this._activeBiotypeFilter=null;this._pickResolver=null;this._pickCanceller=null;this._pickEscapeListener=null;this._pickOutsideClickListener=null;this._paletteRdkitCache=new Map;this._editor=t,this._doc=n?.documentImpl??S(e),this._opts={documentImpl:this._doc,groupByNaturalAnalog:n?.groupByNaturalAnalog??true,allowFavorites:n?.allowFavorites??true},this._loadFavorites(),this._activeTab=this._resolveInitialTab(n?.initialTab),this.element=v(this._doc,\"div\",{class:\"hw-palette\",\"data-testid\":\"palette\"}),e.appendChild(this.element),this._render(),this._libUnsub=t.getService().monomerLib.onChanged.subscribe(()=>{this._destroyed||this.refresh();}),this._themeUnsub=t.on(\"theme:change\",()=>{this._destroyed||this.refresh();}),this._nextAddUnsub=t.on(\"option:change\",o=>{this._destroyed||o.key===\"nextAdd\"&&this._updatePrimedClasses();});}refresh(){this._render();}setFilter(e){this._filter=e.trim().toLowerCase(),this._searchInput!==null&&this._searchInput.value!==e&&(this._searchInput.value=e),this._applyFilter();}setActiveTab(e){this._visibleTabs.includes(e)&&(this._activeTab=e,this._persistActiveTab(),this._applyActiveTabClasses(),this._applyFilter());}getActiveTab(){return this._activeTab}getFavorites(){let e=this._editor.getService().monomerLib,t=[];for(let n of this._favorites)this._findMonomer(e,n)!==null&&t.push(n);return t}setFavorite(e,t){let n=this._favorites.has(e);t!==n&&(t?this._favorites.add(e):this._favorites.delete(e),this._saveFavorites(),this._hidePaletteTooltips(),this._render(),this._emitFavoritesChanged());}clearFavorites(){this._favorites.size===0&&this._favoriteTriplets.length===0||(this._favorites.clear(),this._favoriteTriplets.length=0,this._saveFavorites(),this._render(),this._emitFavoritesChanged());}getFavoriteTriplets(){return this._favoriteTriplets.map(e=>({...e}))}isFavoriteTriplet(e,t,n){let o=Jt({sugar:e,base:t,linker:n});return this._favoriteTriplets.some(r=>Jt(r)===o)}setFavoriteTriplet(e,t,n,o){let r=Jt({sugar:e,base:t,linker:n}),s=this._favoriteTriplets.findIndex(d=>Jt(d)===r),a=s>=0;o!==a&&(o?this._favoriteTriplets.push({sugar:e,base:t,linker:n}):this._favoriteTriplets.splice(s,1),this._saveFavorites(),this._hidePaletteTooltips(),this._render(),this._emitFavoritesChanged());}_hidePaletteTooltips(){let e=this._doc.body;U(e.querySelector('[data-testid=\"palette-tooltip\"]')),U(e.querySelector('[data-testid=\"palette-triplet-tooltip\"]'));}_emitFavoritesChanged(){this.favoritesChanged.next({favorites:this.getFavorites(),triplets:this.getFavoriteTriplets()});}destroy(){this._destroyed||(this._destroyed=true,this._rnaBuilder!==null&&(this._rnaBuilder.destroy(),this._rnaBuilder=null),this._libUnsub(),this._themeUnsub(),this._nextAddUnsub(),this.element.parentNode!==null&&this.element.parentNode.removeChild(this.element));}getRnaBuilder(){return this._rnaBuilder}hasActiveBiotypeFilter(){return this._activeBiotypeFilter!==null}getActiveBiotypeFilter(){return this._activeBiotypeFilter}cancelBiotypeFilter(){if(this._activeBiotypeFilter===null)return;let e=this._pickCanceller;this._teardownPickMode(),e?.();}_buildPaletteFilterHooks(){return {beginBiotypeFilter:(e,t,n)=>{this._activeBiotypeFilter!==null&&this._teardownPickMode(),this._activeBiotypeFilter=e,this._pickResolver=t,this._pickCanceller=n,this._applyFilter();let o=d=>{d.key===\"Escape\"&&this.cancelBiotypeFilter();};this._pickEscapeListener=o,this._doc.defaultView?.addEventListener(\"keydown\",o);let s=d=>{if(this._activeBiotypeFilter===null)return;let l=d.target;if(l==null)return;let u=this._activeBiotypeFilter,c=l;for(;c!==null;){let m=c.getAttribute===void 0?null:c.getAttribute(\"class\");if(m!==null){let p=m.split(/\\s+/);if(p.includes(\"hw-palette__tile\")){if((c.getAttribute(\"data-biotype\")??\"\")===u)return;break}if(p.includes(\"hw-rna-builder__slot\")){if(this._isInsideOwnPalette(c))return;break}}c=c.parentElement;}this.cancelBiotypeFilter();};this._pickOutsideClickListener=s,this._doc.addEventListener(\"mousedown\",s,true);},endBiotypeFilter:()=>this._teardownPickMode()}}_scrollActivePaneToTop(){let e=this.element.querySelector(`.hw-palette__pane[data-tab=\"${this._activeTab}\"]`);if(e===null)return;let t=e;try{if(typeof t.scrollTo==\"function\"){t.scrollTo({top:0,behavior:\"smooth\"});return}}catch{}typeof t.scrollTop==\"number\"&&(t.scrollTop=0);}_isInsideOwnPalette(e){let t=e;for(;t!==null;){if(t===this.element)return true;t=t.parentElement;}return false}_teardownPickMode(){this._activeBiotypeFilter!==null&&(this._activeBiotypeFilter=null,this._pickResolver=null,this._pickCanceller=null,this._pickEscapeListener!==null&&(this._doc.defaultView?.removeEventListener(\"keydown\",this._pickEscapeListener),this._pickEscapeListener=null),this._pickOutsideClickListener!==null&&(this._doc.removeEventListener(\"mousedown\",this._pickOutsideClickListener,true),this._pickOutsideClickListener=null),this._applyFilter());}_render(){for(this._rnaBuilder!==null&&(this._pendingRnaSelection=this._rnaBuilder.getSelection(),this._rnaBuilder.destroy(),this._rnaBuilder=null);this.element.firstChild!==null;)this.element.removeChild(this.element.firstChild);let e=this._doc.createElement(\"input\");e.setAttribute(\"type\",\"search\"),e.setAttribute(\"class\",\"hw-palette__search\"),e.setAttribute(\"placeholder\",\"Search monomers...\"),e.setAttribute(\"data-testid\",\"palette-search\"),this._filter!==\"\"&&(e.value=this._filter),e.addEventListener(\"input\",()=>this.setFilter(e.value)),this._searchInput=e,this.element.appendChild(e),this._visibleTabs=this._computeVisibleTabs(),this._visibleTabs.includes(this._activeTab)||(this._activeTab=ue);let t=v(this._doc,\"div\",{class:\"hw-palette__tabs\",role:\"tablist\",\"data-testid\":\"palette-tabs\"});for(let s of this._visibleTabs){let a=s===this._activeTab,d=v(this._doc,\"button\",{class:\"hw-palette__tab\",type:\"button\",role:\"tab\",\"aria-controls\":`hw-palette-pane-${s}`,\"aria-selected\":a?\"true\":\"false\",\"data-testid\":`palette-tab-${s}`,\"data-tab\":s,title:Wn[s]},[Wn[s]]);d.addEventListener(\"click\",()=>this.setActiveTab(s)),t.appendChild(d);}this.element.appendChild(t);let n=v(this._doc,\"div\",{class:\"hw-palette__panes\"}),o=this._theme(),r=this._editor.getService().monomerLib;for(let s of this._visibleTabs){let a=s===this._activeTab,d=v(this._doc,\"div\",{class:\"hw-palette__pane\",id:`hw-palette-pane-${s}`,role:\"tabpanel\",\"data-testid\":`palette-pane-${s}`,\"data-tab\":s,hidden:!a});s===ue?this._buildFavoritesPane(d,r,o):this._buildPolymerPane(d,s,r,o),n.appendChild(d);}this.element.appendChild(n),this._applyFilter();}_computeVisibleTabs(){let e=this._editor.getService().monomerLib,t=new Set;for(let o of e.getPolymerTypes())t.add(o);let n=[];n.push(ue);for(let o of Xt)o!==ue&&t.has(o)&&n.push(o);return n}_buildFavoritesPane(e,t,n){let o=this._resolveFavoriteMonomers(t),r=this._favoriteTriplets;if(o.length===0&&r.length===0){let s=v(this._doc,\"div\",{class:\"hw-palette__placeholder\",\"data-testid\":\"palette-favorites-empty\"},[\"No favorites yet \\u2014 click the \\u2606 on any tile to add one.\"]);e.appendChild(s);return}for(let[s,a]of this._groupByPolymerAndType(o))e.appendChild(this._renderGroup(s,a));r.length>0&&e.appendChild(this._renderTripletGroup(\"RNA \\xB7 Triplets\",r,t));}_groupByPolymerAndType(e){let t=new Map;for(let s of e){let a=s.polymerType,d=s.monomerType??\"Undefined\",l=`${a}|${d}`,u=t.get(l);u===void 0&&(u={pt:a,mt:d,list:[]},t.set(l,u)),u.list.push(s);}let n=s=>{let a=Xt.indexOf(s);return a<0?99:a},o={Backbone:0,Branch:1,Terminal:2,Undefined:3};return Array.from(t.values()).sort((s,a)=>n(s.pt)-n(a.pt)||(o[s.mt]??9)-(o[a.mt]??9)||s.mt.localeCompare(a.mt)).map(s=>[`${this._polymerLabel(s.pt)} \\xB7 ${s.mt}`,s.list])}_polymerLabel(e){return Wn[e]??e}_renderTripletGroup(e,t,n){let o=v(this._doc,\"div\",{class:\"hw-palette__group\",\"data-natural-analog\":e}),r=v(this._doc,\"div\",{class:\"hw-palette__group-header\",\"data-testid\":`palette-group-${e}`},[e]),s=v(this._doc,\"div\",{class:\"hw-triplet-chips\",\"data-testid\":\"palette-triplet-favorites\"});for(let a of t)s.appendChild(this._renderTripletChip(a,n));return o.appendChild(r),o.appendChild(s),o}_renderTripletChip(e,t){let n=Ye(e.sugar,e.base,e.linker),o=t.getMonomerSet(g.BASE).get(e.base)??null,r=D(o,g.BASE,this._theme().colorTheme),s=this.isFavoriteTriplet(e.sugar,e.base,e.linker),a=o?.name!==void 0&&o.name!==\"\"?`${n} \\u2014 ${o.name}`:n,{root:d}=$i(this._doc,{sugar:e.sugar,base:e.base,linker:e.linker,label:n,title:a,background:At(r.background),textColor:r.text,favorite:s,showStar:this._opts.allowFavorites});return this._wireTripletChip(d,e),d}_wireTripletChip(e,t){e.addEventListener(\"mouseenter\",n=>{let o=n,r=ie(this._doc,\"palette-triplet-tooltip\",\"hw-palette-tooltip hw-triplet-tooltip\");xi(this._doc,r,{title:Ye(t.sugar,t.base,t.linker),parts:this._tripletTooltipParts(t),hint:\"Click to add this triplet\",rdkitTestid:\"palette-triplet-tooltip-rdkit-svg\"}),Y(r,typeof o.clientX==\"number\"?o.clientX:0,typeof o.clientY==\"number\"?o.clientY:0);}),e.addEventListener(\"mouseleave\",()=>{U(this._doc.body.querySelector('[data-testid=\"palette-triplet-tooltip\"]'));}),e.addEventListener(\"click\",n=>{let o=n.target;if(this._opts.allowFavorites&&o?.classList?.contains(\"hw-triplet-chip__star\")===true){this.setFavoriteTriplet(t.sugar,t.base,t.linker,!this.isFavoriteTriplet(t.sugar,t.base,t.linker)),n.stopPropagation();return}this._editor.placeRnaTriplet(t.sugar,t.base,t.linker);}),e.addEventListener(\"keydown\",n=>{let o=n;(o.key===\"Enter\"||o.key===\" \")&&this._editor.placeRnaTriplet(t.sugar,t.base,t.linker);});}_buildRnaDefaultChips(e){let t=this._pickSymbol(e.getMonomerSet(g.SUGAR),[\"r\",\"R\"]),n=this._pickSymbol(e.getMonomerSet(g.LINKER),[\"p\",\"P\"]),o=e.getMonomerSet(g.BASE);if(t===null||n===null)return null;let r=Je._DEFAULT_TRIPLET_BASES.filter(a=>o.has(a));if(r.length===0)return null;let s=v(this._doc,\"div\",{class:\"hw-triplet-chips hw-triplet-chips--defaults\",\"data-testid\":\"rna-default-triplets\"});for(let a of r)s.appendChild(this._renderTripletChip({sugar:t,base:a,linker:n},e));return s}_tripletTooltipParts(e){let t=this._editor.getService().monomerLib,n=(o,r,s)=>{let a=t.getMonomerSet(r).get(s)??null;return {role:o,symbol:s,...a?.name!==void 0?{name:a.name}:{},rdkitSvg:a===null?null:this._paletteRdkitSvg(a)}};return [n(\"Sugar\",g.SUGAR,e.sugar),n(\"Base\",g.BASE,e.base),n(\"Linker\",g.LINKER,e.linker)]}_pickSymbol(e,t){for(let o of t)if(e.has(o))return o;let n=e.keys().next();return n.done===true?null:n.value}_restoreRnaSelection(){let e=this._pendingRnaSelection;if(this._pendingRnaSelection=null,e===null||this._rnaBuilder===null)return;let t=this._editor.getService().monomerLib;e.sugar!==\"\"&&t.getMonomerSet(g.SUGAR).has(e.sugar)&&this._rnaBuilder.setField(\"sugar\",e.sugar),e.base!==\"\"&&t.getMonomerSet(g.BASE).has(e.base)&&this._rnaBuilder.setField(\"base\",e.base),e.linker!==\"\"&&t.getMonomerSet(g.LINKER).has(e.linker)&&this._rnaBuilder.setField(\"linker\",e.linker);}_resolveFavoriteMonomers(e){let t=[];for(let n of this._favorites){let o=this._findMonomer(e,n);o!==null&&t.push(o);}return t}_findMonomer(e,t){for(let n of e.getPolymerTypes()){let o=e.getMonomer(n,t);if(o!==null)return o}return null}_buildPolymerPane(e,t,n,o){let r=t,s=this._monomersForPolymer(r,n);if(s.length===0)return;if(r===x.RNA){this._rnaBuilder=new qt(e,this._editor,{documentImpl:this._doc,paletteHooks:this._buildPaletteFilterHooks(),favoriteHooks:this._opts.allowFavorites?{isFavoriteTriplet:(m,p,h)=>this.isFavoriteTriplet(m,p,h),toggleFavoriteTriplet:(m,p,h)=>this.setFavoriteTriplet(m,p,h,!this.isFavoriteTriplet(m,p,h))}:null}),this._restoreRnaSelection();let u=this._buildRnaDefaultChips(n);u!==null&&e.appendChild(u);let c=this._groupRna(s);for(let[m,p]of c)p.length!==0&&e.appendChild(this._renderGroup(m,p));return}if(r===x.PEPTIDE&&this._opts.groupByNaturalAnalog){let u=this._groupByAnalog(s);for(let[c,m]of u){let p=c===\"\"?\"Other\":c;e.appendChild(this._renderGroup(p,m));}return}let a=v(this._doc,\"div\",{class:\"hw-palette__group-tiles\"}),d=this._editor.getNextAddSymbol(),l=this._sortByColor(s);for(let u of l){let c=this._biotype(u,r);a.appendChild(this._renderTile(u,c,d));}e.appendChild(a);}_renderGroup(e,t){let n=v(this._doc,\"div\",{class:\"hw-palette__group\",\"data-natural-analog\":e}),o=v(this._doc,\"div\",{class:\"hw-palette__group-header\",\"data-testid\":`palette-group-${e}`},[e]),r=v(this._doc,\"div\",{class:\"hw-palette__group-tiles\"}),s=this._editor.getNextAddSymbol(),a=this._sortByColor(t);for(let d of a){let l=this._biotype(d,d.polymerType);r.appendChild(this._renderTile(d,l,s));}return n.appendChild(o),n.appendChild(r),n}_sortByColor(e){let t=this._theme(),n=e.map((o,r)=>{let s=this._biotype(o,o.polymerType),a=D(o,s,t.colorTheme),d=so(a.background),l=d.s===0?1:0;return {m:o,idx:r,h:d.h,s:d.s,l:d.l,isGrey:l}});return n.sort((o,r)=>o.isGrey!==r.isGrey?o.isGrey-r.isGrey:o.h!==r.h?o.h-r.h:o.s!==r.s?o.s-r.s:o.l!==r.l?o.l-r.l:o.idx-r.idx),n.map(o=>o.m)}_monomersForPolymer(e,t){let n=t.getMonomerSymbolsByType(e),o=[];for(let r of n){let s=t.getMonomer(e,r);s!==null&&o.push(s);}return o.sort((r,s)=>r.symbol.localeCompare(s.symbol)),o}_groupByAnalog(e){let t=new Map;for(let r of e){let s=r.naturalAnalog??\"\",a=t.get(s);a===void 0&&(a=[],t.set(s,a)),a.push(r);}let n=[],o=Array.from(t.keys()).sort((r,s)=>r===\"\"&&s!==\"\"?1:s===\"\"&&r!==\"\"?-1:r.localeCompare(s));for(let r of o)n.push([r,t.get(r)]);return new Map(n)}_groupRna(e){let t=[],n=[],o=[],r=[];for(let a of e){let d=te(a);d===g.SUGAR?t.push(a):d===g.BASE?n.push(a):d===g.LINKER?o.push(a):r.push(a);}let s=new Map;return s.set(\"Backbones\",t),s.set(\"Bases\",n),s.set(\"Linkers\",o),r.length>0&&s.set(\"Other\",r),s}_renderTile(e,t,n){let o=this._favorites.has(e.symbol),r=n!==null&&n.symbol===e.symbol&&n.biotype===t,{root:s,star:a}=Hi(this._doc,{monomer:e,biotype:t,theme:this._theme(),favorite:o,primed:r});return this._wireTile(s,a,e,t),s}_rdkit(){let t=this._editor.getService().options?.rdkitModule;return t??null}_paletteRdkitSvg(e){let t=e.smiles;if(t===void 0||t===\"\")return null;let n=this._rdkit();if(n===null)return null;let o=`${e.polymerType}:${e.symbol}`;if(this._paletteRdkitCache.has(o))return this._paletteRdkitCache.get(o)??null;let r=ye(n,t,220,140);if(this._paletteRdkitCache.size>=Je._PALETTE_RDKIT_CACHE_LIMIT){let s=this._paletteRdkitCache.keys().next().value;s!==void 0&&this._paletteRdkitCache.delete(s);}return this._paletteRdkitCache.set(o,r),r}_wireTile(e,t,n,o){e.addEventListener(\"mouseenter\",r=>{let s=r,a=ie(this._doc,\"palette-tooltip\",\"hw-palette-tooltip\");Te(this._doc,a,{symbol:n.symbol,name:n.name??\"\",rdkitSvg:this._paletteRdkitSvg(n),rdkitTestid:\"palette-tooltip-rdkit-svg\"});let d=typeof s.clientX==\"number\"?s.clientX:0,l=typeof s.clientY==\"number\"?s.clientY:0;Y(a,d,l);}),e.addEventListener(\"mouseleave\",()=>{U(this._doc.body.querySelector('[data-testid=\"palette-tooltip\"]'));}),e.addEventListener(\"click\",r=>{let s=r.target;if(this._opts.allowFavorites&&s!==void 0&&s?.classList?.contains(\"hw-palette__star\")===true){this.setFavorite(n.symbol,!this._favorites.has(n.symbol)),r.stopPropagation();return}if(this._activeBiotypeFilter!==null&&this._activeBiotypeFilter===o){let l=this._pickResolver;this._teardownPickMode(),l?.(n.symbol),this._scrollActivePaneToTop(),r.stopPropagation();return}let a=this._editor.getSelection();if(a.atoms.size>0){let l=this._editor.getMol(),u=[];for(let m of a.atoms){let p=l.atoms.find(h=>h.id===m);p!==void 0&&u.push(p);}if(u.length>0&&u.every(m=>m.biotype===o)){this._editor.replaceMonomers(u,n.symbol),r.stopPropagation();return}this._editor.fire(\"editor:status\",{message:`Cannot bulk-replace ${u.length} selected atom(s) with ${n.symbol}: selection contains incompatible biotypes for ${o}.`,severity:\"warn\",durationMs:3e3}),r.stopPropagation();return}let d=this._editor.getNextAddSymbol();if(d!==null&&d.symbol===n.symbol&&d.biotype===o){this._editor.setNextAddSymbol(null),this._updatePrimedClasses();return}this._editor.setNextAddSymbol(n.symbol,o),this._updatePrimedClasses();}),e.addEventListener(\"dragstart\",r=>{let s=r.dataTransfer;if(s!=null)try{s.setData(\"application/x-hwe-monomer\",JSON.stringify({symbol:n.symbol,biotype:o})),s.effectAllowed=\"copy\";}catch{}U(this._doc.body.querySelector('[data-testid=\"palette-tooltip\"]')),this._editor.startPaletteDrag(n.symbol,o);});}_biotype(e,t){let n=te(e);if(n!==null)return n;switch(t){case x.PEPTIDE:return g.AA;case x.RNA:return g.SUGAR;case x.CHEM:return g.CHEM;case x.BLOB:return g.BLOB;default:return g.CHEM}}_theme(){let e=this._editor;return typeof e._currentTheme==\"function\"?e._currentTheme():this._editor.getService().theme}_applyFilter(){let e=this._filter,t=this._activeBiotypeFilter,n=this.element.querySelector(`.hw-palette__pane[data-tab=\"${this._activeTab}\"]`),o=(n??this.element).querySelectorAll(\".hw-palette__tile\");for(let a=0;a<o.length;a++){let d=o[a],l=(d.getAttribute(\"data-symbol\")??\"\").toLowerCase(),u=(d.getAttribute(\"title\")??\"\").toLowerCase(),c=d.getAttribute(\"data-biotype\")??\"\",h=(e===\"\"||l.indexOf(e)>=0||u.indexOf(e)>=0)&&(t===null||c===t);d.style.display=h?\"\":\"none\";}let r=(n??this.element).querySelectorAll(\".hw-triplet-chip\");for(let a=0;a<r.length;a++){let d=r[a],l=[d.getAttribute(\"data-triplet\")??\"\",d.getAttribute(\"data-sugar\")??\"\",d.getAttribute(\"data-base\")??\"\",d.getAttribute(\"data-linker\")??\"\"].join(\" \").toLowerCase(),u=(e===\"\"||l.indexOf(e)>=0)&&t===null;d.style.display=u?\"\":\"none\";}let s=(n??this.element).querySelectorAll(\".hw-palette__group\");for(let a=0;a<s.length;a++){let d=s[a],l=d.querySelectorAll(\".hw-palette__tile, .hw-triplet-chip\"),u=false;for(let c=0;c<l.length;c++)if(l[c].style.display!==\"none\"){u=true;break}u?(d.removeAttribute(\"hidden\"),d.removeAttribute(\"data-section-empty\")):(d.setAttribute(\"hidden\",\"\"),d.setAttribute(\"data-section-empty\",\"true\"));}}_updatePrimedClasses(){let e=this._editor.getNextAddSymbol(),t=this.element.querySelectorAll(\".hw-palette__tile\");for(let n=0;n<t.length;n++){let o=t[n],r=o.getAttribute(\"data-symbol\")??\"\",s=o.getAttribute(\"data-biotype\")??\"\",a=e!==null&&e.symbol===r&&e.biotype===s,l=(o.getAttribute(\"class\")??\"\").split(/\\s+/).filter(u=>u!==\"hw-palette__tile--primed\").join(\" \");o.setAttribute(\"class\",a?`${l} hw-palette__tile--primed`:l),o.setAttribute(\"aria-pressed\",a?\"true\":\"false\");}}_applyActiveTabClasses(){let e=this.element.querySelectorAll(\".hw-palette__tab\");for(let n=0;n<e.length;n++){let o=e[n],r=o.getAttribute(\"data-tab\")??\"\";o.setAttribute(\"aria-selected\",r===this._activeTab?\"true\":\"false\");}let t=this.element.querySelectorAll(\".hw-palette__pane\");for(let n=0;n<t.length;n++){let o=t[n];(o.getAttribute(\"data-tab\")??\"\")===this._activeTab?o.removeAttribute(\"hidden\"):o.setAttribute(\"hidden\",\"\");}}_localStorage(){if(!this._opts.allowFavorites)return null;let e=this._doc.defaultView;if(e==null)return null;try{return e.localStorage??null}catch{return null}}_resolveInitialTab(e){if(e!==void 0&&Xt.includes(e))return e;let t=this._localStorage();if(t!==null)try{let n=t.getItem(Fi);if(n!==null&&Xt.includes(n))return n}catch{}return ue}_persistActiveTab(){let e=this._localStorage();if(e!==null)try{e.setItem(Fi,this._activeTab);}catch{}}_loadFavorites(){let e=this._localStorage();if(e!==null){try{let t=e.getItem(Ni);if(t!==null&&t!==\"\"){let n=JSON.parse(t),o=this._extractSymbols(n);for(let r of o)this._favorites.add(r);for(let r of this._extractTriplets(n))this._favoriteTriplets.push(r);return}}catch{}try{let t=e.getItem(el);if(t===null||t===\"\")return;let n=JSON.parse(t);if(Array.isArray(n)){for(let o of n){if(typeof o!=\"string\")continue;let r=o.indexOf(\"|\"),s=r>=0?o.slice(r+1):o;s!==\"\"&&this._favorites.add(s);}this._saveFavorites();}}catch{}}}_extractSymbols(e){if(Array.isArray(e)){let t=[];for(let n of e)typeof n==\"string\"&&t.push(n);return t}if(e!==null&&typeof e==\"object\"){let t=e;if(Array.isArray(t.symbols)){let n=[];for(let o of t.symbols)typeof o==\"string\"&&n.push(o);return n}}return []}_extractTriplets(e){if(e===null||typeof e!=\"object\")return [];let t=e;if(!Array.isArray(t.triplets))return [];let n=[];for(let o of t.triplets){if(o===null||typeof o!=\"object\")continue;let r=o;typeof r.sugar==\"string\"&&typeof r.base==\"string\"&&typeof r.linker==\"string\"&&n.push({sugar:r.sugar,base:r.base,linker:r.linker});}return n}_saveFavorites(){let e=this._localStorage();if(e!==null)try{let t={symbols:Array.from(this._favorites)};this._favoriteTriplets.length>0&&(t.triplets=this._favoriteTriplets.map(n=>({...n}))),e.setItem(Ni,JSON.stringify(t));}catch{}}};Je._DEFAULT_TRIPLET_BASES=[\"A\",\"C\",\"G\",\"U\",\"T\"],Je._PALETTE_RDKIT_CACHE_LIMIT=256;var ct=Je;var z='<svg xmlns=\"http://www.w3.org/2000/svg\" viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"currentColor\" stroke-width=\"1.5\" stroke-linecap=\"round\" stroke-linejoin=\"round\">',tl={new:`${z}<path d=\"M13 3H7a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h10a2 2 0 0 0 2-2V9z\"/><path d=\"M13 3v6h6\"/><line x1=\"12\" y1=\"12.5\" x2=\"12\" y2=\"17.5\"/><line x1=\"9.5\" y1=\"15\" x2=\"14.5\" y2=\"15\"/></svg>`,open:`${z}<path d=\"m6 14 1.45-2.9A2 2 0 0 1 9.24 10H20a2 2 0 0 1 1.94 2.5l-1.55 6a2 2 0 0 1-1.94 1.5H4a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h3.93a2 2 0 0 1 1.66.9l.82 1.2a2 2 0 0 0 1.66.9H18a2 2 0 0 1 2 2v2\"/></svg>`,save:`${z}<rect x=\"8\" y=\"2\" width=\"8\" height=\"4\" rx=\"1\" ry=\"1\"/><path d=\"M16 4h2a2 2 0 0 1 2 2v14a2 2 0 0 1-2 2H6a2 2 0 0 1-2-2V6a2 2 0 0 1 2-2h2\"/><path d=\"m9 14 2 2 4-4\"/></svg>`,undo:`${z}<path d=\"M3 12a9 9 0 1 0 9-9 9.7 9.7 0 0 0-6.7 2.8L3 8\"/><path d=\"M3 3v5h5\"/></svg>`,redo:`${z}<path d=\"M21 12a9 9 0 1 1-9-9 9.7 9.7 0 0 1 6.7 2.8L21 8\"/><path d=\"M21 3v5h-5\"/></svg>`,eraser:`${z}<path d=\"m7 21-4.3-4.3c-1-1-1-2.5 0-3.4l9.6-9.6c1-1 2.5-1 3.4 0l5.6 5.6c1 1 1 2.5 0 3.4L13 21\"/><path d=\"M22 21H7\"/><path d=\"m5 11 9 9\"/></svg>`,select:`${z}<path d=\"m4 4 7.07 17 2.51-7.39L21 11.07z\"/></svg>`,hbond:`${z}<path d=\"M9 17H7A5 5 0 0 1 7 7h2\"/><path d=\"M15 7h2a5 5 0 1 1 0 10h-2\"/><line x1=\"8\" y1=\"12\" x2=\"16\" y2=\"12\"/></svg>`,\"zoom-in\":`${z}<circle cx=\"11\" cy=\"11\" r=\"8\"/><line x1=\"21\" y1=\"21\" x2=\"16.65\" y2=\"16.65\"/><line x1=\"11\" y1=\"8\" x2=\"11\" y2=\"14\"/><line x1=\"8\" y1=\"11\" x2=\"14\" y2=\"11\"/></svg>`,\"zoom-out\":`${z}<circle cx=\"11\" cy=\"11\" r=\"8\"/><line x1=\"21\" y1=\"21\" x2=\"16.65\" y2=\"16.65\"/><line x1=\"8\" y1=\"11\" x2=\"14\" y2=\"11\"/></svg>`,fit:`${z}<polyline points=\"15 3 21 3 21 9\"/><polyline points=\"9 21 3 21 3 15\"/><line x1=\"21\" y1=\"3\" x2=\"14\" y2=\"10\"/><line x1=\"3\" y1=\"21\" x2=\"10\" y2=\"14\"/></svg>`,move:`${z}<polyline points=\"5 9 2 12 5 15\"/><polyline points=\"9 5 12 2 15 5\"/><polyline points=\"15 19 12 22 9 19\"/><polyline points=\"19 9 22 12 19 15\"/><line x1=\"2\" y1=\"12\" x2=\"22\" y2=\"12\"/><line x1=\"12\" y1=\"2\" x2=\"12\" y2=\"22\"/></svg>`,clean:`${z}<path d=\"m21.64 3.64-1.28-1.28a1.21 1.21 0 0 0-1.72 0L2.36 18.64a1.21 1.21 0 0 0 0 1.72l1.28 1.28a1.2 1.2 0 0 0 1.72 0L21.64 5.36a1.2 1.2 0 0 0 0-1.72Z\"/><path d=\"m14 7 3 3\"/><path d=\"M5 6v4\"/><path d=\"M19 14v4\"/><path d=\"M10 2v2\"/><path d=\"M7 8H3\"/><path d=\"M21 16h-4\"/><path d=\"M11 3H9\"/></svg>`,find:`${z}<circle cx=\"11\" cy=\"11\" r=\"8\"/><line x1=\"21\" y1=\"21\" x2=\"16.65\" y2=\"16.65\"/></svg>`,theme:`${z}<circle cx=\"12\" cy=\"12\" r=\"9\"/><path d=\"M12 3a9 9 0 0 1 0 18z\" fill=\"currentColor\" stroke=\"none\"/></svg>`},nl={new:\"New \\u2014 clear the canvas\",open:\"Open \\u2014 paste a HELM string\",save:\"Save \\u2014 copy HELM string to clipboard\",undo:\"Undo last action\",redo:\"Redo last undone action\",eraser:\"Eraser \\u2014 click an atom or bond to delete it\",select:\"Select mode (default)\",hbond:\"H-Bond mode \\u2014 drag between two RNA bases to add a Watson-Crick pair\",\"zoom-in\":\"Zoom in\",\"zoom-out\":\"Zoom out\",fit:\"Fit to content \\u2014 reset zoom and pan\",move:\"Move/Pan mode \\u2014 drag the canvas to scroll\",clean:\"Clean layout \\u2014 re-run automatic layout\",find:\"Find / Replace monomer\",theme:\"Toggle dark / light theme\"},Gi=[{id:\"new\",label:\"New\",icon:\"New\"},{id:\"open\",label:\"Open\",icon:\"Open\"},{id:\"save\",label:\"Save\",icon:\"Save\"},{id:\"undo\",label:\"Undo\",icon:\"\\u21BA\",shortcut:\"Ctrl+Z\",separator:true},{id:\"redo\",label:\"Redo\",icon:\"\\u21BB\",shortcut:\"Ctrl+Y\"},{id:\"eraser\",label:\"Eraser\",icon:\"Eraser\",separator:true},{id:\"select\",label:\"Select\",icon:\"Select\"},{id:\"hbond\",label:\"H-Bond\",icon:\"H-Bond\"},{id:\"zoom-in\",label:\"Zoom In\",icon:\"+\",shortcut:\"Ctrl++\",separator:true},{id:\"zoom-out\",label:\"Zoom Out\",icon:\"\\u2212\",shortcut:\"Ctrl+\\u2212\"},{id:\"fit\",label:\"Fit\",icon:\"Fit\",shortcut:\"0\"},{id:\"move\",label:\"Move\",icon:\"Move\"},{id:\"clean\",label:\"Clean\",icon:\"Clean\",separator:true},{id:\"find\",label:\"Find\",icon:\"Find\",shortcut:\"Ctrl+F\"},{id:\"theme\",label:\"Theme\",icon:\"Theme\",separator:true}],ut=class{constructor(e,t,n){this._buttons=new Map;this._unsubs=[];this._destroyed=false;this._editor=t,this._doc=n?.documentImpl??S(e);let o=n?.buttons??Gi;this.element=v(this._doc,\"div\",{class:\"hw-toolbar\",\"data-testid\":\"toolbar\"}),e.appendChild(this.element);for(let s of o){if(s.separator===true){let d=v(this._doc,\"span\",{class:\"hw-toolbar__separator\"});this.element.appendChild(d);}let a=this._buildButton(s);this.element.appendChild(a),this._buttons.set(s.id,a);}let r=()=>this._refreshHistoryState();this._unsubs.push(t.on(\"mol:changed\",r)),this._unsubs.push(t.on(\"helm:changed\",r)),r(),this._reflectMode(),this._unsubs.push(t.on(\"option:change\",s=>{s.key===\"mode\"&&this._reflectMode();}));}setButtonEnabled(e,t){let n=this._buttons.get(e);n!==void 0&&(t?n.removeAttribute(\"disabled\"):n.setAttribute(\"disabled\",\"\"));}destroy(){if(!this._destroyed){this._destroyed=true,this._hideTip();for(let e of this._unsubs)e();this.element.parentNode!==null&&this.element.parentNode.removeChild(this.element);}}_buildButton(e){let t=this._doc.createElement(\"button\");t.setAttribute(\"class\",\"hw-toolbar__btn\"),t.setAttribute(\"type\",\"button\"),t.setAttribute(\"data-action\",e.id),t.setAttribute(\"data-testid\",`toolbar-${e.id}`);let n=nl[e.id]??e.label,o=e.shortcut!==void 0?`${n} (${e.shortcut})`:n;t.setAttribute(\"data-tooltip\",o),t.setAttribute(\"aria-label\",n),t.addEventListener(\"mouseenter\",s=>{let a=s;this._showTip(o,typeof a.clientX==\"number\"?a.clientX:0,typeof a.clientY==\"number\"?a.clientY:0);}),t.addEventListener(\"mouseleave\",()=>this._hideTip()),t.addEventListener(\"click\",()=>this._hideTip());let r=tl[e.id];if(r!==void 0){let s=this._doc.createElement(\"span\");s.setAttribute(\"class\",\"hw-toolbar__btn-icon\"),s.setAttribute(\"aria-hidden\",\"true\"),s.innerHTML=r,t.appendChild(s);}else {let s=e.icon??e.label;t.appendChild(this._doc.createTextNode(s));}return t.addEventListener(\"click\",()=>this._invoke(e.id)),t}_showTip(e,t,n){let o=ie(this._doc,\"toolbar-tooltip\",\"hw-toolbar-tooltip\");for(;o.firstChild!==null;)o.removeChild(o.firstChild);o.appendChild(this._doc.createTextNode(e)),Y(o,t,n);}_hideTip(){U(this._doc.body.querySelector('[data-testid=\"toolbar-tooltip\"]'));}_invoke(e){let t=false;this._editor.fire(\"key:command\",{command:e,preventDefault:()=>{t=true;}}),!t&&this._execute(e);}_execute(e){switch(e){case \"new\":this._editor.setHelm(\"\");return;case \"open\":{let t=this._doc.defaultView;if(t!=null&&typeof t.prompt==\"function\"){let n=t.prompt(\"Enter HELM string\");n!==null&&this._editor.setHelm(n);}return}case \"save\":{let t=this._editor.getHelm();this._editor.fire(\"clipboard:copy\",{format:\"helm\",payload:t});return}case \"undo\":this._editor.undo();return;case \"redo\":this._editor.redo();return;case \"eraser\":{if(!this._editor.getSelection().isEmpty){this._editor.deleteSelection();return}this._editor.setMode(\"eraser\");return}case \"select\":case \"hbond\":case \"move\":this._editor.setMode(e);return;case \"zoom-in\":this._editor.zoom(1.1,this._molCenterOrUndefined());return;case \"zoom-out\":this._editor.zoom(1/1.1,this._molCenterOrUndefined());return;case \"fit\":this._editor.fitToContent();return;case \"clean\":this._editor.cleanLayout();return;case \"find\":this._editor.openFindReplace();return;case \"theme\":{let t=this._editor,n=typeof t._currentTheme==\"function\"?t._currentTheme():null,o=n!==null&&n.name===\"dark\";this._editor.setTheme(o?$:In);return}default:return}}_refreshHistoryState(){this.setButtonEnabled(\"undo\",this._editor.canUndo()),this.setButtonEnabled(\"redo\",this._editor.canRedo());}_molCenterOrUndefined(){let e=this._editor.getMol();if(e.atoms.length===0)return;let t=e.atoms[0].p.x,n=t,o=e.atoms[0].p.y,r=o;for(let s=1;s<e.atoms.length;s++){let a=e.atoms[s].p;a.x<t&&(t=a.x),a.x>n&&(n=a.x),a.y<o&&(o=a.y),a.y>r&&(r=a.y);}return {x:(t+n)/2,y:(o+r)/2}}_reflectMode(){let e=this._editor.getMode();for(let t of [\"select\",\"eraser\",\"hbond\",\"move\"]){let n=this._buttons.get(t);if(n===void 0)continue;let r=(n.getAttribute(\"class\")??\"\").split(/\\s+/).filter(s=>s!==\"hw-toolbar__btn--active\").join(\" \");n.setAttribute(\"class\",t===e?`${r} hw-toolbar__btn--active`:r);}}};var mt=class{constructor(e,t,n){this._unsubs=[];this._destroyed=false;this._editor=t,this._doc=n?.documentImpl??S(e),this._content=v(this._doc,\"pre\",{class:\"hw-pane__content hw-pane__sequence\",\"data-testid\":\"sequence-pane-content\"}),this.element=v(this._doc,\"div\",{class:\"hw-pane hw-pane--sequence\",\"data-testid\":\"pane-sequence\"},[this._content]),e.appendChild(this.element),this.refresh(),this._unsubs.push(t.on(\"helm:changed\",()=>this.refresh())),this._unsubs.push(t.on(\"mol:changed\",()=>this.refresh()));}refresh(){if(this._destroyed)return;let e=this._compute();for(;this._content.firstChild!==null;)this._content.removeChild(this._content.firstChild);this._content.appendChild(this._doc.createTextNode(e));}destroy(){if(!this._destroyed){this._destroyed=true;for(let e of this._unsubs)e();this.element.parentNode!==null&&this.element.parentNode.removeChild(this.element);}}_compute(){let e=this._editor.getMol(),t=[],n;for(let o of e.atoms){let r=o.bio.chainId;n!==void 0&&r!==n&&t.push(\"|\"),n=r;let s=o.monomer?.naturalAnalog;t.push(s!==void 0&&s!==\"\"?s:o.symbol);}return t.join(\"\")}};var pt=class{constructor(e,t,n){this._unsubs=[];this._destroyed=false;this._suppressNext=false;this._editor=t,this._doc=n?.documentImpl??S(e),this._input=v(this._doc,\"div\",{class:\"hw-pane__content hw-pane__notation\",contenteditable:\"true\",spellcheck:\"false\",\"data-testid\":\"notation-pane-content\"}),this._error=v(this._doc,\"div\",{class:\"hw-pane__error\",\"data-testid\":\"notation-pane-error\"}),this.element=v(this._doc,\"div\",{class:\"hw-pane hw-pane--notation\",\"data-testid\":\"pane-helm\"},[this._input,this._error]),e.appendChild(this.element),this.refresh(),this._input.addEventListener(\"blur\",()=>this._commit()),this._input.addEventListener(\"keydown\",o=>{o.key===\"Enter\"&&(o.preventDefault(),o.stopPropagation(),o.stopImmediatePropagation(),this._commit());}),this._unsubs.push(t.on(\"helm:changed\",()=>{if(this._suppressNext){this._suppressNext=false;return}this.refresh();})),this._unsubs.push(t.on(\"mol:changed\",()=>this.refresh()));}refresh(){if(this._destroyed)return;let e=this._editor.getHelm();for(;this._input.firstChild!==null;)this._input.removeChild(this._input.firstChild);this._input.appendChild(this._doc.createTextNode(e)),this._clearError();}destroy(){if(!this._destroyed){this._destroyed=true;for(let e of this._unsubs)e();this.element.parentNode!==null&&this.element.parentNode.removeChild(this.element);}}_commit(){if(this._destroyed)return;let e=(this._input.textContent??\"\").trim(),t=this._editor.getHelm();if(e===t){this._clearError();return}let r=this._editor.getService().validate(e).filter(s=>s.severity===\"error\");if(r.length>0){this._showError(r.map(s=>s.message).join(\"; \"));return}this._clearError(),this._suppressNext=true,this._editor.setHelm(e);}_showError(e){for(;this._error.firstChild!==null;)this._error.removeChild(this._error.firstChild);this._error.appendChild(this._doc.createTextNode(e)),this._error.setAttribute(\"class\",\"hw-pane__error hw-pane__error--visible\");}_clearError(){for(;this._error.firstChild!==null;)this._error.removeChild(this._error.firstChild);this._error.setAttribute(\"class\",\"hw-pane__error\");}};var ol=1e3,ht=class{constructor(e,t,n){this._unsubs=[];this._destroyed=false;this._editor=t,this._doc=n?.documentImpl??S(e),this._body=v(this._doc,\"div\",{class:\"hw-pane__content hw-pane__properties\",\"data-testid\":\"properties-pane-content\"}),this.element=v(this._doc,\"div\",{class:\"hw-pane hw-pane--properties\",\"data-testid\":\"pane-properties\"},[this._body]),e.appendChild(this.element),this.refresh(),this._unsubs.push(t.on(\"helm:changed\",()=>this.refresh())),this._unsubs.push(t.on(\"mol:changed\",()=>this.refresh()));}refresh(){if(this._destroyed)return;for(;this._body.firstChild!==null;)this._body.removeChild(this._body.firstChild);let e=this._editor.getHelm();if(e.length>ol){this._body.appendChild(v(this._doc,\"div\",{class:\"hw-pane__placeholder\"},[\"(too long)\"]));return}let t=this._editor.getService(),n=\"\",o=0,r=0;try{let s=t.getFormula(e);n=il(s.elements),o=s.mw;}catch{n=\"\\u2014\";}try{o=t.getMolWeight(e);}catch{}try{r=t.getExtinctionCoefficient(e);}catch{}this._body.appendChild(this._makeRow(\"Formula\",n,\"formula\")),this._body.appendChild(this._makeRow(\"Molecular Weight\",o===0?\"\\u2014\":o.toFixed(2),\"mw\")),this._body.appendChild(this._makeRow(\"Extinction Coefficient\",r===0?\"\\u2014\":r.toFixed(0),\"extinction\"));}destroy(){if(!this._destroyed){this._destroyed=true;for(let e of this._unsubs)e();this.element.parentNode!==null&&this.element.parentNode.removeChild(this.element);}}_makeRow(e,t,n){let o=v(this._doc,\"span\",{class:\"hw-pane__prop-label\"},[e]),r=v(this._doc,\"span\",{class:\"hw-pane__prop-value\",\"data-testid\":`properties-${n}`},[t]);return v(this._doc,\"div\",{class:\"hw-pane__prop-row\"},[o,r])}};function il(i){let e=Array.from(i.keys()).sort((n,o)=>n===o?0:n===\"C\"?-1:o===\"C\"?1:n===\"H\"?-1:o===\"H\"?1:n.localeCompare(o)),t=\"\";for(let n of e){let o=i.get(n);o===void 0||o===0||(t+=o===1?n:`${n}${o}`);}return t===\"\"?\"\\u2014\":t}var ft=class{constructor(e,t,n){this._unsubs=[];this._destroyed=false;this._refreshToken=0;this._editor=t,this._doc=n?.documentImpl??S(e),this._content=v(this._doc,\"pre\",{class:\"hw-pane__content hw-pane__atomic\",\"data-testid\":\"atomic-pane-content\"}),this.element=v(this._doc,\"div\",{class:\"hw-pane hw-pane--atomic\",\"data-testid\":\"pane-atomic\"},[this._content]),e.appendChild(this.element),this.refresh(),this._unsubs.push(t.on(\"helm:changed\",()=>{this.refresh();}));}async refresh(){if(this._destroyed)return;let e=++this._refreshToken,t=this._editor.getHelm(),n=this._editor.getService();if(!n.hasAtomicMolfileProvider()){this._render(\"Atomic structure unavailable\");return}try{let o=await n.getAtomicMolfile(t);if(this._destroyed||e!==this._refreshToken)return;this._render(o);}catch(o){if(this._destroyed||e!==this._refreshToken)return;let r=o instanceof Error?o.message:String(o);this._render(`Atomic structure unavailable: ${r}`);}}destroy(){if(!this._destroyed){this._destroyed=true;for(let e of this._unsubs)e();this.element.parentNode!==null&&this.element.parentNode.removeChild(this.element);}}_render(e){for(;this._content.firstChild!==null;)this._content.removeChild(this._content.firstChild);this._content.appendChild(this._doc.createTextNode(e));}};function Zt(i){return i.toLowerCase().replace(/[^a-z0-9]+/g,\"-\").replace(/^-|-$/g,\"\")}var bt=class{constructor(e,t,n,o,r){this._unsubs=[];this._destroyed=false;this._active=false;this._dirty=true;this._refreshToken=0;this._editor=t,this._provider=o,this.name=n,this._doc=r?.documentImpl??S(e);let s=Zt(n);this._content=v(this._doc,\"div\",{class:\"hw-pane__content hw-pane__extra\",\"data-testid\":`extra-pane-content-${s}`}),this.element=v(this._doc,\"div\",{class:\"hw-pane hw-pane--extra\",\"data-testid\":`pane-extra-${s}`},[this._content]),e.appendChild(this.element),this._unsubs.push(t.on(\"helm:changed\",()=>{this._dirty=true,this._active&&this.refresh();}));}setActive(e){this._active=e,e&&this._dirty&&this.refresh();}async refresh(){if(this._destroyed)return;let e=++this._refreshToken;this._dirty=false;let t=this._editor.getHelm();try{let n=await this._provider(t);if(this._destroyed||e!==this._refreshToken)return;this._mount(n);}catch(n){if(this._destroyed||e!==this._refreshToken)return;let o=n instanceof Error?n.message:String(n);this._renderText(`Pane \"${this.name}\" failed: ${o}`);}}destroy(){if(!this._destroyed){this._destroyed=true;for(let e of this._unsubs)e();this.element.parentNode!==null&&this.element.parentNode.removeChild(this.element);}}_mount(e){for(;this._content.firstChild!==null;)this._content.removeChild(this._content.firstChild);this._content.appendChild(e);}_renderText(e){for(;this._content.firstChild!==null;)this._content.removeChild(this._content.firstChild);this._content.appendChild(this._doc.createTextNode(e));}};var rl=\"extra:\";function Qt(i){return rl+i}var sl=[{id:\"sequence\",label:\"Sequence\"},{id:\"helm\",label:\"HELM\"},{id:\"properties\",label:\"Properties\"},{id:\"atomic\",label:\"Atomic Structure\"}],yt=class{constructor(e,t){this._paneByName=new Map;this._tabsByName=new Map;this._unsubs=[];this._activePane=\"helm\";this._destroyed=false;this._statusModeNode=null;this._statusMessageNode=null;this._statusMessageTimeout=null;this._host=e,this._doc=t.documentImpl??S(e);let o=(t.theme??$).name===\"dark\"?\"hw-app hw-app--dark\":\"hw-app\";this.element=v(this._doc,\"div\",{class:o,\"data-testid\":\"app-root\"}),this._toolbarHost=v(this._doc,\"div\",{class:\"hw-app__toolbar\"}),this._paletteHost=v(this._doc,\"div\",{class:\"hw-app__palette\"}),this._canvasHost=v(this._doc,\"div\",{class:\"hw-app__canvas\",\"data-testid\":\"canvas-host\"});let r=v(this._doc,\"div\",{class:\"hw-app__main\"},[this._paletteHost,this._canvasHost]);this._tabsHost=v(this._doc,\"div\",{class:\"hw-app__tabs\",role:\"tablist\"}),this._paneBody=v(this._doc,\"div\",{class:\"hw-app__pane-body\"});let s=v(this._doc,\"div\",{class:\"hw-app__panes\"},[this._tabsHost,this._paneBody]);this.element.appendChild(this._toolbarHost),this.element.appendChild(r),this.element.appendChild(s),e.appendChild(this.element);let a={service:t.service};t.initialHelm!==void 0&&(a.initialHelm=t.initialHelm),t.width!==void 0&&(a.width=t.width),t.height!==void 0&&(a.height=t.height),this.canvas=new at(this._canvasHost,a),t.theme!==void 0&&this.canvas.setTheme(t.theme);let d={documentImpl:this._doc};t.toolbarButtons!==void 0&&(d.buttons=t.toolbarButtons),this.toolbar=new ut(this._toolbarHost,this.canvas,d),this.palette=new ct(this._paletteHost,this.canvas,{documentImpl:this._doc,...t.paletteOptions}),this.sequencePane=new mt(this._paneBody,this.canvas,{documentImpl:this._doc}),this.notationPane=new pt(this._paneBody,this.canvas,{documentImpl:this._doc}),this.propertiesPane=new ht(this._paneBody,this.canvas,{documentImpl:this._doc}),t.service.hasAtomicMolfileProvider()?this.atomicStructurePane=new ft(this._paneBody,this.canvas,{documentImpl:this._doc}):this.atomicStructurePane=null,this._paneByName.set(\"sequence\",this.sequencePane.element),this._paneByName.set(\"helm\",this.notationPane.element),this._paneByName.set(\"properties\",this.propertiesPane.element),this.atomicStructurePane!==null&&this._paneByName.set(\"atomic\",this.atomicStructurePane.element);let l=[];for(let[p,h]of t.service.getExtraPanes()){let y=new bt(this._paneBody,this.canvas,p,h,{documentImpl:this._doc});l.push(y),this._paneByName.set(Qt(p),y.element);}this.extraPanes=l;let u=this._resolveVisiblePanes(t),c=[];for(let p of u){let h=sl.find(y=>y.id===p);h!==void 0&&c.push({id:h.id,label:h.label,testid:`tab-${h.id}`});}for(let p of l)c.push({id:Qt(p.name),label:p.name,testid:`tab-extra-${Zt(p.name)}`});for(let{id:p,label:h,testid:y}of c){let f=this._doc.createElement(\"button\");f.setAttribute(\"type\",\"button\"),f.setAttribute(\"class\",\"hw-app__tab\"),f.setAttribute(\"role\",\"tab\"),f.setAttribute(\"data-pane\",p),f.setAttribute(\"data-testid\",y),f.appendChild(this._doc.createTextNode(h)),f.addEventListener(\"click\",()=>this.activatePane(p)),this._tabsHost.appendChild(f),this._tabsByName.set(p,f);}let m=u.includes(\"helm\")?\"helm\":u[0]??\"helm\";this.activatePane(m),this._unsubs.push(this.canvas.on(\"theme:change\",p=>this._applyTheme(p.theme))),this._buildStatusBar(),this._applyMode(this.canvas.getMode()),this._unsubs.push(this.canvas.on(\"option:change\",p=>{p.key===\"mode\"&&this._applyMode(p.newValue),p.key===\"nextAdd\"&&this._refreshStatus();})),this._unsubs.push(this.canvas.on(\"mol:changed\",()=>this._refreshStatus())),this._unsubs.push(this.canvas.on(\"helm:changed\",()=>this._refreshStatus())),this._unsubs.push(this.canvas.on(\"editor:status\",p=>{this._showStatusMessage(p.message,p.severity,p.durationMs);})),this._unsubs.push(this.canvas.on(\"monomer:contextmenu\",p=>{p.preventDefault(),this.canvas.openAtomProps(p.atom);})),this._unsubs.push(this.canvas.on(\"bond:contextmenu\",p=>{p.preventDefault(),this.canvas.openBondProps(p.bond);})),this._onDocKeydown=p=>this._handleEscape(p),this._doc.addEventListener(\"keydown\",this._onDocKeydown,true);}_handleEscape(e){let t=e;t.key===\"Escape\"&&(Gt(this._doc),X.closeTopmost()&&(t.stopImmediatePropagation?.(),t.preventDefault?.()));}_buildStatusBar(){let e=v(this._doc,\"div\",{class:\"hw-status-bar\",\"data-testid\":\"status-bar\"}),t=v(this._doc,\"span\",{class:\"hw-status-bar__mode\",\"data-testid\":\"status-mode\"}),n=v(this._doc,\"span\",{class:\"hw-status-bar__message\",\"data-testid\":\"status-message\",role:\"status\",\"aria-live\":\"polite\"});e.appendChild(t),e.appendChild(n),this._canvasHost.appendChild(e),this._statusModeNode=t,this._statusMessageNode=n,this._refreshStatus();}_refreshStatus(){let e=this._statusModeNode;if(e===null)return;let t=this.canvas.getMode(),n=this.canvas.getNextAddSymbol();for(;e.firstChild!==null;)e.removeChild(e.firstChild);if(n===null){e.appendChild(this._doc.createTextNode(`Mode: ${t} | Next add: none`));return}e.appendChild(this._doc.createTextNode(`Mode: ${t} | Next add: `));let o=v(this._doc,\"span\",{class:\"hw-status-bar__next-add-symbol\",\"data-testid\":\"status-next-add-symbol\"},[n.symbol]);e.appendChild(o);let r=v(this._doc,\"button\",{type:\"button\",class:\"hw-status-bar__next-add-clear\",\"data-testid\":\"status-next-add-clear\",\"aria-label\":\"Clear next-add monomer\",title:\"Clear (Esc)\"},[\"\\xD7\"]);r.addEventListener(\"click\",s=>{s.preventDefault(),s.stopPropagation(),this.canvas.setNextAddSymbol(null);}),e.appendChild(r);}_showStatusMessage(e,t,n){let o=this._statusMessageNode;if(o!==null){for(this._statusMessageTimeout!==null&&(clearTimeout(this._statusMessageTimeout),this._statusMessageTimeout=null);o.firstChild!==null;)o.removeChild(o.firstChild);o.appendChild(this._doc.createTextNode(e)),o.setAttribute(\"data-severity\",t),n>0&&(this._statusMessageTimeout=setTimeout(()=>{let r=this._statusMessageNode;if(r!==null){for(;r.firstChild!==null;)r.removeChild(r.firstChild);r.removeAttribute(\"data-severity\"),this._statusMessageTimeout=null;}},n));}}_applyMode(e){let t=this._canvasHost.querySelector(\".hw-editor-view\");if(t===null)return;let o=(t.getAttribute(\"class\")??\"\").split(/\\s+/).filter(r=>!r.startsWith(\"hw-editor-view--\")).join(\" \");t.setAttribute(\"class\",`${o} hw-editor-view--${e}`.trim()),this._refreshStatus();}setHelm(e){this.canvas.setHelm(e);}getHelm(){return this.canvas.getHelm()}on(e,t){return this.canvas.on(e,t)}activatePane(e){if(!(!this._paneByName.has(e)&&!this._tabsByName.has(e))){this._activePane=e;for(let[t,n]of this._paneByName.entries())n.style.display=t===e?\"\":\"none\";for(let[t,n]of this._tabsByName.entries()){let r=(n.getAttribute(\"class\")??\"\").split(/\\s+/).filter(s=>s!==\"hw-app__tab--active\").join(\" \");n.setAttribute(\"class\",t===e?`${r} hw-app__tab--active`:r);}for(let t of this.extraPanes)t.setActive(this._activePane===Qt(t.name));}}getActivePane(){return this._activePane}destroy(){if(!this._destroyed){this._destroyed=true,this._statusMessageTimeout!==null&&(clearTimeout(this._statusMessageTimeout),this._statusMessageTimeout=null),this._doc.removeEventListener(\"keydown\",this._onDocKeydown,true);for(let e of this._unsubs)e();for(let e of this.extraPanes)e.destroy();this.atomicStructurePane!==null&&this.atomicStructurePane.destroy(),this.propertiesPane.destroy(),this.notationPane.destroy(),this.sequencePane.destroy(),this.palette.destroy(),this.toolbar.destroy(),this.canvas.destroy(),this.element.parentNode!==null&&this.element.parentNode.removeChild(this.element),this._host;}}_resolveVisiblePanes(e){let t=e.service.hasAtomicMolfileProvider(),n=e.visiblePanes??[\"sequence\",\"helm\",\"properties\",\"atomic\"];return t||(n=n.filter(o=>o!==\"atomic\")),n}_applyTheme(e){let t=e.name===\"dark\",o=(this.element.getAttribute(\"class\")??\"\").split(/\\s+/).filter(r=>r!==\"hw-app--dark\").join(\" \");this.element.setAttribute(\"class\",t?`${o} hw-app--dark`:o);}};var jn=class{constructor(e){this.T=\"ATOM\";this.selected=e.selected,this.highlighted=e.highlighted,this.p={x:e.p.x,y:e.p.y},this.elem=e.symbol,this.bio={type:e.biotype,continuousId:e.bio.continuousId,chainId:e.bio.chainId,positionInChain:e.bio.positionInChain,...e.bio.annotation!==void 0?{annotation:e.bio.annotation}:{},...e.bio.blobtype!==void 0?{blobtype:e.bio.blobtype}:{},...e.bio.ambiguity!==void 0?{ambiguity:e.bio.ambiguity}:{},id:e.id},e.inlineSource!==void 0&&(this.inlineSource=e.inlineSource);}biotype(){return this.bio.type}},qn=class{constructor(e,t,n){this.a1=t,this.a2=n,this.r1=Vi(e.r1),this.r2=Vi(e.r2),this.kind=e.kind;}};function Vi(i){switch(i.kind){case \"numeric\":return i.r;case \"positional\":return i.r;default:return 0}}function se(i){let e=[],t=new Map;for(let r of i.atoms){let s=new jn(r);e.push(s),t.set(r.id,s);}let n=[];for(let r of i.bonds){let s=t.get(r.a1.id),a=t.get(r.a2.id);s===void 0||a===void 0||n.push(new qn(r,s,a));}return {atoms:e,bonds:n,clone(r){return se(i)},_internalMol:i}}var al=400,ll=100,dl=14,ae=class{constructor(e,t,n){this._laidMol=null;this._currentHelm=\"\";this._drawOptions={fontsize:dl};this._noDraw=false;this._svgEl=null;this.host=e,this._service=t,this._doc=n?.documentImpl??S(e),this._width=n?.width??al,this._height=n?.height??ll,this._mol=me(),this._molView=se(this._mol),this.editor=this._buildEditor();}resizeEditor(e,t){this._width=e,this._height=t,this._redraw();}_buildEditor(){let e=this,t={get noDraw(){return e._noDraw},set noDraw(n){e._noDraw=n;},get jsd(){return e.editor}};return {get div(){return e.host},get m(){return e._molView},set m(n){e._molView=n;},get helm(){return t},get options(){return {width:e._width,height:e._height}},setData(n,o){if(o!==\"helm\")throw new Error(`LegacyEditorWrapper: only 'helm' format supported (got '${o}').`);e._setHelm(n);},setHelm(n){e._setHelm(n);},setMol(n){e._mol=n._internalMol,e._molView=e._buildView(e._mol),e._currentHelm=e._service.serialize(e._mol),e._redraw();},getHelm(n){return e._currentHelm},getMolfile(){return Dt(e._mol)},resize(n,o){e._width=n,e._height=o,e._redraw();},setSize(n,o){e._width=n,e._height=o,e._redraw();},redraw(){e._redraw();},reset(){e._mol=me(),e._laidMol=null,e._molView=se(e._mol),e._currentHelm=\"\",e._removeSvg();},getFormula(n){return cl(fe(e._mol))},getMolWeight(){return De(e._mol)},getExtinctionCoefficient(){return Oe(e._mol)},getDrawOptions(){return e._drawOptions}}}_setHelm(e){this._currentHelm=e;let t=this._service.parse(e,{mode:\"lenient\",resolveMonomers:true});this._mol=t.mol,this._molView=this._buildView(this._mol),this._redraw();}_buildView(e){return this._laidMol=this._noDraw?null:oe(e),se(this._laidMol??e)}_redraw(){if(this._noDraw){this._removeSvg();return}if(this._currentHelm===\"\"||this._laidMol===null){this._removeSvg();return}let e=new Set,t=new Set;for(let o of this._molView.atoms){let r=o.bio.id;r!==void 0&&(o.selected&&e.add(r),o.highlighted&&t.add(r));}let n=this._service.renderMolResult(this._laidMol,{width:this._width,height:this._height,maxScale:1/0,showIds:true,selectedAtomIds:e,highlightedAtomIds:t});this._bakeViewToSurface(n.bbox,n.drawBox),this._mountSvg(n.svg);}_bakeViewToSurface(e,t){if(this._laidMol===null)return;let n=t.scale,o=t.x-e.x*n,r=t.y-e.y*n,s=this._laidMol.atoms,a=this._molView.atoms,d=Math.min(s.length,a.length);for(let l=0;l<d;l++){let u=s[l].p,c=a[l].p;c.x=u.x*n+o,c.y=u.y*n+r;}}_mountSvg(e){this._removeSvg();let t=ul(this._doc,e,this._width,this._height);t.setAttribute(\"pointer-events\",\"none\"),this.host.firstChild!==null?this.host.insertBefore(t,this.host.firstChild):this.host.appendChild(t),this._svgEl=t;}_removeSvg(){this._svgEl!==null&&this._svgEl.parentNode!==null&&this._svgEl.parentNode.removeChild(this._svgEl),this._svgEl=null;}},Ui=[\"C\",\"H\",\"N\",\"O\",\"S\",\"P\"];function cl(i){let e=o=>{let r=Ui.indexOf(o);return r===-1?Ui.length:r},t=[...i.elements.keys()].sort((o,r)=>{let s=e(o),a=e(r);return s!==a?s-a:o<r?-1:o>r?1:0}),n=[];for(let o of t){let r=i.elements.get(o);n.push(r===1?o:`${o}${r}`);}return n.join(\"\")}function ul(i,e,t,n){let o=ml(i,e);if(o!==null)return o;let r=i.createElementNS(\"http://www.w3.org/2000/svg\",\"svg\");return r.setAttribute(\"width\",String(t)),r.setAttribute(\"height\",String(n)),r}function ml(i,e){let t=globalThis.DOMParser;if(t===void 0)return null;try{let r=new t().parseFromString(e,\"image/svg+xml\").documentElement;return r==null?null:i.importNode(r,!0)}catch{return null}}var pl=800,hl=400,fl=32,bl=14,Yn=class{constructor(e){this._width=0;this._height=0;this._doc=e;}resize(e,t){this._width=e,this._height=t;}select(){}dblclick(){}createMonomerDiv(e,t,n){let o=v(this._doc,\"div\",{\"data-monomer\":t,\"data-biotype\":n,\"data-testid\":`legacy-mex-monomer-${t}`});return e.appendChild(o),o}getSize(){return {width:this._width,height:this._height}}},gt=class{constructor(e,t,n){this.toolbarheight=fl;this._drawOptions={fontsize:bl};this._unsubs=[];this._destroyed=false;this._host=e,this._service=t,this._doc=n?.documentImpl??S(e),this._width=n?.width??pl,this._height=n?.height??hl;let o={service:t};n?.initialHelm!==void 0&&(o.initialHelm=n.initialHelm),n?.documentImpl!==void 0&&(o.documentImpl=n.documentImpl),n?.width!==void 0&&(o.width=n.width),n?.height!==void 0&&(o.height=n.height),this._app=new yt(e,o),this.sequence=this._app.sequencePane.element,this.notation=this._app.notationPane.element,this.properties={parent:this._app.propertiesPane.element},this._structureviewHost=v(this._doc,\"div\",{class:\"hwe-legacy-app__structureview\",\"data-testid\":\"legacy-app-structureview\"}),this._structureviewWrapper=new ae(this._structureviewHost,t,{documentImpl:this._doc}),this.structureview=this._structureviewWrapper,this.mex=new Yn(this._doc),this._editorFacade=this._buildEditorFacade();let r=this._editorFacade;this.canvas={get host(){return r.div},get editor(){return r},get helm(){return r.helm},resizeEditor:(a,d)=>{this._resize(a,d);},getHelm:a=>r.getHelm(a),setHelm:a=>{r.setHelm(a);}};let s=()=>{this._structureviewWrapper.editor.setHelm(this._app.getHelm());};this._unsubs.push(this._app.canvas.on(\"helm:changed\",s)),n?.initialHelm!==void 0&&n.initialHelm.length>0&&s();}get editorApp(){return this._app}_buildEditorFacade(){let e=this,t=this._app,n={noDraw:false,get jsd(){return e._editorFacade}};return {get div(){return t.element},get m(){return e._currentMolView()},set m(o){o!=null&&o._internalMol!==void 0&&t.canvas.setMol(o._internalMol);},get helm(){return n},get options(){return {width:e._width,height:e._height}},setData(o,r){if(r!==\"helm\")throw new Error(`LegacyAppWrapper: only 'helm' format supported (got '${r}').`);t.setHelm(o);},setHelm(o){t.setHelm(o);},setMol(o){t.canvas.setMol(o._internalMol);},getHelm(o){return t.getHelm()},getMolfile(){return e._service.getMolfile(t.getHelm())},resize(o,r){e._resize(o,r);},setSize(o,r){e._resize(o,r);},redraw(){t.canvas.redraw();},reset(){t.setHelm(\"\");},getFormula(o){return yl(fe(t.canvas.getMol()))},getMolWeight(){return De(t.canvas.getMol())},getExtinctionCoefficient(){return Oe(t.canvas.getMol())},getDrawOptions(){return e._drawOptions}}}_currentMolView(){let e=this._app.canvas.getMol(),t=se(e),n=this._app.canvas.getSelection();if(!n.isEmpty)for(let o of t.atoms){let r=o.bio.id;typeof r==\"number\"&&(o.selected=n.atoms.has(r));}return t}_resize(e,t){this._width=e,this._height=t,this._app.canvas.resize(e,t);}calculateSizes(){let e=zi(this._host.clientWidth,this._width),t=zi(this._host.clientHeight,this._height);this._resize(e,Math.max(50,t-this.toolbarheight));}destroy(){if(!this._destroyed){this._destroyed=true;for(let e of this._unsubs)e();this._unsubs.length=0,this._app.destroy();}}};function yl(i){let e=[];for(let[t,n]of i.elements.entries())e.push(n===1?t:`${t}${n}`);return e.join(\"\")}function zi(i,e){return typeof i!=\"number\"||isNaN(i)||i<=0?e:i}var gl=240,_l=80,_t=class{constructor(e,t,n){this._tooltip=null;this._destroyed=false;this.name=e,this._service=t;let o=n?.documentImpl??vl();if(o===null)throw new Error(\"LegacyInputWrapper: no Document available.\");this._doc=o,this._host=v(this._doc,\"div\",{class:\"hwe-legacy-input\",\"data-testid\":\"legacy-input-host\"}),this.viewer=new ae(this._host,t,{width:n?.editorOptions?.width??gl,height:n?.editorOptions?.height??_l,documentImpl:this._doc});}get value(){return this.viewer.editor.getHelm()}set value(e){this._ensureLive(),this.viewer.editor.setHelm(e);}get molValue(){return this.viewer.editor.m}set molValue(e){this._ensureLive(),this.viewer.editor.setMol(e);}redraw(){this._ensureLive(),this.viewer.editor.redraw();}showTooltip(e,t){this._ensureLive(),this._tooltip!==null&&this._tooltip.parentNode!==null&&this._tooltip.parentNode.removeChild(this._tooltip);let n=v(this._doc,\"div\",{class:\"hwe-legacy-input__tooltip\",\"data-testid\":\"legacy-input-tooltip\",style:`position: absolute; left: ${t.p.x}px; top: ${t.p.y}px;`});typeof e==\"string\"?n.appendChild(this._doc.createTextNode(e)):n.appendChild(e),this._host.appendChild(n),this._tooltip=n;}destroy(){this._destroyed||(this._destroyed=true,this._tooltip!==null&&this._tooltip.parentNode!==null&&this._tooltip.parentNode.removeChild(this._tooltip),this._host.parentNode!==null&&this._host.parentNode.removeChild(this._host));}getHost(){return this._host}getTooltip(){return this._tooltip}_ensureLive(){if(this._destroyed)throw new Error(\"LegacyInputWrapper: this instance has been destroyed.\");this._service;}};function vl(){return globalThis.document??null}var xl=/^R([1-9][0-9]*)$/,Wi=new Set([x.PEPTIDE,x.RNA,x.CHEM,x.BLOB]),wl=new Set([\"Backbone\",\"Branch\",\"Terminal\",\"Undefined\"]);function Ki(i){if(typeof i.symbol!=\"string\"||i.symbol.length===0||typeof i.molfile!=\"string\"||!Wi.has(i.polymerType)||!wl.has(i.monomerType))return null;let e=[];for(let n of i.rgroups??[]){if(typeof n.label!=\"string\"||!xl.test(n.label))continue;let o={label:n.label,capGroupName:typeof n.capGroupName==\"string\"?n.capGroupName:\"\",capGroupSMILES:et(n)??\"\"};typeof n.alternateId==\"string\"&&(o.alternateId=n.alternateId),e.push(o);}let t={symbol:i.symbol,molfile:i.molfile,polymerType:i.polymerType,monomerType:i.monomerType,rgroups:e};return typeof i.name==\"string\"&&(t.name=i.name),typeof i.smiles==\"string\"&&(t.smiles=i.smiles),typeof i.naturalAnalog==\"string\"&&(t.naturalAnalog=i.naturalAnalog),i.meta!==void 0&&i.meta!==null&&(t.meta={...i.meta}),typeof i.author==\"string\"&&(t.author=i.author),i.createDate!==void 0&&(t.createDate=i.createDate),typeof i.id==\"number\"&&(t.id=i.id),t}function kl(i){return i===x.PEPTIDE?g.AA:i===x.RNA?g.SUGAR:i===x.CHEM?g.CHEM:i===x.BLOB?g.BLOB:g.AA}function Xn(i,e,t){if(i===x.PEPTIDE)return g.AA;if(i===x.CHEM)return g.CHEM;if(i===x.BLOB)return g.BLOB;if(i===x.RNA){if(e===\"Branch\")return g.BASE;if(e===\"Backbone\")return t===\"P\"||t===\"p\"?g.LINKER:g.SUGAR}return g.AA}function Al(i,e){let t=i.subscribe(e);return ()=>{t!=null&&typeof t.unsubscribe==\"function\"&&t.unsubscribe();}}var en=class{constructor(e,t){this._cache=new Map;this._polymerTypesCache=null;this._version=0;this._base=e,this.source=t??(typeof e.source==\"string\"?e.source:\"datagrok-bridge\"),this.onChanged=new Z,this._unsub=Al(e.onChanged,()=>{this._cache.clear(),this._polymerTypesCache=null,this._version+=1,this.onChanged.next({type:\"reload\"});});}get version(){return this._version}get isEmpty(){return typeof this._base.isEmpty==\"boolean\"?this._base.isEmpty:this.getPolymerTypes().length===0}getMonomer(e,t){let n=`${e}|${t}`;if(this._cache.has(n))return this._cache.get(n)??null;let o=this._base.getMonomer(e,t),r=o==null?null:this._enrichColors(Ki(o));return this._cache.set(n,r),r}_enrichColors(e){if(e===null)return null;let t=this._base;if(typeof t.getMonomerColors!=\"function\")return e;let n=Xn(e.polymerType,e.monomerType,e.naturalAnalog),o=null;try{o=t.getMonomerColors(n,e.symbol);}catch{o=null;}if(o==null)return e;let r=o.backgroundcolor,s=o.textcolor,a=o.linecolor;if(typeof r!=\"string\"||typeof s!=\"string\"||typeof a!=\"string\")return e;let d={...e.meta??{},colors:{...e.meta?.colors??{},default:{line:a,text:s,background:r}}};return {...e,meta:d}}registerInlineSmilesMonomer(e,t){let n=this._base;typeof n.getWebEditorMonomer==\"function\"&&n.getWebEditorMonomer(kl(e),t);let o=n.getMonomer(e,t),r=o==null?null:this._enrichColors(Ki(o));if(r===null)throw new Error(`BridgedMonomerLib: could not register inline SMILES monomer '${t}'`);return this._cache.set(`${e}|${t}`,r),this._cache.set(`${e}|${r.symbol}`,r),r}getMonomerSet(e){let t=new Map;for(let n of this.getPolymerTypes())for(let o of this.getMonomerSymbolsByType(n)){let r=this.getMonomer(n,o);r!==null&&Xn(r.polymerType,r.monomerType,r.naturalAnalog)===e&&t.set(o,r);}return t}getMonomerSymbolsByType(e){return this._base.getMonomerSymbolsByType(e)}getByNaturalAnalog(e,t){let n=[];for(let o of this.getMonomerSymbolsByType(e)){let r=this.getMonomer(e,o);r!==null&&r.naturalAnalog===t&&n.push(r);}return n}getPolymerTypes(){if(this._polymerTypesCache!==null)return this._polymerTypesCache;let e=[],t=typeof this._base.getPolymerTypes==\"function\"?this._base.getPolymerTypes():Object.values(x);for(let n of t){if(!Wi.has(n))continue;let o=this._base.getMonomerSymbolsByType(n);Array.isArray(o)&&o.length>0&&e.push(n);}return this._polymerTypesCache=e,e}getColors(e,t){let n=t===\"dark\"?Ie:we,o=e===null?g.AA:Xn(e.polymerType,e.monomerType,e.naturalAnalog);return D(e,o,n)}addMonomer(e){throw new Error(\"BridgedMonomerLib: mutation is not supported on a Datagrok-bridged library.\")}removeMonomer(e,t){return false}merge(e){throw new Error(\"BridgedMonomerLib: mutation is not supported on a Datagrok-bridged library.\")}toJSON(){let e=[];for(let t of this.getPolymerTypes())for(let n of this.getMonomerSymbolsByType(t)){let o=this.getMonomer(t,n);o!==null&&e.push(o);}return e}destroy(){this._unsub(),this.onChanged.complete(),this._cache.clear();}};function Jn(i,e){return new en(i,e)}var tn=class tn{constructor(e){this._overriddenFuncs=null;this._originalFuncs=null;this._molfilesEditor=null;this._molfilesEditorHost=null;this._molfilesGcTimer=null;if(e.service===void 0||e.service===null)throw new TypeError(\"HelmHelperAdapter: options.service is required\");this._service=e.service,this.seqHelper=e.seqHelper??null,this._logger=e.logger??new Ce,this._bridge=e.monomerLibBridge??(t=>Jn(t)),this._doc=e.documentImpl??ji();}get service(){return this._service}createHelmInput(e,t){let n={...t};return n.documentImpl===void 0&&this._doc!==null&&(n.documentImpl=this._doc),new _t(e,this._service,n)}createHelmWebEditor(e,t){let n=e??this._createDetachedHost();return new ae(n,this._service,{...t?.width!==void 0?{width:t.width}:{},...t?.height!==void 0?{height:t.height}:{},...this._doc!==null?{documentImpl:this._doc}:{}})}createWebEditorApp(e,t){return new gt(e,this._service,{...t!==void 0?{initialHelm:t}:{},...this._doc!==null?{documentImpl:this._doc}:{}})}get originalMonomersFuncs(){return this._originalFuncs}buildMonomersFuncsFromLib(e){let t=this._bridge(e),n=e;function o(s,a){if(typeof n.getWebEditorMonomer==\"function\"){let p=n.getWebEditorMonomer(s,a);if(p!=null)return p}let{biotype:d,symbol:l}=qi(s,a);if(l===null)return null;let u=Tl(l),c=Yi(d),m=t.getMonomer(c,u);return m===null?null:Xi(m,u)}function r(s){let{biotype:a}=qi(s,void 0),d=Yi(a),l={};for(let u of t.getMonomerSymbolsByType(d)){let c=t.getMonomer(d,u);c!==null&&(l[u]=Xi(c,u));}return l}return {getMonomer:o,getMonomerSet:r}}overrideMonomersFuncs(e){let t=this._overriddenFuncs;return this._originalFuncs===null&&(this._originalFuncs=t??this._defaultFuncs()),this._overriddenFuncs=e,t??this._originalFuncs}revertOriginalMonomersFuncs(){let e=this._originalFuncs??this._defaultFuncs(),t=this._overriddenFuncs??e;return this._overriddenFuncs=e,this._originalFuncs=null,t}getHoveredAtom(e,t,n,o){let s=new q(n._internalMol,$).test({x:e,y:t});if(s===null||s.atom===void 0)return null;for(let a of n.atoms)if(a.bio.id===s.atom.id||a.bio.id===void 0&&a.bio.continuousId===s.atom.bio.continuousId)return a;return null}getMolfiles(e){let t=this._ensureMolfilesEditor();t.editor.helm.noDraw=true;try{let n=[];for(let o of e){if(typeof o!=\"string\"||o.length===0){n.push(\"\");continue}t.editor.setHelm(o),n.push(t.editor.getMolfile());}return n}finally{t.editor.helm.noDraw=false,this._scheduleMolfilesEditorGc();}}parse(e,t){let n=this._service.parse(e,{mode:\"lenient\",resolveMonomers:false}),o=oe(n.mol);return se(o)}removeGaps(e){let t;try{t=this._service.removeGaps(e);}catch(o){throw o instanceof j&&o.type===void 0&&(o.type=\"HelmNotSupportedError\"),o}let n=Ml(this._service,e);return {srcHelm:t.srcHelm,resHelm:t.resHelm,monomerMap:n?new Map(t.monomerMap):null}}destroy(){this._molfilesGcTimer!==null&&(clearTimeout(this._molfilesGcTimer),this._molfilesGcTimer=null),this._removeMolfilesEditorNow();}_defaultFuncs(){return {getMonomer:(e,t)=>null,getMonomerSet:e=>({})}}_createDetachedHost(){let e=this._doc??ji();if(e===null)throw new Error(\"HelmHelperAdapter: no Document available\");let t=e.createElement(\"div\");return t.style.width=\"0px\",t.style.height=\"0px\",t.style.position=\"fixed\",t}_ensureMolfilesEditor(){if(this._molfilesEditor!==null)return this._molfilesGcTimer!==null&&(clearTimeout(this._molfilesGcTimer),this._molfilesGcTimer=null),this._molfilesEditor;let e=this._createDetachedHost();return this._molfilesEditorHost=e,this._molfilesEditor=new ae(e,this._service,{width:100,height:100,...this._doc!==null?{documentImpl:this._doc}:{}}),this._logger,this._molfilesEditor}_scheduleMolfilesEditorGc(){this._molfilesGcTimer!==null&&clearTimeout(this._molfilesGcTimer),typeof setTimeout==\"function\"&&(this._molfilesGcTimer=setTimeout(()=>{this._molfilesGcTimer=null,this._removeMolfilesEditorNow();},tn._MOLFILES_GC_MS));}_removeMolfilesEditorNow(){this._molfilesEditor=null,this._molfilesEditorHost!==null&&this._molfilesEditorHost.parentNode!==null&&this._molfilesEditorHost.parentNode.removeChild(this._molfilesEditorHost),this._molfilesEditorHost=null;}};tn._MOLFILES_GC_MS=1e3;var vt=tn;function ji(){return globalThis.document??null}function Ml(i,e){try{let t=i.parse(e,{mode:\"lenient\",resolveMonomers:!1});for(let n of t.mol.atoms)if(n.symbol===\"*\")return !0;return !1}catch{return false}}function Tl(i){return i.length>=2&&i.charAt(0)===\"[\"&&i.charAt(i.length-1)===\"]\"?i.slice(1,i.length-1):i}function qi(i,e){if(typeof i==\"string\")return {biotype:i,symbol:e??null};if(i!==null&&typeof i==\"object\"&&i.T===\"ATOM\"){let t=i;return {biotype:t.bio.type,symbol:e??t.elem}}return {biotype:g.AA,symbol:e??null}}function Yi(i){switch(i){case g.AA:return x.PEPTIDE;case g.SUGAR:case g.BASE:case g.LINKER:case g.NUCLEOTIDE:return x.RNA;case g.CHEM:return x.CHEM;case g.BLOB:return x.BLOB;default:return x.PEPTIDE}}function Xi(i,e){let t={};for(let o of i.rgroups)t[o.label]=o.capGroupName;let n={id:e??i.symbol,m:i.molfile,rs:i.rgroups.length,type:i.polymerType,mt:i.monomerType,at:t};return i.name!==void 0&&(n.n=i.name),i.naturalAnalog!==void 0&&(n.na=i.naturalAnalog),i.smiles!==void 0&&(n.smiles=i.smiles),n}function Sl(i,e){if(e==null)throw new TypeError(\"registerWithDatagrok: options is required\");let t=new vt({service:e.service,...e.seqHelper!==void 0?{seqHelper:e.seqHelper}:{},...e.logger!==void 0?{logger:e.logger}:{},...e.documentImpl!==void 0?{documentImpl:e.documentImpl}:{}}),n=()=>{};if(typeof e.libProvider==\"function\"){let o=e.libProvider;Promise.resolve().then(()=>o()).then(r=>{if(r==null)return;let s=r.onChanged.subscribe(()=>{t.buildMonomersFuncsFromLib(r);});n=()=>{s!=null&&typeof s.unsubscribe==\"function\"&&s.unsubscribe();};}).catch(()=>{});}return {adapter:t,unsubscribe(){n();}}}\nexport{We as AtomPropsDialog,ft as AtomicStructurePane,je as BondPropsDialog,en as BridgedMonomerLib,Ke as ChooseRDialog,Gi as DEFAULT_TOOLBAR_BUTTONS,Fe as EventBus,bt as ExtraPane,qe as FindReplaceDialog,at as HelmEditor,yt as HelmEditorApp,vt as HelmHelperAdapter,j as HelmNotSupportedError,F as HelmParseError,Vn as HelmService,g as HelmTypes,Ze as HelmValidationError,Ge as HistoryStack,P as HwError,gt as LegacyAppWrapper,ae as LegacyEditorWrapper,_t as LegacyInputWrapper,hn as MonomerLib,rn as MonomerNotFoundError,ct as MonomerPalette,or as MonomerTypes,pt as NotationPane,x as PolymerTypes,ht as PropertiesPane,V as Selection,mt as SequencePane,ut as Toolbar,Ot as bondsOnAtom,Jn as bridgeMonomerLib,se as buildHelmMolView,In as darkTheme,Ss as defineTheme,Qt as extraPaneId,Zt as extraPaneSlug,W as freeRgroups,xa as hasFreeRgroup,$ as lightTheme,Sl as registerWithDatagrok,bi as takenRgroups,be as totalRgroups};","// HELM type vocabulary is owned by `@datagrok-libraries/hwe` (the standalone\n// HELM editor) and re-exported here as the single source of truth. The string\n// values match the canonical Pistoia HELM Web Editor, except `NUCLEOTIDE` which\n// uses the corrected spelling `HELM_NUCLEOTIDE` (was `HELM_NUCLETIDE`).\nimport { HelmTypes, MonomerTypes, PolymerTypes } from '@datagrok-libraries/hwe';\nexport { HelmTypes, MonomerTypes, PolymerTypes };\n// hwe migration: these two small enums are not part of the hwe value vocabulary.\n// They are defined here locally (replicating the legacy HELM Web Editor values)\n// so `@datagrok-libraries/bio` no longer depends on\n// `@datagrok-libraries/helm-web-editor`.\nexport var MonomerNumberingTypes;\n(function (MonomerNumberingTypes) {\n MonomerNumberingTypes[MonomerNumberingTypes[\"default\"] = 0] = \"default\";\n MonomerNumberingTypes[MonomerNumberingTypes[\"continuous\"] = 1] = \"continuous\";\n})(MonomerNumberingTypes || (MonomerNumberingTypes = {}));\nexport var HelmTabKeys;\n(function (HelmTabKeys) {\n HelmTabKeys[\"Sequence\"] = \"sequence\";\n HelmTabKeys[\"Helm\"] = \"notation\";\n HelmTabKeys[\"Properties\"] = \"properties\";\n HelmTabKeys[\"StructureView\"] = \"structureview\";\n})(HelmTabKeys || (HelmTabKeys = {}));\n//# sourceMappingURL=consts.js.map","import { PolymerTypes } from '../helm/consts';\nexport const monomerWorksConsts = {\n // constants for parsing molfile V2000\n V2K_RGP_SHIFT: 8,\n V2K_RGP_LINE: 'M RGP',\n V2K_A_LINE: 'A ',\n // constants for parsing/reconstruction of molfile V3000\n V3K_COUNTS_SHIFT: 14,\n V3K_IDX_SHIFT: 7,\n V3K_HEADER_FIRST_LINE: '\\nDatagrok macromolecule handler\\n\\n',\n V3K_HEADER_SECOND_LINE: ' 0 0 0 0 0 0 999 V3000\\n',\n V3K_BEGIN_CTAB_BLOCK: 'M V30 BEGIN CTAB\\n',\n V3K_END_CTAB_BLOCK: 'M V30 END CTAB\\n',\n V3K_BEGIN_COUNTS_LINE: 'M V30 COUNTS ',\n V3K_COUNTS_LINE_ENDING: ' 0 0 0\\n',\n V3K_BEGIN_ATOM_BLOCK: 'M V30 BEGIN ATOM\\n',\n V3K_END_ATOM_BLOCK: 'M V30 END ATOM\\n',\n V3K_BEGIN_BOND_BLOCK: 'M V30 BEGIN BOND\\n',\n V3K_END_BOND_BLOCK: 'M V30 END BOND\\n',\n V3K_BOND_CONFIG: ' CFG=',\n V3K_BEGIN_DATA_LINE: 'M V30 ',\n V3K_END: 'M END',\n PRECISION_FACTOR: 10000, // HELMCoreLibrary has 4 significant digits after decimal point in atom coordinates\n // symbols for the corresponding monomers in HELM library\n DEOXYRIBOSE: { polymerType: PolymerTypes.RNA, symbol: 'd' },\n RIBOSE: { polymerType: PolymerTypes.RNA, symbol: 'r' },\n PHOSPHATE: { polymerType: PolymerTypes.RNA, symbol: 'p' },\n OXYGEN: 'O',\n HYDROGEN: 'H',\n};\n//# sourceMappingURL=consts.js.map","export function getMolGraph(dict, libKey) {\n return dict[libKey.polymerType]?.[libKey.symbol];\n}\nexport function hasMolGraph(dict, libKey) {\n return !!dict[libKey.polymerType]?.[libKey.symbol];\n}\nexport function setMolGraph(dict, libKey, value) {\n let pt = dict[libKey.polymerType];\n if (!pt)\n pt = dict[libKey.polymerType] = {};\n pt[libKey.symbol] = value;\n}\n/** Role of an entry in a HELM RNA splitted sequence.\n * SUGAR/BASE/PHOSPHATE are the standard triple positions.\n * TERMINAL_5P marks a 5'-end terminal modifier (e.g. Chol) — a monomer\n * with R2 only that takes the place of the leading sugar.\n * TERMINAL_3P marks a 3'-end terminal modifier (e.g. GalNAc) — a monomer\n * with R1 only that takes the place of the trailing phosphate. The OH cap\n * MUST be omitted when a TERMINAL_3P is present. */\nexport var NucleotideRole;\n(function (NucleotideRole) {\n NucleotideRole[NucleotideRole[\"SUGAR\"] = 0] = \"SUGAR\";\n NucleotideRole[NucleotideRole[\"BASE\"] = 1] = \"BASE\";\n NucleotideRole[NucleotideRole[\"PHOSPHATE\"] = 2] = \"PHOSPHATE\";\n NucleotideRole[NucleotideRole[\"TERMINAL_5P\"] = 3] = \"TERMINAL_5P\";\n NucleotideRole[NucleotideRole[\"TERMINAL_3P\"] = 4] = \"TERMINAL_3P\";\n})(NucleotideRole || (NucleotideRole = {}));\nexport class MonomerMap extends Map {\n constructor(entries) {\n super(entries);\n }\n}\n/** @property monomers key - helm seq position, */\nexport class MolfileWithMap {\n constructor(molfile, monomers) {\n this.molfile = molfile;\n this.monomers = monomers;\n }\n static createEmpty() { return new MolfileWithMap('', new MonomerMap(null)); }\n}\n//# sourceMappingURL=types.js.map","import { MonomerTypes, PolymerTypes } from '../helm/consts';\n// hwe exports the HELM type vocabulary as `as const` objects (value-only), not\n// TS enums, so we re-create the value+type duality the old `import X = Enum`\n// aliases provided — consumers use these both as a value (`.RNA`) and as a type.\nconst HELM_POLYMER_TYPE = PolymerTypes;\nconst HELM_MONOMER_TYPE = MonomerTypes;\nexport { HELM_POLYMER_TYPE, HELM_MONOMER_TYPE };\n// core fields of HELM library object used in toAtomicLevel function\nexport const HELM_CORE_FIELDS = [\n \"symbol\" /* HELM_FIELDS.SYMBOL */,\n \"molfile\" /* HELM_FIELDS.MOLFILE */,\n \"rgroups\" /* HELM_FIELDS.RGROUPS */,\n \"name\" /* HELM_FIELDS.NAME */,\n // HELM_FIELDS.MONOMER_TYPE, // add if terminal monomers for PEPTIDEs to be\n // supported\n];\nexport const SDF_MONOMER_NAME = 'MonomerName';\n// todo: ideally, keys should be expressed via constants\nexport const jsonSdfMonomerLibDict = {\n 'monomerType': null, // -> Backbone\n 'smiles': null,\n 'name': 'Name',\n 'author': null,\n 'molfile': 'molecule',\n 'naturalAnalog': 'MonomerNaturalAnalogCode',\n 'rgroups': 'MonomerCaps',\n 'createDate': null,\n 'id': null,\n 'polymerType': 'MonomerType',\n 'symbol': 'MonomerName'\n};\nexport const DUMMY_MONOMER = {\n 'monomerType': 'Backbone',\n 'smiles': '',\n 'name': '',\n 'author': 'Datagrok',\n 'molfile': '',\n 'naturalAnalog': '',\n 'rgroups': [],\n 'createDate': null,\n 'id': 0,\n 'polymerType': 'PEPTIDE',\n 'symbol': ''\n};\n// range of hex nubers used in PepSea library to endode monomers\nexport const MONOMER_ENCODE_MIN = 0x100;\nexport const MONOMER_ENCODE_MAX = 0x40A;\nexport const RIBOSE_SYMBOL = 'r';\nexport const DEOXYRIBOSE_SYMBOL = 'd';\nexport const PHOSPHATE_SYMBOL = 'p';\nexport const HELM_WRAPPERS_REGEXP = new RegExp(`[${RIBOSE_SYMBOL}${DEOXYRIBOSE_SYMBOL}]\\\\((\\\\w)\\\\)${PHOSPHATE_SYMBOL}?`, 'g');\n//# sourceMappingURL=const.js.map","import { CandidateType } from './types';\n/** enum type to simplify setting \"user-friendly\" notation if necessary */\nexport var NOTATION;\n(function (NOTATION) {\n NOTATION[\"FASTA\"] = \"fasta\";\n NOTATION[\"SEPARATOR\"] = \"separator\";\n NOTATION[\"HELM\"] = \"helm\";\n /* Requires notation handler */ NOTATION[\"CUSTOM\"] = \"custom\";\n /* Requires notation handler */ NOTATION[\"BILN\"] = \"biln\";\n})(NOTATION || (NOTATION = {}));\nexport var ALPHABET;\n(function (ALPHABET) {\n ALPHABET[\"DNA\"] = \"DNA\";\n ALPHABET[\"RNA\"] = \"RNA\";\n ALPHABET[\"PT\"] = \"PT\";\n /** Unknown */\n ALPHABET[\"UN\"] = \"UN\";\n})(ALPHABET || (ALPHABET = {}));\nexport var TAGS;\n(function (TAGS) {\n TAGS[\"aligned\"] = \"aligned\";\n TAGS[\"alphabet\"] = \"alphabet\";\n TAGS[\"alphabetSize\"] = \".alphabetSize\";\n TAGS[\"alphabetIsMultichar\"] = \".alphabetIsMultichar\";\n TAGS[\"separator\"] = \"separator\";\n TAGS[\"isHelmCompatible\"] = \".isHelmCompatible\";\n TAGS[\"positionNames\"] = \".positionNames\";\n TAGS[\"positionLabels\"] = \".positionLabels\";\n TAGS[\"regions\"] = \".regions\";\n TAGS[\"positionShift\"] = \".positionShift\";\n TAGS[\"selectedPosition\"] = \".selectedPosition\";\n TAGS[\"polymerTypeColumnName\"] = \".polymerTypeColumnName\";\n TAGS[\"annotations\"] = \".annotations\";\n TAGS[\"numberingScheme\"] = \".numberingScheme\";\n TAGS[\"annotationColumnName\"] = \".annotationColumnName\";\n})(TAGS || (TAGS = {}));\nexport { TAGS as BioTags };\nexport const positionSeparator = ', ';\nexport const monomerRe = /(?:\\[([A-Za-z0-9_\\-,()]+)\\])|([A-Za-z\\-])/g;\nexport const helmRe = /(PEPTIDE1|DNA1|RNA1)\\{([^}]+)}/g;\nexport const helmPp1Re = /\\[([^\\[\\]]+)]/g;\nexport const Alphabets = new class {\n constructor() {\n this.fasta = {\n peptide: new Set([\n 'G', 'L', 'Y', 'S', 'E', 'Q', 'D', 'N', 'F', 'A',\n 'K', 'R', 'H', 'C', 'V', 'P', 'W', 'I', 'M', 'T',\n ]),\n dna: new Set(['A', 'C', 'G', 'T']),\n rna: new Set(['A', 'C', 'G', 'U']),\n };\n }\n}();\nexport const candidateAlphabets = [\n new CandidateType(ALPHABET.PT, Alphabets.fasta.peptide, 0.50),\n new CandidateType(ALPHABET.DNA, Alphabets.fasta.dna, 0.55),\n new CandidateType(ALPHABET.RNA, Alphabets.fasta.rna, 0.55),\n];\n/** Canonical gap symbol */\nexport const GAP_SYMBOL = '';\nexport const GapOriginals = {\n [NOTATION.FASTA]: '-',\n [NOTATION.SEPARATOR]: '',\n [NOTATION.HELM]: '*',\n [NOTATION.BILN]: '',\n};\nexport const MONOMER_MOTIF_SPLITTER = ' , ';\n/** Tag on Monomer columns storing the nqName of a function that returns an IMonomerCanonicalizer.\n * The `.%` prefix ensures this tag is persisted with projects. */\nexport const MONOMER_CANONICALIZER_FUNC_TAG = '.%monomer-canonicalizer-func';\n/** Column temp key for the cached IMonomerCanonicalizer instance */\nexport const MONOMER_CANONICALIZER_TEMP = 'monomer-canonicalizer';\nexport const NOTATION_PROVIDER_CONSTRUCTOR_ROLE = 'notationProviderConstructor';\n//# sourceMappingURL=consts.js.map","import { NOTATION_PROVIDER_CONSTRUCTOR_ROLE } from './consts';\nexport class NotationProviderBase {\n /** Name of the custom notation */\n static get notationName() {\n return 'Custom';\n }\n ;\n /** flag to let bio know if this provider implements method for converting helm to it */\n static get implementsFromHelm() {\n return false;\n }\n ;\n /** Method for converting HELM to this notation */\n static convertFromHelm(helm, options) {\n throw new Error(`Method convertFromHelm not implemented for this notation provider`);\n }\n ;\n static async getProviderConstructors() {\n // this is terrible, I know, but otherwise this gets put in webworkers and fails due to DG resolution)))\n // @ts-ignore\n if (window?.DG) {\n // @ts-ignore\n const constFuncs = window.DG.Func.find({ meta: { role: NOTATION_PROVIDER_CONSTRUCTOR_ROLE } });\n return Promise.all(constFuncs.map((f) => f.apply({})));\n }\n return [];\n }\n}\n/** Alphabet candidate type */\nexport class CandidateType {\n constructor(name, alphabet, cutoff) {\n this.name = name;\n this.alphabet = alphabet;\n this.cutoff = cutoff;\n }\n}\n/** Alphabet candidate similarity type */\nexport class CandidateSimType extends CandidateType {\n constructor(candidate, freq, similarity) {\n super(candidate.name, candidate.alphabet, candidate.cutoff);\n this.freq = freq;\n this.similarity = similarity;\n }\n}\n//# sourceMappingURL=types.js.map","import { HelmTypes, PolymerTypes } from '../helm/consts';\nexport class MonomerWorks {\n //private molfileConverter: IMolfileConverter;\n constructor(monomerLib /*, molfileConverter: IMolfileConverter*/) {\n this.monomerLib = monomerLib;\n //this.molfileConverter = molfileConverter;\n }\n //types according to Monomer possible\n getCappedRotatedMonomer(monomerType, monomerName) {\n // TODO: Check type of monomerType arg\n const monomer = this.monomerLib.getMonomer(monomerType, monomerName);\n if (monomer)\n return monomer.molfile; //TODO cap\n return null;\n }\n}\nexport function helmTypeToPolymerType(helmType) {\n let polymerType = undefined;\n switch (helmType) {\n case HelmTypes.BASE:\n case HelmTypes.SUGAR: // r - ribose, d - deoxyribose\n case HelmTypes.LINKER: // p - phosphate\n case HelmTypes.NUCLEOTIDE:\n // @ts-ignore\n case 'nucleotide':\n polymerType = PolymerTypes.RNA;\n break;\n case HelmTypes.AA:\n polymerType = PolymerTypes.PEPTIDE;\n break;\n case HelmTypes.CHEM:\n polymerType = PolymerTypes.CHEM;\n break;\n case HelmTypes.BLOB:\n polymerType = PolymerTypes.BLOB;\n break;\n default:\n polymerType = PolymerTypes.PEPTIDE;\n console.warn(`Unexpected HelmType '${helmType}'`);\n }\n return polymerType;\n}\n//# sourceMappingURL=monomer-works.js.map","/* eslint-disable max-len */\nimport { monomerWorksConsts as C } from './consts';\nimport { getMolGraph, MolfileWithMap, MonomerMap, NucleotideRole } from './types';\nimport { HELM_CORE_FIELDS, HELM_POLYMER_TYPE, HELM_MONOMER_TYPE, } from '../utils/const';\nimport { ALPHABET, GAP_SYMBOL } from '../utils/macromolecule/consts';\nimport { helmTypeToPolymerType } from './monomer-works';\n/** Get a mapping of peptide symbols to HELM monomer library objects with selected fields.\n * @param {IMonomerLib} monomerLib - Monomer library\n * @param {HELM_POLYMER_TYPE} polymerType - Polymer type\n * @param {ALPHABET} alphabet - Alphabet of the column\n * @return {Map<string, any>} - Mapping of peptide symbols to HELM monomer library objects with selected fields*/\nexport function getFormattedMonomerLib(monomerLib, polymerType, alphabet) {\n const map = new Map();\n for (const monomerSymbol of monomerLib.getMonomerSymbolsByType(polymerType)) {\n const it = monomerLib.getMonomer(polymerType, monomerSymbol);\n if (\n // RNA: all branch monomers (bases) and all backbone monomers (sugars +\n // phosphates, including modified ones). Modifications are looked up by\n // symbol at assembly time, so they MUST be present in the formatted lib.\n polymerType === HELM_POLYMER_TYPE.RNA || (polymerType === HELM_POLYMER_TYPE.PEPTIDE &&\n it[\"monomerType\" /* HELM_FIELDS.MONOMER_TYPE */] !== HELM_MONOMER_TYPE.BRANCH)) {\n const monomerObject = {};\n HELM_CORE_FIELDS.forEach((field) => {\n //@ts-ignore\n monomerObject[field] = it[field];\n });\n map.set(monomerSymbol, monomerObject);\n }\n }\n return map;\n}\n/** Translate a sequence of monomer symbols into Molfile V3000\n * @param {ISeqMonomer[]} monomerSeq - Sequence of monomer symbols (canonical)\n * @param {MonomerMolGraphMap} monomersDict - Mapping of monomer symbols to MolGraph objects\n * @param {ALPHABET} alphabet - Alphabet of the column\n * @param {PolymerType} polymerType - Polymer type\n * @param {Array} roles - Optional per-position NucleotideRole tags. When set, RNA assembly\n * uses per-position sugars/phosphates from monomerSeq directly (HELM triples mode).\n * @param {number[]} chainStarts - Optional 0-based start positions of disjoint HELM chains.\n * When more than one chain is present each chain is assembled independently and the\n * chains are stacked vertically into a single molfile (multi-strand HELM support).\n * @return {MolfileWithMap} - Molfile V3000 + per-position monomer index map */\nexport function monomerSeqToMolfile(monomerSeq, monomersDict, alphabet, polymerType, roles, chainStarts) {\n if (monomerSeq.length === 0) {\n // throw new Error('monomerSeq is empty');\n return MolfileWithMap.createEmpty();\n }\n // Multi-chain HELM (e.g. RNA1{...}|RNA2{...}): assemble each disjoint chain\n // on its own, then stack them vertically into a single molfile. Each chain\n // reuses the exact single-chain assembly below, so its geometry, capping and\n // per-monomer atom/bond map are unchanged; combineMolfilesVertically shifts\n // the coordinates and re-bases the atom/bond indices and monomer-map keys.\n if (chainStarts && chainStarts.length > 1) {\n const parts = new Array(chainStarts.length);\n for (let c = 0; c < chainStarts.length; ++c) {\n const s = chainStarts[c];\n const e = c + 1 < chainStarts.length ? chainStarts[c + 1] : monomerSeq.length;\n const subSeq = monomerSeq.slice(s, e);\n const subRoles = roles ? roles.slice(s, e) : undefined;\n parts[c] = monomerSeqToMolfile(subSeq, monomersDict, alphabet, polymerType, subRoles);\n }\n return combineMolfilesVertically(parts, chainStarts);\n }\n // Triples mode is on only when the caller flagged the row with roles\n // (built and validated by `buildRolesForHelmRna` in to-atomic-level.ts).\n // The roles array carries the per-position semantics — including\n // TERMINAL_5P / TERMINAL_3P for non-canonical chain ends — so we don't\n // re-validate the length here.\n const triplesMode = polymerType === HELM_POLYMER_TYPE.RNA && !!roles &&\n roles.length === monomerSeq.length;\n // define atom and bond counts, taking into account the bond type\n const { atomCount, bondCount, needsCapping } = getResultingAtomBondCounts(monomerSeq, monomersDict, alphabet, polymerType, triplesMode, roles);\n // create arrays to store lines of the resulting molfile\n const molfileAtomBlock = new Array(atomCount);\n const molfileBondBlock = new Array(bondCount);\n let addMonomerToMolblock;\n let sugar = null;\n let phosphate = null;\n if (polymerType === HELM_POLYMER_TYPE.PEPTIDE)\n addMonomerToMolblock = addAminoAcidToMolblock;\n else { // nucleotides\n addMonomerToMolblock = addNucleotideToMolblock;\n // Default sugar/phosphate are only consulted in bases-only mode. In\n // triples mode, every nucleotide carries its own.\n if (!triplesMode) {\n sugar = (alphabet === ALPHABET.DNA) ? getMolGraph(monomersDict, C.DEOXYRIBOSE) : getMolGraph(monomersDict, C.RIBOSE);\n phosphate = getMolGraph(monomersDict, C.PHOSPHATE);\n }\n }\n const v = {\n i: 0,\n nodeShift: 0,\n bondShift: 0,\n backbonePositionShift: new Array(2).fill(0),\n branchPositionShift: new Array(2).fill(0),\n backboneAttachNode: 0,\n branchAttachNode: 0,\n flipFactor: 1,\n };\n const LC = {\n sugar: sugar,\n phosphate: phosphate,\n // In triples mode, the \"logical\" sequence length is the nucleotide count.\n seqLength: triplesMode ? Math.ceil(monomerSeq.length / 3) : monomerSeq.length,\n atomCount: atomCount,\n bondCount: bondCount,\n };\n const monomers = new MonomerMap();\n const steabsCollection = [];\n let nAtoms = 0;\n let lastMonomerCappingAtom = undefined;\n if (triplesMode) {\n runTriplesAssembly(monomerSeq, roles, monomersDict, molfileAtomBlock, molfileBondBlock, v, LC, monomers, steabsCollection, (a) => { nAtoms += a; }, () => nAtoms);\n }\n else {\n for (v.i = 0; v.i < LC.seqLength; ++v.i) {\n const seqMonomer = monomerSeq[v.i];\n if (seqMonomer.symbol === GAP_SYMBOL)\n continue;\n const monomer = getMolGraph(monomersDict, { symbol: seqMonomer.symbol, polymerType: helmTypeToPolymerType(seqMonomer.biotype) });\n lastMonomerCappingAtom = monomer.terminalR2Atom;\n const mAtomFirst = v.nodeShift;\n const mBondFirst = v.bondShift;\n addMonomerToMolblock(monomer, molfileAtomBlock, molfileBondBlock, v, LC);\n //adding stereo atoms to array for further STEABS block generation\n monomer.stereoAtoms?.forEach((i) => steabsCollection.push(i + nAtoms));\n nAtoms += monomer.atoms.x.length;\n const mAtomCount = v.nodeShift - mAtomFirst;\n const mAtomList = new Array(mAtomCount);\n for (let maI = 0; maI < mAtomCount; ++maI)\n mAtomList[maI] = mAtomFirst + maI;\n const mBondCount = v.bondShift - mBondFirst;\n const mBondList = new Array(mBondCount);\n for (let mbI = 0; mbI < mBondCount; ++mbI)\n mBondList[mbI] = mBondFirst + mbI;\n monomers.set(v.i, {\n biotype: seqMonomer.biotype,\n symbol: seqMonomer.symbol,\n atoms: mAtomList, bonds: mBondList\n });\n }\n }\n // if the last monomer needs to be capped, add the terminal OH to the resulting molfile\n if (needsCapping)\n capResultingMolblock(molfileAtomBlock, molfileBondBlock, v, LC, lastMonomerCappingAtom ?? C.OXYGEN);\n const molfileCountsLine = C.V3K_BEGIN_COUNTS_LINE + atomCount + ' ' + bondCount + C.V3K_COUNTS_LINE_ENDING;\n // todo: possible optimization may be achieved by replacing .join('') with +=\n // since counterintuitively joining an array into a new string is reportedly\n // slower than using += as below\n let result = '';\n result += C.V3K_HEADER_FIRST_LINE;\n result += C.V3K_HEADER_SECOND_LINE;\n result += C.V3K_BEGIN_CTAB_BLOCK;\n result += molfileCountsLine;\n result += C.V3K_BEGIN_ATOM_BLOCK;\n result += molfileAtomBlock.join('');\n result += C.V3K_END_ATOM_BLOCK;\n result += C.V3K_BEGIN_BOND_BLOCK;\n result += molfileBondBlock.join('');\n result += C.V3K_END_BOND_BLOCK;\n if (steabsCollection.length > 0)\n result += getCollectionBlock(steabsCollection);\n result += C.V3K_END_CTAB_BLOCK;\n result += C.V3K_END;\n // return molfileParts.join('');\n return { molfile: result, monomers: monomers };\n}\nfunction getCollectionBlock(collection) {\n //one row in STEABS block can be no longer than 80 symbols\n //maxSymbols = 80 symbols minus ' -\\n' (4 symbols)\n const maxSymbols = 76;\n const rowsArray = [];\n let newCollectionRow = `M V30 MDLV30/STEABS ATOMS=(${collection.length}`;\n for (let i = 0; i < collection.length; i++) {\n const updatedRow = `${newCollectionRow} ${collection[i]}`;\n if (updatedRow.length > maxSymbols) {\n rowsArray.push(`${newCollectionRow} -\\n`);\n newCollectionRow = `M V30 ${collection[i]}`;\n }\n else\n newCollectionRow = updatedRow;\n //in case last atom was added - close the block\n if (i === collection.length - 1)\n rowsArray.push(`${newCollectionRow})\\n`);\n }\n return `M V30 BEGIN COLLECTION\\n${rowsArray.join('')}M V30 END COLLECTION\\n`;\n}\n/** Cap the resulting (after sewing up all the monomers) molfile with 'O'\n * @param {string[]} molfileAtomBlock - Array of lines of the resulting molfile atom block\n * @param {string[]} molfileBondBlock - Array of lines of the resulting molfile bond block\n * @param {LoopVariables} v - Loop variables\n * @param {LoopConstants} LC - Loop constants*/\nfunction capResultingMolblock(molfileAtomBlock, molfileBondBlock, v, LC, cappingAtomType = C.OXYGEN) {\n // add terminal oxygen\n const atomIdx = v.nodeShift + 1;\n molfileAtomBlock[LC.atomCount] = C.V3K_BEGIN_DATA_LINE + atomIdx + ' ' +\n (cappingAtomType ?? C.OXYGEN) + ' ' + keepPrecision(v.backbonePositionShift[0]) + ' ' +\n v.flipFactor * keepPrecision(v.backbonePositionShift[1]) + ' ' + '0.000000 0' + '\\n';\n // add terminal bond\n const firstAtom = v.backboneAttachNode;\n const secondAtom = atomIdx;\n molfileBondBlock[LC.bondCount] = C.V3K_BEGIN_DATA_LINE + v.bondShift + ' ' +\n 1 + ' ' + firstAtom + ' ' + secondAtom + '\\n';\n}\nfunction addAminoAcidToMolblock(monomer, molfileAtomBlock, molfileBondBlock, v) {\n v.flipFactor = (-1) ** (v.i % 2); // to flip every even monomer over OX\n addBackboneMonomerToMolblock(monomer, molfileAtomBlock, molfileBondBlock, v);\n}\nfunction addBackboneMonomerToMolblock(monomer, molfileAtomBlock, molfileBondBlock, v) {\n // todo: remove these comments to the docstrings of the corr. functions\n // construnct the lines of V3K molfile atom block\n fillAtomLines(monomer, molfileAtomBlock, v);\n // construct the lines of V3K molfile bond block\n fillBondLines(monomer, molfileBondBlock, v);\n // peptide bond\n fillChainExtendingBond(monomer, molfileBondBlock, v);\n // update branch variables if necessary\n if (monomer.meta.branchShift !== null && monomer.meta.terminalNodes.length > 2)\n updateBranchVariables(monomer, v);\n // update loop variables\n updateChainExtendingVariables(monomer, v);\n}\nfunction addNucleotideToMolblock(nucleobase, molfileAtomBlock, molfileBondBlock, v, LC) {\n // construnct the lines of V3K molfile atom block corresponding to phosphate\n // and sugar\n if (v.i === 0)\n addBackboneMonomerToMolblock(LC.sugar, molfileAtomBlock, molfileBondBlock, v);\n else {\n for (const monomer of [LC.phosphate, LC.sugar])\n addBackboneMonomerToMolblock(monomer, molfileAtomBlock, molfileBondBlock, v);\n }\n addBranchMonomerToMolblock(nucleobase, molfileAtomBlock, molfileBondBlock, v);\n}\nfunction addBranchMonomerToMolblock(monomer, molfileAtomBlock, molfileBondBlock, v) {\n fillBranchAtomLines(monomer, molfileAtomBlock, v);\n fillBondLines(monomer, molfileBondBlock, v);\n fillBackboneToBranchBond(monomer, molfileBondBlock, v);\n // C-N bond\n const bondIdx = v.bondShift;\n const firstAtom = v.branchAttachNode;\n const secondAtom = monomer.meta.terminalNodes[0] + v.nodeShift;\n molfileBondBlock[bondIdx - 1] = C.V3K_BEGIN_DATA_LINE + bondIdx + ' ' +\n 1 + ' ' + firstAtom + ' ' + secondAtom + '\\n';\n // update loop variables\n v.bondShift += monomer.bonds.atomPairs.length + 1;\n v.nodeShift += monomer.atoms.atomTypes.length;\n}\nfunction updateChainExtendingVariables(monomer, v) {\n v.backboneAttachNode = v.nodeShift + monomer.meta.terminalNodes[1];\n v.bondShift += monomer.bonds.atomPairs.length + 1;\n v.nodeShift += monomer.atoms.atomTypes.length;\n v.backbonePositionShift[0] += monomer.meta.backboneShift?.[0] ?? 0; // todo: non-null check\n v.backbonePositionShift[1] += v.flipFactor * (monomer.meta.backboneShift?.[1] ?? 0);\n}\nfunction updateBranchVariables(monomer, v) {\n v.branchAttachNode = v.nodeShift + monomer.meta.terminalNodes[2];\n for (let i = 0; i < 2; ++i)\n v.branchPositionShift[i] = v.backbonePositionShift[i] + monomer.meta.branchShift[i];\n}\nfunction fillAtomLines(monomer, molfileAtomBlock, v) {\n for (let j = 0; j < monomer.atoms.atomTypes.length; ++j) {\n const atomIdx = v.nodeShift + j + 1;\n molfileAtomBlock[v.nodeShift + j] = C.V3K_BEGIN_DATA_LINE + atomIdx + ' ' +\n monomer.atoms.atomTypes[j] + ' ' +\n keepPrecision(v.backbonePositionShift[0] + monomer.atoms.x[j]) + ' ' +\n keepPrecision(v.backbonePositionShift[1] + v.flipFactor * monomer.atoms.y[j]) +\n ' ' + monomer.atoms.kwargs[j];\n }\n}\n// todo: remove as quickfix\nfunction fillBranchAtomLines(monomer, molfileAtomBlock, v) {\n for (let j = 0; j < monomer.atoms.atomTypes.length; ++j) {\n const atomIdx = v.nodeShift + j + 1;\n molfileAtomBlock[v.nodeShift + j] = C.V3K_BEGIN_DATA_LINE + atomIdx + ' ' +\n monomer.atoms.atomTypes[j] + ' ' +\n keepPrecision(v.branchPositionShift[0] + monomer.atoms.x[j]) + ' ' +\n keepPrecision(v.branchPositionShift[1] + v.flipFactor * monomer.atoms.y[j]) +\n ' ' + monomer.atoms.kwargs[j];\n }\n}\nfunction fillBondLines(monomer, molfileBondBlock, v) {\n // construct the lines of V3K molfile bond block\n for (let j = 0; j < monomer.bonds.atomPairs.length; ++j) {\n const bondIdx = v.bondShift + j + 1;\n const firstAtom = monomer.bonds.atomPairs[j][0] + v.nodeShift;\n const secondAtom = monomer.bonds.atomPairs[j][1] + v.nodeShift;\n let bondCfg = '';\n if (monomer.bonds.bondConfiguration.has(j)) {\n // flip orientation when necessary\n let orientation = monomer.bonds.bondConfiguration.get(j);\n if (v.flipFactor < 0)\n orientation = (orientation === 1) ? 3 : 1;\n bondCfg = ' CFG=' + orientation;\n }\n const kwargs = monomer.bonds.kwargs.has(j) ?\n ' ' + monomer.bonds.kwargs.get(j) : '';\n molfileBondBlock[v.bondShift + j] = C.V3K_BEGIN_DATA_LINE + bondIdx + ' ' +\n monomer.bonds.bondTypes[j] + ' ' +\n firstAtom + ' ' + secondAtom + bondCfg + kwargs + '\\n';\n }\n}\nfunction fillChainExtendingBond(monomer, molfileBondBlock, v) {\n if (v.backboneAttachNode !== 0) {\n const bondIdx = v.bondShift;\n const firstAtom = v.backboneAttachNode;\n const secondAtom = monomer.meta.terminalNodes[0] + v.nodeShift;\n molfileBondBlock[v.bondShift - 1] = C.V3K_BEGIN_DATA_LINE + bondIdx + ' ' +\n 1 + ' ' + firstAtom + ' ' + secondAtom + '\\n';\n }\n}\n// todo: remove\nfunction fillBackboneToBranchBond(branchMonomer, molfileBondBlock, v) {\n const bondIdx = v.bondShift;\n const firstAtom = v.branchAttachNode;\n const secondAtom = branchMonomer.meta.terminalNodes[0] + v.nodeShift;\n molfileBondBlock[bondIdx - 1] = C.V3K_BEGIN_DATA_LINE + bondIdx + ' ' +\n 1 + ' ' + firstAtom + ' ' + secondAtom + '\\n';\n}\n/** Compute the atom/bond counts for the resulting molfile, depending on the\n * type of polymer (peptide/nucleotide)\n * @param {ISeqMonomer[]} monomerSeq - the sequence of monomers\n * @param {MonomerMolGraphMap} monomersDict - the dictionary of monomers\n * @param {ALPHABET} alphabet - the alphabet of the monomers\n * @param {PolymerType} polymerType - the type of polymer\n * @param {boolean} triplesMode - true when monomerSeq is a flat list of HELM RNA triples\n * @param {Array} roles - per-position role tags (only meaningful when triplesMode is true)\n * @return {Object} the atom/bond counts plus needsCapping flag */\nfunction getResultingAtomBondCounts(monomerSeq, monomersDict, alphabet, polymerType, triplesMode, roles) {\n let atomCount = 0;\n let bondCount = 0;\n let monomerCount = 0;\n let needsCapping = true;\n let lastMonomerGraph = null;\n let lastPhosphateGraph = null;\n // sum up all the atoms/nodes provided by the sequence\n for (let i = 0; i < monomerSeq.length; ++i) {\n const seqMonomer = monomerSeq[i];\n if (seqMonomer.symbol === GAP_SYMBOL)\n continue; // Skip for gap/empty monomer in MSA\n if (seqMonomer.symbol == '*')\n throw new Error(`Gap canonical symbol is '', not '*`);\n lastMonomerGraph = getMolGraph(monomersDict, { symbol: seqMonomer.symbol, polymerType: helmTypeToPolymerType(seqMonomer.biotype) });\n atomCount += lastMonomerGraph.atoms.x.length;\n bondCount += lastMonomerGraph.bonds.bondTypes.length;\n monomerCount++;\n // In triples mode, every 3rd entry (index 2 mod 3) is a phosphate. Track\n // the LAST one — its atoms/bonds are dropped at the 3'-terminus.\n if (triplesMode && i % 3 === 2)\n lastPhosphateGraph = lastMonomerGraph;\n }\n // add extra values depending on the polymer type\n if (polymerType === HELM_POLYMER_TYPE.PEPTIDE) {\n // add the rightmost/terminating cap group 'OH' (i.e. 'O')\n atomCount += 1;\n // add chain-extending bonds (C-NH per each monomer pair and terminal C-OH)\n bondCount += monomerCount;\n // if the last monomer is something like NH2, which only has R1, there is no need to cap it\n // although, this should never happen, but hey... in other bits of code, there is a chunk that adds pseudo-R2 as hydrogen\n // we should also check, if the R2 of the last monomer is not hydrogen, that case should also be omitted\n if (monomerCount > 0) {\n if ((lastMonomerGraph?.meta?.rNodes?.length ?? 0) < 2 || lastMonomerGraph?.terminalR2Atom?.toLowerCase() === C.HYDROGEN.toLowerCase()) {\n needsCapping = false;\n atomCount -= 1; // remove the last atom (the terminal 'O')\n bondCount -= 1; // remove the last bond (the terminal C-OH)\n }\n }\n }\n else if (triplesMode) { // nucleotides — HELM triples (per-position sugar/base/phosphate)\n void lastPhosphateGraph; // kept for symmetry; trailing P is now retained when HELM wrote it\n // Per-monomer-loop already summed sugars + bases + phosphates for every\n // entry in monomerSeq (terminals included). Reservation: each backbone\n // emit (sugar / phosphate / terminal) reserves +1 bond slot for the\n // chain-extending bond, each branch (base) reserves +1 for its branch\n // bond. Total reservations = monomerCount.\n bondCount += monomerCount;\n // OH cap atom rides on the 3'-end. Skip it when HELM specified a\n // 3'-terminal modifier (e.g. GalNAc) that IS the chain end.\n const has3pTerm = !!roles && roles.length > 0 &&\n roles[roles.length - 1] === NucleotideRole.TERMINAL_3P;\n if (has3pTerm) {\n needsCapping = false;\n // Mirror the peptide branch (which does both atomCount-- and bondCount--\n // when it skips the terminal cap). `bondCount += monomerCount` above\n // reserves one chain-extending slot per monomer; the LAST monomer's slot\n // is normally filled by the terminal OH cap bond. With a 3'-terminal\n // modifier there is no cap, so that last reserved slot stays empty —\n // leaving the declared bond count one higher than the emitted bond\n // lines. Drop it so the V3000 COUNTS line matches the bond block exactly\n // (otherwise the pre-OCL molfile is malformed and only survives because\n // the OCL chirality pass re-derives the counts).\n bondCount -= 1;\n }\n else\n atomCount += 1; // OH cap atom (rides on trailing P or on last sugar's R2)\n }\n else { // nucleotides — bases-only legacy path with default sugar/phosphate\n const sugar = (alphabet === ALPHABET.DNA) ?\n getMolGraph(monomersDict, C.DEOXYRIBOSE) : getMolGraph(monomersDict, C.RIBOSE);\n const phosphate = getMolGraph(monomersDict, C.PHOSPHATE);\n // add phosphate per each pair of nucleobase symbols\n atomCount += (monomerSeq.length - 1) * phosphate.atoms.x.length;\n // add sugar per each nucleobase symbol\n atomCount += monomerSeq.length * sugar.atoms.x.length;\n // add the leftmost cap group 'OH' (i.e. 'O')\n atomCount += 1;\n // add bonds from phosphate monomers\n bondCount += (monomerSeq.length - 1) * phosphate.bonds.bondTypes.length;\n // add bonds from sugar monomers\n bondCount += monomerSeq.length * sugar.bonds.bondTypes.length;\n // exclude the first chain-extending bond O-P (absent, no 'leftmost' phosphate)\n bondCount -= 1;\n // add chain-extending and branch bonds (O-P, C-O and C-N per each nucleotide)\n bondCount += monomerSeq.length * 3;\n }\n return { atomCount, bondCount, needsCapping };\n}\n// Role-driven RNA assembly. Walks the monomers in chain order and emits\n// each one according to its NucleotideRole (assigned by `buildRolesForHelmRna`\n// from the library, not from a fixed triple index):\n// - BASE → branch monomer, attached to the\n// branch point of the sugar most\n// recently emitted.\n// - SUGAR / PHOSPHATE / TERMINAL_5P / 3P → backbone monomer, chained to the\n// previous backbone unit.\n//\n// Because the role comes from chemistry, this transparently handles every\n// backbone layout — standard [sugar, base, phosphate] triples, a 5'-leading\n// phosphate, several phosphates / linkers in a row, a linker dropped in the\n// middle of the chain, missing trailing phosphate, and 5'/3' terminal\n// modifiers — without any index arithmetic. The first backbone monomer\n// naturally has no incoming chain bond (v.backboneAttachNode starts at 0),\n// and the trailing OH cap is added by the caller via needsCapping (skipped\n// when a TERMINAL_3P ends the chain).\nfunction runTriplesAssembly(monomerSeq, roles, monomersDict, molfileAtomBlock, molfileBondBlock, v, LC, monomers, steabsCollection, addAtoms, getAtoms) {\n void LC; // assembly is driven by per-monomer roles, not by LC.seqLength\n for (let i = 0; i < monomerSeq.length; ++i) {\n const sm = monomerSeq[i];\n if (sm.symbol === GAP_SYMBOL)\n continue;\n const role = roles[i];\n const mG = getMolGraph(monomersDict, { symbol: sm.symbol, polymerType: helmTypeToPolymerType(sm.biotype) });\n const aFirst = v.nodeShift;\n const bFirst = v.bondShift;\n v.i = i; // keep loop counter monotone (unused by nucleotide geometry)\n if (role === NucleotideRole.BASE)\n // Branch: attaches to v.branchAttachNode, set when the preceding sugar\n // was emitted. Does not advance the backbone, so the next backbone unit\n // still chains from that sugar's 3' side.\n addBranchMonomerToMolblock(mG, molfileAtomBlock, molfileBondBlock, v);\n else\n // Backbone: sugar / phosphate / linker / terminal modifier. Chains from\n // the previous backbone unit (none for the very first one) and, for a\n // sugar, sets up the branch attach point for the next base.\n addBackboneMonomerToMolblock(mG, molfileAtomBlock, molfileBondBlock, v);\n mG.stereoAtoms?.forEach((s) => steabsCollection.push(s + getAtoms()));\n addAtoms(mG.atoms.x.length);\n const aList = [];\n for (let a = aFirst; a < v.nodeShift; ++a)\n aList.push(a);\n const bList = [];\n for (let b = bFirst; b < v.bondShift; ++b)\n bList.push(b);\n monomers.set(i, { biotype: sm.biotype, symbol: sm.symbol, atoms: aList, bonds: bList });\n }\n}\n/** Keep precision upon floating point operations over atom coordinates\n * @param {number}x - the floating point number\n * @return {number} - the floating point number with the same precision\n */\nexport function keepPrecision(x) {\n return Math.round(C.PRECISION_FACTOR * x) / C.PRECISION_FACTOR;\n}\n// Vertical gap (in molfile coordinate units) inserted between stacked chains\n// of a multi-strand HELM. Roughly two bond lengths — enough to read the strands\n// as separate without pushing them far apart.\nconst CHAIN_VERTICAL_GAP = 3.0;\nconst STEABS_MARKER = 'M V30 MDLV30/STEABS ATOMS=(';\n/** Split `body` into its first `n` space-separated tokens plus a trailing\n * remainder token (so the result has n+1 entries). The remainder keeps any\n * embedded spaces of the tail verbatim.\n * @param {string} body - the line body to split\n * @param {number} n - number of leading tokens to peel off\n * @return {string[]} - the n tokens followed by the remainder */\nfunction splitLeadingTokens(body, n) {\n const out = [];\n let s = body;\n for (let i = 0; i < n; ++i) {\n const sp = s.indexOf(' ');\n if (sp === -1) {\n out.push(s);\n s = '';\n continue;\n }\n out.push(s.substring(0, sp));\n s = s.substring(sp + 1);\n }\n out.push(s);\n return out;\n}\n/** Extract the data lines (`M V30 ...`) between a BEGIN/END marker pair.\n * @param {string} molfile - the V3000 molfile\n * @param {string} beginMarker - the block BEGIN marker line\n * @param {string} endMarker - the block END marker line\n * @return {string[]} - the data lines of the block, newline stripped */\nfunction extractBlockDataLines(molfile, beginMarker, endMarker) {\n const begin = molfile.indexOf(beginMarker);\n if (begin === -1)\n return [];\n const start = molfile.indexOf('\\n', begin) + 1;\n const end = molfile.indexOf(endMarker, start);\n return molfile.substring(start, end === -1 ? molfile.length : end)\n .split('\\n')\n .filter((l) => l.startsWith(C.V3K_BEGIN_DATA_LINE))\n .map((l) => l.substring(C.V3K_BEGIN_DATA_LINE.length));\n}\n/** Parse a molfile produced by monomerSeqToMolfile back into atoms / bonds /\n * stereo-atom indices. Robust because we control the exact serialization\n * format; only the fields we need to renumber (indices) and shift (y) are\n * parsed, everything past them is preserved verbatim as an opaque tail.\n * @param {string} molfile - the V3000 molfile\n * @return {ParsedMol} - parsed atoms, bonds and STEABS atom indices */\nfunction parseGeneratedMolfile(molfile) {\n const atoms = [];\n for (const body of extractBlockDataLines(molfile, C.V3K_BEGIN_ATOM_BLOCK, C.V3K_END_ATOM_BLOCK)) {\n // body: \"<idx> <type> <x> <y> <z> <...kwargs>\"\n const t = splitLeadingTokens(body, 4); // [idx, type, x, y, tail]\n atoms.push({ type: t[1], xStr: t[2], y: parseFloat(t[3]), tail: t[4] });\n }\n const bonds = [];\n for (const body of extractBlockDataLines(molfile, C.V3K_BEGIN_BOND_BLOCK, C.V3K_END_BOND_BLOCK)) {\n // body: \"<idx> <btype> <a1> <a2> <...cfg/kwargs>\"\n const t = splitLeadingTokens(body, 4); // [idx, btype, a1, a2, tail]\n bonds.push({ btype: t[1], a1: parseInt(t[2]), a2: parseInt(t[3]), tail: t[4] });\n }\n const steabs = [];\n let idx = molfile.indexOf(STEABS_MARKER);\n while (idx !== -1) {\n idx += STEABS_MARKER.length;\n const closeIdx = molfile.indexOf(')', idx);\n // first entry inside the parens is the atom count, not an atom index\n steabs.push(...molfile.substring(idx, closeIdx).split(' ').slice(1)\n .map((s) => parseInt(s)).filter((n) => !Number.isNaN(n)));\n idx = molfile.indexOf(STEABS_MARKER, closeIdx);\n }\n return { atoms, bonds, steabs };\n}\n/** Combine several already-assembled single-chain molfiles into one molfile,\n * stacking them vertically: the first chain keeps its coordinates, every\n * subsequent chain is shifted straight down so its top-most atom sits just\n * below the running bottom of everything placed so far. Atom / bond indices\n * and per-monomer maps are re-based, STEABS collections merged, and the\n * monomer-map keys offset by each chain's start position so the combined map\n * still keys by original flat HELM position.\n * @param {MolfileWithMap[]} parts - per-chain assembled molfiles (chain order)\n * @param {number[]} chainStarts - flat start position of each chain\n * @return {MolfileWithMap} - single combined molfile + merged monomer map */\nexport function combineMolfilesVertically(parts, chainStarts) {\n const combinedAtomLines = [];\n const combinedBondLines = [];\n const combinedSteabs = [];\n const combinedMap = new MonomerMap();\n let atomOffset = 0;\n let bondOffset = 0;\n let runningBottom = Number.POSITIVE_INFINITY; // lowest y placed so far\n let anyPlaced = false;\n for (let c = 0; c < parts.length; ++c) {\n const part = parts[c];\n if (!part || !part.molfile)\n continue;\n const pm = parseGeneratedMolfile(part.molfile);\n if (pm.atoms.length === 0)\n continue;\n let minY = Number.POSITIVE_INFINITY;\n let maxY = Number.NEGATIVE_INFINITY;\n for (const a of pm.atoms) {\n if (a.y < minY)\n minY = a.y;\n if (a.y > maxY)\n maxY = a.y;\n }\n // First placed chain keeps its coordinates; later chains drop below the\n // current bottom, leaving CHAIN_VERTICAL_GAP between the strands.\n const yShift = anyPlaced ? keepPrecision(runningBottom - CHAIN_VERTICAL_GAP - maxY) : 0;\n for (let ai = 0; ai < pm.atoms.length; ++ai) {\n const a = pm.atoms[ai];\n const newIdx = atomOffset + ai + 1;\n const newY = keepPrecision(a.y + yShift);\n combinedAtomLines.push(C.V3K_BEGIN_DATA_LINE + newIdx + ' ' + a.type + ' ' + a.xStr + ' ' + newY + ' ' + a.tail + '\\n');\n }\n for (let bi = 0; bi < pm.bonds.length; ++bi) {\n const b = pm.bonds[bi];\n const newIdx = bondOffset + bi + 1;\n const tail = b.tail ? ' ' + b.tail : '';\n combinedBondLines.push(C.V3K_BEGIN_DATA_LINE + newIdx + ' ' + b.btype + ' ' + (b.a1 + atomOffset) + ' ' + (b.a2 + atomOffset) + tail + '\\n');\n }\n for (const s of pm.steabs)\n combinedSteabs.push(s + atomOffset);\n const posOffset = chainStarts[c] ?? 0;\n for (const [pos, val] of part.monomers) {\n combinedMap.set(posOffset + pos, {\n biotype: val.biotype,\n symbol: val.symbol,\n atoms: val.atoms.map((x) => x + atomOffset),\n bonds: val.bonds.map((x) => x + bondOffset),\n });\n }\n const newBottom = keepPrecision(minY + yShift);\n runningBottom = anyPlaced ? Math.min(runningBottom, newBottom) : newBottom;\n anyPlaced = true;\n atomOffset += pm.atoms.length;\n bondOffset += pm.bonds.length;\n }\n if (!anyPlaced)\n return MolfileWithMap.createEmpty();\n let result = '';\n result += C.V3K_HEADER_FIRST_LINE;\n result += C.V3K_HEADER_SECOND_LINE;\n result += C.V3K_BEGIN_CTAB_BLOCK;\n result += C.V3K_BEGIN_COUNTS_LINE + atomOffset + ' ' + bondOffset + C.V3K_COUNTS_LINE_ENDING;\n result += C.V3K_BEGIN_ATOM_BLOCK;\n result += combinedAtomLines.join('');\n result += C.V3K_END_ATOM_BLOCK;\n result += C.V3K_BEGIN_BOND_BLOCK;\n result += combinedBondLines.join('');\n result += C.V3K_END_BOND_BLOCK;\n if (combinedSteabs.length > 0)\n result += getCollectionBlock(combinedSteabs);\n result += C.V3K_END_CTAB_BLOCK;\n result += C.V3K_END;\n return { molfile: result, monomers: combinedMap };\n}\n//# sourceMappingURL=to-atomic-level-utils.js.map","import { monomerSeqToMolfile } from './to-atomic-level-utils';\nonmessage = (event) => {\n const { seqList, rolesList, chainStartsList, monomersDict, alphabet, polymerType, start, end } = event.data;\n const resMolList = new Array(end - start);\n const molfileWarningList = new Array(0);\n for (let rowI = start; rowI < end; ++rowI) {\n try {\n const seq = seqList[rowI];\n const roles = rolesList ? rolesList[rowI] : undefined;\n const chainStarts = chainStartsList ? chainStartsList[rowI] : undefined;\n resMolList[rowI - start] = monomerSeqToMolfile(seq, monomersDict, alphabet, polymerType, roles, chainStarts);\n }\n catch (err) {\n const errMsg = err instanceof Error ? err.message : err.toString();\n const msg = `Cannot get molfile of row #${rowI}: ${errMsg}.`;\n molfileWarningList.push(msg);\n }\n }\n postMessage({ molfiles: resMolList, warnings: molfileWarningList });\n};\n//# sourceMappingURL=seq-to-molfile-worker.js.map"],"names":["performance","now","Date","Set","PROCESS","process","AC","globalThis","AbortController","AS","AbortSignal","onabort","_onabort","reason","aborted","addEventListener","_","fn","this","push","constructor","warnACPolyfill","signal","abort","printACPolyfillWarning","env","LRU_CACHE_IGNORE_AC_WARNING","msg","type","code","emitWarning","console","error","Symbol","iterator","toStringTag","Error","Map","g","x","PEPTIDE","RNA","CHEM","BLOB","G","Z","_listeners","_completed","subscribe","e","add","delete","next","t","complete","clear","observerCount","size","L","i","line","text","background","ar","cn","Re","exec","n","parseInt","slice","ln","toString","padStart","un","mn","o","r","s","Math","max","a","min","d","c","l","dn","io","round","At","u","oo","pow","wt","h","lr","kt","b","dr","ao","A","T","C","U","lo","R","co","P","p","uo","N","D","E","Q","H","I","K","M","F","S","W","Y","V","mo","po","B","ho","we","name","fallback","errorTriple","palette","g_BASE","g_SUGAR","g_LINKER","g_AA","g_CHEM","g_BLOB","g_NUCLEOTIDE","xe","Object","entries","Ie","meta","colors","light","dark","default","naturalAnalog","te","polymerType","monomerType","PI","Bt","y","width","height","Number","isInteger","isFinite","is","Cn","length","Wo","cos","sin","Ln","abs","Bn","Rn","sqrt","ei","ti","aa","strokeWidth","sugar","cornerRadius","base","linker","chem","blob","nucleotide","$","defaultStroke","defaultFill","selectionColor","highlightColor","errorColor","fontSize","fontFamily","bondLength","textColor","idColor","annotationColor","tagDotColor","hbondColor","nonCanonicalHbondColor","crossPolymerBondColor","colorTheme","softenCanvas","shapes","it","It","$e","biotype","symbol","Jo","jo","qo","Yo","Xo","pe","he","Es","Ls","test","replace","Me","join","On","class","atoms","has","id","fill","stroke","Nn","WeakMap","bonds","isEmpty","freeze","ownerDocument","document","v","createElement","keys","setAttribute","String","appendChild","createTextNode","ye","get_mol","get_svg","ie","body","children","getAttribute","style","display","Te","firstChild","removeChild","rdkitSvg","rdkitTestid","innerHTML","hint","left","top","Gt","endsWith","Ut","_baseTransform","_viewport","scale","offset","_pinnedBbox","_tooltip","_bondTooltip","_rdkitSvgCache","_unsubs","_destroyed","host","_editor","_doc","documentImpl","_width","_height","querySelector","textContent","head","documentElement","_i","_svgRoot","_renderFresh","on","_hideTooltip","_hideBondTooltip","_refreshOverlays","_applyResize","viewport","_applyViewport","_showTooltip","atom","clientX","clientY","_showBondTooltip","bond","_paintBondPreview","start","cursor","candidate","_clearBondPreview","_paintSelectionRect","origin","_paintSelectionRectFromRect","rect","_clearSelectionRect","svgRoot","resize","redraw","destroy","parentNode","getService","_currentTheme","getMol","Dn","renderMol","theme","fixedModelBbox","vi","_applyOverlaysToCurrent","getSelection","selectedAtomIds","highlightLayer","highlightedAtomIds","selectionLayer","gi","_editorHighlights","_spliceLayer","createElementNS","replaceChild","_currentHighlights","monomer","bio","positionInChain","chainId","_renderRdkitTooltipSvg","m","options","rdkitModule","smiles","get","_RDKIT_CACHE_LIMIT","value","set","wi","r1","r2","a1","a2","kind","_paintSelectionRectAt","position","re","_onClose","_primaryAction","_host","role","testId","title","stopPropagation","key","target","tagName","preventDefault","stopImmediatePropagation","close","root","anyOpen","_openStack","closeTopmost","open","includes","indexOf","splice","setPrimaryAction","isOpen","Un","startsWith","Ye","ce","Di","ja","lt","zn","Kn","Yt","onValueSet","onPickModeChange","_slots","_favStar","_pickMode","_builderRdkitCache","_hooks","paletteHooks","_favHooks","favoriteHooks","element","tabindex","preview","toggleFavoriteTriplet","_hintEl","hidden","_buildSvg","_preview","_addBtn","_onAddClicked","monomerLib","onChanged","refresh","_repaintSlotColors","_libUnsub","_populateDefaults","_updatePreview","setField","_setLabelText","labelEl","_repaintSlot","field","startPickMode","_setSlotPressed","_setHintActive","beginBiotypeFilter","_exitPickMode","cancelPickMode","endBiotypeFilter","getPickMode","triggerAdd","Xe","_buildSlot","groupEl","_showSlotTooltip","_hideSlotTooltip","shapeEl","nextSibling","nodeName","Xa","insertBefore","values","_theme","getMonomerSet","Qa","Ja","Za","some","_updateFavStar","isFavoriteTriplet","removeAttribute","placeRnaTriplet","split","filter","_rdkit","_builderRdkitSvgFor","_BUILDER_RDKIT_CACHE_LIMIT","_slotHint","_slotTitle","getBoundingClientRect","qt","sort","localeCompare","ue","Wn","Xt","Ni","Fi","Jt","Je","favoritesChanged","_nextAddUnsub","_favorites","_favoriteTriplets","_pendingRnaSelection","_visibleTabs","_activeTab","_searchInput","_filter","_rnaBuilder","_activeBiotypeFilter","_pickResolver","_pickCanceller","_pickEscapeListener","_pickOutsideClickListener","_paletteRdkitCache","_opts","groupByNaturalAnalog","allowFavorites","_loadFavorites","_resolveInitialTab","initialTab","_render","_themeUnsub","_updatePrimedClasses","setFilter","trim","toLowerCase","_applyFilter","setActiveTab","_persistActiveTab","_applyActiveTabClasses","getActiveTab","getFavorites","_findMonomer","setFavorite","_saveFavorites","_hidePaletteTooltips","_emitFavoritesChanged","clearFavorites","getFavoriteTriplets","map","setFavoriteTriplet","findIndex","favorites","triplets","getRnaBuilder","hasActiveBiotypeFilter","getActiveBiotypeFilter","cancelBiotypeFilter","_teardownPickMode","_buildPaletteFilterHooks","defaultView","_isInsideOwnPalette","parentElement","_scrollActivePaneToTop","scrollTo","behavior","scrollTop","removeEventListener","_computeVisibleTabs","_buildFavoritesPane","_buildPolymerPane","getPolymerTypes","_resolveFavoriteMonomers","_groupByPolymerAndType","_renderGroup","_renderTripletGroup","pt","mt","list","Backbone","Branch","Terminal","Undefined","Array","from","_polymerLabel","_renderTripletChip","showStar","favorite","label","star","$i","_wireTripletChip","parts","xi","_tripletTooltipParts","classList","contains","_buildRnaDefaultChips","_pickSymbol","_DEFAULT_TRIPLET_BASES","_paletteRdkitSvg","done","_restoreRnaSelection","getMonomer","_monomersForPolymer","_groupRna","_groupByAnalog","getNextAddSymbol","_sortByColor","_biotype","_renderTile","so","idx","isGrey","getMonomerSymbolsByType","ro","Wa","primed","draggable","Hi","_wireTile","_PALETTE_RDKIT_CACHE_LIMIT","find","every","replaceMonomers","fire","message","severity","durationMs","setNextAddSymbol","dataTransfer","setData","JSON","stringify","effectAllowed","startPaletteDrag","querySelectorAll","_localStorage","localStorage","getItem","setItem","parse","_extractSymbols","_extractTriplets","isArray","symbols","MonomerNumberingTypes","HelmTabKeys","monomerWorksConsts","V2K_RGP_SHIFT","V2K_RGP_LINE","V2K_A_LINE","V3K_COUNTS_SHIFT","V3K_IDX_SHIFT","V3K_HEADER_FIRST_LINE","V3K_HEADER_SECOND_LINE","V3K_BEGIN_CTAB_BLOCK","V3K_END_CTAB_BLOCK","V3K_BEGIN_COUNTS_LINE","V3K_COUNTS_LINE_ENDING","V3K_BEGIN_ATOM_BLOCK","V3K_END_ATOM_BLOCK","V3K_BEGIN_BOND_BLOCK","V3K_END_BOND_BLOCK","V3K_BOND_CONFIG","V3K_BEGIN_DATA_LINE","V3K_END","PRECISION_FACTOR","DEOXYRIBOSE","RIBOSE","PHOSPHATE","OXYGEN","HYDROGEN","getMolGraph","dict","libKey","NucleotideRole","MonomerMap","super","MolfileWithMap","molfile","monomers","createEmpty","HELM_POLYMER_TYPE","NOTATION","ALPHABET","TAGS","RegExp","CandidateType","alphabet","cutoff","Alphabets","fasta","peptide","dna","rna","helmTypeToPolymerType","helmType","warn","monomerSeqToMolfile","monomerSeq","monomersDict","roles","chainStarts","subSeq","subRoles","undefined","combinedAtomLines","combinedBondLines","combinedSteabs","combinedMap","atomOffset","bondOffset","runningBottom","POSITIVE_INFINITY","anyPlaced","part","pm","parseGeneratedMolfile","minY","maxY","NEGATIVE_INFINITY","yShift","keepPrecision","CHAIN_VERTICAL_GAP","ai","newIdx","newY","xStr","tail","bi","btype","steabs","posOffset","pos","val","newBottom","result","getCollectionBlock","combineMolfilesVertically","triplesMode","atomCount","bondCount","needsCapping","monomerCount","lastMonomerGraph","lastPhosphateGraph","seqMonomer","bondTypes","rNodes","terminalR2Atom","TERMINAL_3P","DNA","phosphate","getResultingAtomBondCounts","molfileAtomBlock","molfileBondBlock","addMonomerToMolblock","addAminoAcidToMolblock","addNucleotideToMolblock","nodeShift","bondShift","backbonePositionShift","branchPositionShift","backboneAttachNode","branchAttachNode","flipFactor","LC","seqLength","ceil","steabsCollection","lastMonomerCappingAtom","nAtoms","addAtoms","sm","mG","aFirst","bFirst","BASE","addBranchMonomerToMolblock","addBackboneMonomerToMolblock","stereoAtoms","forEach","aList","bList","runTriplesAssembly","mAtomFirst","mBondFirst","mAtomCount","mAtomList","maI","mBondCount","mBondList","mbI","cappingAtomType","atomIdx","firstAtom","secondAtom","capResultingMolblock","molfileCountsLine","collection","rowsArray","newCollectionRow","updatedRow","j","atomTypes","kwargs","fillAtomLines","fillBondLines","bondIdx","terminalNodes","fillChainExtendingBond","branchShift","updateBranchVariables","atomPairs","backboneShift","updateChainExtendingVariables","nucleobase","fillBranchAtomLines","branchMonomer","fillBackboneToBranchBond","bondCfg","bondConfiguration","orientation","PT","FASTA","SEPARATOR","HELM","BILN","STEABS_MARKER","splitLeadingTokens","out","sp","substring","extractBlockDataLines","beginMarker","endMarker","begin","end","parseFloat","closeIdx","isNaN","onmessage","event","seqList","rolesList","chainStartsList","data","resMolList","molfileWarningList","rowI","seq","err","postMessage","molfiles","warnings"],"sourceRoot":""}