@datagrok/helm 3.0.1 → 3.0.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1 @@
1
+ {"version":3,"file":"489.js","mappings":"4BAGA,iBAAAA,aACAA,aACA,mBAAAA,YAAAC,IACAD,YACAE,KACA,IAAAC,IALA,MAOAC,EAAA,iBAAAC,SAAAA,QAAAA,QAAA,GAOA,IAAAC,EAAAC,WAAAC,gBACAC,EAAAF,WAAAG,YAEA,YAAAJ,EAAA,CAEAG,EAAA,MACAE,QACAC,SAAA,GACAC,OACAC,SAAA,EACA,gBAAAC,CAAAC,EAAAC,GACAC,KAAAN,SAAAO,KAAAF,EACA,GAGAX,EAAA,MACA,WAAAc,GACAC,GACA,CACAC,OAAA,IAAAb,EACA,KAAAc,CAAAV,GACA,IAAAK,KAAAI,OAAAR,QAAA,CAGAI,KAAAI,OAAAT,OAAAA,EAEAK,KAAAI,OAAAR,SAAA,EAEA,UAAAG,KAAAC,KAAAI,OAAAV,SACAK,EAAAJ,GAEAK,KAAAI,OAAAX,UAAAE,EATA,CAUA,GAEA,IAAAW,EAAA,MAAApB,EAAAqB,KAAAC,4BACA,MAAAL,EAAA,KAxCA,IAAAM,EAAAC,EAAAC,EAAAZ,EAyCAO,IAEAA,GAAA,EA3CAG,EA4CA,maA5CAC,EAkDA,sBAlDAC,EAkDA,UAlDAZ,EAkDAI,EAjDA,mBAAAjB,EAAA0B,YACA1B,EAAA0B,YAAAH,EAAAC,EAAAC,EAAAZ,GACAc,QAAAC,MAAA,IAA4BH,MAASD,MAASD,MAiD9C,CAGAM,OAAA,QAwmBAA,OAAAC,SAQAD,OAAAE,YCnrBiCC,MACi+B,IAAAC,IAAA,6OAAqkB,IAAAA,IAAid,IAAAC,EAAO,UAAPA,EAAO,aAAPA,EAAO,YAAPA,EAAO,cAAPA,EAAO,YAAPA,EAAO,YAAPA,EAAO,kBAAqIC,EAAA,CAAIC,QAAA,UAAAC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AAqS,GAAAtR,SAAAf,EAAA,IAAAsS,GAAAvR,SAAAf,EAAA,IAAA2nB,KAAA3nB,EAAA,IACrB,CACA,MAAA8nB,EAAA,GACA,IAAAzH,EAAAqE,EAAA5Q,QAAAia,IACA,UAAA1N,GAAA,CACAA,GAAA0N,GAAAjnB,OACA,MAAA4nB,EAAAhK,EAAA5Q,QAAA,IAAAuM,GAEAyH,EAAAhqB,QAAA4mB,EAAAyJ,UAAA9N,EAAAqO,GAAAhW,MAAA,KAAA1X,MAAA,GACAqb,IAAA7a,GAAAT,SAAAS,IAAAmX,OAAA7X,IAAA2F,OAAAkoB,MAAA7tB,KACAuf,EAAAqE,EAAA5Q,QAAAia,GAAAW,EACA,CACA,OAAalkB,QAAAO,QAAA+c,SACb,CChiBA8G,UAAAC,IACA,MAAAC,QAAYA,EAAAC,UAAAA,EAAAC,gBAAAA,EAAAjJ,aAAAA,EAAAZ,SAAAA,EAAAlf,YAAAA,EAAAkJ,MAAAA,EAAAqf,IAAAA,GAAuFK,EAAAI,KACnGC,EAAA,IAAA3Q,MAAAiQ,EAAArf,GACAggB,EAAA,IAAA5Q,MAAA,GACA,QAAA6Q,EAAAjgB,EAA2BigB,EAAAZ,IAAYY,EACvC,IACA,MAAAC,EAAAP,EAAAM,GACApJ,EAAA+I,EAAAA,EAAAK,QAAAhJ,EACAH,EAAA+I,EAAAA,EAAAI,QAAAhJ,EACA8I,EAAAE,EAAAjgB,GAAuC0W,GAAmBwJ,EAAAtJ,EAAAZ,EAAAlf,EAAA+f,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 I=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);}},N=class extends I{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);}},Ye=class extends I{constructor(e,t){let n=Object.freeze([...e]),o=t??Vi(n);super(\"helm-validation-failed\",o),this.name=\"HelmValidationError\",this.diagnostics=n,Object.setPrototypeOf(this,new.target.prototype);}};function Vi(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 I{constructor(e,t,n){super(e,t??`HELM operation not supported: ${e}`,n),this.name=\"HelmNotSupportedError\",Object.setPrototypeOf(this,new.target.prototype);}},Qt=class extends I{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 Te=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 Se=class{debug(e,t){}info(e,t){}warn(e,t){}error(e,t){}};function en(i){return i>=65&&i<=90||i>=97&&i<=122}function Xe(i){return i>=48&&i<=57}function Ui(i){return i===32||i===9||i===10||i===13}var tn=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(Ui(t))throw new N(\"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(en(t)){this.scanIdentifier(e);continue}if(Xe(t)){this.scanNumber(e);continue}let n=zi.get(t);if(n!==void 0){this.pos+=1,this.push(n,this.src.charAt(e),e,this.pos);continue}throw new N(\"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 N(\"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 N(\"unexpected-newline\",`Newline inside bracket at offset ${r}`,{span:{start:r,end:r+1}});r+=1;continue}if(s===10||s===13)throw new N(\"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,l=this.src.slice(e+1,r);this.pos=a,this.push(\"inline-smiles\",l,e,a);return}r+=1;continue}r+=1;}throw new N(\"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 N(\"unexpected-newline\",`Newline inside quote at offset ${n}`,{span:{start:n,end:n+1}});t.push(this.src.charAt(n)),n+=1;}throw new N(\"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(en(o)||Xe(o)||o===95){t+=1;continue}if(o===45&&t+1<this.len&&en(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&&Xe(this.src.charCodeAt(t));)t+=1;if(t+1<this.len&&this.src.charCodeAt(t)===46&&Xe(this.src.charCodeAt(t+1))){for(t+=2;t<this.len&&Xe(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}});}},zi=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 qn(i){let e=new tn(i).tokenize();return Ki(e),e}function Ki(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 N(\"unterminated-apostrophe\",`Unterminated apostrophe block starting at offset ${e.start}`,{span:{start:e.start,end:i.source.length}})}var Wi={perPolymer:new Map,version:\"\"};function me(){return {atoms:[],bonds:[],chains:[],groups:[],annotations:Wi}}function J(i,e){for(let t of i.atoms)if(t.id===e)return t}function _t(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 b={AA:\"HELM_AA\",SUGAR:\"HELM_SUGAR\",BASE:\"HELM_BASE\",LINKER:\"HELM_LINKER\",CHEM:\"HELM_CHEM\",BLOB:\"HELM_BLOB\",NUCLEOTIDE:\"HELM_NUCLEOTIDE\"},v={PEPTIDE:\"PEPTIDE\",RNA:\"RNA\",CHEM:\"CHEM\",BLOB:\"BLOB\",G:\"G\"},ji={BACKBONE:\"Backbone\",BRANCH:\"Branch\",TERMINAL:\"Terminal\",UNDEFINED:\"Undefined\"};var _e=class{constructor(){this._counter=0;}next(){return this._counter+=1,this._counter}reset(){this._counter=0;}get current(){return this._counter}};function Ee(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 Ce(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 qi(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 Yi(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 l=/^_R(\\d{1,2})$/.exec(a);if(l!==null){let d=parseInt(l[1],10);d>=1&&d<=10&&!e.has(d)&&e.set(d,r+s);}s+=a.length+1;}return e}function Xi(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 Yn(i){let e=i.trim();if(e.length===0)return {ok:false,reason:\"empty-smiles\"};let t=qi(e);if(t.size>0)return {ok:true,canonicalSmiles:e,info:{rs:t.size,rgroupPositions:t,flavor:\"jsdraw\"}};let n=Yi(e);if(n.size>0)return {ok:true,canonicalSmiles:e,info:{rs:n.size,rgroupPositions:n,flavor:\"chemaxon\"}};let o=Xi(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 B(i){return {line:\"#202020\",text:\"#000000\",background:i}}function Ji(i){return {line:\"#e0e0e0\",text:\"#ffffff\",background:rn(i,.25)}}function Le(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 nn(i){return i.toString(16).padStart(2,\"0\")}function sn(i,e,t){return `#${nn(i)}${nn(e)}${nn(t)}`}function an(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),l=(s+a)/2;if(s===a)return [0,0,l];let d=s-a,c=l>.5?d/(2-s-a):d/(s+a),u;return s===n?u=((o-r)/d+(o<r?6:0))*60:s===o?u=((r-n)/d+2)*60:u=((n-o)/d+4)*60,[u,c,l]}function on(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 Jn(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(on(o,n,r+1/3)*255),Math.round(on(o,n,r)*255),Math.round(on(o,n,r-1/3)*255)]}function xt(i,e=.3,t=.1){let n=Le(i);if(n===null)return i;let[o,r,s]=an(n[0],n[1],n[2]),a=Math.max(0,Math.min(1,r*(1-e))),l=Math.max(0,Math.min(.95,s+t*(1-s))),[d,c,u]=Jn(o,a,l);return sn(d,c,u)}function Xn(i){let e=Le(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 Zn(i,e){let t=Xn(i),n=Xn(e),o=Math.max(t,n),r=Math.min(t,n);return (o+.05)/(r+.05)}function Qn(i){let e=Le(i);if(e===null)return {h:0,s:0,l:0};let[t,n,o]=an(e[0],e[1],e[2]);return {h:t,s:n,l:o}}function Zi(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]=Jn(e,t,n);return sn(o,r,s)}function vt(i){let e=Le(i);if(e===null)return \"#1f2937\";let[t,n,o]=an(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 Zi({h:t,s,l:r})}function Qi(i){let e=Le(i);return e===null?null:{r:e[0]/255,g:e[1]/255,b:e[2]/255}}function wt(i){let e=Qi(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 rn(i,e){let t=Le(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 sn(o,r,s)}var eo={A:B(\"#A0A0FF\"),G:B(\"#FF7070\"),T:B(\"#A0FFA0\"),C:B(\"#FF8C4B\"),U:B(\"#FF8080\")},to={R:B(\"#7a85c1\"),r:B(\"#7a85c1\")},no={P:B(\"#9aa5e1\"),p:B(\"#9aa5e1\")},oo={A:B(\"#C8C8C8\"),R:B(\"#145AFF\"),N:B(\"#00DCDC\"),D:B(\"#E60A0A\"),C:B(\"#E6E600\"),E:B(\"#00DCDC\"),Q:B(\"#E60A0A\"),G:B(\"#EBEBEB\"),H:B(\"#8282D2\"),I:B(\"#0F820F\"),L:B(\"#0F820F\"),K:B(\"#145AFF\"),M:B(\"#E6E600\"),F:B(\"#3232AA\"),P:B(\"#DC9682\"),S:B(\"#FA9600\"),T:B(\"#FA9600\"),W:B(\"#B45AB4\"),Y:B(\"#3232AA\"),V:B(\"#0F820F\")},io={R:B(\"#eeeeee\")},ro={B:B(\"#999999\"),G:B(\"#e2e2e2\")},so={P:B(\"#9aa5e1\")},we={name:\"light\",fallback:{line:\"#202020\",text:\"#000000\",background:\"#eeeeee\"},errorTriple:{line:\"#cc0000\",text:\"#000000\",background:\"#FFFF00\"},palette:{[b.BASE]:eo,[b.SUGAR]:to,[b.LINKER]:no,[b.AA]:oo,[b.CHEM]:io,[b.BLOB]:ro,[b.NUCLEOTIDE]:so}};function ve(i){let e={};for(let[t,n]of Object.entries(i))e[t]=Ji(n.background);return e}var Be={name:\"dark\",fallback:{line:\"#e0e0e0\",text:\"#ffffff\",background:rn(\"#eeeeee\",.5)},errorTriple:{line:\"#ff5050\",text:\"#ffffff\",background:rn(\"#FFFF00\",.4)},palette:{[b.BASE]:ve(eo),[b.SUGAR]:ve(to),[b.LINKER]:ve(no),[b.AA]:ve(oo),[b.CHEM]:ve(io),[b.BLOB]:ve(ro),[b.NUCLEOTIDE]:ve(so)}};function $(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:vt(r.background)};if(n.default!==void 0)return {...n.default,line:vt(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:vt(s.background),text:wt(s.background)}}}return {...t.fallback,line:vt(t.fallback.background),text:wt(t.fallback.background)}}function Je(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 ao(i){let e=false,t=i.rgroups.map(n=>{let o=Je(n);return o!==void 0&&n.capGroupSMILES!==o?(e=true,{...n,capGroupSMILES:o}):n});return e?{...i,rgroups:t}:i}var er=new Set([\"PEPTIDE\",\"RNA\",\"CHEM\",\"BLOB\"]),tr=new Set([\"Backbone\",\"Branch\",\"Terminal\",\"Undefined\"]),nr=/^R[1-9][0-9]*$/;function kt(i){let e=[];if(!Array.isArray(i))return {ok:false,errors:[{path:\"$\",message:`Expected a JSON array of monomers, got ${F(i)}`}]};for(let t=0;t<i.length;t++)or(i[t],`$.${t}`,e);return e.length>0?{ok:false,errors:e}:{ok:true,data:i}}function or(i,e,t){if(!Qe(i)){t.push({path:e,message:`Expected an object, got ${F(i)}`});return}ln(i,\"symbol\",e,t,{minLength:1}),ln(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 ${F(n)}`}):er.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 ${F(o)}`}):tr.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 ${F(r)}`});else {let s=new Set;for(let a=0;a<r.length;a++)ir(r[a],`${e}.rgroups[${a}]`,t,s);}if(Ze(i,\"name\",e,t),Ze(i,\"smiles\",e,t),Ze(i,\"naturalAnalog\",e,t),Ze(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 ${F(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 ${F(s)}`});}if(\"meta\"in i&&i.meta!==void 0){let s=i.meta;Qe(s)?s.colors!==void 0&&rr(s.colors,`${e}.meta.colors`,t):t.push({path:`${e}.meta`,message:`Expected object, got ${F(s)}`});}}function ir(i,e,t,n){if(!Qe(i)){t.push({path:e,message:`Expected an object, got ${F(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 ${F(o)}`}):nr.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}'`}),ln(i,\"capGroupName\",e,t),Je(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\"});}Ze(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 ${F(i.id)}`});}function rr(i,e,t){if(!Qe(i)){t.push({path:e,message:`Expected object, got ${F(i)}`});return}for(let n of [\"default\",\"light\",\"dark\"])i[n]!==void 0&&sr(i[n],`${e}.${n}`,t);}function sr(i,e,t){if(!Qe(i)){t.push({path:e,message:`Expected object, got ${F(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 ${F(i[n])}`});}function ln(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 ${F(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 Ze(i,e,t,n){let o=i[e];o!==void 0&&typeof o!=\"string\"&&n.push({path:`${t}.${e}`,message:`Expected string, got ${F(o)}`});}function Qe(i){return typeof i==\"object\"&&i!==null&&!Array.isArray(i)}function F(i){return i===null?\"null\":Array.isArray(i)?\"array\":typeof i}var ar=/^R([1-9][0-9]*)$/;function ee(i){switch(i.polymerType){case v.PEPTIDE:return b.AA;case v.CHEM:return b.CHEM;case v.BLOB:return b.BLOB;case v.RNA:{if(i.monomerType===\"Branch\")return b.BASE;if(i.monomerType===\"Backbone\"){let e=i.naturalAnalog;return e===\"P\"||e===\"p\"?b.LINKER:b.SUGAR}return null}default:return null}}function lr(i){let e=new Map;for(let t of i.rgroups){let n=ar.exec(t.label);n!==null&&e.set(parseInt(n[1],10),t);}return Object.assign({},i,{rs:i.rgroups.length,rgroupMap:e})}var dn=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=kt([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 I(\"invalid-monomer-lib\",`MonomerLib.fromText: JSON.parse failed \\u2014 ${s}`)}let o=kt(n);if(!o.ok)throw new I(\"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 I(\"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 I(\"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=dr(t),o=e===null?b.AA:ee(e)??b.AA;return $(e,o,n)}getResolved(e){return this._resolved.get(e)}addMonomer(e){let t=kt([e]);if(!t.ok)throw new I(\"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=ee(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 l=this._byNaturalAnalog.get(e)?.get(s);if(l!==void 0){let d=l.indexOf(o);d>=0&&l.splice(d,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 I(\"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)}),l=Object.assign({},o,{meta:a});this._addNoFire(l),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=Yn(t);if(!o.ok)throw new I(\"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((c,u)=>c-u);for(let c of a)s.push({label:`R${c}`,capGroupName:\"H\",capGroupSMILES:\"\"});let l=n?.symbolHint!==void 0?{smilesHint:n.symbolHint}:void 0,d={symbol:r,polymerType:e,monomerType:\"Undefined\",molfile:\"\",smiles:o.canonicalSmiles,rgroups:s,...l!==void 0?{meta:l}:{}};return this._addNoFire(d),this._bumpVersion(),this.onChanged.next({type:\"add\",affectedSymbols:[r]}),d}toJSON(){let e=[];for(let t of this._byPolymerSymbol.values())for(let n of t.values())e.push(n);return e}_addNoFire(e){e=ao(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=ee(o);if(a!==null){let d=this._byBiotypeSymbol.get(a);d!==void 0&&d.delete(o.symbol);}let l=o.naturalAnalog;if(l!==void 0&&l!==\"\"){let d=this._byNaturalAnalog.get(t)?.get(l);if(d!==void 0){let c=d.indexOf(o);c>=0&&d.splice(c,1);}}this._resolved.delete(o);}let r=ee(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 l=a.get(s);l===void 0&&(l=[],a.set(s,l)),l.push(e);}return this._resolved.set(e,lr(e)),o!==void 0}_bumpVersion(){this._version+=1;}};function dr(i){return i===\"dark\"?Be:we}function xe(i,e,t){return new cn(i,e,t??{}).run()}var cr=new Set([\"?\",\"*\",\"_\",\"X\",\"N\"]),ur=/^R([1-9][0-9]*)$/;function mr(i){return typeof i.registerInlineSmilesMonomer==\"function\"}var cn=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 l=e.get(a.bio.chainId)??null,d=this.resolveAtom(a,l);this.oldToNew.set(a.id,d);}for(let a of this.mol.atoms){let l=this.oldToNew.get(a.id);if(l===void 0||a.branchAtom===void 0)continue;let d=this.oldToNew.get(a.branchAtom.id);d!==void 0&&(l.branchAtom=d);}let t=[];for(let a of this.mol.bonds){let l=this.oldToNew.get(a.a1.id),d=this.oldToNew.get(a.a2.id);l===void 0||d===void 0||t.push({...a,a1:l,a2:d});}let n=new Map;for(let a of t)n.set(a.id,a);let o=[];for(let a of this.mol.chains){let l=[];for(let c of a.backboneAtoms){let u=this.oldToNew.get(c.id);u!==void 0&&l.push(u);}let d=[];for(let c of a.bonds){let u=n.get(c.id);u!==void 0&&d.push(u);}o.push({id:a.id,polymerType:a.polymerType,backboneAtoms:l,bonds:d,...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=ee(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(Ce(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=ee(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=ur.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 !!(cr.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(mr(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 '${pr(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 pr(i,e){return i.length<=e?i:i.slice(0,e-1)+\"\\u2026\"}function et(i,e,t){let n=t?.mode??\"lenient\",o;try{o=qn(i);}catch(r){if(r instanceof N){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 co(o,e,t)}function co(i,e,t){let o=new mn(i,e,t?.mode??\"lenient\").parseDocument();if(e===null||t?.resolveMonomers===false)return o;let r=xe(o.mol,e,{mode:t?.mode??\"lenient\",...t?.legacyCaseFallback===true?{legacyCaseFallback:true}:{}});return {mol:r.mol,diagnostics:[...o.diagnostics,...r.diagnostics]}}var un=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\"}},hr=/^(PEPTIDE|RNA|DNA|CHEM|BLOB|G)([0-9]+)$/;function lo(i){let e=hr.exec(i);if(e===null)return null;let t=e[1],n=parseInt(e[2],10);switch(t){case \"PEPTIDE\":return {rawTypeName:\"PEPTIDE\",polymerType:v.PEPTIDE,number:n,isDnaShim:false,isGroup:false};case \"RNA\":return {rawTypeName:\"RNA\",polymerType:v.RNA,number:n,isDnaShim:false,isGroup:false};case \"DNA\":return {rawTypeName:\"DNA\",polymerType:v.RNA,number:n,isDnaShim:true,isGroup:false};case \"CHEM\":return {rawTypeName:\"CHEM\",polymerType:v.CHEM,number:n,isDnaShim:false,isGroup:false};case \"BLOB\":return {rawTypeName:\"BLOB\",polymerType:v.BLOB,number:n,isDnaShim:false,isGroup:false};case \"G\":return {rawTypeName:\"G\",polymerType:v.PEPTIDE,number:n,isDnaShim:false,isGroup:true};default:return null}}var mn=class{constructor(e,t,n){this.diagnostics=[];this.chains=[];this.chainById=new Map;this.pendingBonds=[];this.groups=[];this.atomIds=new _e;this.bondIds=new _e;this.cursor=new un(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=lo(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 v.PEPTIDE:this.parsePeptideBody(o);break;case v.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 v.CHEM:this.parseChemBody(o);break;case v.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:l,inlineSource:d,span:c}=t,u=this.makeAtom(e,b.AA,n);o!==void 0&&(u.tag=o),r!==void 0&&(u.bio.ambiguity=r),s!==void 0&&(u.bio.ambiguityKind=s),d!==void 0&&(u.inlineSource=d),a&&this.registerInlineSmiles(l,c,v.PEPTIDE),this.addToChain(e,u,true);let m=e.backboneAtoms[e.backboneAtoms.length-2];return m!==void 0&&this.addBond(e,m,u,\"backbone\",{kind:\"numeric\",r:2},{kind:\"numeric\",r:1}),u}parsePeptideAlternation(e){let t=this.cursor.currentSpan();if(this.cursor.advance(),this.peptideContentIsSubsequence()){let d=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 c=e.backboneAtoms.slice(d);this.maybeRepeatBracket(e,c),this.maybeAttachAnnotation(e);return}let n=[],o=null;for(;!this.cursor.at(\"rparen\")&&!this.cursor.isAtEnd();){let d=this.parseAlternationCandidate(v.PEPTIDE);if(n.push(d),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(d=>d.symbol+(d.ratio!==void 0?`:${String(d.ratio)}`:\"\")).join(r)})`,a=this.makeAtom(e,b.AA,\"?\");a.bio.ambiguity=s,a.bio.ambiguityKind=o===\"and\"?\"and\":\"or\",this.addToChain(e,a,true);let l=e.backboneAtoms[e.backboneAtoms.length-2];if(l!==void 0&&this.addBond(e,l,a,\"backbone\",{kind:\"numeric\",r:2},{kind:\"numeric\",r:1}),o===\"and\")for(let d of n)typeof d.ratio==\"number\"&&d.ratio<0&&this.emit(\"error\",\"ratio-and-negative\",`Negative ratio ${d.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 d=this.makeAtom(e,b.NUCLEOTIDE,\"*\");this.addToChain(e,d,true);let c=e.backboneAtoms[e.backboneAtoms.length-2];c!==void 0&&this.addBond(e,c,d,\"backbone\",{kind:\"numeric\",r:2},{kind:\"numeric\",r:1}),this.maybeRepeatBracket(e,[d]),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 l=e.backboneAtoms[s-1];this.addBond(e,l,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),l=this.makeAtom(e,b.SUGAR,n);return s!==void 0&&(l.inlineSource=s),o&&this.registerInlineSmiles(r,a,v.RNA),this.addToChain(e,l,true),l}parseRnaBaseSymbol(e){let{symbol:t,isInlineSmiles:n,rawPayload:o,inlineSource:r,span:s}=this.consumeMonomerSymbol(false),a=this.makeAtom(e,b.BASE,t);return r!==void 0&&(a.inlineSource=r),n&&this.registerInlineSmiles(o,s,v.RNA),this.addToChain(e,a,false),a}parseRnaLinker(e){if(this.cursor.at(\"asterisk\")){this.cursor.currentSpan();this.cursor.advance();let d=this.makeAtom(e,b.LINKER,\"*\");return this.addToChain(e,d,true),d}let{symbol:t,isInlineSmiles:n,rawPayload:o,inlineSource:r,span:s}=this.consumeMonomerSymbol(false),a=this.makeAtom(e,b.LINKER,t);return r!==void 0&&(a.inlineSource=r),n&&this.registerInlineSmiles(o,s,v.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(v.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\"?\"+\":\",\",l=`(${r.map(u=>u.symbol+(u.ratio!==void 0?`:${String(u.ratio)}`:\"\")).join(a)})`,d=this.makeAtom(e,b.BASE,\"?\");d.bio.ambiguity=l,d.bio.ambiguityKind=s===\"and\"?\"and\":\"or\",this.addToChain(e,d,true);let c=e.backboneAtoms[e.backboneAtoms.length-2];c!==void 0&&this.addBond(e,c,d,\"backbone\",{kind:\"numeric\",r:2},{kind:\"numeric\",r:1}),this.maybeRepeatBracket(e,[d]),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,b.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,b.CHEM,n),s!==void 0&&(t.inlineSource=s),o&&this.registerInlineSmiles(r,a,v.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 d=this.cursor.advance();o=Ce(d.value),r=d.value,t=d.value,n=d.value,s=d.value,a=d.span;}else if(this.cursor.at(\"identifier\")){let d=this.cursor.advance();t=d.value,n=d.value,a=d.span;}else this.emit(\"error\",\"unknown-blobtype\",\"Expected BLOB identifier\",this.cursor.currentSpan()),t=\"?\",n=\"?\";let l=this.makeAtom(e,b.BLOB,t);l.bio.blobtype=n,s!==void 0&&(l.inlineSource=s),o&&this.registerInlineSmiles(r,a,v.BLOB),this.addToChain(e,l,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(),l=this.cursor.optional(\"quote-string\"),d=r.kind===\"pair\"&&a.kind===\"pair\"?\"hbond\":\"cross-polymer\",c={chain1:t.value,pos1:o,r1:r,chain2:n.value,pos2:s,r2:a,kind:d,span:{start:e.start,end:l?.span.end??this.cursor.peek().span.start},...l!==null?{tag:l.value}:{}};this.pendingBonds.push(c);}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=lo(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,l]of Object.entries(r))l!==null&&typeof l==\"object\"&&!Array.isArray(l)?(s.set(a,{...l}),this.chainById.has(a)||this.emit(\"warning\",\"annotation-unknown-polymer\",`Annotation references unknown polymer '${a}'`,e)):s.set(a,{value:l});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=Ce(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===v.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(Ce(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 l=this.chainById.get(a.chain1),d=this.chainById.get(a.chain2);if(l===void 0){this.emit(\"error\",\"unknown-chain-reference\",`Connection references unknown chain '${a.chain1}'`,a.span);continue}if(d===void 0){this.emit(\"error\",\"unknown-chain-reference\",`Connection references unknown chain '${a.chain2}'`,a.span);continue}let c=this.resolveAtomByPosition(l,a.pos1,a.span),u=this.resolveAtomByPosition(d,a.pos2,a.span);if(c===null||u===null)continue;a.r1.kind===\"pair\"&&c.branchAtom!==void 0&&(c=c.branchAtom),a.r2.kind===\"pair\"&&u.branchAtom!==void 0&&(u=u.branchAtom);let p={id:this.bondIds.next(),a1:c,a2:u,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 u of a.allAtoms)t.push(u);for(let u of a.bonds)n.push(u);let l=this.annotations.perPolymer.get(a.id),d=l===void 0?void 0:l.strandtype,c=d===\"ss\"||d===\"as\"?d:void 0;o.push({id:a.id,polymerType:a.polymerType,backboneAtoms:a.backboneAtoms,bonds:a.bonds,...a.annotation!==void 0?{annotation:a.annotation}:{},...c!==void 0?{strandType:c}:{}});}for(let a of e)n.push(a);let r=0;for(let a of this.chains)for(let l of a.backboneAtoms)r+=1,l.bio.continuousId=r,l.branchAtom!==void 0&&(r+=1,l.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(l=>l.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 N(t,n,{...o!==void 0?{span:{start:o.start,end:o.end}}:{}})}};function uo(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 fr(i){let e=false;for(let c of i.chains){for(let u=0;u<c.backboneAtoms.length-1;u++){let m=c.backboneAtoms[u],p=c.backboneAtoms[u+1];if(!uo(m,p,i.bonds)){e=true;break}}if(e)break}if(!e)return i;let t=new Set(i.chains.map(c=>c.id)),n=c=>{let u=1;for(;t.has(`${c}${u}`);)u+=1;let m=`${c}${u}`;return t.add(m),m},o=[];for(let c of i.chains){let u=[[]],m=u[0];for(let p=0;p<c.backboneAtoms.length;p++){let h=c.backboneAtoms[p];if(m.push(h),p<c.backboneAtoms.length-1){let f=c.backboneAtoms[p+1];uo(h,f,i.bonds)||(m=[],u.push(m));}}for(let p=0;p<u.length;p++){let f={id:p===0?c.id:n(c.polymerType),polymerType:c.polymerType,atoms:u[p]};p===0&&c.annotation!==void 0&&(f.annotation=c.annotation),o.push(f);}}let r=new Map;for(let c of o)for(let u=0;u<c.atoms.length;u++){let m=c.atoms[u];r.set(m.id,{chainId:c.id,pos:u+1}),m.branchAtom!==void 0&&r.set(m.branchAtom.id,{chainId:c.id,pos:u+1});}let s=new Map;for(let c of i.atoms){let u=r.get(c.id);if(u===void 0){s.set(c.id,c);continue}if(c.bio.chainId===u.chainId&&c.bio.positionInChain===u.pos){s.set(c.id,c);continue}s.set(c.id,{...c,bio:{...c.bio,chainId:u.chainId,positionInChain:u.pos}});}for(let c of i.atoms){if(c.branchAtom===void 0)continue;let u=s.get(c.id),m=s.get(c.branchAtom.id);u===void 0||m===void 0||(u.branchAtom=m);}let a=i.bonds.map(c=>{let u=s.get(c.a1.id)??c.a1,m=s.get(c.a2.id)??c.a2;return u===c.a1&&m===c.a2?c:{...c,a1:u,a2:m}}),l=o.map(c=>{let u=c.atoms.map(f=>s.get(f.id)??f),m=new Set;for(let f of c.atoms)m.add(f.id),f.branchAtom!==void 0&&m.add(f.branchAtom.id);let p=[];for(let f of a)m.has(f.a1.id)&&m.has(f.a2.id)&&p.push(f);return {id:c.id,polymerType:c.polymerType,backboneAtoms:u,bonds:p,...c.annotation!==void 0?{annotation:c.annotation}:{}}});return {atoms:i.atoms.map(c=>s.get(c.id)??c),bonds:a,chains:l,groups:i.groups,annotations:i.annotations}}function Re(i,e){let t=fr(i);return new pn(t,e??{}).emit()}var pn=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?`\"${te(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],l=t.find(c=>c.startAtomId===a.id);l!==void 0&&s===null&&(n.push(\"(\"),s=l,r+=1),n.push(this.emitMonomerToken(a));let d=a.tag!==void 0?`\"${te(a.tag)}\"`:\"\";n.push(d),s!==null&&s.endAtomId===a.id&&(n.push(`)${mo(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=d=>{s!==null&&s.endAtomId===d&&(n.push(`)${mo(s.min,s.max)}`),s=null);},l=d=>{let c=t.find(u=>u.startAtomId===d);c!==void 0&&s===null&&(n.push(\"(\"),s=c);};for(;o<e.backboneAtoms.length;){let d=e.backboneAtoms[o];if(r||n.push(\".\"),r=false,d.biotype===b.NUCLEOTIDE){l(d.id),n.push(this.emitMonomerToken(d)),d.tag!==void 0&&n.push(`\"${te(d.tag)}\"`),a(d.id),o+=1;continue}if(d.biotype===b.SUGAR){l(d.id),n.push(this.emitMonomerToken(d)),d.tag!==void 0&&n.push(`\"${te(d.tag)}\"`),d.branchAtom!==void 0&&(n.push(\"(\"),n.push(this.emitMonomerToken(d.branchAtom)),d.branchAtom.tag!==void 0&&n.push(`\"${te(d.branchAtom.tag)}\"`),n.push(\")\"));let c=e.backboneAtoms[o+1];c!==void 0&&c.biotype===b.LINKER?(n.push(this.emitMonomerToken(c)),c.tag!==void 0&&n.push(`\"${te(c.tag)}\"`),a(c.id),o+=2):(a(d.id),o+=1);continue}l(d.id),n.push(this.emitMonomerToken(d)),d.tag!==void 0&&n.push(`\"${te(d.tag)}\"`),a(d.id),o+=1;}return n.join(\"\")}emitChemBody(e){let t=e.backboneAtoms[0];if(t===void 0)return \"\";let n=t.tag!==void 0?`\"${te(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?`\"${te(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=po(e.r1,e.kind),n=po(e.r2,e.kind),o=e.tag!==void 0?`\"${te(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=>br(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 l of o.members){let d=parseInt(l.target,10);Number.isFinite(d)&&r.push(d);}if(r.length===0)continue;let s=new Set;for(let l of r){let d=n.get(l);d!==void 0&&s.add(d);}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 te(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 mo(i,e){return i===e?`'${i}'`:`'${i}-${e}'`}function po(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 br(i){return i.ratio===void 0?i.target:`${i.target}:${i.ratio}`}function fn(i){return new hn(i).run()}var hn=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:fo(m.id,p.id)),t={},n=[];for(let m of e){let p=yr(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 y of m.backboneAtoms){let w=o.get(y.id);w!==void 0&&h.push(w);}let f=[];for(let y of m.bonds){let w=s.get(y.id);w!==void 0&&f.push(w);}return {id:p,polymerType:m.polymerType,backboneAtoms:h,bonds:f,...m.annotation!==void 0&&m.annotation.length>0?{annotation:m.annotation}:{}}}),l=new Map;for(let m of a)l.set(m.id,m);r.sort((m,p)=>{let h=ho(m.kind),f=ho(p.kind);if(h&&!f)return 1;if(!h&&f)return -1;if(!h&&!f)return m.id-p.id;let y=m.a1.bio.chainId,w=p.a1.bio.chainId;if(y!==w)return y<w?-1:1;let _=m.a2.bio.chainId,M=p.a2.bio.chainId;if(_!==M)return _<M?-1:1;let k=le(m.a1,l.get(m.a1.bio.chainId)),x=le(p.a1,l.get(p.a1.bio.chainId));if(k!==x)return k-x;let T=le(m.a2,l.get(m.a2.bio.chainId)),E=le(p.a2,l.get(p.a2.bio.chainId));return T-E});let d=this.renumberGroups(this.mol.groups),c=this.rekeyAnnotations(this.mol.annotations);return {atoms:this.mol.atoms.map(m=>o.get(m.id)),bonds:r,chains:a,groups:d,annotations:c}}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)=>fo(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 yr(i){switch(i){case \"PEPTIDE\":return \"PEPTIDE\";case \"RNA\":return \"RNA\";case \"CHEM\":return \"CHEM\";case \"BLOB\":return \"BLOB\";default:return \"BLOB\"}}function ho(i){return i===\"cross-polymer\"||i===\"hbond\"}function fo(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 bo(i){let e=Ee(i),t=new Map;for(let a of i.atoms){let l=e.get(a.id);if(l===void 0||l===a.bio.continuousId){t.set(a.id,a);continue}t.set(a.id,{...a,bio:{...a.bio,continuousId:l}});}for(let a of i.atoms){if(a.branchAtom===void 0)continue;let l=t.get(a.id),d=t.get(a.branchAtom.id);l===void 0||d===void 0||(l.branchAtom=d);}let n=i.bonds.map(a=>{let l=t.get(a.a1.id),d=t.get(a.a2.id);return l===void 0||d===void 0||l===a.a1&&d===a.a2?a:{...a,a1:l,a2:d}}),o=new Map;for(let a of n)o.set(a.id,a);let r=i.chains.map(a=>{let l=[];for(let c of a.backboneAtoms){let u=t.get(c.id);l.push(u??c);}let d=[];for(let c of a.bonds){let u=o.get(c.id);d.push(u??c);}return {id:a.id,polymerType:a.polymerType,backboneAtoms:l,bonds:d,...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 bn(i,e){let n=et(i,e??null,{mode:\"lenient\",resolveMonomers:false}),o=gr(n.mol),r=bo(o.mol),s=new Map;for(let d of r.atoms)s.set(d.id,d.bio.continuousId);let a=new Map;for(let[d,c]of o.survivorByOldContinuousId){let u=s.get(c);u!==void 0&&a.set(d,u);}let l=Re(r,{version:\"V2.0\"});return {srcHelm:i,resHelm:l,monomerMap:a}}function gr(i){let e=new Map;for(let u of i.atoms)e.set(u.bio.continuousId,u.id);let t=new Set;for(let u of i.atoms)u.symbol===\"*\"&&t.add(u.id);if(t.size===0)return {mol:i,survivorByOldContinuousId:e};let n=new Map;for(let u of i.atoms)n.set(u.id,[]);for(let u of i.bonds)n.get(u.a1.id)?.push(u),n.get(u.a2.id)?.push(u);for(let u of t){let m=n.get(u)??[];if(m.some(f=>f.kind===\"cross-polymer\"||f.kind===\"hbond\"))throw new j(\"gap-at-complex-junction\",`Gap atom ${u} participates in a cross-polymer/hbond bond`,{atomId:u});let h=m.filter(f=>f.kind===\"backbone\");if(h.length>2)throw new j(\"gap-at-complex-junction\",`Gap atom ${u} has ${h.length} backbone bonds (max 2 allowed)`,{atomId:u,bondCount:h.length})}let o=i.atoms.filter(u=>!t.has(u.id)),r=[],s=[];for(let u of i.chains){let m=u.backboneAtoms.filter(f=>!t.has(f.id)),p=(()=>{let f=0;for(let y of i.bonds)y.id>f&&(f=y.id);return f+1})(),h=[];for(let f of u.bonds)t.has(f.a1.id)||t.has(f.a2.id)||h.push(f);for(let f=0;f<u.backboneAtoms.length;f++){let y=u.backboneAtoms[f];if(!t.has(y.id))continue;let w=_r(u.backboneAtoms,f,t),_=vr(u.backboneAtoms,f,t);if(w===null||_===null)continue;let M={id:p++,a1:w,a2:_,kind:\"backbone\",r1:{kind:\"numeric\",r:2},r2:{kind:\"numeric\",r:1}};h.find(x=>x.a1.id===w.id&&x.a2.id===_.id)===void 0&&h.push(M);}for(let f of h)s.push(f);r.push({id:u.id,polymerType:u.polymerType,backboneAtoms:m,bonds:h,...u.annotation!==void 0?{annotation:u.annotation}:{}});}for(let u of i.bonds)u.kind!==\"cross-polymer\"&&u.kind!==\"hbond\"||t.has(u.a1.id)||t.has(u.a2.id)||s.push(u);let a=new Map;for(let u of r){let m=0;for(let p of u.backboneAtoms)m+=1,a.set(p.id,{...p,bio:{...p.bio,positionInChain:m}});}for(let u of o)a.has(u.id)||a.set(u.id,u);let l=r.map(u=>{let m=u.backboneAtoms.map(h=>a.get(h.id)),p=u.bonds.map(h=>({...h,a1:a.get(h.a1.id),a2:a.get(h.a2.id)}));return {id:u.id,polymerType:u.polymerType,backboneAtoms:m,bonds:p,...u.annotation!==void 0?{annotation:u.annotation}:{}}}),d=s.map(u=>({...u,a1:a.get(u.a1.id),a2:a.get(u.a2.id)}));return {mol:{atoms:o.map(u=>a.get(u.id)),bonds:d,chains:l,groups:i.groups,annotations:i.annotations},survivorByOldContinuousId:e}}function _r(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 vr(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 yn(i,e,t){let n=t?.mode??\"lenient\",o=[];for(let s of wr)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 Ye(s)}return r}var wr=[xr,kr,Ar,Mr,Tr,Er,Cr,Lr];function xr(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 l=0;for(let d of s.backboneAtoms)l+=d.branchAtom!==void 0?2:1;for(let d of [a.a1,a.a2]){if(d.bio.chainId!==s.id)continue;let c=le(d,s);(c<1||c>l)&&t.push({severity:\"error\",code:\"position-out-of-range\",message:`Position ${c} out of range for chain '${s.id}' (length ${l})`,context:{chainId:s.id,atomId:d.id,found:c}});}}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 l of s.members)o.has(l.target)&&a.push(l.target);r.set(s.id,a);}for(let s of r.keys()){let a=new Set,l=[s];for(;l.length>0;){let d=l.pop();if(a.has(d))continue;a.add(d);let c=r.get(d)??[];for(let u of c)u===s?t.push({severity:\"error\",code:\"group-cycle\",message:`Group cycle detected involving '${s}'`,context:{found:s}}):a.has(u)||l.push(u);}}return t}function kr(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 Ar(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 Mr(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===b.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===b.LINKER&&(n.backboneAtoms.slice(0,r).some(l=>l.biotype===b.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===b.SUGAR||s.biotype===b.LINKER;}}}return t}function Tr(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!==b.BASE||r.a2.biotype!==b.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}`}}),Sr(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 Sr(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 Er(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=yo(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=yo(o,\",\"),s=0,a=false;for(let l of r)typeof l.ratio==\"number\"&&(s+=l.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 yo(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 l=s.slice(0,a),d=s.slice(a+1),c=parseFloat(d);Number.isFinite(c)?o.push({symbol:l,ratio:c}):o.push({symbol:l});}return o}function Cr(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 Lr(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 go(i){let e=[],t=new Map;for(let n of i.chains)for(let o of n.backboneAtoms)t.set(o.id,n.id);for(let n of i.chains)for(let o of n.backboneAtoms)o.branchAtom!==void 0&&t.set(o.branchAtom.id,n.id);for(let n of i.chains){let o=Br(n.polymerType),r=n.backboneAtoms,s=[],a=[],l=[];for(let c of n.bonds)c.kind===\"backbone\"&&l.push(c);if(o===\"RNA\")for(let c of r){if(c.biotype!==b.SUGAR){s.push(null),a.push(null);continue}let u=null,m=null;for(let p of n.bonds){if(p.kind!==\"branch\")continue;let h=p.a1.id===c.id?p.a2:p.a2.id===c.id?p.a1:null;if(h!==null&&h.biotype===b.BASE){u=h,m=p;break}}s.push(u),a.push(m);}else for(let c=0;c<r.length;c++)s.push(null),a.push(null);let d=Rr(i,n.id,r,t);e.push({id:n.id,polymerType:o,backbone:r,bases:s,backboneBonds:l,baseBonds:a,isCyclic:d,...n.strandType!==void 0?{strandType:n.strandType}:{}});}return e}function Br(i){switch(i){case v.PEPTIDE:return \"PEPTIDE\";case v.RNA:return \"RNA\";case v.CHEM:return \"CHEM\";case v.BLOB:return \"BLOB\";default:return \"BLOB\"}}function Rr(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),l=n.get(s.a2.id);if(a!==e||l!==e||!(s.a1.id===r.id&&s.a2.id===o.id||s.a2.id===r.id&&s.a1.id===o.id))continue;let c=s.a1.id===o.id?s.r1:s.r2,u=s.a1.id===r.id?s.r1:s.r2,m=c.kind===\"numeric\"&&c.r===1,p=u.kind===\"numeric\"&&u.r===2;if(m&&p)return true}return false}var gn=44.800000000000004,_o=1.5*28,At=1.5*28/gn,_n=1.5*28/gn,vn=1.5*28/gn;function ke(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 Ir=Math.PI/180;function Mt(i,e){let t=i.backbone.length;if(t<=2){let d={};return e?.bondLength!==void 0&&(d.bondLength=e.bondLength),e?.origin!==void 0&&(d.origin=e.origin),ke(i,d)}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)),l=new Map;for(let d=0;d<t;d++){let c=i.backbone[d],m=(r+d*360/t)*Ir;l.set(c.id,{x:o.x+a*Math.cos(m),y:o.y+a*Math.sin(m)});}return l}var Pr=10,Hr=1.5/1.6;function vo(i,e){let t=e?.bondLength??28,n=e?.origin??{x:0,y:0},o=Math.max(1,e?.perRow??Pr),r=e?.rowSpacing??Hr,s=1.6*t,a=r*s,l=new Map;for(let d=0;d<i.backbone.length;d++){let c=i.backbone[d],u=Math.floor(d/o),m=d%o,p=u%2===0?n.x+m*s:n.x+(o-1-m)*s,h=n.y+u*a;l.set(c.id,{x:p,y:h});}return l}function wo(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 l=Math.min(s,a),d=Math.max(s,a);d-l<2||l===0&&d===n||o.push({lo:l,hi:d});}return o}function xo(i,e){return e===null?false:wo(i,e).length>0}function wn(i,e,t){if(e===null)return ke(i,t);let n=t?.bondLength??28,o=t?.origin??{x:0,y:0},r=1.6*n,s=wo(i,e);if(s.length===0)return ke(i,t);let a=s[0].lo,l=s[0].hi;for(let L of s)L.lo<a&&(a=L.lo),L.hi>l&&(l=L.hi);let d=i.backbone.slice(a,l+1),c=d.length,u=r/(2*Math.sin(Math.PI/c)),m={id:i.id,polymerType:i.polymerType,backbone:d,bases:new Array(c).fill(null),baseBonds:new Array(c).fill(null)},p=a,h={x:o.x+p*r+u,y:o.y},f=Mt(m,{bondLength:n,origin:h,startDegrees:180}),y=new Map;for(let L=0;L<a;L++){let z=i.backbone[L];y.set(z.id,{x:o.x+L*r,y:o.y});}for(let[L,z]of f)y.set(L,z);let w=d[c-1],_=f.get(w.id)??h,M=_.x-h.x,k=_.y-h.y,x=Math.hypot(M,k);x<1e-6&&(M=0,k=1,x=1);let T=M/x,E=k/x,C={x:_.x+T*r,y:_.y+E*r},P=Math.sign(_.x-h.x);if(P===0&&c>=2){let L=f.get(d[c-2].id);L!==void 0&&(P=Math.sign(_.x-L.x));}P===0&&(P=1);for(let L=l+1;L<i.backbone.length;L++){let z=i.backbone[L],ae=L-(l+1);y.set(z.id,ae===0?C:{x:C.x+P*r*ae,y:C.y});}return y}function Ao(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 ko(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 Mo(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=ko(i.a1.id,e,t),s=ko(i.a2.id,e,t);return r===null||s===null||r===s?null:{lo:Math.min(r,s),hi:Math.max(r,s)}}function To(i,e){if(i.polymerType!==\"RNA\"||i.backbone.length===0)return false;let{sugarToIdx:t,baseToIdx:n}=Ao(i);for(let o of e.bonds)if(Mo(o,t,n)!==null)return true;return false}function $r(i,e){let t=i.backbone.length,n=new Int32Array(t).fill(-1);if(t===0)return n;let{sugarToIdx:o,baseToIdx:r}=Ao(i),s=[];for(let l of e.bonds){let d=Mo(l,o,r);d!==null&&s.push([d.lo,d.hi]);}s.sort((l,d)=>l[0]-d[0]||d[1]-l[1]);let a=[];for(let l of s){let[d,c]=l,u=false;for(let[m,p]of a){let h=c<m||d>p,f=d>m&&c<p||d<m&&c>p;if(!h&&!f){u=true;break}}u||n[d]!==-1||n[c]!==-1||(n[d]=c,n[c]=d,a.push(l));}return n}function Dr(i){return e(0,i.length-1,null);function e(t,n,o){let r=[],s=-1,a=t;for(;a<=n;){let l=i[a];if(l>a&&l<=n){s!==-1&&(r.push({kind:\"unpaired\",from:s,to:a-1}),s=-1);let d=1;for(;a+2*d<l-2*d&&i[a+2*d]===l-2*d&&i[a+2*d-1]===-1&&i[l-2*d+1]===-1;)d+=1;let c=a+2*(d-1),u=l-2*(d-1),m=[c,u],p=e(c+1,u-1,m);r.push({kind:\"stem\",fromIdx:a,toIdx:l,numPairs:d,child:p}),a=l+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 Tt(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 Or(i){return {x:-i.y,y:i.x}}function xn(i,e,t){return {x:i.x+e*Math.cos(t),y:i.y+e*Math.sin(t)}}function Nr(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 l=0;l<64;l++){let d=i/(2*a),u=2*Math.asin(Math.min(.9999,Math.max(-0.9999,d))),m=(2*Math.PI-r*u)*a-s,p=d,h=Math.sqrt(Math.max(1e-12,1-p*p)),y=2*(-i/(2*a*a)/h),w=2*Math.PI-r*u-r*a*y;if(!Number.isFinite(w)||Math.abs(w)<1e-12)break;let _=m/w,M=a-_;if(!Number.isFinite(M)||M<i/2+.001){a=i/2+.001;break}if(a=M,Math.abs(_)<1e-9)break}return Math.max(a,i/2+.001)}function St(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 So(i,e,t){let{chain:n,step:o,rail:r,baseInwardHang:s,out:a}=t,l=2*i.numPairs-1,d={x:e.normal.x,y:e.normal.y},c={x:-e.normal.x,y:-e.normal.y};for(let m=0;m<l;m++){let p=n.backbone[i.fromIdx+m],h=n.backbone[i.toIdx-m],f=m*o,y={x:e.origin.x+f*e.tangent.x,y:e.origin.y+f*e.tangent.y},w={x:e.origin.x+f*e.tangent.x+r*e.normal.x,y:e.origin.y+f*e.tangent.y+r*e.normal.y};a.set(p.id,y),a.set(h.id,w),St(i.fromIdx+m,y,d,s,t),St(i.toIdx-m,w,c,s,t);}let u=(l-1)*o;return {origin:{x:e.origin.x+u*e.tangent.x,y:e.origin.y+u*e.tangent.y},tangent:e.tangent,normal:e.normal}}function Eo(i,e,t,n){if(i.closingPair===null)return;let{step:o,rail:r,out:s}=t,a=0,l=0;for(let T of i.nodes)T.kind===\"unpaired\"?a+=T.to-T.from+1:l+=1;let d=Nr(r,o,a,l),c=s.get(t.chain.backbone[i.closingPair[0]].id),u=s.get(t.chain.backbone[i.closingPair[1]].id),m={x:(c.x+u.x)/2,y:(c.y+u.y)/2},p=Math.sqrt(Math.max(0,d*d-r/2*(r/2))),h={x:m.x+p*e.tangent.x,y:m.y+p*e.tangent.y},f=Math.atan2(c.y-h.y,c.x-h.x),w=Math.atan2(u.y-h.y,u.x-h.x)-f;for(;w>Math.PI;)w-=2*Math.PI;for(;w<=-Math.PI;)w+=2*Math.PI;let _=w>0?-1:1,M=2*Math.asin(Math.min(.9999,Math.max(-0.9999,r/(2*d)))),k=o/d,x=f;for(let T of i.nodes)if(T.kind===\"unpaired\")for(let E=T.from;E<=T.to;E++){x=x+_*k;let C=xn(h,d,x);s.set(t.chain.backbone[E].id,C);let P=Tt({x:C.x-h.x,y:C.y-h.y});St(E,C,P,t.step,t);}else {x=x+_*k;let E=xn(h,d,x);x=x+_*M;let C=xn(h,d,x);s.set(t.chain.backbone[T.fromIdx].id,E),s.set(t.chain.backbone[T.toIdx].id,C);let P=Tt({x:(E.x+C.x)/2-h.x,y:(E.y+C.y)/2-h.y}),L=Tt({x:C.x-E.x,y:C.y-E.y}),ae=So(T,{origin:E,tangent:P,normal:L},t);Eo(T.child,ae,t);}}function Fr(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},l={x:-e.normal.x,y:-e.normal.y};for(let d of i.nodes)if(d.kind===\"unpaired\")for(let c=d.from;c<=d.to;c++){let u={x:s.x,y:s.y};r.set(t.chain.backbone[c].id,u),St(c,u,{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 c={origin:{x:s.x,y:s.y},tangent:l,normal:a},u=So(d,c,t);Eo(d.child,u,t),s={x:s.x+(o+n)*a.x,y:s.y+(o+n)*a.y};}}function Co(i,e,t){let n=t?.bondLength??28,o=1.6*n,r=o/2,a=_o*(n/28)+2*r,l=t?.origin??{x:0,y:0},d=Tt(t?.rootDirection??{x:1,y:0}),c=Or(d),u=new Map;if(i.backbone.length===0)return u;let m=$r(i,e),p=Dr(m);Fr(p,{origin:l,tangent:d,normal:c},{chain:i,step:o,rail:a,baseInwardHang:r,out:u});for(let y of i.backbone)u.has(y.id)||u.set(y.id,{x:l.x,y:l.y});return u}function Lo(i,e,t){if(i.polymerType!==\"RNA\")return e;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],l=e.get(a.id);if(l===void 0)continue;let d=Gr(i,r,e);e.set(s.id,{x:l.x+o*d.x,y:l.y+o*d.y});}return e}function Gr(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,l=s!==void 0?t.get(s.id):void 0,d=0,c=0;if(a!==void 0&&l!==void 0){let u=l.x-a.x,m=l.y-a.y,p=Math.hypot(u,m);if(p===0)return {x:0,y:1};let h={x:m/p,y:-u/p},f={x:-m/p,y:u/p},y=h.y>=f.y?h:f;d=y.x,c=y.y;}else if(l!==void 0){let u=l.x-o.x,m=l.y-o.y,p=Math.hypot(u,m);if(p===0)return {x:0,y:1};let h={x:m/p,y:-u/p},f={x:-m/p,y:u/p},y=h.y>=f.y?h:f;d=y.x,c=y.y;}else if(a!==void 0){let u=o.x-a.x,m=o.y-a.y,p=Math.hypot(u,m);if(p===0)return {x:0,y:1};let h={x:m/p,y:-u/p},f={x:-m/p,y:u/p},y=h.y>=f.y?h:f;d=y.x,c=y.y;}else return {x:0,y:1};return {x:d,y:c}}function Io(i,e,t,n){let o=n?.bondLength??28,r=1.6*o,s=new Map,a=new Map;for(let h of i){let f=new Set;for(let y of h.backbone)f.add(y.id);for(let y of h.bases)y!==null&&f.add(y.id);a.set(h.id,{chain:h,atomIds:f});for(let y of f)s.set(y,h);}let l=new Set;if(i.length>0){let h=i.find(f=>f.strandType===\"ss\");l.add((h??i[0]).id);}let d=new Map;for(let h of i)d.set(h.id,h.id);let c=h=>{let f=h;for(;d.get(f)!==f;)f=d.get(f);let y=h;for(;d.get(y)!==f;){let w=d.get(y);d.set(y,f),y=w;}return f},u=(h,f)=>{d.set(c(h),c(f));},m=h=>{let f=c(h),y=new Set;for(let[w,_]of a)if(c(w)===f)for(let M of _.atomIds)y.add(M);return y},p=h=>{let f=c(h),y=0;for(let w of d.keys())c(w)===f&&(y+=1);return y};for(let h of t.bonds){if(h.kind===\"backbone\"||h.kind===\"branch\")continue;let f=s.get(h.a1.id),y=s.get(h.a2.id);if(f===void 0||y===void 0||f.id===y.id)continue;h.kind===\"hbond\"&&(f.strandType===\"as\"&&y.strandType===\"ss\"?l.add(y.id):y.strandType===\"as\"&&f.strandType===\"ss\"?l.add(f.id):f.strandType===\"as\"&&!l.has(y.id)?l.add(y.id):y.strandType===\"as\"&&!l.has(f.id)&&l.add(f.id));let w=y,_=h.a1,M=h.a2;if(l.has(y.id)&&!l.has(f.id))w=f,_=h.a2,M=h.a1;else if(!l.has(f.id)&&!l.has(y.id)){if(l.size>0){let T=new Set;for(let L of l){let z=a.get(L);if(z!==void 0)for(let ae of z.atomIds)T.add(ae);}let E=Ho(T,e),C=a.get(f.id),P=Po(C.atomIds,e);if(E!==null&&P!==null){let L=E+r*At-P;L>0&&tt(C.atomIds,e,0,L);}}l.add(f.id),w=y,_=h.a1,M=h.a2;}else if(l.has(f.id)&&l.has(y.id)){if(c(f.id)===c(y.id)||h.kind!==\"cross-polymer\")continue;let T=m(f.id),E=m(y.id),C=T.size<=E.size,P=C?T:E,L=C?E:T,z=e.get((C?h.a1:h.a2).id),ae=e.get((C?h.a2:h.a1).id);z!==void 0&&ae!==void 0&&Ro(P,z,L,ae,r,e),u(f.id,y.id);continue}let k=e.get(_.id),x=e.get(M.id);if(!(k===void 0||x===void 0)){if(h.kind===\"hbond\"){let T=a.get(w.id);Vr(T.atomIds,e),Ur(T.atomIds,e);let E=e.get(M.id),C=k.x-E.x,P=k.y+r*_n-E.y;P=Bo(P,T,l,a,e,r*_n),tt(T.atomIds,e,C,P);}else if(w.isCyclic&&w.backbone.length>=3){let T=a.get(w.id),E=w.id===f.id?y:f,C=a.get(E.id);Kr(T.atomIds,x,C.atomIds,k,r,e);}else {let T=a.get(w.id),E=k.x-x.x,C=k.y+r*vn-x.y;C=Bo(C,T,l,a,e,r*vn);let P=Math.abs(x.y+C-k.y),L=s.get(_.id),z=L!==void 0&&p(L.id)>1;h.kind===\"cross-polymer\"&&z&&P>2*r?Ro(T.atomIds,x,m(L.id),k,r,e):tt(T.atomIds,e,E,C);}l.add(w.id),u(f.id,y.id);}}return l}function Bo(i,e,t,n,o,r){let s=Po(e.atomIds,o);if(s===null)return i;let a=null;for(let c of t){let u=n.get(c);if(u===void 0)continue;let m=Ho(u.atomIds,o);m!==null&&(a===null||m>a)&&(a=m);}if(a===null)return i;let l=s+i,d=a+r;return l<d?d-s:i}function Po(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 Ho(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 tt(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 Vr(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 Ur(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 kn(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 Ro(i,e,t,n,o,r){let s=kn(t,r),a=n.x-s.x,l=n.y-s.y,d=Math.hypot(a,l);d<1e-6&&(a=0,l=1,d=1);let c=a/d,u=l/d,m=n.x+c*o,p=n.y+u*o;tt(i,r,m-e.x,p-e.y);}function zr(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 l=a.x-t.x,d=a.y-t.y;e.set(s,{x:t.x+l*o-d*r,y:t.y+l*r+d*o});}}function Kr(i,e,t,n,o,r){let s=kn(t,r),a=n.x-s.x,l=n.y-s.y,d=Math.hypot(a,l);d<1e-6&&(a=1,l=0,d=1);let c=a/d,u=l/d,m=kn(i,r),p=Math.hypot(e.x-m.x,e.y-m.y),h=Math.atan2(e.y-m.y,e.x-m.x),f=Math.atan2(-u,-c);zr(i,r,m,f-h);let y=n.x+c*(o+p),w=n.y+u*(o+p);tt(i,r,y-m.x,w-m.y);}function $o(i,e,t,n){let o=n?.bondLength??28,r=n?.gap??At,s=1.6*o,a=r*s,l=0,d=false;for(let u of i)if(t.has(u.id)){for(let m of u.backbone){let p=e.get(m.id);p!==void 0&&(d?p.y>l&&(l=p.y):(l=p.y,d=true));}for(let m of u.bases){if(m===null)continue;let p=e.get(m.id);p!==void 0&&p.y>l&&(l=p.y);}}d||(l=0);let c=l+a;for(let u of i){if(t.has(u.id))continue;let m=Number.POSITIVE_INFINITY,p=Number.NEGATIVE_INFINITY;for(let f of u.backbone){let y=e.get(f.id);y!==void 0&&(y.y<m&&(m=y.y),y.y>p&&(p=y.y));}for(let f of u.bases){if(f===null)continue;let y=e.get(f.id);y!==void 0&&(y.y<m&&(m=y.y),y.y>p&&(p=y.y));}if(m===Number.POSITIVE_INFINITY){t.add(u.id);continue}let h=c-m;for(let f of u.backbone){let y=e.get(f.id);y!==void 0&&e.set(f.id,{x:y.x,y:y.y+h});}for(let f of u.bases){if(f===null)continue;let y=e.get(f.id);y!==void 0&&e.set(f.id,{x:y.x,y:y.y+h});}c=p+h+a,t.add(u.id);}}var Wr=20,jr=40,qr=250,Yr=4;function Xr(i,e){let t=1,n=qr;for(;e>n;)t*=2,n*=Yr;return i*t}function ne(i,e){let t=e?.bondLength??28,n=e?.perRow,o=e?.rowsThreshold,r=e?.circleThreshold??20,s=go(i),a=new Map;for(let d of s){let c=Jr(d,i,t,n,o,r);for(let[u,m]of c)a.set(u,m);d.polymerType===\"RNA\"&&Lo(d,a,{bondLength:t});}let l=Io(s,a,i,{bondLength:t});$o(s,a,l,{bondLength:t});for(let d of i.atoms)a.has(d.id)||a.set(d.id,{x:0,y:0});return Zr(i,a)}function Jr(i,e,t,n,o,r){let s=i.backbone.length;if(s===0)return new Map;let a=i.polymerType===\"RNA\",d=n??Xr(a?jr:Wr,s),c=o??d;if(i.polymerType===\"RNA\"&&To(i,e))return Co(i,e,{bondLength:t});if(i.isCyclic&&s<=r)return Mt(i,{bondLength:t});if(!i.isCyclic&&xo(i,e))return wn(i,e,{bondLength:t});if(s>c){let u=a?2:void 0;return vo(i,u!==void 0?{bondLength:t,perRow:d,rowSpacing:u}:{bondLength:t,perRow:d})}return i.isCyclic?ke(i,{bondLength:t}):wn(i,e,{bondLength:t})}function Zr(i,e){let t=new Map,n=[];for(let s of i.atoms){let a=e.get(s.id)??s.p,l={...s,p:{x:a.x,y:a.y}};t.set(s.id,l),n.push(l);}for(let s=0;s<n.length;s++){let a=i.atoms[s];if(a.branchAtom!==void 0){let l=t.get(a.branchAtom.id);l!==void 0&&(n[s]={...n[s],branchAtom:l}),t.set(n[s].id,n[s]);}}let o=[];for(let s of i.bonds){let a=t.get(s.a1.id),l=t.get(s.a2.id);a===void 0||l===void 0||o.push({...s,a1:a,a2:l});}let r=[];for(let s of i.chains){let a=s.backboneAtoms.map(d=>t.get(d.id)??d),l=s.bonds.map(d=>{let c=t.get(d.a1.id)??d.a1,u=t.get(d.a2.id)??d.a2;return {...d,a1:c,a2:u}});r.push({id:s.id,polymerType:s.polymerType,backboneAtoms:a,bonds:l,...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 Et(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 A(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 An(i){if(i.length===0)return \"\";let e=i[0],t=`M ${A(e.x)} ${A(e.y)}`;for(let n=1;n<i.length;n++){let o=i[n];t+=` L ${A(o.x)} ${A(o.y)}`;}return t+=` L ${A(e.x)} ${A(e.y)} Z`,t}function Do(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 Oo(i,e,t=-30){return An(Do(i,6,e,t))}function No(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 An(t)}function Fo(i,e,t=-90){return An(Do(i,5,e,t))}function Mn(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,l=i.y-r,d=a+o*2,c=l+r*2,u=`M ${A(a+s)} ${A(l)}`;return u+=` L ${A(d-s)} ${A(l)}`,u+=` A ${A(s)} ${A(s)} 0 0 1 ${A(d)} ${A(l+s)}`,u+=` L ${A(d)} ${A(c-s)}`,u+=` A ${A(s)} ${A(s)} 0 0 1 ${A(d-s)} ${A(c)}`,u+=` L ${A(a+s)} ${A(c)}`,u+=` A ${A(s)} ${A(s)} 0 0 1 ${A(a)} ${A(c-s)}`,u+=` L ${A(a)} ${A(l+s)}`,u+=` A ${A(s)} ${A(s)} 0 0 1 ${A(a+s)} ${A(l)}`,u+=\" Z\",u}function Tn(i,e,t){let n=Math.abs(e),o=Math.abs(t);return `M ${A(i.x-n)} ${A(i.y)} A ${A(n)} ${A(o)} 0 1 0 ${A(i.x+n)} ${A(i.y)} A ${A(n)} ${A(o)} 0 1 0 ${A(i.x-n)} ${A(i.y)} Z`}function Go(i,e,t,n){return Mn(i,e,t,n)}function Vo(i,e){return Tn(i,e,e)}function Uo(i,e){return `M ${A(i.x)} ${A(i.y)} L ${A(e.x)} ${A(e.y)}`}function zo(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 ${A(i.x)} ${A(i.y)} L ${A(i.x)} ${A(i.y)}`;let s=n/r,a=o/r,l=-a,d=s,c=(i.x+e.x)/2,u=(i.y+e.y)/2,m=t/2,p=Math.min(t*.6,r*.25),h=c-s*p,f=u-a*p,y=c+s*p,w=u+a*p;return `M ${A(h-l*m)} ${A(f-d*m)} L ${A(h+l*m)} ${A(f+d*m)} M ${A(y-l*m)} ${A(w-d*m)} L ${A(y+l*m)} ${A(w+d*m)}`}function Sn(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 Ct=14,Ko='\"Helvetica Neue\", Helvetica, Arial, sans-serif';function Wo(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 H={name:\"light\",background:\"#ffffff\",defaultStroke:\"#202020\",defaultFill:\"#ffffff\",selectionColor:\"#FFC107\",highlightColor:\"#A4E2DC\",errorColor:\"#cc0000\",fontSize:Ct,fontFamily:Ko,bondLength:28,textColor:\"#000000\",idColor:\"#00aa00\",annotationColor:\"#FFA500\",tagDotColor:\"#dd2222\",hbondColor:\"#888888\",nonCanonicalHbondColor:\"#cc8800\",crossPolymerBondColor:\"#1f5fcd\",colorTheme:we,palette:{softenCanvas:false},shapes:Wo(Ct)},En={name:\"dark\",background:\"#1a1d23\",defaultStroke:\"#e0e0e0\",defaultFill:\"#2b2f37\",selectionColor:\"#FFD54F\",highlightColor:\"#7DD8CC\",errorColor:\"#ff5050\",fontSize:Ct,fontFamily:Ko,bondLength:28,textColor:\"#ffffff\",idColor:\"#33ff33\",annotationColor:\"#FFB84D\",tagDotColor:\"#ff6464\",hbondColor:\"#aaaaaa\",nonCanonicalHbondColor:\"#ffaa44\",crossPolymerBondColor:\"#6699ff\",colorTheme:Be,palette:{softenCanvas:false},shapes:Wo(Ct)};function Qr(i,e){let t=e.shapes===void 0?i.shapes:{...i.shapes,...e.shapes};return {...i,...e,shapes:t}}function nt(i,e){switch(e){case b.AA:return i.shapes.aa;case b.SUGAR:return i.shapes.sugar;case b.BASE:return i.shapes.base;case b.LINKER:return i.shapes.linker;case b.CHEM:return i.shapes.chem;case b.BLOB:return i.shapes.blob;case b.NUCLEOTIDE:return i.shapes.nucleotide}}var jo=\"*\";function Lt(i){switch(i){case b.AA:return \"hexagon\";case b.SUGAR:return \"rounded-rect\";case b.BASE:return \"diamond\";case b.LINKER:return \"circle\";case b.CHEM:return \"rounded-rect\";case b.BLOB:return \"blob\";case b.NUCLEOTIDE:return \"pentagon\"}}function Ie(i,e,t=0){let n=nt(e,i.biotype);if(i.symbol===jo)return Vo(i.p,n.size+t);switch(Lt(i.biotype)){case \"hexagon\":{let r=t===0?0:t/Math.cos(Math.PI/6);return Oo(i.p,n.size+r)}case \"diamond\":{let r=t===0?0:t/Math.cos(Math.PI/4);return No(i.p,n.size+r)}case \"pentagon\":{let r=t===0?0:t/Math.cos(Math.PI/5);return Fo(i.p,n.size+r)}case \"rounded-rect\":return Mn(i.p,n.size+2*t,n.size+2*t,(n.cornerRadius??0)+t);case \"blob\":return Go(i.p,n.size+2*t,n.size+2*t,(n.cornerRadius??0)+t);case \"circle\":return Tn(i.p,n.size+t,n.size+t)}}function pe(i,e){let t=nt(e,i.biotype),n=i.symbol===jo?\"circle\":Lt(i.biotype),o;switch(n){case \"hexagon\":case \"diamond\":case \"pentagon\":case \"circle\":o=Sn(n,i.p,t.size);break;case \"rounded-rect\":case \"blob\":o=Sn(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 qo(i,e){return nt(e,i.biotype).size}function he(i,e){return nt(e,i.biotype)}var es=/[&\"'<>]/,ts=/[&<>]/;function ns(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 ts.test(i)?i.replace(/&/g,\"&amp;\").replace(/</g,\"&lt;\").replace(/>/g,\"&gt;\"):i}function Ae(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}=\"${Ae(r)}\"`:n+=` ${o}=\"${ns(r)}\"`;}}return t===void 0?`${n}/>`:typeof t==\"string\"?`${n}>${t}</${i}>`:`${n}>${t.join(\"\")}</${i}>`}var os=\"http://www.w3.org/2000/svg\",Cn=.525,Ln=.8,Bn=1.125,is=\".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;}\",rs=[[\"A\",\"T\"],[\"A\",\"U\"],[\"G\",\"C\"]];function Rt(i,e={}){let t=e.theme??H,n=e.width??400,o=e.height??100,r=e.padding??16,s=e.backColor??t.background,a=e.showIds??false,l=e.showAnnotations??true,d=e.fontSize??t.fontSize,c=e.selectedAtomIds??new Set,u=e.highlightedAtomIds??new Set;e.documentImpl??(typeof globalThis<\"u\"&&typeof globalThis.document<\"u\"?globalThis.document:void 0);let p=e.fixedModelBbox??Rn(i,t),h=ss(p,n,o,r,e.maxScale??1),f=h.x-p.x*h.scale,y=h.y-p.y*h.scale,w=In(i,t,u),_=Pn(i,t,c),M=as(i,t),k=ps(i,t,d,a,e.bondLength??t.bondLength),x=l?bs(i,t,d):\"\",T=`translate(${Ae(f)} ${Ae(y)}) scale(${Ae(h.scale)})`,E=R(\"g\",{class:\"hw-content\",transform:T},[M,k,x,w,_].join(\"\")),C=R(\"defs\",void 0,`<style>${is}</style>`),P=R(\"rect\",{class:\"hw-bg\",x:0,y:0,width:n,height:o,fill:s});return {svg:R(\"svg\",{xmlns:os,viewBox:`0 0 ${Ae(n)} ${Ae(o)}`,width:n,height:o,\"data-hw-theme\":t.name},[C,P,E].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 Rn(i,e=H){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=Et(t,pe(i.atoms[n],e));return t}function ss(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 c=i.width>0?r/i.width:Number.POSITIVE_INFINITY,u=i.height>0?s/i.height:Number.POSITIVE_INFINITY;a=Math.min(c,u,o),(!Number.isFinite(a)||a<=0)&&(a=1);}let l=i.width*a,d=i.height*a;return {x:(e-l)/2,y:(t-d)/2,width:l,height:d,scale:a}}var Bt=3;function In(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+Bt)/2,a=Ie(o,e,s);n.push(R(\"path\",{d:a,class:\"hw-highlight\",fill:\"none\",stroke:e.highlightColor,\"stroke-width\":Bt,\"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 Pn(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+Bt)/2,a=Ie(o,e,s);n.push(R(\"path\",{d:a,class:\"hw-selection\",fill:\"none\",stroke:e.selectionColor,\"stroke-width\":Bt,\"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 as(i,e){let t=[];for(let n of i.bonds)t.push(ls(n,e));return R(\"g\",{class:\"hw-layer hw-bonds\"},t.join(\"\"))}function ls(i,e){let t=i.a1.p,n=i.a2.p,o=ds(i,e),r=cs(i),s=us(),l={d:Uo(t,n),class:\"hw-bond__stroke\",fill:\"none\",stroke:o,\"stroke-width\":s};r!==void 0&&(l[\"stroke-dasharray\"]=r);let d=[R(\"path\",l)];return i.kind===\"hbond\"&&d.push(R(\"path\",{d:zo(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}`},d.join(\"\"))}function ds(i,e){switch(i.kind){case \"backbone\":case \"branch\":return e.defaultStroke;case \"cross-polymer\":return e.crossPolymerBondColor;case \"hbond\":return ms(i)?e.hbondColor:e.nonCanonicalHbondColor;case \"group\":return e.defaultStroke}}function cs(i){if(i.kind===\"hbond\")return \"4 3\"}function us(i){return Bn}function ms(i){if(i.a1.biotype!==b.BASE||i.a2.biotype!==b.BASE)return false;let e=Yo(i.a1),t=Yo(i.a2);for(let[n,o]of rs)if(e===n&&t===o||e===o&&t===n)return true;return false}function Yo(i){let e=i.monomer?.naturalAnalog,t=e!==void 0&&e!==\"\"?e:i.symbol;return t.length===0?\"\":t.charAt(0).toUpperCase()}function ps(i,e,t,n,o=e.bondLength){let r=[];for(let s of i.atoms)s.hidden||r.push(hs(s,e,t,n,o));return R(\"g\",{class:\"hw-layer hw-atoms\"},r.join(\"\"))}function hs(i,e,t,n,o=e.bondLength){let r=he(i,e),s=Ie(i,e),a=$(i.monomer,i.biotype,e.colorTheme),l=a.background,d=a.text,c=i.symbol===\"*\"?\"3 3\":void 0,u={d:s,class:\"hw-atom__shape\",fill:l,stroke:l,\"stroke-width\":r.strokeWidth,\"stroke-linejoin\":\"round\",\"stroke-linecap\":\"round\"};c!==void 0&&(u[\"stroke-dasharray\"]=c);let m=[R(\"path\",u)],p=i.monomer?.symbol??i.symbol;if(p!==\"\"){let f=p.length<=1?1:Math.min(1,2/p.length),y=t*f;m.push(R(\"text\",{class:\"hw-atom__label\",x:i.p.x,y:i.p.y+y*.35,\"text-anchor\":\"middle\",\"font-size\":y,\"font-family\":e.fontFamily,fill:d},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:d},de(i.bio.ambiguity))),n){let f=o*Cn;m.push(R(\"text\",{class:\"hw-atom__id\",x:i.p.x-f,y:i.p.y-f,\"font-size\":t*Ln,\"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=fs(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 fs(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 bs(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],l=r.length>=2?r[1]:null,d=r.length>=2?r[r.length-2]:null,c=e.fontSize*1.4,u=Xo(s.p,l?.p??null,c),m=Xo(a.p,d?.p??null,c),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:u.x,y:u.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 Xo(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 It(i,e,t,n={}){let o=n.theme??H,r=n.padding??16,s=gs(e,o),a=_s(s,t.width,t.height,r,n.maxScale??1),l=t.x+a.x,d=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(l,d),i.scale(a.scale,a.scale),i.translate(-s.x,-s.y),vs(i,e,o),xs(i,e,o,n.fontSize??o.fontSize,n.showIds??false,n.bondLength??o.bondLength),n.showAnnotations!==false&&ws(i,e,o,n.fontSize??o.fontSize),i.restore(),{bbox:{x:s.x,y:s.y,width:s.width,height:s.height},drawBox:{x:l,y:d,width:a.width,height:a.height}}}async function ei(i,e={}){let t=ys();if(t===null&&e.canvas===void 0)throw new Error(\"renderToPng: OffscreenCanvas is not available in this environment\");let n=e.theme??H,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))),l=a.getContext(\"2d\");if(l===null)throw new Error(\"renderToPng: failed to acquire 2D context\");l.save(),l.scale(s,s),It(l,i,{x:0,y:0,width:o,height:r},{...e,backColor:e.backColor??n.background}),l.restore();let d=a;if(typeof d.convertToBlob!=\"function\")throw new Error(\"renderToPng: canvas.convertToBlob is not available\");let u=await(await d.convertToBlob({type:\"image/png\"})).arrayBuffer();return new Uint8Array(u)}function ys(){let i=globalThis;return typeof i.OffscreenCanvas==\"function\"?i.OffscreenCanvas:null}function gs(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=Et(t,pe(i.atoms[n],e));return t}function _s(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 c=i.width>0?r/i.width:Number.POSITIVE_INFINITY,u=i.height>0?s/i.height:Number.POSITIVE_INFINITY;a=Math.min(c,u,o),(!Number.isFinite(a)||a<=0)&&(a=1);}let l=i.width*a,d=i.height*a;return {x:(e-l)/2,y:(t-d)/2,width:l,height:d,scale:a}}function vs(i,e,t){for(let n of e.bonds)i.save(),i.strokeStyle=As(n,t),i.lineWidth=Ms(),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 ws(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],l=s[s.length-1],d=s.length>=2?s[1]:null,c=s.length>=2?s[s.length-2]:null,u=Jo(a.p,d?.p??null,o),m=Jo(l.p,c?.p??null,o),p=r.strandType!==void 0?`5'${r.strandType}`:\"5'\",h=r.strandType!==void 0?`3'${r.strandType}`:\"3'\";i.fillText(p,u.x,u.y),i.fillText(h,m.x,m.y);}i.restore();}function Jo(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),l=$(s.monomer,s.biotype,t.colorTheme);i.save(),i.fillStyle=l.background,i.strokeStyle=l.background,i.lineWidth=a.strokeWidth,i.lineJoin=\"round\",i.lineCap=\"round\",s.symbol===\"*\"?i.setLineDash([3,3]):i.setLineDash([]),ks(i,s,a.size,a.cornerRadius??0),i.fill(),i.stroke(),i.restore();let d=s.monomer?.symbol??s.symbol;if(d!==\"\"){let c=d.length<=1?1:Math.min(1,2/d.length),u=n*c;i.save(),i.fillStyle=l.text,i.font=`${u}px ${t.fontFamily}`,i.textAlign=\"center\",i.textBaseline=\"middle\",i.fillText(d,s.p.x,s.p.y),i.restore();}if(o){let c=r*Cn;i.save(),i.fillStyle=t.idColor,i.font=`${n*Ln}px ${t.fontFamily}`,i.textAlign=\"right\",i.textBaseline=\"bottom\",i.fillText(String(s.bio.continuousId),s.p.x-c,s.p.y-c),i.restore();}}}function ks(i,e,t,n){let o=e.p,r=e.symbol===\"*\"?\"circle\":Lt(e.biotype);switch(i.beginPath(),r){case \"hexagon\":Zo(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\":Zo(i,o,5,t,-90);break;case \"rounded-rect\":case \"blob\":{let s=t/2,a=Math.max(0,Math.min(n,s)),l=o.x-s,d=o.y-s,c=s*2,u=s*2;i.moveTo(l+a,d),i.lineTo(l+c-a,d),i.quadraticCurveTo(l+c,d,l+c,d+a),i.lineTo(l+c,d+u-a),i.quadraticCurveTo(l+c,d+u,l+c-a,d+u),i.lineTo(l+a,d+u),i.quadraticCurveTo(l,d+u,l,d+u-a),i.lineTo(l,d+a),i.quadraticCurveTo(l,d,l+a,d),i.closePath();break}case \"circle\":i.ellipse(o.x,o.y,t,t,0,0,Math.PI*2);break}}function Zo(i,e,t,n,o){let r=360/t;for(let s=0;s<t;s++){let a=(o+s*r)*Math.PI/180,l=e.x+n*Math.cos(a),d=e.y+n*Math.sin(a);s===0?i.moveTo(l,d):i.lineTo(l,d);}i.closePath();}function As(i,e){switch(i.kind){case \"backbone\":case \"branch\":return e.defaultStroke;case \"cross-polymer\":return e.crossPolymerBondColor;case \"hbond\":return Ss(i)?e.hbondColor:e.nonCanonicalHbondColor;case \"group\":return e.defaultStroke}}function Ms(i){return Bn}var Ts=[[\"A\",\"T\"],[\"A\",\"U\"],[\"G\",\"C\"]];function Ss(i){if(i.a1.biotype!==b.BASE||i.a2.biotype!==b.BASE)return false;let e=Qo(i.a1),t=Qo(i.a2);for(let[n,o]of Ts)if(e===n&&t===o||e===o&&t===n)return true;return false}function Qo(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 l=t.get(s);l===void 0&&(l=[],t.set(s,l)),l.push(o);}for(let o of i.atoms)ti(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(l=>l.target)),a=new Map;for(let l of i.atoms){if(!s.has(l.bio.chainId))continue;let d=new Map;ti(d,l,t.get(l.id)??[]);for(let[c,u]of d)a.set(c,(a.get(c)??0)+u*(r-1));}for(let[l,d]of a)e.set(l,(e.get(l)??0)+d);}for(let[o,r]of [...e])r===0&&e.delete(o);let n=Ls(e);return {elements:e,mw:n}}var Es={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},Cs={C:4,N:3,O:2,S:2,P:3,F:1,Cl:1,Br:1,I:1,H:1};function Ls(i){let e=0;for(let[t,n]of i){let o=Es[t];o!==void 0&&(e+=o*n);}return Math.round(e*1e3)/1e3}function ti(i,e,t){if(e.monomer===null)return;let n=Rs(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=Bs(e.monomer,r);if(s===void 0)continue;let a=oi(s);for(let[l,d]of a)i.set(l,(i.get(l)??0)-d);}}function Bs(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 oi(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 ni=new WeakMap;function Rs(i){let e=ni.get(i);if(e!==void 0)return e;let t=Is(i);return ni.set(i,t),t}function Is(i){let e=new Map;if(i.molfile===void 0||i.molfile===\"\")return {elements:e};let t=Ps(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=Cs[s];if(a===void 0)continue;let l=o[r]??0,d=a-l;d>0&&e.set(\"H\",(e.get(\"H\")??0)+d);}for(let r of i.rgroups){let s=r.capGroupName;if(s===void 0)continue;let a=oi(s);for(let[l,d]of a)e.set(l,(e.get(l)??0)+d);}return {elements:e}}function Ps(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 l=e[4+a];if(l===void 0)return null;let d=l.slice(31,34).trim();r.push(d);}let s=new Array(n).fill(0);for(let a=0;a<o;a++){let l=e[4+n+a];if(l===void 0)return null;let d=parseInt(l.slice(0,3),10),c=parseInt(l.slice(3,6),10),u=parseInt(l.slice(6,9),10);if(!Number.isFinite(d)||!Number.isFinite(c)||!Number.isFinite(u))continue;let m=u===4?1:u;d>=1&&d<=n&&(s[d-1]=(s[d-1]??0)+m),c>=1&&c<=n&&(s[c-1]=(s[c-1]??0)+m);}return {atoms:r,bondOrders:s}}function Pe(i){return fe(i).mw}var Hn={W:5.5,Y:1.49,C:.0625},Hs={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},ii={A:15.4,C:7.4,G:11.7,U:10,T:8.8};function He(i){let e=0;for(let t of i.chains)t.polymerType===\"PEPTIDE\"?e+=$s(t.backboneAtoms):t.polymerType===\"RNA\"&&(e+=Ds(t.backboneAtoms));return Math.round(e*1e4)/1e4}function $s(i){let e=0,t=0,n=0;for(let o of i){let r=ri(o);r===\"W\"?e++:r===\"Y\"?t++:r===\"C\"&&n++;}return Hn.W*e+Hn.Y*t+Hn.C*n}function Ds(i){let e=[];for(let o of i)if(o.branchAtom!==void 0&&o.branchAtom.biotype===b.BASE){let r=ri(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 ii[o]??0}let t=0;for(let o=0;o<e.length-1;o++){let r=e[o],s=e[o+1],a=Hs[r+s];a!==void 0&&(t+=a);}let n=0;for(let o=1;o<e.length-1;o++){let r=e[o];n+=ii[r]??0;}return 2*t-n}function ri(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 Pt(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(Os(t,n));for(let r of i.atoms)e.push(Ns(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(Fs(s,a));}return e.push(\"M END\"),e.join(`\n`)+`\n`}function Os(i,e){return $e(i)+$e(e)+\" 0 0 0 0 0 0 0 0999 V2000\"}function Ns(i){let e=Gs(i);return $n(i.p.x)+$n(i.p.y)+$n(0)+\" \"+Vs(e,3)+\" 0 0 0 0 0 0 0 0 0 0 0 0\"}function Fs(i,e){return $e(i)+$e(e)+$e(1)+$e(0)}function Gs(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 $e(i){let e=String(i);return e.length>=3?e:\" \".repeat(3-e.length)+e}function Vs(i,e){return i.length>=e?i:i+\" \".repeat(e-i.length)}function $n(i){let e=i.toFixed(4);return e.length>=10?e.slice(0,10):\" \".repeat(10-e.length)+e}var Us=new Map;function zs(i){return `${i.mode}|${i.resolveMonomers?1:0}|${i.helm}`}function Ks(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 Ws=256,Dn=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??H,this.logger=e.logger??new Se,this.options=Object.freeze({...e});let t=e.cacheSize??Ws;this._parseCache=new Te({max:t}),this._layoutCache=new Te({max:t}),this._renderCache=new Te({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=zs({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},l=et(e,this.monomerLib,a),d={mol:l.mol,diagnostics:Object.freeze([...l.diagnostics])};return this._parseCache.set(r,d),d}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 Re(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=yn(n,this.monomerLib,r);return [...o,...s]}canonicalize(e){this._ensureLive(),e=this._normalizeHelm(e);let{mol:t}=this.parse(e,{mode:\"lenient\"}),n=fn(t);return Re(n,{canonicalize:true,version:\"V2.0\"})}removeGaps(e){return this._ensureLive(),bn(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:l}=Rt(a,n);return this._renderCache.set(o,l),l}renderMol(e,t){this._ensureLive();let n=this._resolveRenderOptions(t),{svg:o}=Rt(e,n);return o}renderMolResult(e,t){this._ensureLive();let n=this._resolveRenderOptions(t);return Rt(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 ei(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:l,drawBox:d}=It(e,a,n,r);return {mol:a,bbox:l,drawBox:d}}renderMolToCanvas(e,t,n,o){this._ensureLive();let r=this._resolveRenderOptions(o),{bbox:s,drawBox:a}=It(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 Pe(t)}getExtinctionCoefficient(e){this._ensureLive();let{mol:t}=this.parse(this._normalizeHelm(e),{mode:\"lenient\"});return He(t)}getMolfile(e){this._ensureLive();let{mol:t}=this.parse(this._normalizeHelm(e),{mode:\"lenient\"});return Pt(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??Us}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,l=t.padding??-1,d=t.bondLength??-1,c=t.backColor??\"\",u=t.showIds===true?1:0,m=t.showAnnotations===false?0:1,p=t.maxScale??1;return `${r}|${o}|${s}x${a}|p${l}|b${d}|bg${c}|i${u}a${m}|s${p}|${e}`}_layout(e,t){let n=Ks(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?ne(e,{bondLength:t}):ne(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);}},si=new Q(new Set,new Set),G={empty(){return si},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 si;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 ai(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(ai(i,e)),o=[];for(let r=1;r<=t;r++)n.has(r)||o.push(r);return o}function js(i,e){return W(i,e).length>0}function Ht(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 qs(i){switch(i){case b.AA:return v.PEPTIDE;case b.SUGAR:case b.BASE:case b.LINKER:case b.NUCLEOTIDE:return v.RNA;case b.CHEM:return v.CHEM;case b.BLOB:return v.BLOB}}function Ys(i){switch(i){case v.PEPTIDE:return \"PEPTIDE\";case v.RNA:return \"RNA\";case v.CHEM:return \"CHEM\";case v.BLOB:return \"BLOB\";case v.G:return \"G\"}}function Xs(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 $t(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 O=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 _e;let t=Xs(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=qs(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 l=Math.max(0,Math.min(s-1,r.backboneAtomIds.length));return r.backboneAtomIds.splice(l,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&&$t(r.r1,e.r1)&&$t(r.r2,e.r2),a=r.a1Id===e.a2&&r.a2Id===e.a1&&$t(r.r1,e.r2)&&$t(r.r2,e.r1);if(s||a)throw new Error(`Transaction.addBond: duplicate bond ${e.a1}:${li(e.r1)}-${e.a2}:${li(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 l of this._atomOrder){let d=this._atoms.get(l);if(d===void 0)continue;let c={id:d.id,p:{x:d.p.x,y:d.p.y},biotype:d.biotype,symbol:d.symbol,monomer:d.monomer,bio:{...d.bio},hidden:d.hidden,selected:d.selected,highlighted:d.highlighted,...d.tag!==void 0?{tag:d.tag}:{},...d.inlineSource!==void 0?{inlineSource:d.inlineSource}:{}};e.set(l,c);}for(let l of this._atomOrder){let d=this._atoms.get(l);if(d===void 0||d.branchAtomId===void 0)continue;let c=e.get(l),u=e.get(d.branchAtomId);c===void 0||u===void 0||(c.branchAtom=u);}let t=new Map;for(let l of this._bondOrder){let d=this._bonds.get(l);if(d===void 0)continue;let c=e.get(d.a1Id),u=e.get(d.a2Id);if(c===void 0||u===void 0)continue;let m={id:d.id,a1:c,a2:u,kind:d.kind,r1:d.r1,r2:d.r2,...d.ratio!==void 0?{ratio:{...d.ratio}}:{},...d.tag!==void 0?{tag:d.tag}:{}};t.set(l,m);}let n=[];for(let l of this._chainOrder){let d=this._chains.get(l);if(d===void 0||d.backboneAtomIds.length===0&&d.bondIds.length===0)continue;let c=[];for(let m of d.backboneAtomIds){let p=e.get(m);p!==void 0&&c.push(p);}let u=[];for(let m of d.bondIds){let p=t.get(m);p!==void 0&&u.push(p);}n.push({id:d.id,polymerType:d.polymerType,backboneAtoms:c,bonds:u,...d.annotation!==void 0?{annotation:d.annotation}:{}});}let o=this._atomOrder.map(l=>e.get(l)).filter(l=>l!==void 0),r=this._bondOrder.map(l=>t.get(l)).filter(l=>l!==void 0),s={atoms:o,bonds:r,chains:n,groups:[...this._groups],annotations:this._annotations};this._topologyDirty&&(s=Js(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=Ys(e),n=1;for(;this._chains.has(`${t}${n}`);)n+=1;return `${t}${n}`}};function li(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 Js(i){let e=Ee(i),t=new Map;for(let a of i.atoms){let l=e.get(a.id);if(l===void 0||l===a.bio.continuousId){t.set(a.id,a);continue}t.set(a.id,{...a,bio:{...a.bio,continuousId:l}});}for(let a of i.atoms){if(a.branchAtom===void 0)continue;let l=t.get(a.id),d=t.get(a.branchAtom.id);l===void 0||d===void 0||(l.branchAtom=d);}let n=i.bonds.map(a=>{let l=t.get(a.a1.id),d=t.get(a.a2.id);return l===void 0||d===void 0||l===a.a1&&d===a.a2?a:{...a,a1:l,a2:d}}),o=new Map;for(let a of n)o.set(a.id,a);let r=i.chains.map(a=>{let l=[];for(let c of a.backboneAtoms)l.push(t.get(c.id)??c);let d=[];for(let c of a.bonds)d.push(o.get(c.id)??c);return {id:a.id,polymerType:a.polymerType,backboneAtoms:l,bonds:d,...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:qo(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(!Dt(e,r.bbox))continue;let s=e.x-r.atom.p.x,a=e.y-r.atom.p.y,l=Math.sqrt(s*s+a*a);l>r.hitRadius||(t===null||l<t.d?(n=t,t={entry:r,d:l}):(n===null||l<n.d)&&(n={entry:r,d:l}));}if(t!==null)return {atom:t.entry.atom};let o=null;for(let r of this.bonds){let s=Zs(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)Dt(o.atom.p,e)&&t.push(o.atom);let n=[];for(let o of this.bonds)Dt(o.a,e)&&Dt(o.b,e)&&n.push(o.bond);return {atoms:t,bonds:n}}atomCount(){return this.atoms.length}bondCount(){return this.bonds.length}};function Dt(i,e){return i.x>=e.x&&i.x<=e.x+e.width&&i.y>=e.y&&i.y<=e.y+e.height}function Zs(i,e,t){let n=t.x-e.x,o=t.y-e.y,r=n*n+o*o;if(r===0){let u=i.x-e.x,m=i.y-e.y;return Math.sqrt(u*u+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,l=e.y+s*o,d=i.x-a,c=i.y-l;return Math.sqrt(d*d+c*c)}var De=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 Oe=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 di(i,e={}){let t=e.theme??H,n=e.selectedAtomIds??new Set,o=e.highlightedAtomIds??new Set;return {highlightLayer:In(i,t,o),selectionLayer:Pn(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 g(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 ci(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 ui(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 oe(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=g(i,\"div\",{class:t,[n]:e});return o.style.display=\"none\",i.body.appendChild(o),o}function Me(i,e,t){for(;e.firstChild!==null;)e.removeChild(e.firstChild);if(e.appendChild(g(i,\"div\",{class:\"hw-tooltip__symbol\"},[t.symbol])),t.name!==void 0&&t.name!==\"\"&&t.name!==t.symbol&&e.appendChild(g(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=g(i,\"div\",n);o.innerHTML=t.rdkitSvg,e.appendChild(o);}t.hint!==void 0&&t.hint!==\"\"&&e.appendChild(g(i,\"div\",{class:\"hw-tooltip__hint\"},[t.hint]));}function mi(i,e,t){for(;e.firstChild!==null;)e.removeChild(e.firstChild);e.appendChild(g(i,\"div\",{class:\"hw-tooltip__symbol\"},[t.title]));let n=g(i,\"div\",{class:\"hw-tooltip__triplet\"});for(let o of t.parts){let r=g(i,\"div\",{class:\"hw-tooltip__triplet-part\"});if(r.appendChild(g(i,\"div\",{class:\"hw-tooltip__triplet-role\"},[`${o.role}: ${o.symbol}`])),o.name!==void 0&&o.name!==\"\"&&o.name!==o.symbol&&r.appendChild(g(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=g(i,\"div\",s);a.innerHTML=o.rdkitSvg,r.appendChild(a);}n.appendChild(r);}e.appendChild(n),t.hint!==void 0&&t.hint!==\"\"&&e.appendChild(g(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 V(i){i!==null&&(i.style.display=\"none\");}function Ot(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\")&&V(o);}}var Ft=class Ft{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,ci(e);let o=this._doc.createElement(\"div\");o.setAttribute(\"class\",\"hw-editor-view\"),e.appendChild(o),this._tooltip=oe(this._doc,\"atom-tooltip\",\"hw-atom-tooltip\"),this._bondTooltip=oe(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),V(this._tooltip),V(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=Rn(n,t));let o=e.renderMol(n,{width:this._width,height:this._height,theme:t,fixedModelBbox:this._pinnedBbox});this._svgRoot=ui(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=di(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,l=e.bio.chainId===\"\"?\"?\":e.bio.chainId,d=s!==\"\"&&s!==r?`${s} @ ${l}:${a}`:`${r} @ ${l}:${a}`,c=this._renderRdkitTooltipSvg(e);Me(this._doc,o,{symbol:r,name:d,rdkitSvg:c,rdkitTestid:\"atom-tooltip-rdkit-svg\"});let u=s!==\"\"&&s!==r?`${r} \\u2014 ${s} @ ${l}:${a}`:`${r} @ ${l}:${a}`,m=this._doc.createElement(\"div\");m.setAttribute(\"class\",\"hw-atom-tooltip__text\"),m.style.display=\"none\",m.appendChild(this._doc.createTextNode(u)),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>=Ft._RDKIT_CACHE_LIMIT){let l=this._rdkitSvgCache.keys().next().value;l!==void 0&&this._rdkitSvgCache.delete(l);}return this._rdkitSvgCache.set(s,a),a}_hideTooltip(){V(this._tooltip);}_showBondTooltip(e,t,n){let o=this._bondTooltip;if(o===null)return;let r=pi(e.r1),s=pi(e.r2),a=`${e.a1.symbol}@${e.a1.bio.chainId}:${e.a1.bio.positionInChain}`,l=`${e.a2.symbol}@${e.a2.bio.chainId}:${e.a2.bio.positionInChain}`;Me(this._doc,o,{symbol:`${r}-${s} (${e.kind})`,name:`${a} \\u2194 ${l}`}),Y(o,t,n);}_hideBondTooltip(){V(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);}};Ft._RDKIT_CACHE_LIMIT=256;var Nt=Ft;function pi(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 ie=class ie{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=g(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=g(n,\"div\",s),l=g(n,\"div\",{class:\"hw-modal__header\"},[t.title]),d=g(n,\"div\",{class:\"hw-modal__body\"});a.appendChild(l),a.appendChild(d),r.appendChild(a);let c=u=>{u.stopPropagation();};for(let u of [\"mousedown\",\"mousemove\",\"mouseup\",\"mouseover\",\"mouseenter\",\"mouseleave\",\"wheel\",\"contextmenu\",\"dblclick\",\"keydown\",\"keyup\",\"keypress\"])r.addEventListener(u,c);a.addEventListener(\"keydown\",u=>{let m=u;if(m.key!==\"Enter\"||m.target?.tagName===\"TEXTAREA\")return;let p=this._primaryAction;p!==null&&(m.preventDefault?.(),m.stopImmediatePropagation?.(),p());}),r.addEventListener(\"click\",u=>{if(u.target===r){this.close();return}u.stopPropagation();}),this.root=r,this.body=d;}static anyOpen(){return ie._openStack.length>0}static closeTopmost(){let e=ie._openStack[ie._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),ie._openStack.includes(this)||ie._openStack.push(this),Ot(this._doc);}close(){let e=ie._openStack.indexOf(this);e>=0&&ie._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}};ie._openStack=[];var X=ie;function Ne(i,e,t,n){let o=`hw-input-${Math.random().toString(36).slice(2,9)}`,r=g(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:g(i,\"div\",{class:\"hw-modal__row\"},[r,s]),input:s}}function Fe(i,e,t,n,o){let r=`hw-sel-${Math.random().toString(36).slice(2,9)}`,s=g(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 d of t){let c=i.createElement(\"option\");c.setAttribute(\"value\",d.value),d.value===n&&c.setAttribute(\"selected\",\"\"),c.appendChild(i.createTextNode(d.label)),a.appendChild(c);}return {row:g(i,\"div\",{class:\"hw-modal__row\"},[s,a]),select:a}}function Ge(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:g(i,\"div\",{class:\"hw-modal__actions\"},[t,n]),ok:t,cancel:n}}var Ve=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=fi(e,n?.freeR1,n?.currentR1,this._editor),a=fi(t,n?.freeR2,n?.currentR2,this._editor),l=g(this._doc,\"div\",{class:\"hw-modal__info\"},[`${e.symbol} (${e.bio.chainId})`]),d=n?.currentR1!==void 0?String(n.currentR1):s[0]?.value??\"1\",c=n?.currentR2!==void 0?String(n.currentR2):a[0]?.value??\"1\",u=Fe(this._doc,\"R-group on side A\",s,d,\"choose-r-r1\"),m=g(this._doc,\"div\",{class:\"hw-modal__info\"},[`${t.symbol} (${t.bio.chainId})`]),p=Fe(this._doc,\"R-group on side B\",a,c,\"choose-r-r2\"),h=Ge(this._doc,\"choose-r\"),f=[];return s.length===0&&f.push(g(this._doc,\"div\",{class:\"hw-modal__info hw-modal__note-fully-booked\"},[`All R-groups on ${e.symbol} are in use.`])),a.length===0&&f.push(g(this._doc,\"div\",{class:\"hw-modal__info hw-modal__note-fully-booked\"},[`All R-groups on ${t.symbol} are in use.`])),new Promise(y=>{let w=false,_=x=>{w||(w=true,y(x));},M=x=>{_(x),this.close();},k=()=>M({r1:hi(u.select),r2:hi(p.select)});h.ok.addEventListener(\"click\",k),h.cancel.addEventListener(\"click\",()=>M(null)),r.setPrimaryAction(k),r.body.appendChild(l),r.body.appendChild(u.row),r.body.appendChild(m),r.body.appendChild(p.row);for(let x of f)r.body.appendChild(x);r.body.appendChild(h.row),r.open(()=>_(null));})}get isOpen(){return this._modal!==null&&this._modal.isOpen}close(){this._modal!==null&&(this._modal.close(),this._modal=null);}};function hi(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 fi(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 l=1;l<=o.length;l++)r.add(l);t!==void 0&&t>=1&&t<=o.length&&r.add(t);let s=[],a=Array.from(r).sort((l,d)=>l-d);for(let l of a){let d=o[l-1];if(d===void 0)continue;let c=d.capGroupName!==void 0&&d.capGroupName!==\"\"?` (${d.capGroupName})`:\"\";s.push({value:String(l),label:`${d.label}${c}`});}return s}var bi=\"next-add-cursor\",ot=28,Gt=ot*2;function yi(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)===bi)return o}let t=i.createElement(\"div\");return t.className=\"hw-next-add-cursor\",t.setAttribute(e,bi),t.style.display=\"none\",i.body.appendChild(t),t}function gi(i,e,t,n,o,r,s){let l=Ie({p:{x:0,y:0},biotype:t,symbol:e},o),c=$(n,t,o.colorTheme).background,u=wt(c),m=e.length,p=m<=1?1:Math.min(1,2/m),h=o.fontSize*p,f=`<svg xmlns=\"http://www.w3.org/2000/svg\" viewBox=\"${-ot} ${-ot} ${Gt} ${Gt}\" width=\"${Gt}\" height=\"${Gt}\" class=\"hw-next-add-cursor__svg\" aria-hidden=\"true\"><path d=\"${l}\" fill=\"${c}\" stroke=\"${c}\" 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=\"${u}\">${Qs(e)}</text></svg>`;i.innerHTML=f;let y=i.style;y.left=`${r-ot}px`,y.top=`${s-ot}px`,y.display=\"block\";}function it(i){i!==null&&(i.style.display=\"none\");}function Qs(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 Vt=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\")&&it(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),it(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,l=s.y-this._panStart.origin.y;this._editor.panTo({x:this._panStart.initialOffset.x+a,y:this._panStart.initialOffset.y+l}),this._panMoved=true;return}if(this._atomDragState!==null){let s=this._toModel(e),a=s.x-this._atomDragState.pointerDownModel.x,l=s.y-this._atomDragState.pointerDownModel.y,d=[];for(let c of this._atomDragState.atomIds){let u=this._atomDragState.initialPositions.get(c);u!==void 0&&d.push({atomId:c,p:{x:u.x+a,y:u.y+l}});}this._editor.moveAtoms(d),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=ki(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=xi(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=xi(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(),d=a.atoms.has(n.atom.id)?Array.from(a.atoms):[n.atom.id],c=this._editor.getMol(),u=new Map;for(let m of d){let p=c.atoms.find(h=>h.id===m);p!==void 0&&u.set(m,{x:p.p.x,y:p.p.y});}this._atomDragState={atomIds:d,pointerDownModel:{x:t.x,y:t.y},initialPositions:u},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,l=this._bondDragMoved;this._bondStart=null;let d=this._toModel(e),u=this._tester.test(d)?.atom;if(l&&u!==void 0&&u.id!==a.id){if(this._editor.fire(\"bond:preview-end\",{start:a}),this._editor.getMode()===\"hbond\"){try{this._editor.addHydrogenBond(a,u);}catch{this._editor.fire(\"bond:cancel\",{start:a});}return}let m=a.bio.chainId===u.bio.chainId&&wi(a,u,this._editor.getMol())?\"backbone\":\"cross-polymer\",p=_i(a,u,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,u,p.r1,p.r2,p.kind);}catch{this._editor.fire(\"bond:cancel\",{start:a});}return}this._openChooseR(a,u,m,p.freeR1,p.freeR2);return}if(l){let m=this._addsEnabled()?this._editor.getNextAddSymbol():null;if(m!==null){let p;try{p=this._editor.addAtom(d,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(M=>M.id===a.id);if(h===void 0){this._editor.fire(\"bond:cancel\",{start:a}),this._editor.fire(\"bond:preview-end\",{start:a});return}let f=h.bio.chainId===p.bio.chainId&&wi(h,p,this._editor.getMol())?\"backbone\":\"cross-polymer\",y=W(h,this._editor.getMol().bonds),w=W(p,this._editor.getMol().bonds);if(y.includes(2)&&w.includes(1)){try{this._editor.addBond(h,p,2,1,f);}catch{this._editor.fire(\"bond:cancel\",{start:a});}this._editor.fire(\"bond:preview-end\",{start:a});return}let _=_i(h,p,this._editor.getMol().bonds,f);if(_.mode===\"fail\"){this._editor.fire(\"bond:cancel\",{start:a}),this._editor.fire(\"editor:status\",{message:_.reason,severity:\"error\",durationMs:3e3}),this._editor.fire(\"bond:preview-end\",{start:a});return}if(_.mode===\"auto\"){try{this._editor.addBond(h,p,_.r1,_.r2,_.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,f,_.freeR1,_.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=ki(this._dragOrigin,t);this._dragOrigin=null;let o=this._tester.testRect(n),r=G.fromAtomsAndBonds(o.atoms.map(a=>a.id),o.bonds.map(a=>a.id)),s=G.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,it(this._nextAddCursorEl);}_openChooseR(e,t,n,o,r){this._chooseRDialog===null&&(this._chooseRDialog=new Ve(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&&it(this._nextAddCursorEl);return}let a=this._host.ownerDocument;if(a===null)return;this._nextAddCursorEl===null&&(this._nextAddCursorEl=yi(a));let l=this._editor.getService().monomerLib,d=null;for(let c of l.getPolymerTypes()){let u=l.getMonomer(c,t.symbol);if(u!==null){d=u;break}}gi(this._nextAddCursorEl,t.symbol,t.biotype,d,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,l=this._editor.getViewport();this._editor.panTo({x:l.offset.x-s,y:l.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=vi(n,e.clientX,e.clientY);if(r!==null)return r;let s=this._host.getBoundingClientRect(),a=e.clientX-s.left,l=e.clientY-s.top,d=ta(n.getAttribute(\"transform\")??\"\");return d!==null?{x:(a-d.tx)/(d.scale===0?1:d.scale),y:(l-d.ty)/(d.scale===0?1:d.scale)}:{x:a,y:l}}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=vi(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,l=ea(t.getAttribute(\"viewBox\"));return l!==null&&r.width>0&&r.height>0?{x:s*(l.w/r.width),y:a*(l.h/r.height)}:{x:s,y:a}}let n=this._host.getBoundingClientRect();return {x:e.clientX-n.left,y:e.clientY-n.top}}};function _i(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 l=s[0],d=a[0];return {mode:\"auto\",r1:l,r2:d,kind:n}}return {mode:\"choose\",freeR1:s,freeR2:a}}function vi(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 l=o;typeof l.inverse==\"function\"&&(r=l.inverse());}catch{return null}if(r===null)return null;let s=n.ownerSVGElement;if(s!=null&&typeof s.createSVGPoint==\"function\"){let l=s.createSVGPoint();l.x=e,l.y=t;let d=l.matrixTransform(r);return {x:d.x,y:d.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 ta(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],l=(r[2]??\"\").split(/[,\\s]+/).map(d=>Number(d)).filter(d=>Number.isFinite(d));if(a===\"translate\"){let d=l[0]??0,c=l[1]??0;e=e+n*d,t=t+n*c;}else if(a===\"scale\"){let d=l[0]??1;n=n*d;}}return s?{tx:e,ty:t,scale:n}:null}function wi(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 xi(i){return {shift:i.shiftKey===true,alt:i.altKey===true,ctrl:i.ctrlKey===true,meta:i.metaKey===true}}function ki(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 Ut=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=na(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 na(i){return {shift:i.shiftKey===true,alt:i.altKey===true,ctrl:i.ctrlKey===true,meta:i.metaKey===true}}var oa=\"application/x-hwe-monomer\",zt=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(oa):\"\";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,l={symbol:n,biotype:o,clientX:e.clientX,clientY:e.clientY};a!==void 0&&(l.target=a),this._editor.fire(\"dnd:drop\",l),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=ia(n,e.clientX,e.clientY);if(r!==null)return r;let s=this._host.getBoundingClientRect(),a=e.clientX-s.left,l=e.clientY-s.top,d=ra(n.getAttribute(\"transform\")??\"\");return d!==null?{x:(a-d.tx)/(d.scale===0?1:d.scale),y:(l-d.ty)/(d.scale===0?1:d.scale)}:{x:a,y:l}}let o=this._host.getBoundingClientRect();return {x:e.clientX-o.left,y:e.clientY-o.top}}};function ia(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 l=o;typeof l.inverse==\"function\"&&(r=l.inverse());}catch{return null}if(r===null)return null;let s=n.ownerSVGElement;if(s!=null&&typeof s.createSVGPoint==\"function\"){let l=s.createSVGPoint();l.x=e,l.y=t;let d=l.matrixTransform(r);return {x:d.x,y:d.y}}let a=r;return {x:a.a*e+a.c*t+a.e,y:a.b*e+a.d*t+a.f}}function ra(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],l=(r[2]??\"\").split(/[,\\s]+/).map(d=>Number(d)).filter(d=>Number.isFinite(d));if(a===\"translate\"){let d=l[0]??0,c=l[1]??0;e=e+n*d,t=t+n*c;}else if(a===\"scale\"){let d=l[0]??1;n=n*d;}}return s?{tx:e,ty:t,scale:n}:null}var Ue=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=g(this._doc,\"div\",{class:\"hw-modal__info\"},[`Position ${e.bio.continuousId} in ${e.bio.chainId}`]),r=Ne(this._doc,\"Symbol\",e.symbol,\"atom-props-symbol\"),s=Ne(this._doc,\"Annotation\",e.bio.annotation??\"\",\"atom-props-annotation\"),a=Ge(this._doc,\"atom-props\"),l=()=>this._commit(r.input.value,s.input.value);a.ok.addEventListener(\"click\",l),a.cancel.addEventListener(\"click\",()=>this.close()),n.setPrimaryAction(l),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 O(this._editor.getMol()),l={};l.tag=t===\"\"?void 0:t,a.updateAtom(n.id,l);let{mol:d}=a.commit();this._editor.setMol(d);let c=d.atoms.find(u=>u.id===n.id);if(c!==void 0){let u={atom:c};n.bio.annotation!==void 0&&(u.oldAnnotation=n.bio.annotation),t!==\"\"&&(u.newAnnotation=t),this._editor.fire(\"monomer:annotate\",u);}}this.close();}};var ze=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=g(this._doc,\"div\",{class:\"hw-modal__info\"},[`Kind: ${e.kind}`]),r=this._buildAtomsPreviewRow(e),s=e.r1.kind===\"numeric\",a=e.r2.kind===\"numeric\",l=s&&a,c=this._editor.getMol().bonds,u=l?Ai(e.r1,e.a1,c):[],m=l?Ai(e.r2,e.a2,c):[],p=null,h=null;if(l){let w=String(e.r1.r),_=String(e.r2.r);p=Fe(this._doc,`R-group on ${e.a1.symbol} (${e.a1.bio.chainId}:${e.a1.bio.positionInChain})`,u,w,\"bond-props-r1\"),h=Fe(this._doc,`R-group on ${e.a2.symbol} (${e.a2.bio.chainId}:${e.a2.bio.positionInChain})`,m,_,\"bond-props-r2\");}let f=Ge(this._doc,\"bond-props\"),y=()=>{let w=p!==null?Number(Mi(p.select,e.r1.r)):null,_=h!==null?Number(Mi(h.select,e.r2.r)):null;this._commit(w,_);};f.ok.addEventListener(\"click\",y),f.cancel.addEventListener(\"click\",()=>this.close()),n.setPrimaryAction(y),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(f.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=g(this._doc,\"div\",{class:\"hw-bond-props__bond-arrow\"},[\"\\u2194\"]);return g(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=g(this._doc,\"div\",{class:\"hw-bond-props__atom-label\"},[r]),a={class:\"hw-bond-props__atom-rdkit\",\"data-testid\":`${n}-rdkit`},l=g(this._doc,\"div\",a),d=e.monomer?.smiles;if(t!==null&&d!==void 0&&d!==\"\"){let c=ye(t,d,220,140);c!==null&&c!==\"\"&&(l.innerHTML=c);}return g(this._doc,\"div\",{class:\"hw-bond-props__atom\",\"data-testid\":n},[s,l])}_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,l=n.a1,d=n.a2;this._editor.removeBond(n);try{this._editor.addBond(l,d,e,t,a);}catch(c){if(o!==null&&r!==null)try{this._editor.addBond(l,d,o,r,n.kind);}catch{}}}this.close();}};function Ai(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,l)=>a-l),s=[];for(let a of r){let l=n[a-1];if(l===void 0)continue;let d=l.capGroupName!==void 0&&l.capGroupName!==\"\"?` (${l.capGroupName})`:\"\";s.push({value:String(a),label:`${l.label}${d}`});}return s}function Mi(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 Ke=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=Ne(this._doc,\"Find\",\"\",\"find-replace-find\"),o=Ne(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 l=this._doc.createElement(\"button\");l.setAttribute(\"class\",\"hw-modal__cancel\"),l.setAttribute(\"type\",\"button\"),l.setAttribute(\"data-testid\",\"find-replace-close\"),l.appendChild(this._doc.createTextNode(\"Close\")),l.addEventListener(\"click\",()=>this.close());let d=g(this._doc,\"div\",{class:\"hw-modal__actions\"},[r,s,a,l]),c=g(this._doc,\"div\",{class:\"hw-modal__result\",\"data-testid\":\"find-replace-result\"},[\"0 matches\"]);this._result=c,t.setPrimaryAction(()=>this._findNext()),t.body.appendChild(n.row),t.body.appendChild(o.row),t.body.appendChild(d),t.body.appendChild(c),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),sa=.2,aa=8,rt=class{constructor(e,t){this._events=new De;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=G.empty(),this._highlights=ge,this._theme=t.service.theme??H,this._viewport={scale:1,offset:{x:0,y:0}},this._viewOnly=t.viewOnly??false,this._history=new Oe({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 Nt(this._host,this,t),this._viewOnly!==true&&(this._pointer=new Vt(this._host,this,{enableContextMenu:this._options.enableContextMenu??true})),this._options.enableKeyboard!==false&&(this._keyboard=new Ut(this._host,this,{enableKeyboard:true})),this._options.enableDragDrop!==false&&(this._dnd=new zt(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(G.toggle(this._selection,{kind:\"atom\",id:n.atom.id}));return}if(o.shift===true){this.setSelection(G.union(this._selection,G.fromAtoms([n.atom.id])));return}this.setSelection(G.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(d=>d.severity===\"error\").length>0&&this._events.fire(\"helm:parse-error\",{helm:e,diagnostics:r});for(let d of r)d.severity===\"error\"?this._events.fire(\"validation:error\",{diagnostic:d}):d.severity===\"warning\"&&this._events.fire(\"validation:warning\",{diagnostic:d});let a=o.mol;if(n){let d=this._service.canonicalize(e);a=this._service.parse(d,{mode:\"lenient\"}).mol;}let l=ne(a,this._options.bondLength!==void 0?{bondLength:this._options.bondLength}:void 0);return this._replaceMol(l,\"setHelm\",\"api\"),{mol:l,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(),G.equals(this._selection,e))return;let t=G.difference(e,this._selection),n=G.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(G.fromAtomsAndBonds(e,t));}clearSelection(){this._ensureLive(),!this._selection.isEmpty&&this.setSelection(G.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 O(this._mol),r=o.addAtom({p:e,biotype:t,symbol:n}),{mol:s}=o.commit(),a=xe(s,this._service.monomerLib,{mode:\"lenient\"}).mol;this._replaceMol(a,`addAtom:${n}`,\"api\");let l=J(a,r);if(l===void 0)throw new Error(\"HelmEditor.addAtom: lost atom after commit\");return this._events.fire(\"monomer:add\",{atom:l,source:\"api\"}),l}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 O(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 d=r??\"backbone\",c=this._maybeMergeForLinearExtend(e,t,n,o,d);if(c!==null)({id:s,mol:a}=c);else {let u=new O(this._mol);s=u.addBond({a1:e.id,a2:t.id,kind:r??\"backbone\",r1:{kind:\"numeric\",r:n},r2:{kind:\"numeric\",r:o}}),{mol:a}=u.commit();}}catch(d){let c=d instanceof I?d.message:this._friendlyBondError(d instanceof Error?d.message:String(d),e,t,n,o);throw this._events.fire(\"editor:status\",{message:`Could not add bond: ${c}`,severity:\"error\",durationMs:3e3}),d}this._replaceMol(a,\"addBond\",\"api\");let l=_t(a,s);if(l===void 0)throw new Error(\"HelmEditor.addBond: lost bond after commit\");return this._events.fire(\"bond:add\",{bond:l,source:\"api\"}),l}_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(l=>l.id===e.bio.chainId),a=this._mol.chains.find(l=>l.id===t.bio.chainId);if(s===void 0||a===void 0||s.polymerType!==a.polymerType)return null;if(n===2&&o===1){let l=s.backboneAtoms[s.backboneAtoms.length-1],d=a.backboneAtoms[0];if(l!==void 0&&d!==void 0&&l.id===e.id&&d.id===t.id)return this._mergeChains(s,a,r)}if(n===1&&o===2){let l=s.backboneAtoms[0],d=a.backboneAtoms[a.backboneAtoms.length-1];if(l!==void 0&&d!==void 0&&l.id===e.id&&d.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 _ of t.backboneAtoms)r.add(_.id),_.branchAtom!==void 0&&r.add(_.branchAtom.id);let s=new Map,a=o;for(let _ of t.backboneAtoms){a+=1;let M={..._,bio:{..._.bio,chainId:e.id,positionInChain:a}};if(s.set(_.id,M),_.branchAtom!==void 0){let k=_.branchAtom,x={...k,bio:{...k.bio,chainId:e.id,positionInChain:a}};s.set(k.id,x);}}for(let _ of t.backboneAtoms){let M=s.get(_.id);if(M===void 0||_.branchAtom===void 0)continue;let k=s.get(_.branchAtom.id);k!==void 0&&(M.branchAtom=k);}for(let _ of this._mol.atoms)s.has(_.id)||s.set(_.id,_);let l=0;for(let _ of this._mol.atoms)_.id>l&&(l=_.id);for(let _ of this._mol.bonds)_.id>l&&(l=_.id);let d=l+1,c=s.get(e.backboneAtoms[e.backboneAtoms.length-1].id),u=s.get(t.backboneAtoms[0].id),m={id:d,a1:c,a2:u,kind:\"backbone\",r1:{kind:\"numeric\",r:2},r2:{kind:\"numeric\",r:1}},p=[];for(let _ of this._mol.bonds){let M=s.get(_.a1.id)??_.a1,k=s.get(_.a2.id)??_.a2;M===_.a1&&k===_.a2?p.push(_):p.push({..._,a1:M,a2:k});}p.push(m);let h=[],f=[...e.backboneAtoms];for(let _ of t.backboneAtoms)f.push(s.get(_.id));for(let _ of this._mol.chains)if(_.id!==t.id)if(_.id===e.id){let M=_.bonds.map(k=>{let x=s.get(k.a1.id)??k.a1,T=s.get(k.a2.id)??k.a2;return x===k.a1&&T===k.a2?k:{...k,a1:x,a2:T}});for(let k of t.bonds){let x=s.get(k.a1.id)??k.a1,T=s.get(k.a2.id)??k.a2;M.push(x===k.a1&&T===k.a2?k:{...k,a1:x,a2:T});}M.push(m),h.push({id:_.id,polymerType:_.polymerType,backboneAtoms:f,bonds:M,..._.annotation!==void 0?{annotation:_.annotation}:{}});}else {let M=_.backboneAtoms.map(x=>s.get(x.id)??x),k=_.bonds.map(x=>{let T=s.get(x.a1.id)??x.a1,E=s.get(x.a2.id)??x.a2;return T===x.a1&&E===x.a2?x:{...x,a1:T,a2:E}});h.push({id:_.id,polymerType:_.polymerType,backboneAtoms:M,bonds:k,..._.annotation!==void 0?{annotation:_.annotation}:{}});}let w={atoms:this._mol.atoms.map(_=>s.get(_.id)??_),bonds:p,chains:h,groups:this._mol.groups,annotations:this._mol.annotations};return w=this._refreshContinuousIdsLocal(w),{id:d,mol:w}}_refreshContinuousIdsLocal(e){let t=Ee(e),n=new Map;for(let l of e.atoms){let d=t.get(l.id);if(d===void 0||d===l.bio.continuousId){n.set(l.id,l);continue}n.set(l.id,{...l,bio:{...l.bio,continuousId:d}});}for(let l of e.atoms){if(l.branchAtom===void 0)continue;let d=n.get(l.id),c=n.get(l.branchAtom.id);d===void 0||c===void 0||(d.branchAtom=c);}let o=e.bonds.map(l=>{let d=n.get(l.a1.id)??l.a1,c=n.get(l.a2.id)??l.a2;return d===l.a1&&c===l.a2?l:{...l,a1:d,a2:c}}),r=new Map;for(let l of o)r.set(l.id,l);let s=e.chains.map(l=>{let d=l.backboneAtoms.map(u=>n.get(u.id)??u),c=l.bonds.map(u=>r.get(u.id)??u);return {id:l.id,polymerType:l.polymerType,backboneAtoms:d,bonds:c,...l.annotation!==void 0?{annotation:l.annotation}:{}}});return {atoms:e.atoms.map(l=>n.get(l.id)??l),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 I(\"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 I(\"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 l=Ht(e,r).find(d=>d.rNumber===n);if(l!==void 0){let d=l.side===\"r1\"?l.bond.a2:l.bond.a1;throw new I(\"rgroup-already-bonded\",`R-group R${n} on '${e.symbol}' is already bonded to '${d.symbol}' (${d.bio.chainId}:${d.bio.positionInChain})`,{atomId:e.id,requested:n,conflictingBondId:l.bond.id})}}if(a>0){let l=Ht(t,r).find(d=>d.rNumber===o);if(l!==void 0){let d=l.side===\"r1\"?l.bond.a2:l.bond.a1;throw new I(\"rgroup-already-bonded\",`R-group R${o} on '${t.symbol}' is already bonded to '${d.symbol}' (${d.bio.chainId}:${d.bio.positionInChain})`,{atomId:t.id,requested:o,conflictingBondId:l.bond.id})}}for(let l of r){if(l.r1.kind!==\"numeric\"||l.r2.kind!==\"numeric\")continue;let d=l.a1.id===e.id&&l.a2.id===t.id&&l.r1.r===n&&l.r2.r===o,c=l.a1.id===t.id&&l.a2.id===e.id&&l.r1.r===o&&l.r2.r===n;if(d||c)throw new I(\"duplicate-bond\",`bond ${e.symbol}:R${n} \\u2194 ${t.symbol}:R${o} already exists`,{atomId:e.id,bondId:l.id})}}_freeRgroupsOn(e){return W(e,this._mol.bonds)}addHydrogenBond(e,t){this._ensureLive();let n=new O(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=_t(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=_t(this._mol,t);if(n===void 0)return;let o=new O(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 O(this._mol);r.updateAtom(e.id,{symbol:t});let{mol:s}=r.commit(),a=xe(s,this._service.monomerLib,{mode:\"lenient\"}).mol;this._replaceMol(a,`replaceMonomer:${o}->${t}`,\"api\");let l=J(a,e.id);l!==void 0&&this._events.fire(\"monomer:replace\",{atom:l,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 O(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 O(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=ne(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(aa,Math.max(sa,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 l=t??{x:0,y:0};this._events.fire(\"view:zoom\",{scale:o,center:l,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 u of this._mol.atoms){if(!s){t=o=u.p.x,n=r=u.p.y,s=true;continue}u.p.x<t&&(t=u.p.x),u.p.x>o&&(o=u.p.x),u.p.y<n&&(n=u.p.y),u.p.y>r&&(r=u.p.y);}let a=s?{x:t,y:n,width:o-t,height:r-n}:{x:0,y:0,width:0,height:0},l={...this._viewport.offset},d=this._viewport.scale,c={scale:1,offset:{x:0,y:0}};this._viewport=c,d!==1&&this._events.fire(\"view:zoom\",{scale:1,center:{x:0,y:0},previousScale:d}),(l.x!==0||l.y!==0)&&this._events.fire(\"view:pan\",{offset:c.offset,previousOffset:l}),this._events.fire(\"view:viewport-change\",{viewport:c}),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 Ue(this)),this._atomDialog.open(e));}openBondProps(e){this._ensureLive(),this._host!==null&&(this._bondDialog===null&&(this._bondDialog=new ze(this)),this._bondDialog.open(e));}openFindReplace(){this._ensureLive(),this._host!==null&&(this._findReplaceDialog===null&&(this._findReplaceDialog=new Ke(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 d=e,c=t;if(n=this.findMonomers(d),n.length===0)return 0;if(d===c)return n.length;o=`${d}->${c}`;}else {let d=t,c=new Set,u=[];for(let m of e){if(c.has(m.id))continue;c.add(m.id);let p=J(this._mol,m.id);p!==void 0&&p.symbol!==d&&u.push(p);}if(u.length===0)return 0;n=u,o=`atoms[${u.length}]->${d}`;}let r=t,s=new O(this._mol);for(let d of n)s.updateAtom(d.id,{symbol:r});let{mol:a}=s.commit(),l=xe(a,this._service.monomerLib,{mode:\"lenient\"}).mol;return this._replaceMol(l,`replaceMonomers:${o}`,\"api\"),n.length}nudgeSelection(e,t){this._ensureLive();let n=this._selection;if(n.atoms.size===0)return;let o=new O(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 O(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=G.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=We(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 M=s[0].p.x,k=s[0].p.y;for(let x of s)x.p.x<M&&(M=x.p.x),x.p.y>k&&(k=x.p.y);r={x:M,y:k+o};}let a={x:r.x+o,y:r.y},l={x:r.x,y:r.y+o},d=new Set;for(let M of this._mol.chains)d.add(M.id);let c=1;for(;d.has(`RNA${c}`);)c+=1;let u=`RNA${c}`,m=new O(this._mol),p=m.addAtom({p:r,biotype:b.SUGAR,symbol:e,chainId:u,positionInChain:1}),h=m.addAtom({p:a,biotype:b.LINKER,symbol:n,chainId:u,positionInChain:2}),f=m.addAtom({p:l,biotype:b.BASE,symbol:t,chainId:u,positionInChain:0});m.addBond({a1:p,a2:f,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:y}=m.commit(),w=this._postProcessTripletMol(y,p,f,u),_=xe(w,this._service.monomerLib,{mode:\"lenient\"}).mol;this._replaceMol(_,\"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 l={...a,branchAtom:s};r.set(t,l);let d=e.bonds.map(h=>{let f=r.get(h.a1.id)??h.a1,y=r.get(h.a2.id)??h.a2;return f===h.a1&&y===h.a2?h:{...h,a1:f,a2:y}}),c=new Map;for(let h of d)c.set(h.id,h);let u=e.chains.map(h=>{let f=[];for(let w of h.backboneAtoms)h.id===o&&w.id===n||f.push(r.get(w.id)??w);let y=h.bonds.map(w=>c.get(w.id)??w);return {id:h.id,polymerType:h.polymerType,backboneAtoms:f,bonds:y,...h.annotation!==void 0?{annotation:h.annotation}:{}}}),p={atoms:e.atoms.map(h=>r.get(h.id)??h),bonds:d,chains:u,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 On(i){return i.startsWith(\"[\")&&i.endsWith(\"]\")||i.length===1&&/^[A-Za-z]$/.test(i)?i:`[${i}]`}function We(i,e,t){return `${On(i)}(${On(e)})${On(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===\"\"?\"\":\".\",f=`${n.matchText.startsWith(\"|\")?\"|\":\"\"}${n.name}{${n.body}${h}${e}}`,y=i.lastIndexOf(n.matchText);return i.slice(0,y)+f+i.slice(y+n.matchText.length)}let r=new Set,s=/RNA(\\d+)\\{/g,a;for(;(a=s.exec(i))!==null;)r.add(Number(a[1]));let l=1;for(;r.has(l);)l+=1;let d=`RNA${l}{${e}}`,c=i.indexOf(\"$\");if(c<0)return `${i}|${d}$$$$V2.0`;let u=i.slice(0,c),m=i.slice(c);return `${u}${u===\"\"?\"\":\"|\"}${d}${m}`}var ca=5,ua=3,ma=14,pa=11,ha=9,fa=8,ba=48,ya=96;function ga(i){return i<=ua?ma:i<=6?pa:i<=9?ha:fa}function Ti(i,e){let t=$(e.monomer,e.biotype,e.theme.colorTheme),n=xt(t.background),o=t.text,r=Zn(o,n)<ca,s=e.monomer.symbol,a=ga(s.length),d=s.length>=10?\"line-height:1.1;letter-spacing:-0.02em;\":\"\",c=`font-size:${a}px;${d}white-space:nowrap;overflow:hidden;text-overflow:ellipsis;max-width:${ya-16}px;display:inline-block;`,u=g(i,\"span\",{class:\"hw-palette__star\"},[e.favorite?\"\\u2605\":\"\\u2606\"]),m=g(i,\"span\",{class:\"hw-palette__label\",style:c},[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,f=`background:${n};color:${o};width:100%;min-width:${ba}px;padding:4px 6px;height:40px;box-sizing:border-box;overflow:hidden;text-overflow:ellipsis;`;return {root:g(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:f},[u,m]),star:u}}function Si(i,e){let t=e.showStar!==false,n=g(i,\"span\",{class:\"hw-triplet-chip__star\"},[e.favorite?\"\\u2605\":\"\\u2606\"]),o=g(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:g(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\",Ei={sugar:b.SUGAR,base:b.BASE,linker:b.LINKER},_a={sugar:[\"r\",\"R\"],base:[\"A\"],linker:[\"p\",\"P\"]},va=200,wa=180,st={x:70,y:60},Nn={x:140,y:60},Fn={x:70,y:130},je=18,Ci=18,at=22,Wt=class Wt{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=g(this._doc,\"div\",{class:\"hw-rna-builder\",\"data-testid\":\"rna-builder\"});let o=g(this._doc,\"div\",{class:\"hw-rna-builder__header\"});if(o.appendChild(g(this._doc,\"div\",{class:\"hw-rna-builder__title\"},[\"RNA builder\"])),this._favHooks!==null){let l=g(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\"]),d=c=>{c.stopPropagation();let u=this.getSelection();u.preview===\"\"||this._favHooks===null||this._favHooks.toggleFavoriteTriplet(u.sugar,u.base,u.linker);};l.addEventListener(\"click\",d),l.addEventListener(\"keydown\",c=>{let u=c;(u.key===\"Enter\"||u.key===\" \")&&d(c);}),this._favStar=l,o.appendChild(l);}this.element.appendChild(o),this._hintEl=g(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=g(this._doc,\"div\",{class:\"hw-rna-builder__preview\",\"data-testid\":\"rna-builder-preview\"}),this.element.appendChild(this._preview),this._addBtn=g(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!==\"\"?We(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(Ei[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 ${va} ${wa}`),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(st.x+je)),t.setAttribute(\"y1\",String(st.y)),t.setAttribute(\"x2\",String(Nn.x-Ci)),t.setAttribute(\"y2\",String(Nn.y)),e.appendChild(t);let n=this._doc.createElementNS(ce,\"line\");n.setAttribute(\"class\",\"hw-rna-builder__bond\"),n.setAttribute(\"x1\",String(st.x)),n.setAttribute(\"y1\",String(st.y+je)),n.setAttribute(\"x2\",String(Fn.x)),n.setAttribute(\"y2\",String(Fn.y-at)),e.appendChild(n);let o=this._doc.createElementNS(ce,\"rect\");o.setAttribute(\"class\",\"hw-rna-builder__slot-shape\"),o.setAttribute(\"x\",String(-je)),o.setAttribute(\"y\",String(-je)),o.setAttribute(\"width\",String(je*2)),o.setAttribute(\"height\",String(je*2)),o.setAttribute(\"rx\",\"8\"),o.setAttribute(\"ry\",\"8\");let r=this._buildSlot(\"sugar\",\"Pick sugar (backbone)\",st,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(Ci));let a=this._buildSlot(\"linker\",\"Pick linker\",Nn,s),l=this._doc.createElementNS(ce,\"path\");l.setAttribute(\"class\",\"hw-rna-builder__slot-shape\"),l.setAttribute(\"d\",`M ${-at} 0 L 0 ${-at} L ${at} 0 L 0 ${at} Z`);let d=this._buildSlot(\"base\",\"Pick base\",Fn,l);return e.appendChild(a.groupEl),e.appendChild(r.groupEl),e.appendChild(d.groupEl),this._slots.set(\"sugar\",r),this._slots.set(\"linker\",a),this._slots.set(\"base\",d),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=l=>{l.stopPropagation(),this.startPickMode(e);};return r.addEventListener(\"click\",a),r.addEventListener(\"keydown\",l=>{let d=l;(d.key===\"Enter\"||d.key===\" \")&&a(l);}),r.addEventListener(\"mouseenter\",l=>this._showSlotTooltip(e,l)),r.addEventListener(\"mouseleave\",()=>this._hideSlotTooltip()),r.addEventListener(\"focus\",()=>this._showSlotTooltip(e,null)),r.addEventListener(\"blur\",()=>this._hideSlotTooltip()),{id:e,biotype:Ei[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 l=s.firstChild;l!==null;l=l.nextSibling)if(l.nodeName===\"title\"||l.nodeName===\"TITLE\"){a=l;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:Ma(t,e.biotype,e.value),r=$(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=ka(e,n.biotype),r=Aa(o,_a[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>=Wt._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=oe(this._doc,\"builder-tooltip\",\"hw-builder-tooltip\");Me(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 l=t;if(l!==null&&typeof l.clientX==\"number\"&&typeof l.clientY==\"number\")Y(a,l.clientX,l.clientY);else {let d=n.groupEl,c=typeof d.getBoundingClientRect==\"function\"?d.getBoundingClientRect():null;c!==null?Y(a,c.left+c.width/2,c.top+c.height/2):Y(a,0,0);}}_hideSlotTooltip(){let e=this._doc.body.querySelector('[data-testid=\"builder-tooltip\"]');V(e);}};Wt._BUILDER_RDKIT_CACHE_LIMIT=256;var Kt=Wt;function xa(i){let e=i.length;return e<=2?16:e<=4?11:e<=7?8:e<=10?6:5}function ka(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 Aa(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 Ma(i,e,t){return i.getMonomerSet(e).get(t)??null}var ue=\"Favorites\",Gn={[ue]:\"\\u2605 Favorites\",[v.PEPTIDE]:\"Peptides\",[v.RNA]:\"RNA\",[v.CHEM]:\"CHEM\",[v.BLOB]:\"BLOB\",G:\"G\"},jt=[ue,v.PEPTIDE,v.RNA,v.CHEM,v.BLOB,\"G\"],Li=\"hwe:palette:favorites\",Bi=\"hwe:palette:active-tab\",Ta=\"hwe.palette.favorites\";function qt(i){return `${i.sugar}|${i.base}|${i.linker}`}var qe=class qe{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=g(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=qt({sugar:e,base:t,linker:n});return this._favoriteTriplets.some(r=>qt(r)===o)}setFavoriteTriplet(e,t,n,o){let r=qt({sugar:e,base:t,linker:n}),s=this._favoriteTriplets.findIndex(l=>qt(l)===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;V(e.querySelector('[data-testid=\"palette-tooltip\"]')),V(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=l=>{l.key===\"Escape\"&&this.cancelBiotypeFilter();};this._pickEscapeListener=o,this._doc.defaultView?.addEventListener(\"keydown\",o);let s=l=>{if(this._activeBiotypeFilter===null)return;let d=l.target;if(d==null)return;let c=this._activeBiotypeFilter,u=d;for(;u!==null;){let m=u.getAttribute===void 0?null:u.getAttribute(\"class\");if(m!==null){let p=m.split(/\\s+/);if(p.includes(\"hw-palette__tile\")){if((u.getAttribute(\"data-biotype\")??\"\")===c)return;break}if(p.includes(\"hw-rna-builder__slot\")){if(this._isInsideOwnPalette(u))return;break}}u=u.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=g(this._doc,\"div\",{class:\"hw-palette__tabs\",role:\"tablist\",\"data-testid\":\"palette-tabs\"});for(let s of this._visibleTabs){let a=s===this._activeTab,l=g(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:Gn[s]},[Gn[s]]);l.addEventListener(\"click\",()=>this.setActiveTab(s)),t.appendChild(l);}this.element.appendChild(t);let n=g(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,l=g(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(l,r,o):this._buildPolymerPane(l,s,r,o),n.appendChild(l);}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 jt)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=g(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,l=s.monomerType??\"Undefined\",d=`${a}|${l}`,c=t.get(d);c===void 0&&(c={pt:a,mt:l,list:[]},t.set(d,c)),c.list.push(s);}let n=s=>{let a=jt.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 Gn[e]??e}_renderTripletGroup(e,t,n){let o=g(this._doc,\"div\",{class:\"hw-palette__group\",\"data-natural-analog\":e}),r=g(this._doc,\"div\",{class:\"hw-palette__group-header\",\"data-testid\":`palette-group-${e}`},[e]),s=g(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=We(e.sugar,e.base,e.linker),o=t.getMonomerSet(b.BASE).get(e.base)??null,r=$(o,b.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:l}=Si(this._doc,{sugar:e.sugar,base:e.base,linker:e.linker,label:n,title:a,background:xt(r.background),textColor:r.text,favorite:s,showStar:this._opts.allowFavorites});return this._wireTripletChip(l,e),l}_wireTripletChip(e,t){e.addEventListener(\"mouseenter\",n=>{let o=n,r=oe(this._doc,\"palette-triplet-tooltip\",\"hw-palette-tooltip hw-triplet-tooltip\");mi(this._doc,r,{title:We(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\",()=>{V(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(b.SUGAR),[\"r\",\"R\"]),n=this._pickSymbol(e.getMonomerSet(b.LINKER),[\"p\",\"P\"]),o=e.getMonomerSet(b.BASE);if(t===null||n===null)return null;let r=qe._DEFAULT_TRIPLET_BASES.filter(a=>o.has(a));if(r.length===0)return null;let s=g(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\",b.SUGAR,e.sugar),n(\"Base\",b.BASE,e.base),n(\"Linker\",b.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(b.SUGAR).has(e.sugar)&&this._rnaBuilder.setField(\"sugar\",e.sugar),e.base!==\"\"&&t.getMonomerSet(b.BASE).has(e.base)&&this._rnaBuilder.setField(\"base\",e.base),e.linker!==\"\"&&t.getMonomerSet(b.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===v.RNA){this._rnaBuilder=new Kt(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 c=this._buildRnaDefaultChips(n);c!==null&&e.appendChild(c);let u=this._groupRna(s);for(let[m,p]of u)p.length!==0&&e.appendChild(this._renderGroup(m,p));return}if(r===v.PEPTIDE&&this._opts.groupByNaturalAnalog){let c=this._groupByAnalog(s);for(let[u,m]of c){let p=u===\"\"?\"Other\":u;e.appendChild(this._renderGroup(p,m));}return}let a=g(this._doc,\"div\",{class:\"hw-palette__group-tiles\"}),l=this._editor.getNextAddSymbol(),d=this._sortByColor(s);for(let c of d){let u=this._biotype(c,r);a.appendChild(this._renderTile(c,u,l));}e.appendChild(a);}_renderGroup(e,t){let n=g(this._doc,\"div\",{class:\"hw-palette__group\",\"data-natural-analog\":e}),o=g(this._doc,\"div\",{class:\"hw-palette__group-header\",\"data-testid\":`palette-group-${e}`},[e]),r=g(this._doc,\"div\",{class:\"hw-palette__group-tiles\"}),s=this._editor.getNextAddSymbol(),a=this._sortByColor(t);for(let l of a){let d=this._biotype(l,l.polymerType);r.appendChild(this._renderTile(l,d,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=$(o,s,t.colorTheme),l=Qn(a.background),d=l.s===0?1:0;return {m:o,idx:r,h:l.h,s:l.s,l:l.l,isGrey:d}});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 l=ee(a);l===b.SUGAR?t.push(a):l===b.BASE?n.push(a):l===b.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}=Ti(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>=qe._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=oe(this._doc,\"palette-tooltip\",\"hw-palette-tooltip\");Me(this._doc,a,{symbol:n.symbol,name:n.name??\"\",rdkitSvg:this._paletteRdkitSvg(n),rdkitTestid:\"palette-tooltip-rdkit-svg\"});let l=typeof s.clientX==\"number\"?s.clientX:0,d=typeof s.clientY==\"number\"?s.clientY:0;Y(a,l,d);}),e.addEventListener(\"mouseleave\",()=>{V(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 d=this._pickResolver;this._teardownPickMode(),d?.(n.symbol),this._scrollActivePaneToTop(),r.stopPropagation();return}let a=this._editor.getSelection();if(a.atoms.size>0){let d=this._editor.getMol(),c=[];for(let m of a.atoms){let p=d.atoms.find(h=>h.id===m);p!==void 0&&c.push(p);}if(c.length>0&&c.every(m=>m.biotype===o)){this._editor.replaceMonomers(c,n.symbol),r.stopPropagation();return}this._editor.fire(\"editor:status\",{message:`Cannot bulk-replace ${c.length} selected atom(s) with ${n.symbol}: selection contains incompatible biotypes for ${o}.`,severity:\"warn\",durationMs:3e3}),r.stopPropagation();return}let l=this._editor.getNextAddSymbol();if(l!==null&&l.symbol===n.symbol&&l.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{}V(this._doc.body.querySelector('[data-testid=\"palette-tooltip\"]')),this._editor.startPaletteDrag(n.symbol,o);});}_biotype(e,t){let n=ee(e);if(n!==null)return n;switch(t){case v.PEPTIDE:return b.AA;case v.RNA:return b.SUGAR;case v.CHEM:return b.CHEM;case v.BLOB:return b.BLOB;default:return b.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 l=o[a],d=(l.getAttribute(\"data-symbol\")??\"\").toLowerCase(),c=(l.getAttribute(\"title\")??\"\").toLowerCase(),u=l.getAttribute(\"data-biotype\")??\"\",h=(e===\"\"||d.indexOf(e)>=0||c.indexOf(e)>=0)&&(t===null||u===t);l.style.display=h?\"\":\"none\";}let r=(n??this.element).querySelectorAll(\".hw-triplet-chip\");for(let a=0;a<r.length;a++){let l=r[a],d=[l.getAttribute(\"data-triplet\")??\"\",l.getAttribute(\"data-sugar\")??\"\",l.getAttribute(\"data-base\")??\"\",l.getAttribute(\"data-linker\")??\"\"].join(\" \").toLowerCase(),c=(e===\"\"||d.indexOf(e)>=0)&&t===null;l.style.display=c?\"\":\"none\";}let s=(n??this.element).querySelectorAll(\".hw-palette__group\");for(let a=0;a<s.length;a++){let l=s[a],d=l.querySelectorAll(\".hw-palette__tile, .hw-triplet-chip\"),c=false;for(let u=0;u<d.length;u++)if(d[u].style.display!==\"none\"){c=true;break}c?(l.removeAttribute(\"hidden\"),l.removeAttribute(\"data-section-empty\")):(l.setAttribute(\"hidden\",\"\"),l.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,d=(o.getAttribute(\"class\")??\"\").split(/\\s+/).filter(c=>c!==\"hw-palette__tile--primed\").join(\" \");o.setAttribute(\"class\",a?`${d} hw-palette__tile--primed`:d),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&&jt.includes(e))return e;let t=this._localStorage();if(t!==null)try{let n=t.getItem(Bi);if(n!==null&&jt.includes(n))return n}catch{}return ue}_persistActiveTab(){let e=this._localStorage();if(e!==null)try{e.setItem(Bi,this._activeTab);}catch{}}_loadFavorites(){let e=this._localStorage();if(e!==null){try{let t=e.getItem(Li);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(Ta);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(Li,JSON.stringify(t));}catch{}}};qe._DEFAULT_TRIPLET_BASES=[\"A\",\"C\",\"G\",\"U\",\"T\"],qe._PALETTE_RDKIT_CACHE_LIMIT=256;var lt=qe;var U='<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\">',Sa={new:`${U}<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:`${U}<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:`${U}<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:`${U}<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:`${U}<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:`${U}<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:`${U}<path d=\"m4 4 7.07 17 2.51-7.39L21 11.07z\"/></svg>`,hbond:`${U}<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\":`${U}<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\":`${U}<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:`${U}<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:`${U}<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:`${U}<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:`${U}<circle cx=\"11\" cy=\"11\" r=\"8\"/><line x1=\"21\" y1=\"21\" x2=\"16.65\" y2=\"16.65\"/></svg>`,theme:`${U}<circle cx=\"12\" cy=\"12\" r=\"9\"/><path d=\"M12 3a9 9 0 0 1 0 18z\" fill=\"currentColor\" stroke=\"none\"/></svg>`},Ea={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\"},Ri=[{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}],dt=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??Ri;this.element=g(this._doc,\"div\",{class:\"hw-toolbar\",\"data-testid\":\"toolbar\"}),e.appendChild(this.element);for(let s of o){if(s.separator===true){let l=g(this._doc,\"span\",{class:\"hw-toolbar__separator\"});this.element.appendChild(l);}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=Ea[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=Sa[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=oe(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(){V(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?H:En);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 ct=class{constructor(e,t,n){this._unsubs=[];this._destroyed=false;this._editor=t,this._doc=n?.documentImpl??S(e),this._content=g(this._doc,\"pre\",{class:\"hw-pane__content hw-pane__sequence\",\"data-testid\":\"sequence-pane-content\"}),this.element=g(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 ut=class{constructor(e,t,n){this._unsubs=[];this._destroyed=false;this._suppressNext=false;this._editor=t,this._doc=n?.documentImpl??S(e),this._input=g(this._doc,\"div\",{class:\"hw-pane__content hw-pane__notation\",contenteditable:\"true\",spellcheck:\"false\",\"data-testid\":\"notation-pane-content\"}),this._error=g(this._doc,\"div\",{class:\"hw-pane__error\",\"data-testid\":\"notation-pane-error\"}),this.element=g(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 Ca=1e3,mt=class{constructor(e,t,n){this._unsubs=[];this._destroyed=false;this._editor=t,this._doc=n?.documentImpl??S(e),this._body=g(this._doc,\"div\",{class:\"hw-pane__content hw-pane__properties\",\"data-testid\":\"properties-pane-content\"}),this.element=g(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>Ca){this._body.appendChild(g(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=La(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=g(this._doc,\"span\",{class:\"hw-pane__prop-label\"},[e]),r=g(this._doc,\"span\",{class:\"hw-pane__prop-value\",\"data-testid\":`properties-${n}`},[t]);return g(this._doc,\"div\",{class:\"hw-pane__prop-row\"},[o,r])}};function La(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 pt=class{constructor(e,t,n){this._unsubs=[];this._destroyed=false;this._refreshToken=0;this._editor=t,this._doc=n?.documentImpl??S(e),this._content=g(this._doc,\"pre\",{class:\"hw-pane__content hw-pane__atomic\",\"data-testid\":\"atomic-pane-content\"}),this.element=g(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 Yt(i){return i.toLowerCase().replace(/[^a-z0-9]+/g,\"-\").replace(/^-|-$/g,\"\")}var ht=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=Yt(n);this._content=g(this._doc,\"div\",{class:\"hw-pane__content hw-pane__extra\",\"data-testid\":`extra-pane-content-${s}`}),this.element=g(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 Ba=\"extra:\";function Xt(i){return Ba+i}var Ra=[{id:\"sequence\",label:\"Sequence\"},{id:\"helm\",label:\"HELM\"},{id:\"properties\",label:\"Properties\"},{id:\"atomic\",label:\"Atomic Structure\"}],ft=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??H).name===\"dark\"?\"hw-app hw-app--dark\":\"hw-app\";this.element=g(this._doc,\"div\",{class:o,\"data-testid\":\"app-root\"}),this._toolbarHost=g(this._doc,\"div\",{class:\"hw-app__toolbar\"}),this._paletteHost=g(this._doc,\"div\",{class:\"hw-app__palette\"}),this._canvasHost=g(this._doc,\"div\",{class:\"hw-app__canvas\",\"data-testid\":\"canvas-host\"});let r=g(this._doc,\"div\",{class:\"hw-app__main\"},[this._paletteHost,this._canvasHost]);this._tabsHost=g(this._doc,\"div\",{class:\"hw-app__tabs\",role:\"tablist\"}),this._paneBody=g(this._doc,\"div\",{class:\"hw-app__pane-body\"});let s=g(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 rt(this._canvasHost,a),t.theme!==void 0&&this.canvas.setTheme(t.theme);let l={documentImpl:this._doc};t.toolbarButtons!==void 0&&(l.buttons=t.toolbarButtons),this.toolbar=new dt(this._toolbarHost,this.canvas,l),this.palette=new lt(this._paletteHost,this.canvas,{documentImpl:this._doc,...t.paletteOptions}),this.sequencePane=new ct(this._paneBody,this.canvas,{documentImpl:this._doc}),this.notationPane=new ut(this._paneBody,this.canvas,{documentImpl:this._doc}),this.propertiesPane=new mt(this._paneBody,this.canvas,{documentImpl:this._doc}),t.service.hasAtomicMolfileProvider()?this.atomicStructurePane=new pt(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 d=[];for(let[p,h]of t.service.getExtraPanes()){let f=new ht(this._paneBody,this.canvas,p,h,{documentImpl:this._doc});d.push(f),this._paneByName.set(Xt(p),f.element);}this.extraPanes=d;let c=this._resolveVisiblePanes(t),u=[];for(let p of c){let h=Ra.find(f=>f.id===p);h!==void 0&&u.push({id:h.id,label:h.label,testid:`tab-${h.id}`});}for(let p of d)u.push({id:Xt(p.name),label:p.name,testid:`tab-extra-${Yt(p.name)}`});for(let{id:p,label:h,testid:f}of u){let y=this._doc.createElement(\"button\");y.setAttribute(\"type\",\"button\"),y.setAttribute(\"class\",\"hw-app__tab\"),y.setAttribute(\"role\",\"tab\"),y.setAttribute(\"data-pane\",p),y.setAttribute(\"data-testid\",f),y.appendChild(this._doc.createTextNode(h)),y.addEventListener(\"click\",()=>this.activatePane(p)),this._tabsHost.appendChild(y),this._tabsByName.set(p,y);}let m=c.includes(\"helm\")?\"helm\":c[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\"&&(Ot(this._doc),X.closeTopmost()&&(t.stopImmediatePropagation?.(),t.preventDefault?.()));}_buildStatusBar(){let e=g(this._doc,\"div\",{class:\"hw-status-bar\",\"data-testid\":\"status-bar\"}),t=g(this._doc,\"span\",{class:\"hw-status-bar__mode\",\"data-testid\":\"status-mode\"}),n=g(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=g(this._doc,\"span\",{class:\"hw-status-bar__next-add-symbol\",\"data-testid\":\"status-next-add-symbol\"},[n.symbol]);e.appendChild(o);let r=g(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===Xt(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 Vn=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}},Un=class{constructor(e,t,n){this.a1=t,this.a2=n,this.r1=Ii(e.r1),this.r2=Ii(e.r2),this.kind=e.kind;}};function Ii(i){switch(i.kind){case \"numeric\":return i.r;case \"positional\":return i.r;default:return 0}}function re(i){let e=[],t=new Map;for(let r of i.atoms){let s=new Vn(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 Un(r,s,a));}return {atoms:e,bonds:n,clone(r){return re(i)},_internalMol:i}}var Ia=400,Pa=100,Ha=14,se=class{constructor(e,t,n){this._laidMol=null;this._currentHelm=\"\";this._drawOptions={fontsize:Ha};this._noDraw=false;this._svgEl=null;this.host=e,this._service=t,this._doc=n?.documentImpl??S(e),this._width=n?.width??Ia,this._height=n?.height??Pa,this._mol=me(),this._molView=re(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 Pt(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=re(e._mol),e._currentHelm=\"\",e._removeSvg();},getFormula(n){return $a(fe(e._mol))},getMolWeight(){return Pe(e._mol)},getExtinctionCoefficient(){return He(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:ne(e),re(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,l=Math.min(s.length,a.length);for(let d=0;d<l;d++){let c=s[d].p,u=a[d].p;u.x=c.x*n+o,u.y=c.y*n+r;}}_mountSvg(e){this._removeSvg();let t=Da(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;}},Pi=[\"C\",\"H\",\"N\",\"O\",\"S\",\"P\"];function $a(i){let e=o=>{let r=Pi.indexOf(o);return r===-1?Pi.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 Da(i,e,t,n){let o=Oa(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 Oa(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 Na=800,Fa=400,Ga=32,Va=14,zn=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=g(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}}},bt=class{constructor(e,t,n){this.toolbarheight=Ga;this._drawOptions={fontsize:Va};this._unsubs=[];this._destroyed=false;this._host=e,this._service=t,this._doc=n?.documentImpl??S(e),this._width=n?.width??Na,this._height=n?.height??Fa;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 ft(e,o),this.sequence=this._app.sequencePane.element,this.notation=this._app.notationPane.element,this.properties={parent:this._app.propertiesPane.element},this._structureviewHost=g(this._doc,\"div\",{class:\"hwe-legacy-app__structureview\",\"data-testid\":\"legacy-app-structureview\"}),this._structureviewWrapper=new se(this._structureviewHost,t,{documentImpl:this._doc}),this.structureview=this._structureviewWrapper,this.mex=new zn(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,l)=>{this._resize(a,l);},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 Ua(fe(t.canvas.getMol()))},getMolWeight(){return Pe(t.canvas.getMol())},getExtinctionCoefficient(){return He(t.canvas.getMol())},getDrawOptions(){return e._drawOptions}}}_currentMolView(){let e=this._app.canvas.getMol(),t=re(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=Hi(this._host.clientWidth,this._width),t=Hi(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 Ua(i){let e=[];for(let[t,n]of i.elements.entries())e.push(n===1?t:`${t}${n}`);return e.join(\"\")}function Hi(i,e){return typeof i!=\"number\"||isNaN(i)||i<=0?e:i}var za=240,Ka=80,yt=class{constructor(e,t,n){this._tooltip=null;this._destroyed=false;this.name=e,this._service=t;let o=n?.documentImpl??Wa();if(o===null)throw new Error(\"LegacyInputWrapper: no Document available.\");this._doc=o,this._host=g(this._doc,\"div\",{class:\"hwe-legacy-input\",\"data-testid\":\"legacy-input-host\"}),this.viewer=new se(this._host,t,{width:n?.editorOptions?.width??za,height:n?.editorOptions?.height??Ka,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=g(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 Wa(){return globalThis.document??null}var ja=/^R([1-9][0-9]*)$/,Di=new Set([v.PEPTIDE,v.RNA,v.CHEM,v.BLOB]),qa=new Set([\"Backbone\",\"Branch\",\"Terminal\",\"Undefined\"]);function $i(i){if(typeof i.symbol!=\"string\"||i.symbol.length===0||typeof i.molfile!=\"string\"||!Di.has(i.polymerType)||!qa.has(i.monomerType))return null;let e=[];for(let n of i.rgroups??[]){if(typeof n.label!=\"string\"||!ja.test(n.label))continue;let o={label:n.label,capGroupName:typeof n.capGroupName==\"string\"?n.capGroupName:\"\",capGroupSMILES:Je(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 Ya(i){return i===v.PEPTIDE?b.AA:i===v.RNA?b.SUGAR:i===v.CHEM?b.CHEM:i===v.BLOB?b.BLOB:b.AA}function Kn(i,e,t){if(i===v.PEPTIDE)return b.AA;if(i===v.CHEM)return b.CHEM;if(i===v.BLOB)return b.BLOB;if(i===v.RNA){if(e===\"Branch\")return b.BASE;if(e===\"Backbone\")return t===\"P\"||t===\"p\"?b.LINKER:b.SUGAR}return b.AA}function Xa(i,e){let t=i.subscribe(e);return ()=>{t!=null&&typeof t.unsubscribe==\"function\"&&t.unsubscribe();}}var Jt=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=Xa(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($i(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=Kn(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 l={...e.meta??{},colors:{...e.meta?.colors??{},default:{line:a,text:s,background:r}}};return {...e,meta:l}}registerInlineSmilesMonomer(e,t){let n=this._base;typeof n.getWebEditorMonomer==\"function\"&&n.getWebEditorMonomer(Ya(e),t);let o=n.getMonomer(e,t),r=o==null?null:this._enrichColors($i(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&&Kn(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(v);for(let n of t){if(!Di.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\"?Be:we,o=e===null?b.AA:Kn(e.polymerType,e.monomerType,e.naturalAnalog);return $(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 Wn(i,e){return new Jt(i,e)}var Zt=class Zt{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 Se,this._bridge=e.monomerLibBridge??(t=>Wn(t)),this._doc=e.documentImpl??Oi();}get service(){return this._service}createHelmInput(e,t){let n={...t};return n.documentImpl===void 0&&this._doc!==null&&(n.documentImpl=this._doc),new yt(e,this._service,n)}createHelmWebEditor(e,t){let n=e??this._createDetachedHost();return new se(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 bt(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:l,symbol:d}=Ni(s,a);if(d===null)return null;let c=Za(d),u=Fi(l),m=t.getMonomer(u,c);return m===null?null:Gi(m,c)}function r(s){let{biotype:a}=Ni(s,void 0),l=Fi(a),d={};for(let c of t.getMonomerSymbolsByType(l)){let u=t.getMonomer(l,c);u!==null&&(d[c]=Gi(u,c));}return d}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,H).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=ne(n.mol);return re(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=Ja(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??Oi();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 se(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();},Zt._MOLFILES_GC_MS));}_removeMolfilesEditorNow(){this._molfilesEditor=null,this._molfilesEditorHost!==null&&this._molfilesEditorHost.parentNode!==null&&this._molfilesEditorHost.parentNode.removeChild(this._molfilesEditorHost),this._molfilesEditorHost=null;}};Zt._MOLFILES_GC_MS=1e3;var gt=Zt;function Oi(){return globalThis.document??null}function Ja(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 Za(i){return i.length>=2&&i.charAt(0)===\"[\"&&i.charAt(i.length-1)===\"]\"?i.slice(1,i.length-1):i}function Ni(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:b.AA,symbol:e??null}}function Fi(i){switch(i){case b.AA:return v.PEPTIDE;case b.SUGAR:case b.BASE:case b.LINKER:case b.NUCLEOTIDE:return v.RNA;case b.CHEM:return v.CHEM;case b.BLOB:return v.BLOB;default:return v.PEPTIDE}}function Gi(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 Qa(i,e){if(e==null)throw new TypeError(\"registerWithDatagrok: options is required\");let t=new gt({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{Ue as AtomPropsDialog,pt as AtomicStructurePane,ze as BondPropsDialog,Jt as BridgedMonomerLib,Ve as ChooseRDialog,Ri as DEFAULT_TOOLBAR_BUTTONS,De as EventBus,ht as ExtraPane,Ke as FindReplaceDialog,rt as HelmEditor,ft as HelmEditorApp,gt as HelmHelperAdapter,j as HelmNotSupportedError,N as HelmParseError,Dn as HelmService,b as HelmTypes,Ye as HelmValidationError,Oe as HistoryStack,I as HwError,bt as LegacyAppWrapper,se as LegacyEditorWrapper,yt as LegacyInputWrapper,dn as MonomerLib,Qt as MonomerNotFoundError,lt as MonomerPalette,ji as MonomerTypes,ut as NotationPane,v as PolymerTypes,mt as PropertiesPane,G as Selection,ct as SequencePane,dt as Toolbar,Ht as bondsOnAtom,Wn as bridgeMonomerLib,re as buildHelmMolView,En as darkTheme,Qr as defineTheme,Xt as extraPaneId,Yt as extraPaneSlug,W as freeRgroups,js as hasFreeRgroup,H as lightTheme,Qa as registerWithDatagrok,ai 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","b","v","PEPTIDE","RNA","CHEM","BLOB","G","Z","_listeners","_completed","subscribe","e","add","delete","next","t","complete","clear","observerCount","size","B","i","line","text","background","Ji","rn","Le","exec","n","parseInt","slice","nn","toString","padStart","sn","an","o","r","s","Math","max","a","min","l","u","d","on","Jn","round","xt","c","Xn","pow","vt","h","Zi","wt","g","Qi","eo","A","T","C","U","to","R","no","P","p","oo","N","D","E","Q","H","I","L","K","M","F","S","W","Y","V","io","ro","so","we","name","fallback","errorTriple","palette","b_BASE","b_SUGAR","b_LINKER","b_AA","b_CHEM","b_BLOB","b_NUCLEOTIDE","ve","Object","entries","Be","$","meta","colors","light","dark","default","naturalAnalog","ee","polymerType","monomerType","PI","Et","x","y","width","height","Number","isInteger","isFinite","is","An","length","Do","cos","sin","Mn","abs","Tn","Sn","sqrt","Ko","Wo","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","nt","Lt","Ie","biotype","symbol","Vo","Oo","No","Fo","Go","pe","he","es","ns","test","replace","Ae","join","In","class","atoms","has","id","fill","stroke","Pn","WeakMap","bonds","isEmpty","freeze","ownerDocument","document","createElement","keys","setAttribute","String","appendChild","createTextNode","ye","get_mol","get_svg","oe","body","children","getAttribute","style","display","Me","firstChild","removeChild","rdkitSvg","rdkitTestid","innerHTML","hint","left","top","Ot","endsWith","Ft","_baseTransform","_viewport","scale","offset","_pinnedBbox","_tooltip","_bondTooltip","_rdkitSvgCache","_unsubs","_destroyed","host","_editor","_doc","documentImpl","_width","_height","querySelector","textContent","head","documentElement","ci","_svgRoot","_renderFresh","_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","Rn","renderMol","theme","fixedModelBbox","ui","_applyOverlaysToCurrent","getSelection","selectedAtomIds","highlightLayer","highlightedAtomIds","selectionLayer","di","_editorHighlights","_spliceLayer","createElementNS","replaceChild","_currentHighlights","monomer","bio","positionInChain","chainId","_renderRdkitTooltipSvg","m","options","rdkitModule","smiles","get","_RDKIT_CACHE_LIMIT","value","set","pi","r1","r2","a1","a2","kind","_paintSelectionRectAt","position","ie","_onClose","_primaryAction","_host","role","testId","title","stopPropagation","key","target","tagName","preventDefault","stopImmediatePropagation","close","root","anyOpen","_openStack","closeTopmost","open","includes","indexOf","splice","setPrimaryAction","isOpen","On","startsWith","We","ce","Ei","_a","st","Nn","Fn","Wt","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","je","_buildSlot","groupEl","_showSlotTooltip","_hideSlotTooltip","shapeEl","nextSibling","nodeName","xa","insertBefore","values","_theme","getMonomerSet","Ma","ka","Aa","some","_updateFavStar","isFavoriteTriplet","removeAttribute","placeRnaTriplet","split","filter","_rdkit","_builderRdkitSvgFor","_BUILDER_RDKIT_CACHE_LIMIT","_slotHint","_slotTitle","getBoundingClientRect","Kt","sort","localeCompare","ue","Gn","jt","Li","Bi","qt","qe","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","Si","_wireTripletChip","parts","mi","_tripletTooltipParts","classList","contains","_buildRnaDefaultChips","_pickSymbol","_DEFAULT_TRIPLET_BASES","_paletteRdkitSvg","done","_restoreRnaSelection","getMonomer","_monomersForPolymer","_groupRna","_groupByAnalog","getNextAddSymbol","_sortByColor","_biotype","_renderTile","Qn","idx","isGrey","getMonomerSymbolsByType","Zn","ga","primed","f","draggable","Ti","_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":""}