@but212/atom-effect-jquery 0.22.1 → 0.23.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +1 -1
- package/dist/atom-effect-jquery.min.js +2 -1
- package/dist/atom-effect-jquery.min.js.map +1 -1
- package/dist/index.cjs +2 -1
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.ts +53 -147
- package/dist/index.mjs +1583 -1170
- package/dist/index.mjs.map +1 -1
- package/package.json +3 -3
package/dist/index.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.mjs","sources":["../../core/dist/index.mjs","../src/constants.ts","../src/utils.ts","../src/debug.ts","../src/namespace.ts","../src/registry.ts","../src/effect-factory.ts","../src/jquery-patch.ts","../src/types.ts","../src/input-binding.ts","../src/unified.ts","../src/chainable.ts","../src/list.ts","../src/mount.ts","../src/route.ts","../src/fetch.ts","../src/index.ts"],"sourcesContent":["const b = {\n IDLE: \"idle\",\n PENDING: \"pending\",\n RESOLVED: \"resolved\",\n REJECTED: \"rejected\"\n}, u = {\n DISPOSED: 1,\n EXECUTING: 8\n}, $ = {\n DISPOSED: 1,\n /** Marker bit: identifies this node as a computed. */\n IS_COMPUTED: 2,\n DIRTY: 8,\n IDLE: 16,\n PENDING: 32,\n RESOLVED: 64,\n REJECTED: 128,\n RECOMPUTING: 256,\n HAS_ERROR: 512\n}, a = {\n DISPOSED: 1,\n SYNC: 8,\n NOTIFICATION_SCHEDULED: 16\n}, Dt = {\n MAX_SIZE: 1e3,\n WARMUP_SIZE: 100,\n ENABLE_STATS: !1\n}, d = {\n // Infinite loop protection\n MAX_EXECUTIONS_PER_SECOND: 1e3,\n MAX_EXECUTIONS_PER_EFFECT: 100,\n // Batch processing limits to prevent blocking the main thread for too long\n MAX_EXECUTIONS_PER_FLUSH: 1e4,\n MAX_FLUSH_ITERATIONS: 1e3,\n MIN_FLUSH_ITERATIONS: 10,\n // Memory management\n BATCH_QUEUE_SHRINK_THRESHOLD: 1e3\n}, rt = {\n WARN_INFINITE_LOOP: !0,\n EFFECT_FREQUENCY_WINDOW: 1e3\n}, H = {\n MAX_ASYNC_RETRIES: 3,\n MAX_PROMISE_ID: Number.MAX_SAFE_INTEGER - 1\n}, L = 1073741823, W = typeof process < \"u\" && process.env && !1 || !1, ot = Object.freeze([]);\nclass D extends Error {\n constructor(t, e = null, s = !0) {\n super(t), this.cause = e, this.recoverable = s, this.name = \"AtomError\";\n }\n}\nclass f extends D {\n constructor(t, e = null) {\n super(t, e, !0), this.name = \"ComputedError\";\n }\n}\nclass I extends D {\n constructor(t, e = null) {\n super(t, e, !1), this.name = \"EffectError\";\n }\n}\nclass m extends D {\n constructor(t, e = null) {\n super(t, e, !1), this.name = \"SchedulerError\";\n }\n}\nconst ht = /* @__PURE__ */ Symbol(\"AtomEffect.DebugName\"), ct = /* @__PURE__ */ Symbol(\"AtomEffect.Type\"), x = /* @__PURE__ */ Symbol(\"AtomEffect.NoDefaultValue\"), F = {\n // Dev mode flag\n enabled: W,\n warnInfiniteLoop: rt.WARN_INFINITE_LOOP,\n warn(i, t) {\n },\n checkCircular(i, t) {\n if (i === t)\n throw new f(\"Direct circular dependency detected\");\n },\n attachDebugInfo(i, t, e) {\n },\n getDebugName: (i) => i?.[ht],\n getDebugType: (i) => i?.[ct]\n};\nlet ut = 1;\nconst _t = () => ut++;\nfunction K(i, t, e) {\n if (typeof t == \"function\") {\n const n = t;\n if (e.some((r) => r && r.fn === n)) return;\n e.push(new P(n, void 0));\n return;\n }\n if (\"addDependency\" in t) {\n t.addDependency(i);\n return;\n }\n const s = t;\n e.some((n) => n && n.sub === s) || e.push(new P(void 0, s));\n}\nfunction V(i, t, e) {\n const s = /* @__PURE__ */ new Map();\n t.forEach((n) => {\n n?.unsub && s.set(n.node, n.unsub);\n }), i.forEach((n) => {\n if (!n) return;\n const r = n.node, o = s.get(r);\n o !== void 0 ? (n.unsub = o, s.delete(r)) : (F.checkCircular(r, e), n.unsub = r.subscribe(e));\n }), s.forEach((n) => n());\n}\nclass v {\n constructor(t, e, s = void 0) {\n this.node = t, this.version = e, this.unsub = s;\n }\n}\nclass P {\n constructor(t, e) {\n this.fn = t, this.sub = e;\n }\n}\nconst h = {\n // Computed Errors\n COMPUTED_MUST_BE_FUNCTION: \"Computed target must be a function\",\n COMPUTED_ASYNC_PENDING_NO_DEFAULT: \"Async computation pending with no default value\",\n COMPUTED_COMPUTATION_FAILED: \"Computation execution failed\",\n COMPUTED_ASYNC_COMPUTATION_FAILED: \"Async computation execution failed\",\n COMPUTED_CIRCULAR_DEPENDENCY: \"Circular dependency detected\",\n COMPUTED_DISPOSED: \"Attempted to access disposed computed\",\n // Atom Errors\n ATOM_SUBSCRIBER_MUST_BE_FUNCTION: \"Subscriber must be a function or Subscriber object\",\n ATOM_INDIVIDUAL_SUBSCRIBER_FAILED: \"Subscriber execution failed\",\n // Effect Errors\n EFFECT_MUST_BE_FUNCTION: \"Effect target must be a function\",\n EFFECT_EXECUTION_FAILED: \"Effect execution failed\",\n EFFECT_CLEANUP_FAILED: \"Effect cleanup failed\",\n EFFECT_DISPOSED: \"Attempted to run disposed effect\",\n // Scheduler Errors\n SCHEDULER_FLUSH_OVERFLOW: (i, t) => `Maximum flush iterations (${i}) exceeded. ${t} jobs dropped. Possible infinite loop.`,\n // System / Debug\n CALLBACK_ERROR_IN_ERROR_HANDLER: \"Exception encountered in onError handler\",\n // Effect frequency\n EFFECT_FREQUENCY_LIMIT_EXCEEDED: \"Effect executed too frequently within 1 second. Suspected infinite loop.\",\n SCHEDULER_CALLBACK_MUST_BE_FUNCTION: \"Scheduler callback must be a function\",\n SCHEDULER_END_BATCH_WITHOUT_START: \"endBatch() called without matching startBatch(). Ignoring.\"\n};\nfunction S(i, t, e) {\n if (i instanceof D)\n return i;\n const s = i instanceof Error, n = s ? i.message : String(i), r = s ? i : void 0, O = `${s ? i.constructor.name : \"Unexpected error\"} (${e}): ${n}`;\n return new t(O, r);\n}\nclass J {\n constructor() {\n this.flags = 0, this.version = 0, this._lastSeenEpoch = -1, this.id = _t() & L;\n }\n}\nclass Z extends J {\n /**\n * Adds subscriber.\n */\n subscribe(t) {\n const e = typeof t == \"function\";\n if (!e && (!t || typeof t.execute != \"function\"))\n throw S(\n new TypeError(\"Invalid subscriber\"),\n D,\n h.ATOM_SUBSCRIBER_MUST_BE_FUNCTION\n );\n if (this._subscribers.some((r) => r ? e ? r.fn === t : r.sub === t : !1))\n return () => {\n };\n const s = new P(\n e ? t : void 0,\n e ? void 0 : t\n );\n return this._subscribers.push(s), () => this._unsubscribe(s);\n }\n _unsubscribe(t) {\n const e = this._subscribers, s = e.indexOf(t);\n if (s === -1) return;\n const n = e.pop();\n s < e.length && n && (e[s] = n);\n }\n subscriberCount() {\n return this._subscribers.length;\n }\n _notifySubscribers(t, e) {\n if (this._subscribers.length === 0) return;\n this._subscribers.slice(0).forEach((n) => {\n if (n)\n try {\n n.fn ? n.fn(t, e) : n.sub && n.sub.execute();\n } catch (r) {\n this._handleNotifyError(r);\n }\n });\n }\n _handleNotifyError(t) {\n console.error(S(t, D, h.ATOM_INDIVIDUAL_SUBSCRIBER_FAILED));\n }\n}\nlet k = 0;\nconst w = () => (k = k + 1 & L || 1, k), M = (i) => i + 1 & L;\nlet B = 0, R = !1, tt = 0;\nconst et = () => tt;\nfunction X() {\n return R ? !1 : (R = !0, tt = w(), B = 0, !0);\n}\nconst G = () => {\n R = !1;\n}, at = () => R ? ++B : 0;\nclass lt {\n constructor() {\n this._queueBuffer = [[], []], this._bufferIndex = 0, this._size = 0, this._epoch = 0, this._isProcessing = !1, this._isBatching = !1, this._isFlushingSync = !1, this._batchDepth = 0, this._batchQueue = [], this._batchQueueSize = 0, this._maxFlushIterations = d.MAX_FLUSH_ITERATIONS, this.onOverflow = null, this._boundRunLoop = this._runLoop.bind(this);\n }\n get phase() {\n return this._isProcessing || this._isFlushingSync ? 2 : this._isBatching ? 1 : 0;\n }\n get queueSize() {\n return this._size;\n }\n get isBatching() {\n return this._isBatching;\n }\n /**\n * Schedules job.\n */\n schedule(t) {\n if (t._nextEpoch !== this._epoch) {\n if (t._nextEpoch = this._epoch, this._isBatching || this._isFlushingSync) {\n this._batchQueue[this._batchQueueSize++] = t;\n return;\n }\n this._queueBuffer[this._bufferIndex][this._size++] = t, this._isProcessing || this._flush();\n }\n }\n /**\n * Triggers flush.\n */\n _flush() {\n this._isProcessing || this._size === 0 || (this._isProcessing = !0, queueMicrotask(this._boundRunLoop));\n }\n /**\n * Scheduler loop.\n */\n _runLoop() {\n try {\n if (this._size === 0) return;\n const t = X();\n this._drainQueue(), t && G();\n } finally {\n this._isProcessing = !1, this._size > 0 && !this._isBatching && this._flush();\n }\n }\n _flushSync() {\n this._isFlushingSync = !0;\n const t = X();\n try {\n this._mergeBatchQueue(), this._drainQueue();\n } finally {\n this._isFlushingSync = !1, t && G();\n }\n }\n _mergeBatchQueue() {\n if (this._batchQueueSize === 0) return;\n const t = ++this._epoch, e = this._batchQueue, s = this._queueBuffer[this._bufferIndex];\n let n = this._size;\n e.slice(0, this._batchQueueSize).forEach((r) => {\n r._nextEpoch !== t && (r._nextEpoch = t, s[n++] = r);\n }), this._size = n, this._batchQueueSize = 0, e.length > d.BATCH_QUEUE_SHRINK_THRESHOLD && (e.length = 0);\n }\n _drainQueue() {\n let t = 0;\n for (; this._size > 0; ) {\n if (++t > this._maxFlushIterations) {\n this._handleFlushOverflow();\n return;\n }\n this._processQueue(), this._mergeBatchQueue();\n }\n }\n _processQueue() {\n const t = this._bufferIndex, e = this._queueBuffer[t], s = this._size;\n this._bufferIndex = t ^ 1, this._size = 0, this._epoch++;\n for (let n = 0; n < s; n++)\n try {\n e[n]();\n } catch (r) {\n console.error(new m(\"Error occurred during scheduler execution\", r));\n }\n e.length = 0;\n }\n _handleFlushOverflow() {\n const t = this._size + this._batchQueueSize;\n if (console.error(\n new m(\n h.SCHEDULER_FLUSH_OVERFLOW(this._maxFlushIterations, t)\n )\n ), this._size = 0, this._queueBuffer[this._bufferIndex].length = 0, this._batchQueueSize = 0, this.onOverflow)\n try {\n this.onOverflow(t);\n } catch {\n }\n }\n startBatch() {\n this._batchDepth++, this._isBatching = !0;\n }\n endBatch() {\n this._batchDepth !== 0 && --this._batchDepth === 0 && (this._flushSync(), this._isBatching = !1);\n }\n setMaxFlushIterations(t) {\n if (t < d.MIN_FLUSH_ITERATIONS)\n throw new m(\n `Max flush iterations must be at least ${d.MIN_FLUSH_ITERATIONS}`\n );\n this._maxFlushIterations = t;\n }\n}\nconst T = new lt(), z = /* @__PURE__ */ Symbol.for(\"atom-effect/atom\"), st = /* @__PURE__ */ Symbol.for(\"atom-effect/computed\"), it = /* @__PURE__ */ Symbol.for(\"atom-effect/effect\"), _ = {\n /** Active listener. */\n current: null,\n /**\n * Executes in context.\n *\n * @param listener - The subscriber.\n * @param fn - The logic to execute.\n * @returns The result of `fn`.\n */\n run(i, t) {\n const e = this.current;\n this.current = i;\n try {\n return t();\n } finally {\n this.current = e;\n }\n }\n};\nfunction Ct(i) {\n const t = _.current;\n if (t === null) return i();\n _.current = null;\n try {\n return i();\n } finally {\n _.current = t;\n }\n}\nvar Q;\nclass ft extends Z {\n constructor(t, e) {\n super(), this._pendingOldValue = void 0, this._notifyTask = () => this._flushNotifications(), this._subscribers = [], this[Q] = !0, this._value = t, e && (this.flags |= a.SYNC), F.attachDebugInfo(this, \"atom\", this.id);\n }\n get value() {\n const t = _.current;\n return t && K(this, t, this._subscribers), this._value;\n }\n set value(t) {\n const e = this._value;\n if (Object.is(e, t)) return;\n this._value = t, this.version = M(this.version);\n const s = this.flags;\n if (!(this._subscribers.length === 0 || s & a.NOTIFICATION_SCHEDULED)) {\n if (this._pendingOldValue = e, this.flags = s | a.NOTIFICATION_SCHEDULED, s & a.SYNC && !T.isBatching) {\n this._flushNotifications();\n return;\n }\n T.schedule(this._notifyTask);\n }\n }\n /**\n * Triggers subscribers.\n */\n _flushNotifications() {\n const t = this.flags;\n if (!(t & a.NOTIFICATION_SCHEDULED) || t & a.DISPOSED)\n return;\n const e = this._pendingOldValue;\n this._pendingOldValue = void 0, this.flags &= -17, this._notifySubscribers(this._value, e);\n }\n peek() {\n return this._value;\n }\n dispose() {\n this.flags & a.DISPOSED || (this._subscribers.length = 0, this.flags |= a.DISPOSED, this._value = void 0, this._pendingOldValue = void 0);\n }\n [(Q = z, Symbol.dispose)]() {\n this.dispose();\n }\n}\nfunction gt(i, t = {}) {\n return new ft(i, t.sync ?? !1);\n}\nclass Et {\n /**\n * @param limit - Max unique arrays to hold (default: 50). Prevents the pool itself from consuming too much memory.\n * @param capacity - Max length of an array to accept (default: 256).\n * @param enableStats - Force-enable stats even in production (default: false).\n */\n constructor(t = 50, e = 256, s = !1) {\n this.limit = t, this.capacity = e, this.pool = [], this.stats = null, this.stats = s ? {\n acquired: 0,\n released: 0,\n rejected: { frozen: 0, tooLarge: 0, poolFull: 0 }\n } : null;\n }\n /**\n * Acquires array.\n */\n acquire() {\n return this.stats && this.stats.acquired++, this.pool.pop() ?? [];\n }\n /**\n * Releases array.\n *\n * @param arr - Array to release.\n * @param emptyConst - Optional empty constant.\n */\n release(t, e) {\n if (!(e && t === e)) {\n if (t.length > this.capacity) {\n this.stats && this.stats.rejected.tooLarge++;\n return;\n }\n if (this.pool.length >= this.limit) {\n this.stats && this.stats.rejected.poolFull++;\n return;\n }\n if (Object.isFrozen(t)) {\n this.stats && this.stats.rejected.frozen++;\n return;\n }\n t.length = 0, this.pool.push(t), this.stats && this.stats.released++;\n }\n }\n /**\n * Pool stats.\n */\n getStats() {\n if (!this.stats) return null;\n const { acquired: t, released: e, rejected: s } = this.stats, n = t - e - (s.frozen + s.tooLarge + s.poolFull);\n return {\n acquired: t,\n released: e,\n rejected: { ...s },\n leaked: n,\n poolSize: this.pool.length\n };\n }\n /**\n * Resets pool.\n */\n reset() {\n this.pool.length = 0, this.stats && (this.stats = {\n acquired: 0,\n released: 0,\n rejected: { frozen: 0, tooLarge: 0, poolFull: 0 }\n });\n }\n}\nconst c = Object.freeze(\n []\n), l = new Et();\nfunction Tt(i) {\n return i !== null && typeof i == \"object\" && z in i;\n}\nfunction Ot(i) {\n return i !== null && typeof i == \"object\" && st in i;\n}\nfunction bt(i) {\n return i !== null && typeof i == \"object\" && it in i;\n}\nfunction nt(i) {\n return i !== null && typeof i == \"object\" && typeof i.then == \"function\";\n}\nvar Y, q;\nconst { IDLE: A, DIRTY: p, PENDING: N, RESOLVED: E, REJECTED: g, HAS_ERROR: y, RECOMPUTING: C, DISPOSED: U, IS_COMPUTED: dt } = $;\nfunction pt(i) {\n return i & E ? b.RESOLVED : i & N ? b.PENDING : i & g ? b.REJECTED : b.IDLE;\n}\nclass It extends Z {\n constructor(t, e = {}) {\n if (typeof t != \"function\") throw new f(h.COMPUTED_MUST_BE_FUNCTION);\n super(), this[q] = !0, this[Y] = !0, this._error = null, this._promiseId = 0, this._subscribers = [], this._links = c, this._asyncStartAggregateVersion = 0, this._asyncRetryCount = 0, this._lastDriftEpoch = -1, this._trackEpoch = -1, this._trackLinks = c, this._trackCount = 0, this._value = void 0, this.flags = dt | p | A, this._equal = e.equal ?? Object.is, this._fn = t, this._defaultValue = \"defaultValue\" in e ? e.defaultValue : x, this._onError = e.onError ?? null;\n const s = e.maxAsyncRetries;\n if (this._maxAsyncRetries = (s ?? H.MAX_ASYNC_RETRIES) & L, F.attachDebugInfo(this, \"computed\", this.id), e.lazy === !1)\n try {\n this._recompute();\n } catch {\n }\n }\n _track() {\n const t = _.current;\n t && K(this, t, this._subscribers);\n }\n get value() {\n this._track();\n const t = this.flags;\n if ((t & (E | p | A)) === E)\n return this._value;\n if (t & U)\n throw new f(h.COMPUTED_DISPOSED);\n if (t & C) {\n if (this._defaultValue !== x) return this._defaultValue;\n throw new f(h.COMPUTED_CIRCULAR_DEPENDENCY);\n }\n if (t & (p | A) && (this._recompute(), this.flags & E))\n return this._value;\n const e = this._defaultValue, s = e !== x;\n if (this.flags & N) {\n if (s) return e;\n throw new f(h.COMPUTED_ASYNC_PENDING_NO_DEFAULT);\n }\n if (this.flags & g) {\n if (s) return e;\n throw this._error;\n }\n return this._value;\n }\n peek() {\n return this._value;\n }\n get state() {\n return this._track(), pt(this.flags);\n }\n get hasError() {\n return this._track(), this.flags & (g | y) ? !0 : this._links.some((t) => t?.node?.flags & y);\n }\n get isValid() {\n return !this.hasError;\n }\n get errors() {\n if (this._track(), !this.hasError) return ot;\n const t = [];\n return this._error && t.push(this._error), this._links.forEach((s) => {\n const n = s.node;\n n.flags & y && n.errors.forEach((o) => {\n o && !t.includes(o) && t.push(o);\n });\n }), Object.freeze(t);\n }\n get lastError() {\n return this._track(), this._error;\n }\n get isPending() {\n return this._track(), (this.flags & N) !== 0;\n }\n get isResolved() {\n return this._track(), (this.flags & E) !== 0;\n }\n invalidate() {\n this._markDirty();\n }\n dispose() {\n if (this.flags & U) return;\n const t = this._links;\n t !== c && (t.forEach((e) => e.unsub?.()), l.release(t), this._links = c), this._subscribers.length = 0, this.flags = U | p | A, this._error = null, this._value = void 0;\n }\n [(q = z, Y = st, Symbol.dispose)]() {\n this.dispose();\n }\n addDependency(t) {\n if (t._lastSeenEpoch !== this._trackEpoch) {\n if (t._lastSeenEpoch = this._trackEpoch, this._trackCount < this._trackLinks.length) {\n const e = this._trackLinks[this._trackCount];\n e.node = t, e.version = t.version;\n } else\n this._trackLinks.push(new v(t, t.version));\n this._trackCount++;\n }\n }\n _recompute() {\n if (this.flags & C) return;\n this.flags |= C;\n const t = this._links;\n this._trackEpoch = w(), this._trackLinks = l.acquire(), this._trackCount = 0;\n let e = !1;\n try {\n const s = _.run(this, this._fn);\n this._trackLinks.length = this._trackCount, V(this._trackLinks, t, this), this._links = this._trackLinks, e = !0, nt(s) ? this._handleAsyncComputation(s) : this._finalizeResolution(s);\n } catch (s) {\n if (!e)\n try {\n this._trackLinks.length = this._trackCount, V(this._trackLinks, t, this), this._links = this._trackLinks, e = !0;\n } catch {\n }\n this._handleError(s, h.COMPUTED_COMPUTATION_FAILED, !0);\n } finally {\n e && t !== c ? l.release(t) : e || l.release(this._trackLinks), this._trackEpoch = -1, this._trackLinks = c, this._trackCount = 0, this.flags &= ~C;\n }\n }\n _handleAsyncComputation(t) {\n this.flags = (this.flags | N) & -217, this._notifySubscribers(void 0, void 0), this._asyncStartAggregateVersion = this._captureVersionSnapshot(), this._asyncRetryCount = 0, this._promiseId = (this._promiseId + 1) % H.MAX_PROMISE_ID;\n const e = this._promiseId;\n t.then(\n (s) => {\n if (e === this._promiseId) {\n if (this._captureVersionSnapshot() !== this._asyncStartAggregateVersion) {\n const n = et();\n return this._lastDriftEpoch !== n && (this._lastDriftEpoch = n, this._asyncRetryCount = 0), this._asyncRetryCount++ < this._maxAsyncRetries ? this._markDirty() : this._handleError(\n new f(\n `Async drift threshold exceeded after ${this._maxAsyncRetries} retries.`\n ),\n h.COMPUTED_ASYNC_COMPUTATION_FAILED\n );\n }\n this._finalizeResolution(s), this._notifySubscribers(s, void 0);\n }\n },\n (s) => e === this._promiseId && this._handleError(s, h.COMPUTED_ASYNC_COMPUTATION_FAILED)\n );\n }\n _captureVersionSnapshot() {\n let t = 0;\n const e = this._links;\n for (let s = 0, n = e.length; s < n; s++)\n t = (t << 5) - t + e[s].node.version | 0;\n return t;\n }\n _handleError(t, e, s = !1) {\n const n = S(t, f, e);\n if (!s && !(this.flags & g) && (this.version = M(this.version)), this._error = n, this.flags = this.flags & -121 | g | y, this._onError)\n try {\n this._onError(n);\n } catch (r) {\n console.error(h.CALLBACK_ERROR_IN_ERROR_HANDLER, r);\n }\n if (s) throw n;\n this._notifySubscribers(void 0, void 0);\n }\n _finalizeResolution(t) {\n (!(this.flags & E) || !this._equal(this._value, t)) && (this.version = M(this.version)), this._value = t, this._error = null, this.flags = (this.flags | E) & -697;\n }\n execute() {\n this._markDirty();\n }\n /** @internal */\n _markDirty() {\n this.flags & (C | p) || (this.flags |= p, this._notifySubscribers(void 0, void 0));\n }\n}\nfunction At(i, t = {}) {\n return new It(i, t);\n}\nvar j;\nclass St extends J {\n constructor(t, e = {}) {\n super(), this[j] = !0, this._cleanup = null, this._links = c, this._nextLinks = null, this._prevLinks = c, this._currentEpoch = -1, this._lastFlushEpoch = -1, this._executionsInEpoch = 0, this._executionCount = 0, this._windowStart = 0, this._windowCount = 0, this._execId = 0, this._fn = t, this._onError = e.onError ?? null, this._sync = e.sync ?? !1, this._maxExecutions = e.maxExecutionsPerSecond ?? d.MAX_EXECUTIONS_PER_SECOND, this._maxExecutionsPerFlush = e.maxExecutionsPerFlush ?? d.MAX_EXECUTIONS_PER_EFFECT, this._sync ? (this._executeTask = void 0, this._notifyCallback = () => this.execute()) : (this._executeTask = () => this.execute(), this._notifyCallback = () => T.schedule(this._executeTask)), F.attachDebugInfo(this, \"effect\", this.id);\n }\n run() {\n if (this.flags & u.DISPOSED)\n throw new I(h.EFFECT_DISPOSED);\n this.execute(!0);\n }\n dispose() {\n this.flags & u.DISPOSED || (this.flags |= u.DISPOSED, this._execCleanup(), this._unsubLinks(this._links), this._links !== c && l.release(this._links), this._links = c, this._prevLinks = c);\n }\n [(j = it, Symbol.dispose)]() {\n this.dispose();\n }\n addDependency(t) {\n if (!(this.flags & u.EXECUTING)) return;\n const e = this._currentEpoch;\n if (t._lastSeenEpoch === e) return;\n t._lastSeenEpoch = e;\n const s = this._nextLinks, n = this._prevLinks, r = n.findIndex((o) => o && o.node === t && o.unsub);\n if (r !== -1) {\n const o = n[r];\n o.version = t.version, s.push(o), n[r] = null;\n return;\n }\n try {\n const o = t.subscribe(this._notifyCallback);\n s.push(new v(t, t.version, o));\n } catch (o) {\n const O = S(o, I, h.EFFECT_EXECUTION_FAILED);\n if (console.error(O), this._onError)\n try {\n this._onError(O);\n } catch {\n }\n s.push(new v(t, t.version, void 0));\n }\n }\n /**\n * Executes effect with tracking.\n */\n execute(t = !1) {\n if (this.flags & (u.DISPOSED | u.EXECUTING) || !t && this._links.length > 0 && !this._isDirty()) return;\n this._checkInfiniteLoops(), this.flags |= u.EXECUTING, this._execCleanup(), this._prevLinks = this._links;\n const e = l.acquire();\n this._nextLinks = e, this._currentEpoch = w();\n let s = !1;\n try {\n const n = _.run(this, this._fn);\n this._links = e, s = !0, nt(n) ? this._handleAsyncResult(n) : this._cleanup = typeof n == \"function\" ? n : null;\n } catch (n) {\n this._links = e, s = !0, this._handleExecutionError(n), this._cleanup = null;\n } finally {\n this._finalizeDependencies(s, this._prevLinks, e), this.flags &= -9;\n }\n }\n _handleAsyncResult(t) {\n const e = ++this._execId;\n t.then(\n (s) => {\n if (e !== this._execId || this.flags & u.DISPOSED) {\n if (typeof s == \"function\")\n try {\n s();\n } catch (n) {\n this._handleExecutionError(n, h.EFFECT_CLEANUP_FAILED);\n }\n return;\n }\n typeof s == \"function\" && (this._cleanup = s);\n },\n (s) => e === this._execId && this._handleExecutionError(s)\n );\n }\n _finalizeDependencies(t, e, s) {\n this._nextLinks = null, this._prevLinks = c, t ? (e.forEach((n) => n?.unsub?.()), e !== c && l.release(e)) : (this._unsubLinks(s), l.release(s));\n }\n _unsubLinks(t) {\n t.forEach((e) => e?.unsub?.());\n }\n _isDirty() {\n const t = this._links, e = _.current;\n _.current = null;\n try {\n return t.some((s) => {\n const n = s.node;\n if (n.flags & $.IS_COMPUTED)\n try {\n n.value;\n } catch {\n return !0;\n }\n return n.version !== s.version;\n });\n } finally {\n _.current = e;\n }\n }\n _execCleanup() {\n if (this._cleanup) {\n try {\n this._cleanup();\n } catch (t) {\n this._handleExecutionError(t, h.EFFECT_CLEANUP_FAILED);\n }\n this._cleanup = null;\n }\n }\n _checkInfiniteLoops() {\n const t = et();\n this._lastFlushEpoch !== t && (this._lastFlushEpoch = t, this._executionsInEpoch = 0), ++this._executionsInEpoch > this._maxExecutionsPerFlush && this._throwInfiniteLoopError(\"per-effect\"), at() > d.MAX_EXECUTIONS_PER_FLUSH && this._throwInfiniteLoopError(\"global\"), this._executionCount++;\n }\n get isDisposed() {\n return (this.flags & u.DISPOSED) !== 0;\n }\n get executionCount() {\n return this._executionCount;\n }\n get isExecuting() {\n return (this.flags & u.EXECUTING) !== 0;\n }\n _throwInfiniteLoopError(t) {\n const e = new I(\n `Infinite loop detected (${t}): effect executed ${this._executionsInEpoch} times in current flush. Total executions in flush: ${B}`\n );\n throw this.dispose(), console.error(e), e;\n }\n _handleExecutionError(t, e = h.EFFECT_EXECUTION_FAILED) {\n const s = S(t, I, e);\n if (console.error(s), this._onError)\n try {\n this._onError(s);\n } catch (n) {\n console.error(S(n, I, h.CALLBACK_ERROR_IN_ERROR_HANDLER));\n }\n }\n}\nfunction yt(i, t = {}) {\n if (typeof i != \"function\")\n throw new I(h.EFFECT_MUST_BE_FUNCTION);\n const e = new St(i, t);\n return e.execute(), e;\n}\nfunction Nt(i) {\n if (typeof i != \"function\")\n throw new TypeError(\"Batch callback must be a function\");\n T.startBatch();\n try {\n return i();\n } finally {\n T.endBatch();\n }\n}\nexport {\n z as ATOM_BRAND,\n b as AsyncState,\n D as AtomError,\n st as COMPUTED_BRAND,\n f as ComputedError,\n rt as DEBUG_CONFIG,\n F as DEBUG_RUNTIME,\n it as EFFECT_BRAND,\n I as EffectError,\n Dt as POOL_CONFIG,\n d as SCHEDULER_CONFIG,\n m as SchedulerError,\n gt as atom,\n Nt as batch,\n At as computed,\n yt as effect,\n Tt as isAtom,\n Ot as isComputed,\n bt as isEffect,\n T as scheduler,\n Ct as untracked\n};\n//# sourceMappingURL=index.mjs.map\n","/**\n * Constants for atom-effect-jquery\n */\n\nimport type { RouteConfig } from './types';\n\n// ============================================================================\n// Log Prefixes\n// ============================================================================\n\n/**\n * Log prefixes keyed by subsystem.\n * Each prefix names the specific subsystem that emitted the message so that\n * console output is unambiguous regardless of which binding triggered it.\n */\nexport const LOG_PREFIXES = {\n /** Used by the SPA router ($.route). */\n ROUTE: '[atom-route]',\n /** Used by all reactive binding helpers (bindText, bindCss, bindAttr, …). */\n BINDING: '[atom-binding]',\n /** Used by atomList reactive list rendering. */\n LIST: '[atom-list]',\n /** Used by mount/unmount lifecycle helpers. */\n MOUNT: '[atom-mount]',\n} as const;\n\n// ============================================================================\n// Route Defaults\n// ============================================================================\n\n/**\n * Subset of RouteConfig fields that have default values.\n * Extracted as a named type so the annotation on ROUTE_DEFAULTS stays concise.\n * Any change to the relevant RouteConfig fields will surface here at compile time.\n */\ntype RouteDefaults = Readonly<\n Required<Pick<RouteConfig, 'mode' | 'basePath' | 'autoBindLinks' | 'activeClass'>>\n>;\n\n/**\n * Default values for RouteConfig optional fields.\n * `Object.freeze` provides runtime immutability; the `RouteDefaults` annotation\n * ensures structural compatibility with RouteConfig is verified at compile time.\n */\nexport const ROUTE_DEFAULTS: RouteDefaults = Object.freeze({\n mode: 'hash',\n basePath: '',\n autoBindLinks: false,\n activeClass: 'active',\n});\n\n// ============================================================================\n// Input Defaults\n// ============================================================================\n\n/**\n * Default values for input binding options.\n * DEBOUNCE is intentionally omitted: 0 is self-documenting at the call site\n * (`options.debounce ?? 0`) and extracting it as a named constant adds\n * indirection without clarity.\n * Additional defaults may be added here as the input binding API grows.\n */\nexport const INPUT_DEFAULTS = {\n EVENT: 'input',\n} as const;\n\n// ============================================================================\n// Dangerous DOM Properties\n// ============================================================================\n\n/**\n * Input element tag names accepted by `bindVal`.\n * Stored as a Set for O(1) lookup — consistent with the DANGEROUS_PROPS pattern.\n */\nexport const VALID_INPUT_TAGS: ReadonlySet<string> = new Set(['input', 'select', 'textarea']);\n\n/**\n * DOM properties blocked by `bindProp` to prevent HTML injection and\n * prototype pollution attacks.\n *\n * Stored as a `ReadonlySet` for O(1) lookup and runtime immutability.\n * `as const` alone does not freeze objects at runtime.\n *\n * Blocked categories:\n * - Raw HTML sinks : innerHTML, outerHTML, srcdoc\n * - Prototype access: __proto__, constructor, prototype\n *\n * Note: `src` is intentionally NOT blocked here. `bindProp` targets DOM\n * properties on arbitrary elements; blocking `src` would prevent legitimate\n * use on `<img>`, `<audio>`, `<video>`, etc. URL-bearing *attributes* (including\n * `src` on `<script>`/`<iframe>`) are guarded separately by `bindAttr` via\n * `isDangerousUrl()` in utils.ts.\n */\nexport const DANGEROUS_PROPS: ReadonlySet<string> = new Set([\n 'innerHTML',\n 'outerHTML',\n 'srcdoc',\n '__proto__',\n 'constructor',\n 'prototype',\n]);\n\n// ============================================================================\n// Error Messages\n// ============================================================================\n\n/**\n * Canonical error and warning messages for all subsystems.\n *\n * Every entry is a zero-or-one-argument function so consumers call them\n * uniformly — `ERROR_MESSAGES.X(arg)` — with no special-casing for\n * parameter-free messages. The `as const` here makes the function references\n * themselves readonly (non-reassignable); it does not narrow the string\n * return types.\n */\nexport const ERROR_MESSAGES = {\n ROUTE_NOT_FOUND: (name: string) => `Route \"${name}\" not found and no notFound route configured`,\n TEMPLATE_NOT_FOUND: (selector: string) => `Template \"${selector}\" not found`,\n TARGET_NOT_FOUND: (selector: string) => `Target element \"${selector}\" not found`,\n MALFORMED_URI: (raw: string) => `Malformed URI component: ${raw}`,\n /** Emitted when sanitizeHtml modifies the input. Prefixed at call site with LOG_PREFIXES.BINDING or LIST to identify the originating subsystem. */\n UNSAFE_CONTENT: () => 'Unsafe content neutralized during sanitization.',\n /** Emitted by bindCss when a CSS style property value contains a dangerous protocol. */\n BLOCKED_DANGEROUS_CSS_VALUE: (prop: string) =>\n `Blocked dangerous value in CSS style property \"${prop}\".`,\n BLOCKED_EVENT_HANDLER: (name: string) =>\n `Blocked setting dangerous event handler attribute \"${name}\".`,\n BLOCKED_PROTOCOL: (name: string) => `Blocked dangerous protocol in \"${name}\" attribute.`,\n BLOCKED_DANGEROUS_PROP: (name: string) =>\n `Blocked setting dangerous property \"${name}\". Use html binding for sanitized HTML.`,\n INVALID_INPUT_ELEMENT: (tagName: string) => `Val binding used on non-input element <${tagName}>.`,\n MISSING_SOURCE: (method: string) => `[${method}] source is required when prop/name is a string.`,\n MISSING_CONDITION: (method: string) =>\n `[${method}] condition is required when className is a string.`,\n DUPLICATE_KEY: (key: string | number, index: number) =>\n `Duplicate key \"${key}\" at index ${index}.`,\n UPDATER_ERROR: (debugType: string) => `Updater threw in binding \"${debugType}\"`,\n EFFECT_DISPOSE_ERROR: () => 'Effect dispose error',\n BINDING_CLEANUP_ERROR: () => 'Binding cleanup error',\n PARSE_ERROR: () => 'parse() threw during DOM→Atom sync',\n MOUNT_ERROR: () => 'Mount error',\n MOUNT_CLEANUP_ERROR: () => 'Cleanup error',\n} as const;\n","import type { ReadonlyAtom } from '@but212/atom-effect';\nimport { isAtom } from '@but212/atom-effect';\nimport type { ReactiveValue, RenderRoute, RouteDefinition, TemplateRoute } from './types';\n\n/**\n * Checks if a given value is a reactive node (Atom or Computed).\n *\n * `isAtom` returns `true` for both plain atoms and computed atoms because\n * `ComputedAtomImpl` carries `ATOM_BRAND` in addition to `COMPUTED_BRAND`.\n * A separate `isComputed` check would therefore be redundant.\n */\nexport function isReactive(value: unknown): value is ReadonlyAtom<unknown> {\n return isAtom(value);\n}\n\n/**\n * Extracts the underlying raw value from a ReactiveValue.\n */\nexport function getValue<T>(source: ReactiveValue<T>): T {\n return isReactive(source) ? (source as ReadonlyAtom<T>).value : (source as T);\n}\n\n// ============================================================================\n// DOM helpers\n// ============================================================================\n\n/**\n * Generates a CSS selector string for a DOM element, suitable for debug output.\n * Returns `tagName#id` when an id is present, otherwise `tagName.class1.class2…`.\n */\nexport function getSelector(el: Element): string {\n const tagName = el.tagName.toLowerCase();\n if (el.id) return `${tagName}#${el.id}`;\n\n const list = el.classList;\n const len = list.length;\n if (len === 0) return tagName;\n\n let selector = tagName;\n for (let i = 0; i < len; i++) {\n selector += `.${list[i]!}`;\n }\n return selector;\n}\n\n// ============================================================================\n// HTML sanitization\n// ============================================================================\n\nconst URL_ATTRS = new Set([\n 'href',\n 'src',\n 'action',\n 'formaction',\n 'xlink:href',\n 'data',\n 'poster',\n 'srcset',\n 'background',\n 'cite',\n 'longdesc',\n 'profile',\n 'usemap',\n 'classid',\n 'codebase',\n]);\n\n/** cached hasOwnProperty for safe checks */\nconst hasOwn = Object.prototype.hasOwnProperty;\n\nconst DANGEROUS_PROTOCOL_RE = /^\\s*(?:javascript|vbscript)\\s*:/i;\n\nconst DANGEROUS_CSS_RE =\n // biome-ignore lint/suspicious/noControlCharactersInRegex: Intentionally matching control characters for XSS sanitization\n /(?:expression\\s*\\(|behavior\\s*:|(?:\\\\[0-9a-f]{1,6}\\s*|[\\s\\x00-\\x20/'\"])*(?:j\\s*a\\s*v\\s*a\\s*s\\s*c\\s*r\\s*i\\s*p\\s*t|v\\s*b\\s*s\\s*c\\s*r\\s*i\\s*p\\s*t|d\\s*a\\s*t\\s*a)\\s*:(?!image\\/))/i;\n\n/** Module-level constant — avoids recreating the RegExp on every call. */\nconst DANGEROUS_CSS_URL_RE = /url\\s*\\(\\s*(?:[\"']?\\s*)?(?:javascript|vbscript)\\s*:/i;\n\n// Pre-compiled regexes for sanitizeHtml to avoid reallocation\n// biome-ignore lint/suspicious/noControlCharactersInRegex: Intentionally matching control characters\nconst STRIP_CTRL_RE = /[\\x00-\\x08\\x0b\\x0c\\x0e-\\x1f\\x7f]/g;\nconst STRIP_XML_RE = /<\\?[\\s\\S]*?\\?>/g;\nconst DANGEROUS_TAG_RE =\n /(<(script|iframe|object|embed|base|meta|applet|noscript|form|style|link)\\b[^>]*>([\\s\\S]*?)<\\/\\2>|<(script|iframe|object|embed|base|meta|applet|noscript|form|style|link)\\b[^>]*\\/?>)/gi;\nconst DANGEROUS_PROTOCOL_GLOBAL_RE =\n /(j\\s*a\\s*v\\s*a\\s*s\\s*c\\s*r\\s*i\\s*p\\s*t|v\\s*b\\s*s\\s*c\\s*r\\s*i\\s*p\\s*t)\\s*:/gi;\nconst DANGEROUS_DATA_URI_RE =\n /data\\s*:\\s*(?:text\\/(?:html|javascript|vbscript|xml)|application\\/(?:javascript|xhtml\\+xml|xml|x-shockwave-flash)|image\\/svg\\+xml)/gi;\nconst UNSAFE_ATTR_RE = /\\bon\\w+\\s*=/gim;\nconst DANGEROUS_CSS_GLOBAL_RE = new RegExp(DANGEROUS_CSS_RE.source, 'gim');\n\n// --- Helpers ---\n\n/**\n * HTML sanitization for XSS mitigation using regex-based filtering.\n *\n * Faster than DOMParser but relies on pattern matching.\n * Neutralizes dangerous attributes (on*, protocols) instead of removing them entirely.\n *\n * **Note:** This is a best-effort defense layer, not a full-featured sanitizer.\n * For user-controlled rich text, prefer a dedicated library such as DOMPurify.\n */\nexport function sanitizeHtml(html: string | null | undefined): string {\n let safe = String(html ?? '');\n\n // 0. Pre-process: Remove null bytes and control characters (bypass vectors)\n // These are often used to bypass regex filters while browsers ignore them\n safe = safe.replace(STRIP_CTRL_RE, '');\n\n // 1. Remove dangerous tags entirely (content included or tag stripped)\n // Lightweight first pass — DOMPurify handles the full sanitization.\n // Note: svg/math are NOT removed — they have legitimate uses (icons, equations).\n // Their event handlers (on*) are already neutralized in step 3.\n // Also remove processing instructions <? ... ?> which can be abused in some contexts\n safe = safe.replace(STRIP_XML_RE, '');\n\n // Loop tag removal to prevent nested reassembly bypass (e.g. \"<scr<script>ipt>\")\n let prev: string;\n do {\n prev = safe;\n safe = safe.replace(DANGEROUS_TAG_RE, '');\n } while (safe !== prev);\n\n // 2. Neutralize dangerous protocols (javascript:, vbscript:)\n // Simple whitespace-tolerant regex. Entity-based obfuscation is left to DOMPurify.\n safe = safe.replace(DANGEROUS_PROTOCOL_GLOBAL_RE, 'data-unsafe-protocol:');\n\n // Separately handle dangerous data URIs (e.g. text/html, base64 encoded scripts)\n // Allows common inline images (data:image/...) BUT blocks SVG (can contain scripts) and XML.\n safe = safe.replace(DANGEROUS_DATA_URI_RE, 'data-unsafe-protocol:');\n\n // 3. Neutralize event handlers (on* attributes)\n // Replaces \"onclick=\" with \"data-unsafe-attr=\"\n safe = safe.replace(UNSAFE_ATTR_RE, 'data-unsafe-attr=');\n\n // 4. Neutralize CSS expressions (IE legacy but dangerous) and behavior\n safe = safe.replace(DANGEROUS_CSS_GLOBAL_RE, 'data-unsafe-css:');\n\n return safe;\n}\n\n// ============================================================================\n// Security guards (used by binding layer)\n// ============================================================================\n\n/**\n * Returns `true` when `attrName` is a URL-bearing attribute and `value`\n * contains a `javascript:` or `vbscript:` protocol.\n * Used by `bindAttr` to guard URL-bearing attributes.\n */\nexport function isDangerousUrl(attrName: string, value: string): boolean {\n if (!URL_ATTRS.has(attrName.toLowerCase())) return false;\n return DANGEROUS_PROTOCOL_RE.test(value);\n}\n\n/**\n * Returns `true` when a CSS property value contains a dangerous protocol\n * inside a `url()` function (e.g. `background-image: url(\"javascript:…\")`).\n */\nexport function isDangerousCssValue(value: string): boolean {\n // Fast pre-check before running the full regex\n if (!value.toLowerCase().includes('url(')) return false;\n return DANGEROUS_CSS_URL_RE.test(value);\n}\n\n// ============================================================================\n// Route type guards\n// ============================================================================\n\n/** Narrows a `RouteDefinition` to `TemplateRoute`. */\nexport function isTemplateRoute(r: RouteDefinition): r is TemplateRoute {\n return typeof (r as TemplateRoute).template === 'string';\n}\n\n/** Narrows a `RouteDefinition` to `RenderRoute`. */\nexport function isRenderRoute(r: RouteDefinition): r is RenderRoute {\n return typeof (r as RenderRoute).render === 'function';\n}\n\n// ============================================================================\n// General utilities\n// ============================================================================\n\n/**\n * Shallow equality check for plain objects.\n * Returns `true` if both objects have the same own keys with identical (`===`) values.\n */\nexport function shallowEqual(a: unknown, b: unknown): boolean {\n if (a === b) return true;\n if (a === null || b === null || typeof a !== 'object' || typeof b !== 'object') return false;\n\n const keysA = Object.keys(a);\n const keysB = Object.keys(b);\n if (keysA.length !== keysB.length) return false;\n\n const objA = a as Record<string, unknown>;\n const objB = b as Record<string, unknown>;\n\n for (let i = 0; i < keysA.length; i++) {\n const key = keysA[i]!;\n if (!hasOwn.call(objB, key) || objA[key] !== objB[key]) {\n return false;\n }\n }\n return true;\n}\n\n/**\n * Computes the Longest Increasing Subsequence (LIS) of old-position indices.\n *\n * Used by `atomList` to minimise DOM moves during reconciliation: items whose\n * old-position index appears in the LIS are already in the correct relative\n * order and do not need to be moved.\n *\n * Sentinel value: `-1` means \"not present in the old list\" and is skipped.\n *\n * Time complexity: O(N log N). Space complexity: O(N).\n */\nexport function getLIS(arr: Int32Array | number[]): Int32Array {\n const len = arr.length;\n if (len === 0) return new Int32Array(0);\n\n // predecessors[i] records the index in `arr` that preceded i in the LIS,\n // or -1 if i was the first element. Initialised to -1 so unvisited slots\n // are distinguishable from a valid predecessor at index 0.\n const predecessors = new Int32Array(len).fill(-1);\n const result = new Int32Array(len);\n let resultLen = 0;\n\n for (let i = 0; i < len; i++) {\n const val = arr[i];\n // `undefined` can only occur for a plain `number[]` under noUncheckedIndexedAccess;\n // Int32Array always returns a number. Both cases are treated as absent.\n if (val === undefined || val === -1) continue;\n\n const lastIdx = resultLen > 0 ? result[resultLen - 1] : undefined;\n if (resultLen === 0 || (lastIdx !== undefined && (arr[lastIdx] ?? -1) < val)) {\n predecessors[i] = lastIdx ?? -1;\n result[resultLen++] = i;\n continue;\n }\n\n // Binary search for the leftmost result position whose value >= val\n let left = 0;\n let right = resultLen - 1;\n while (left < right) {\n const mid = (left + right) >>> 1;\n const midIdx = result[mid];\n if (midIdx !== undefined && (arr[midIdx] ?? -1) < val) {\n left = mid + 1;\n } else {\n right = mid;\n }\n }\n\n const leftIdx = result[left];\n if (leftIdx !== undefined && val < (arr[leftIdx] ?? Number.MAX_SAFE_INTEGER)) {\n if (left > 0) {\n predecessors[i] = result[left - 1] ?? -1;\n }\n result[left] = i;\n }\n }\n\n // Back-track through predecessors to reconstruct the LIS indices.\n const lis = new Int32Array(resultLen);\n if (resultLen > 0) {\n let curr: number | undefined = result[resultLen - 1];\n for (let i = resultLen - 1; i >= 0 && curr !== undefined && curr !== -1; i--) {\n lis[i] = curr;\n curr = predecessors[curr];\n }\n }\n\n return lis;\n}\n","/**\n * Debug Mode\n *\n * When $.atom.debug = true is enabled:\n * 1. Logs state changes to the console.\n * 2. Visually highlights DOM updates (red border flash).\n *\n * Debug mode can be enabled in two ways:\n * 1. Build-time: VITE_ATOM_DEBUG=true (opt-in via env var)\n * 2. Runtime: $.atom.debug = true or window.__ATOM_DEBUG__ = true\n *\n * NOTE: debug mode is NOT enabled automatically in DEV builds to avoid\n * polluting the console without explicit opt-in.\n */\n\nimport { LOG_PREFIXES } from './constants';\nimport { getSelector } from './utils';\n\n// ============================================================================\n// Timing constants — HIGHLIGHT_TRANSITION is derived from HIGHLIGHT_DURATION_MS\n// so the two values stay in sync automatically.\n// ============================================================================\n\n/** Duration (ms) of the highlight flash animation. */\nconst HIGHLIGHT_DURATION_MS = 600;\n\n/** CSS transition duration derived from HIGHLIGHT_DURATION_MS. */\nconst HIGHLIGHT_TRANSITION = `${HIGHLIGHT_DURATION_MS / 1000}s`;\n\n// ============================================================================\n// Initial state\n// ============================================================================\n\n/**\n * Determines the initial debug state.\n * Priority: window.__ATOM_DEBUG__ > explicit VITE_ATOM_DEBUG env var.\n * DEV mode alone does NOT enable debug to avoid silent console pollution.\n */\nfunction getInitialDebugState(): boolean {\n if (typeof window !== 'undefined') {\n const flag = (window as Window & { __ATOM_DEBUG__?: boolean }).__ATOM_DEBUG__;\n if (typeof flag === 'boolean') return flag;\n }\n\n // Vite inlines import.meta.env at build time; guard for non-Vite environments\n // (e.g. Jest/Node) where import.meta.env may be undefined.\n if (import.meta.env?.VITE_ATOM_DEBUG === 'true') {\n return true;\n }\n\n return false;\n}\n\nlet debugEnabled = getInitialDebugState();\n\n// ============================================================================\n// Debug object\n// ============================================================================\n\nexport const debug = {\n get enabled() {\n return debugEnabled;\n },\n set enabled(value: boolean) {\n debugEnabled = value;\n },\n\n /**\n * Logs a message only when debug mode is active.\n */\n log(type: string, ...args: unknown[]) {\n if (debugEnabled) {\n console.log(`${LOG_PREFIXES.MOUNT} ${type}:`, ...args);\n }\n },\n\n /**\n * Logs an atom value change only when debug mode is active.\n */\n atomChanged(name: string | undefined, oldVal: unknown, newVal: unknown) {\n if (debugEnabled) {\n console.log(\n `${LOG_PREFIXES.MOUNT} Atom \"${name ?? 'anonymous'}\" changed:`,\n oldVal,\n '→',\n newVal\n );\n }\n },\n\n /**\n * Logs a DOM update and triggers a visual highlight flash.\n * Only active when debug mode is enabled.\n *\n * @param target - The element or jQuery wrapper that was updated.\n * @param type - The binding type (e.g. 'text', 'checked', 'attr.href').\n * @param value - The new value that was applied.\n */\n domUpdated(target: Element | JQuery, type: string, value: unknown) {\n if (!debugEnabled) return;\n\n const el: Element | undefined =\n target instanceof Element ? target : (target[0] as Element | undefined);\n if (!(el instanceof HTMLElement)) return;\n\n console.log(`${LOG_PREFIXES.MOUNT} DOM updated: ${getSelector(el)}.${type} =`, value);\n highlightElement(el);\n },\n\n /**\n * Logs a cleanup event only when debug mode is active.\n */\n cleanup(selector: string) {\n if (debugEnabled) {\n console.log(`${LOG_PREFIXES.MOUNT} Cleanup: ${selector}`);\n }\n },\n\n /**\n * Unconditional warning for runtime errors and unexpected states.\n * Not gated by debugEnabled — these are always surfaced regardless of\n * debug mode because they indicate real problems (e.g. dispose failures,\n * missing route targets, pushState security errors).\n *\n * `prefix` is the subsystem tag (e.g. `LOG_PREFIXES.ROUTE`) so that the\n * originating subsystem appears in the log rather than the generic MOUNT tag.\n * Pass an empty string to emit a prefix-free message.\n */\n warn(prefix: string, message: string, ...rest: unknown[]) {\n console.warn(`${prefix} ${message}`, ...rest);\n },\n\n /**\n * Unconditional error for binding failures.\n * Not gated by debugEnabled — binding errors are always surfaced because\n * they indicate a broken updater that silently stopped applying values.\n */\n error(prefix: string, message: string, cause: unknown) {\n console.error(`${prefix} ${message}`, cause);\n },\n};\n\n// ============================================================================\n// Visual highlight\n// ============================================================================\n\nconst HIGHLIGHT_CLASS = 'atom-debug-highlight';\nconst HIGHLIGHT_STYLE_ATTR = 'data-atom-debug';\n\n/**\n * Injects the highlight CSS once per document lifetime.\n * Uses a WeakRef so that JSDOM test resets naturally invalidate the cache:\n * when the old document is GC'd the WeakRef deref returns undefined and\n * the style is re-injected into the fresh document — no module-level boolean\n * flag needed.\n */\nlet _highlightStyleRef: WeakRef<HTMLStyleElement> | undefined;\nfunction injectHighlightStyle(): void {\n if (_highlightStyleRef?.deref()?.isConnected) return;\n const style = document.createElement('style');\n style.setAttribute(HIGHLIGHT_STYLE_ATTR, '');\n style.textContent =\n `.${HIGHLIGHT_CLASS}{` +\n `outline:2px solid rgba(255,68,68,0.8);` +\n `outline-offset:1px;` +\n `transition:outline ${HIGHLIGHT_TRANSITION} ease-out` +\n `}`;\n document.head.appendChild(style);\n _highlightStyleRef = new WeakRef(style);\n}\n\n// Tracks the pending setTimeout handle per element.\n// Stored outside rAF so that rapid successive calls can cancel a previously\n// scheduled timer even before the rAF callback has fired.\nconst highlightTimers = new WeakMap<HTMLElement, ReturnType<typeof setTimeout>>();\n\n// Tracks pending rAF IDs so that a second call before the first rAF fires\n// can cancel it, preventing duplicate classList.add calls.\nconst highlightRafs = new WeakMap<HTMLElement, ReturnType<typeof requestAnimationFrame>>();\n\n/**\n * Flashes a red outline on an element to indicate a reactive DOM update.\n * Accepts only HTMLElement — callers are responsible for unwrapping JQuery.\n *\n * Handles rapid successive calls correctly:\n * - Cancels any pending rAF before scheduling a new one.\n * - Cancels any pending timeout before scheduling a new one.\n */\nfunction highlightElement(el: HTMLElement): void {\n if (!el.isConnected) return;\n\n injectHighlightStyle();\n\n // Cancel pending rAF to avoid duplicate classList.add.\n // .set() below overwrites the entry, so .delete() here is not needed.\n const existingRaf = highlightRafs.get(el);\n if (existingRaf !== undefined) {\n cancelAnimationFrame(existingRaf);\n }\n\n // Cancel pending timeout so the class is not prematurely removed.\n // .set() in the rAF callback overwrites the entry, so .delete() here is not needed.\n const existingTimer = highlightTimers.get(el);\n if (existingTimer !== undefined) {\n clearTimeout(existingTimer);\n }\n\n const rafId = requestAnimationFrame(() => {\n highlightRafs.delete(el);\n el.classList.add(HIGHLIGHT_CLASS);\n\n highlightTimers.set(\n el,\n setTimeout(() => {\n el.classList.remove(HIGHLIGHT_CLASS);\n highlightTimers.delete(el);\n }, HIGHLIGHT_DURATION_MS)\n );\n });\n\n highlightRafs.set(el, rafId);\n}\n","import {\n batch,\n computed,\n atom as createAtom,\n effect,\n isAtom,\n isComputed,\n untracked,\n} from '@but212/atom-effect';\nimport $ from 'jquery';\nimport { debug } from './debug';\nimport type { AtomOptions, WritableAtom } from './types';\n// isReactive is defined in utils.ts because core's isAtom already covers computed\n// atoms (ComputedAtom carries ATOM_BRAND), making a separate isComputed check redundant.\nimport { isReactive } from './utils';\n\n// ============================================================================\n// atom factory + debug namespace\n// ============================================================================\n\n/**\n * Wraps core's `atom` factory to attach the `$.atom.debug` property.\n *\n * A locally-owned function object is required so that `Object.defineProperty`\n * can add a getter/setter accessor — imported function references cannot be\n * mutated this way. The `debug` accessor is attached below via\n * `Object.defineProperty`; `staticExtensions` then registers both on `$`.\n *\n * `options` is not defaulted here — core's `atom` defaults `options` to `{}`\n * internally, so passing `undefined` is safe and avoids an extra allocation\n * per call.\n */\nfunction atom<T>(initialValue: T, options?: AtomOptions): WritableAtom<T> {\n return createAtom(initialValue, options);\n}\n\n// `atom as unknown as JQueryStatic['atom']` in staticExtensions is required\n// because TypeScript cannot see the runtime-added `debug` accessor through the\n// function's declared type. The `NamespaceExtensions` annotation on\n// `staticExtensions` still verifies that every other field is correctly typed.\nObject.defineProperty(atom, 'debug', {\n enumerable: true,\n // configurable: true allows tests and advanced consumers to redefine or\n // delete the accessor if needed. The default (false) would permanently lock\n // the property on the function object.\n configurable: true,\n get(): boolean {\n return debug.enabled;\n },\n set(value: boolean) {\n debug.enabled = value;\n },\n});\n\n// ============================================================================\n// nextTick\n// ============================================================================\n\n/**\n * Resolves after all pending microtask-scheduled reactive effects have flushed.\n *\n * Implementation uses `setTimeout(0)` (a macrotask) which always runs after\n * the current microtask queue is drained. This is intentional: core's\n * scheduler enqueues effects as microtasks, so by the time the macrotask\n * fires, all pending reactive propagation for the current turn is complete.\n *\n * Note: browsers may enforce a minimum 4 ms delay for nested `setTimeout`\n * calls. For unit tests this is typically not an issue. If sub-millisecond\n * resolution is needed, use `Promise.resolve()` directly to wait for a single\n * microtask tick instead.\n *\n * **Caveats**: A single `await nextTick()` covers one reactive propagation\n * wave. Chains of computed → effect → atom → effect may require multiple\n * awaits — one per propagation step.\n */\nexport function nextTick(): Promise<void> {\n return new Promise<void>((resolve) => setTimeout(resolve, 0));\n}\n\n// ============================================================================\n// Static extension registration\n// ============================================================================\n\n/**\n * The subset of `JQueryStatic` that this module registers.\n *\n * Typed as `Pick<JQueryStatic, ...>` so that the compiler verifies:\n * 1. Every key listed here actually exists on `JQueryStatic`.\n * 2. Every value's type is assignable to the declared `JQueryStatic` member.\n *\n * Adding or removing a key in either `JQueryStatic` or this object without\n * updating the other produces a compile-time error.\n *\n * Exception: `nextTick` originates in this file (not imported from core), so\n * its source of truth is the `export function nextTick` declaration above —\n * `JQueryStatic['nextTick']` is verified against that signature, not the other\n * way around.\n *\n * Note: `$.extend(staticExtensions)` merges the fields into `$` at runtime.\n * TypeScript does not model this mutation on the `$` type — the augmented\n * types are declared separately via global interface merging in `types.ts`.\n */\ntype NamespaceExtensions = Pick<\n JQueryStatic,\n | 'atom'\n | 'computed'\n | 'effect'\n | 'batch'\n | 'untracked'\n | 'isAtom'\n | 'isComputed'\n | 'isReactive'\n | 'nextTick'\n>;\n\nconst staticExtensions: NamespaceExtensions = {\n // `atom` carries a runtime `debug` accessor added via Object.defineProperty.\n // TypeScript cannot see it through the declared function type, so the double\n // cast is unavoidable. The NamespaceExtensions annotation still verifies all\n // other fields; only `atom`'s shape escapes static checking here.\n atom: atom as unknown as JQueryStatic['atom'],\n computed,\n effect,\n batch,\n untracked,\n isAtom,\n isComputed,\n isReactive,\n nextTick,\n};\n\n// $.extend(obj) merges into JQueryStatic (i.e. the $ function itself).\n// Use $.fn.extend(obj) instead to add instance methods on jQuery collections.\n$.extend(staticExtensions);\n","import { ERROR_MESSAGES, LOG_PREFIXES } from './constants';\nimport { debug } from './debug';\nimport type { EffectObject } from './types';\nimport { getSelector } from './utils';\n\n/**\n * CSS class added to every element that has at least one active binding.\n * Used by `querySelectorAll` in `cleanupDescendants` for efficient subtree traversal.\n * Internal use only.\n */\nconst AES_BOUND = '_aes-bound';\n\n/**\n * Per-element record of all reactive resources that must be released on cleanup.\n * Fields are optional to avoid allocating arrays for the common case where only\n * one resource type is used.\n */\ninterface BindingRecord {\n effects?: EffectObject[] | undefined;\n cleanups?: Array<() => void> | undefined;\n componentCleanup?: (() => void) | undefined;\n}\n\n// ============================================================================\n// BindingRegistry\n// ============================================================================\n\n/**\n * Central registry mapping DOM elements to their reactive binding records.\n *\n * Design goals:\n * - Zero memory leaks: all collections use WeakMap/WeakSet keyed by Element.\n * - Minimal allocations in the hot tracking path.\n * - O(bound-descendants) cleanup via a single querySelectorAll pass.\n */\nclass BindingRegistry {\n private records = new WeakMap<Element, BindingRecord>();\n\n // boundElements removed: records is now the Single Source of Truth.\n // WeakMap.has() provides the existence check.\n\n private preservedNodes = new WeakSet<Node>();\n private ignoredNodes = new WeakSet<Node>();\n\n // --------------------------------------------------------------------------\n // Lifecycle flags\n // --------------------------------------------------------------------------\n\n keep(node: Node): void {\n this.preservedNodes.add(node);\n }\n\n isKept(node: Node): boolean {\n return this.preservedNodes.has(node);\n }\n\n markIgnored(node: Node): void {\n this.ignoredNodes.add(node);\n }\n\n isIgnored(node: Node): boolean {\n return this.ignoredNodes.has(node);\n }\n\n // --------------------------------------------------------------------------\n // Tracking\n // --------------------------------------------------------------------------\n\n private getOrCreateRecord(el: Element): BindingRecord {\n let res = this.records.get(el);\n if (!res) {\n res = {};\n this.records.set(el, res);\n el.classList.add(AES_BOUND);\n }\n return res;\n }\n\n trackEffect(el: Element, fx: EffectObject): void {\n const record = this.getOrCreateRecord(el);\n record.effects ??= [];\n record.effects.push(fx);\n }\n\n trackCleanup(el: Element, fn: () => void): void {\n const record = this.getOrCreateRecord(el);\n record.cleanups ??= [];\n record.cleanups.push(fn);\n }\n\n setComponentCleanup(el: Element, fn: (() => void) | undefined): void {\n const record = this.getOrCreateRecord(el);\n record.componentCleanup = fn;\n }\n\n hasBind(el: Element): boolean {\n return this.records.has(el);\n }\n\n // --------------------------------------------------------------------------\n // Cleanup\n // --------------------------------------------------------------------------\n\n cleanup(el: Element): void {\n // Optimization: Single lookup + delete.\n const record = this.records.get(el);\n if (!record) {\n // Already cleaned up or never bound.\n // Ensure specific class is removed just in case of stale DOM state.\n if (el.isConnected) el.classList.remove(AES_BOUND);\n this.preservedNodes.delete(el);\n this.ignoredNodes.delete(el);\n return;\n }\n\n // Atomic deletion doubles as a re-entry guard.\n this.records.delete(el);\n this.preservedNodes.delete(el);\n this.ignoredNodes.delete(el);\n\n // Avoid a classList write for elements that are already leaving the DOM —\n // the browser will discard the class along with the node.\n if (el.isConnected) {\n el.classList.remove(AES_BOUND);\n }\n\n if (debug.enabled) {\n debug.cleanup(getSelector(el));\n }\n\n // Step 0 — Component cleanup runs first so the component can unmount\n // gracefully before its reactive effects are severed.\n if (record.componentCleanup) {\n try {\n record.componentCleanup();\n } catch (e) {\n debug.error(LOG_PREFIXES.MOUNT, ERROR_MESSAGES.MOUNT_CLEANUP_ERROR(), e);\n }\n }\n\n // Step 1 — Sever atom → effect subscriptions.\n record.effects?.forEach((fx) => {\n try {\n fx.dispose();\n } catch (e) {\n debug.error(LOG_PREFIXES.BINDING, ERROR_MESSAGES.EFFECT_DISPOSE_ERROR(), e);\n }\n });\n\n // Step 2 — Run general-purpose cleanup callbacks.\n record.cleanups?.forEach((fn) => {\n try {\n fn();\n } catch (e) {\n debug.error(LOG_PREFIXES.BINDING, ERROR_MESSAGES.BINDING_CLEANUP_ERROR(), e);\n }\n });\n }\n\n cleanupDescendants(el: Element): void {\n // querySelectorAll returns a static NodeList, which is safe to iterate\n // even though cleanup() triggers DOM changes.\n // Iterating with for...of avoids index-access type checking issues.\n const descendants = el.querySelectorAll(`.${AES_BOUND}`);\n for (const child of descendants) {\n if (this.records.has(child)) {\n this.cleanup(child);\n } else {\n // The AES_BOUND class is present but the registry has no record.\n // Remove the stale class and warn so it surfaces in debug mode.\n child.classList.remove(AES_BOUND);\n debug.warn(\n LOG_PREFIXES.BINDING,\n `${AES_BOUND} class found on unregistered element:`,\n child\n );\n }\n }\n }\n\n cleanupTree(el: Element): void {\n this.cleanupDescendants(el);\n this.cleanup(el);\n }\n}\n\n// ============================================================================\n// Singleton + auto-cleanup\n// ============================================================================\n\nexport const registry = new BindingRegistry();\n\nlet observer: MutationObserver | null = null;\nlet observedRoot: Element | null = null;\n\n/**\n * Starts observing `root` for removed elements and automatically disposes\n * their reactive bindings when they leave the DOM.\n *\n * The `root` parameter is required (no default) to make the caller explicit\n * about which subtree is being observed — `document.body` can be null if the\n * script runs before the body is parsed.\n *\n * Idempotent: calling more than once with the same root before\n * `disableAutoCleanup` has no effect. Calling with a different root while\n * already active emits a warning and returns without re-observing.\n */\nexport function enableAutoCleanup(root: Element): void {\n if (observer !== null) {\n if (observedRoot !== root) {\n debug.warn(\n LOG_PREFIXES.BINDING,\n 'enableAutoCleanup() called with a different root while already active. Observation was NOT switched — call disableAutoCleanup() first.',\n { current: observedRoot, requested: root }\n );\n }\n return;\n }\n\n observedRoot = root;\n observer = new MutationObserver((mutations) => {\n // Optimization: use for...of for iteration speed.\n for (const mutation of mutations) {\n // removedNodes is a NodeList, which is iterable in modern environments.\n // If legacy browser support is needed, a C-style loop over .length might be required.\n // Assuming ES6+ target (based on WeekMap usage).\n for (const node of mutation.removedNodes) {\n // Only Element nodes can carry AES_BOUND bindings.\n // 1 === Node.ELEMENT_NODE\n if (node.nodeType !== 1) continue;\n\n // isConnected handles the move case.\n // isKept handles explicit .detach().\n // isIgnored handles .remove().\n if (node.isConnected || registry.isKept(node) || registry.isIgnored(node)) {\n continue;\n }\n\n registry.cleanupTree(node as Element);\n }\n }\n });\n\n observer.observe(root, { childList: true, subtree: true });\n}\n\n/**\n * Stops the MutationObserver started by `enableAutoCleanup`.\n */\nexport function disableAutoCleanup(): void {\n observer?.disconnect();\n observer = null;\n observedRoot = null;\n}\n","import { effect, type ReadonlyAtom, untracked } from '@but212/atom-effect';\nimport { ERROR_MESSAGES, LOG_PREFIXES } from './constants';\nimport { debug } from './debug';\nimport { registry } from './registry';\nimport type { ReactiveValue } from './types';\nimport { isReactive } from './utils';\n\n// ============================================================================\n// Debug type\n// ============================================================================\n\n/**\n * Structured label identifying which binding produced a debug log entry.\n * Fixed bindings use a plain literal; per-key bindings use a `prefix.key` form\n * where the key portion must be non-empty.\n */\nexport type BindingDebugType =\n | 'text'\n | 'html'\n | 'show'\n | 'hide'\n | 'checked'\n | `class.${string & {}}`\n | `css.${string & {}}`\n | `attr.${string & {}}`\n | `prop.${string & {}}`\n | (string & {});\n\n// ============================================================================\n// Core factory\n// ============================================================================\n\n/**\n * Registers a reactive effect that calls `updater` whenever `source` changes,\n * or calls `updater` once immediately if `source` is a static value.\n *\n * Responsibilities:\n * - Reactive path: wraps `updater` in an `effect`, tracks it on the registry.\n * - Static path: applies the value once; no effect is registered.\n * - Debug path: logs both the static initial bind and reactive updates via\n * `debug.domUpdated` so that all DOM writes appear in a uniform format.\n * - Error path: catches `updater` exceptions and surfaces them via `console.error`\n * so that a broken binding does not silently kill the effect loop.\n * Both the reactive and static paths are guarded consistently.\n *\n * @param el DOM element to associate the effect with.\n * @param source Reactive or static value source.\n * @param updater Function that writes the value to the DOM.\n * @param debugType Structured label used in debug log output.\n */\nexport function registerReactiveEffect<T>(\n el: HTMLElement,\n source: ReactiveValue<T>,\n updater: (value: T) => void,\n debugType: BindingDebugType\n): void {\n if (isReactive(source)) {\n const reactiveSource = source as ReadonlyAtom<T>;\n registry.trackEffect(\n el,\n effect(() => {\n // Read the source value inside the tracking context — this is the\n // ONLY dependency this effect should subscribe to.\n const value = reactiveSource.value;\n\n // Run the updater untracked so that any atom reads inside updater\n // (user formatters, guards, computed lookups) cannot accidentally\n // add extra subscriptions to this effect.\n untracked(() => {\n try {\n updater(value);\n } catch (e) {\n debug.error(LOG_PREFIXES.BINDING, `${ERROR_MESSAGES.UPDATER_ERROR(debugType)}:`, e);\n return;\n }\n // debug.domUpdated already guards on debug.enabled internally, but\n // skipping the call entirely avoids a function-call overhead on every\n // atom update in production (debug disabled).\n if (debug.enabled) debug.domUpdated(el, debugType, value);\n });\n })\n );\n } else {\n // Static value: apply once with the same error surface as the reactive path.\n try {\n updater(source);\n } catch (e) {\n debug.error(LOG_PREFIXES.BINDING, `${ERROR_MESSAGES.UPDATER_ERROR(debugType)} (static):`, e);\n return;\n }\n if (debug.enabled) debug.domUpdated(el, debugType, source);\n }\n}\n","import { batch } from '@but212/atom-effect';\nimport $ from 'jquery';\nimport { registry } from './registry';\n\n/** Generic event handler type matching jQuery's internal handler signature. */\ntype EventHandler = JQuery.EventHandlerBase<unknown, JQuery.TriggeredEvent>;\n\n/**\n * Symbol marker attached to handlers registered by this library's internals.\n * Handlers carrying this marker are NOT wrapped in batch() — they already\n * manage atom writes directly and do not need an extra reactive flush.\n */\nexport const INTERNAL_HANDLER = Symbol('atom-effect-internal');\n\n/**\n * WeakMap from original handler function → batch-wrapped handler function.\n * Keys are functions (held alive by jQuery's internal event store for as long\n * as the handler is registered), so entries are naturally released when the\n * handler is removed via .off() and jQuery drops its reference.\n */\nconst handlerMap = new WeakMap<EventHandler, EventHandler>();\n\n// ============================================================================\n// Originals store\n// ============================================================================\n\n/**\n * Snapshot of jQuery prototype methods captured at `enablejQueryOverrides()`\n * time and restored by `disablejQueryOverrides()`.\n * Stored as a typed object so the override closures can reference the fields\n * directly without `!` non-null assertions.\n */\ntype OriginalMethods = {\n on: typeof $.fn.on;\n off: typeof $.fn.off;\n remove: typeof $.fn.remove;\n empty: typeof $.fn.empty;\n detach: typeof $.fn.detach;\n};\n\nlet originals: OriginalMethods | null = null;\n\n// ============================================================================\n// Internal helpers\n// ============================================================================\n\nconst getWrappedHandler = (fn: EventHandler): EventHandler => {\n // Skip wrapping for library-internal handlers.\n if ((fn as unknown as Record<symbol, boolean>)[INTERNAL_HANDLER]) return fn;\n\n let wrapped = handlerMap.get(fn);\n if (!wrapped) {\n // `function` (not arrow) to preserve the jQuery-provided `this` context.\n // Double cast via `unknown` is required because the rest-args signature\n // `(...args: unknown[])` is not directly assignable to `EventHandler`.\n wrapped = function (this: unknown, ...args: unknown[]) {\n return batch(() => fn.apply(this, args as Parameters<EventHandler>));\n } as unknown as EventHandler;\n // Mark the wrapper itself as internal so it isn't double-wrapped if passed again.\n (wrapped as unknown as Record<symbol, boolean>)[INTERNAL_HANDLER] = true;\n handlerMap.set(fn, wrapped);\n }\n return wrapped;\n};\n\n/**\n * Wraps the handlers in an event-map object with `getWrappedHandler`.\n * Uses Object.keys to iterate own properties only, avoiding inherited keys.\n */\nfunction wrapEventMap(map: Record<string, EventHandler>): Record<string, EventHandler> {\n const newMap: Record<string, EventHandler> = {};\n Object.keys(map).forEach((key) => {\n const handler = map[key];\n if (handler) newMap[key] = getWrappedHandler(handler);\n });\n return newMap;\n}\n\n/**\n * Resolves the wrapped counterpart for each handler in an off event-map.\n * Preserves `undefined` values — `.off({ click: undefined })` is a valid\n * jQuery call that removes ALL listeners for that event.\n * Uses Object.keys to iterate own properties only, avoiding inherited keys.\n */\nfunction resolveOffEventMap(\n map: Record<string, EventHandler | undefined>\n): Record<string, EventHandler | undefined> {\n const newMap: Record<string, EventHandler | undefined> = {};\n Object.keys(map).forEach((key) => {\n const handler = map[key];\n newMap[key] = handler ? (handlerMap.get(handler) ?? handler) : undefined;\n });\n return newMap;\n}\n\n// ============================================================================\n// Public API\n// ============================================================================\n\n/**\n * Patches jQuery's `.on()`, `.off()`, `.remove()`, `.empty()`, and `.detach()`\n * to integrate with the reactive system:\n * - Event handlers are wrapped in `batch()` for efficient atom flushing.\n * - DOM removal triggers reactive binding cleanup.\n * - `.detach()` preserves bindings for re-attachment.\n *\n * Idempotent — calling more than once has no effect.\n * Call `disablejQueryOverrides()` to restore original methods.\n */\nexport function enablejQueryOverrides(): void {\n if (originals !== null) return;\n\n originals = {\n on: $.fn.on,\n off: $.fn.off,\n remove: $.fn.remove,\n empty: $.fn.empty,\n detach: $.fn.detach,\n };\n\n const orig = originals;\n\n // --- Lifecycle overrides ---\n\n // .remove() — clean up bindings on the matching elements, then delegate.\n // Only elements matched by `selector` (or all elements when selector is\n // omitted) are cleaned up — other elements in `this` are not affected,\n // mirroring jQuery's own selector-scoped remove behaviour.\n // markIgnored is called BEFORE cleanupTree so that a MutationObserver\n // callback firing synchronously sees the ignored flag and skips redundant cleanup.\n $.fn.remove = function (this: JQuery, selector?: string) {\n const targets = selector ? this.filter(selector) : this;\n for (let i = 0, len = targets.length; i < len; i++) {\n const el = targets[i];\n if (el) {\n registry.markIgnored(el);\n registry.cleanupTree(el);\n }\n }\n return orig.remove.call(this, selector);\n };\n\n // .empty() — recursively clean up descendants, then delegate.\n $.fn.empty = function (this: JQuery) {\n for (let i = 0, len = this.length; i < len; i++) {\n const el = this[i];\n if (el) registry.cleanupDescendants(el);\n }\n return orig.empty.call(this);\n };\n\n // .detach() — mark elements as kept so the MutationObserver does not\n // dispose their bindings while they are temporarily out of the DOM.\n $.fn.detach = function (this: JQuery, selector?: string) {\n const targets = selector ? this.filter(selector) : this;\n for (let i = 0, len = targets.length; i < len; i++) {\n const el = targets[i];\n if (el) registry.keep(el);\n }\n return orig.detach.call(this, selector);\n };\n\n // --- Event overrides ---\n\n // .on() — wrap the handler argument in batch().\n //\n // jQuery's full signature is: .on(events, selector?, data?, handler)\n // When the first arg is an object it is an event-map; otherwise the handler\n // is always the LAST argument (position 1, 2, or 3 depending on overload).\n // Iterating from the end and stopping at the first function is therefore\n // correct for the positional form, because `data` is never a function in\n // jQuery's documented API.\n // `...args: unknown[]` is used instead of jQuery's overloaded signature\n // because TypeScript cannot unify the 4+ overloads into a single rest type.\n // The casts at args[0] and the apply call site are therefore unavoidable.\n $.fn.on = function (this: JQuery, ...args: unknown[]) {\n const types = args[0];\n\n if (types && typeof types === 'object') {\n args[0] = wrapEventMap(types as Record<string, EventHandler>);\n } else {\n for (let i = args.length - 1; i >= 0; i--) {\n if (typeof args[i] === 'function') {\n args[i] = getWrappedHandler(args[i] as EventHandler);\n break;\n }\n }\n }\n\n return orig.on.apply(this, args as Parameters<typeof $.fn.on>);\n };\n\n // .off() — resolve the original handler back to its wrapped counterpart so\n // jQuery can find and remove the correct internal listener.\n $.fn.off = function (this: JQuery, ...args: unknown[]) {\n const types = args[0];\n\n if (types && typeof types === 'object') {\n args[0] = resolveOffEventMap(types as Record<string, EventHandler | undefined>);\n } else {\n for (let i = args.length - 1; i >= 0; i--) {\n if (typeof args[i] === 'function') {\n const fn = args[i] as EventHandler;\n args[i] = handlerMap.get(fn) ?? fn;\n break;\n }\n }\n }\n\n return orig.off.apply(this, args as Parameters<typeof $.fn.off>);\n };\n}\n\n/**\n * Restores all jQuery methods patched by `enablejQueryOverrides()`.\n * Primarily useful in test environments to reset state between suites.\n */\nexport function disablejQueryOverrides(): void {\n if (originals === null) return;\n\n $.fn.on = originals.on;\n $.fn.off = originals.off;\n $.fn.remove = originals.remove;\n $.fn.empty = originals.empty;\n $.fn.detach = originals.detach;\n\n originals = null;\n}\n","import type {\n AtomOptions as BaseAtomOptions,\n ComputedAtom,\n ComputedOptions,\n EffectObject,\n ReadonlyAtom,\n WritableAtom,\n} from '@but212/atom-effect';\n\n/**\n * Cleanup function returned by effects or components.\n */\nexport type EffectCleanup = () => void;\n\n/**\n * Result of a reactive factory or component mount.\n */\nexport type EffectResult = undefined | EffectCleanup;\n\n/**\n * Generic equality predicate shared by `ValOptions` and any future consumer.\n * Extracted as a named type to avoid duplicating the inline function signature.\n */\nexport type EqualFn<T> = (a: T, b: T) => boolean;\n\n/**\n * Extended options for Atom creation.\n */\nexport interface AtomOptions extends BaseAtomOptions {\n /** Name for debugging purposes */\n name?: string;\n}\n\n/**\n * Represents a value that can be either a reactive node (Atom or Computed)\n * or a plain static value of the same type.\n *\n * `ComputedAtom<T>` is a structural sub-type of `ReadonlyAtom<T>`, so it is\n * already covered by `ReadonlyAtom<T>` — listing it separately would be\n * redundant and misleading.\n */\nexport type ReactiveValue<T> = T | ReadonlyAtom<T>;\n\n/**\n * Values allowed for DOM properties and attributes.\n */\nexport type PrimitiveValue = string | number | boolean | null | undefined;\n\n/**\n * CSS value: either a direct reactive value or a numeric tuple of [source, unit].\n *\n * The tuple form `[source, unit]` only accepts numeric sources because appending\n * a unit suffix to a string value (e.g. `\"100%\" + \"px\"`) is semantically\n * meaningless. Use `ReactiveValue<string>` directly when the full CSS value is\n * already a string (e.g. `fontFamilyAtom`).\n */\nexport type CssValue =\n | ReactiveValue<string | number>\n | [source: ReactiveValue<number>, unit: string];\n\n/**\n * CSS bindings map property names to CSS values.\n */\nexport type CssBindings = Record<string, CssValue>;\n\n/**\n * Configuration options for `atomBind`.\n */\nexport interface BindingOptions {\n /** Binds textContent to any reactive source (usually string/number). */\n text?: ReactiveValue<unknown>;\n /** Binds innerHTML to a reactive string source (sanitized). */\n html?: ReactiveValue<string>;\n /** Map of class names to reactive boolean conditions. */\n class?: Record<string, ReactiveValue<boolean>>;\n /** Map of CSS properties to reactive values or [value, unit] tuples. */\n css?: CssBindings;\n /** Binds attributes with consistent primitive constraints. */\n attr?: Record<string, ReactiveValue<PrimitiveValue>>;\n /** Binds DOM properties. */\n prop?: Record<string, ReactiveValue<unknown>>;\n /** Direct visibility control (display: none). */\n show?: ReactiveValue<boolean>;\n /** Inverse visibility control. */\n hide?: ReactiveValue<boolean>;\n /**\n * Two-way binding for input values.\n * Pass a bare atom or a `[atom, options]` tuple to customise parse/format/debounce.\n */\n val?: WritableAtom<unknown> | [atom: WritableAtom<unknown>, options: ValOptions<unknown>];\n /** Two-way binding for checkboxes and radio buttons. */\n checked?: WritableAtom<boolean>;\n /** Event listeners with automatic batched execution and lifecycle-bound cleanup. */\n on?: Record<string, (e: JQuery.Event) => void>;\n}\n\n/**\n * Configuration options for `atomList`.\n */\nexport interface ListOptions<T> {\n /** Key to track items (property name or extractor function). */\n key: keyof T | ((item: T, index: number) => string | number);\n /** Render function for each item. */\n render: (item: T, index: number) => string | Element | DocumentFragment | JQuery;\n /** Optional post-render binding logic. */\n bind?: ($el: JQuery, item: T, index: number) => void;\n /** Optional update logic when item data changes but DOM is reused. */\n update?: ($el: JQuery, item: T, index: number) => void;\n /** Lifecycle hook: called when an element is added to the list. */\n onAdd?: ($el: JQuery) => void;\n /** Lifecycle hook: called when an element is about to be removed. Supports async transitions. */\n onRemove?: ($el: JQuery) => Promise<void> | void;\n /** Content to show when the list is empty. */\n empty?: string | Element | DocumentFragment | JQuery;\n}\n\n/**\n * Configuration options for `atomVal`.\n */\nexport interface ValOptions<T> {\n /** Delay in milliseconds before syncing DOM input to Atom. */\n debounce?: number;\n /** DOM event to trigger sync (default: 'input'). */\n event?: string;\n /** Parser to convert string input to Atom type T. */\n parse?: (v: string) => T;\n /** Formatter to convert Atom type T to string for DOM display. */\n format?: (v: T) => string;\n /** Custom equality check for comparing parsed values. Defaults to Object.is. */\n equal?: EqualFn<T>;\n}\n\n/**\n * Configuration options for `atomFetch`.\n */\nexport interface FetchOptions<T> {\n /**\n * Value exposed by the atom before the first fetch resolves.\n * Also returned while a subsequent fetch is in flight.\n */\n defaultValue: T;\n /**\n * HTTP method forwarded to `$.ajax` (default: `'GET'`).\n * Takes precedence over the same field in `ajaxOptions`.\n * Accepts any string for non-standard methods; common values are\n * auto-completed: `'GET'`, `'POST'`, `'PUT'`, `'PATCH'`, `'DELETE'`.\n */\n method?: 'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE' | 'HEAD' | 'OPTIONS' | (string & {});\n /**\n * HTTP headers forwarded to `$.ajax`.\n * Takes precedence over the same field in `ajaxOptions`.\n */\n headers?: Record<string, string>;\n /**\n * Transforms the raw `$.ajax` response into `T`.\n *\n * When omitted the raw response is cast to `T` with no runtime validation.\n * Provide this function whenever the server response shape is not\n * guaranteed to match `T` at runtime.\n */\n transform?: (raw: unknown) => T;\n /**\n * Additional `$.ajax` settings.\n * Top-level fields (`url`, `method`, `headers`) always override the same\n * fields here, so avoid duplicating them to prevent silent conflicts.\n */\n ajaxOptions?: JQuery.AjaxSettings;\n /**\n * Called when the fetch fails with a non-abort error.\n * Receives the raw rejection value from `$.ajax`.\n * Does not suppress the error — the computed atom still enters its error\n * state and `hasError` becomes true.\n */\n onError?: (err: unknown) => void;\n /**\n * When `true` (default), the first fetch starts immediately on creation.\n * When `false`, the fetch is deferred until `atom.value` is first accessed.\n */\n eager?: boolean;\n}\n\n// ============================================================================\n// Input binding internals\n// Consumed only by input-binding.ts. Centralised here so enum definitions live\n// alongside their sibling types, but marked @internal — not part of the public\n// API surface and subject to change without notice.\n// ============================================================================\n\n/**\n * Bit flags for input binding state management.\n *\n * DESIGN RATIONALE:\n * - Mutually exclusive phases (SyncingTo*) and orthogonal states (Focused, Composing)\n * are packed into a single integer for O(1) state checks.\n * - 'Busy' mask is used as a Re-entrancy Guard to prevent infinite sync loops\n * between DOM events and Atom updates.\n *\n * @internal\n */\nexport enum BindingFlags {\n None = 0,\n /** Element is currently focused by the user. Prevents abrupt external updates from interrupting typing. */\n Focused = 1 << 0,\n /** User is typing via IME (Korean, Chinese, Japanese). Sync is deferred until composition completion. */\n Composing = 1 << 1,\n /** Internal: DOM -> Atom synchronization in progress. Prevents echo effects. */\n SyncingToAtom = 1 << 2,\n /** Internal: Atom -> DOM synchronization in progress. Prevents echo effects. */\n SyncingToDom = 1 << 3,\n /** Combined mask for any active processing phase (excluding simple focus). */\n Busy = Composing | SyncingToAtom | SyncingToDom,\n}\n\n/**\n * Functional Component type.\n * A function that initializes logic on a jQuery element and returns an optional cleanup function.\n * `P` defaults to `object` (empty props) — use `P = Record<string, never>` for strictly no-props\n * components.\n */\nexport type ComponentFn<P = object> = ($el: JQuery, props: P) => EffectResult;\n\n// ============================================================================\n// jQuery global interface augmentation\n// Extends JQueryStatic and JQuery with atom-effect plugin methods.\n// Importing this file applies these augmentations as a side effect.\n// ============================================================================\n\ndeclare global {\n interface JQueryStatic {\n /**\n * Reactive Atom Factory.\n * Also serves as a namespace for global configuration.\n */\n atom: {\n <T>(initialValue: T, options?: AtomOptions): WritableAtom<T>;\n /** Global debug toggle for logging and visual highlighting. */\n debug: boolean;\n };\n /** Sync computing primitive. */\n computed<T>(fn: () => T, options?: ComputedOptions<T>): ComputedAtom<T>;\n /** Async computing primitive with mandatory default value. */\n computed<T>(\n fn: () => Promise<T>,\n options: ComputedOptions<T> & { defaultValue: T }\n ): ComputedAtom<T>;\n /** Side-effect primitive. Returns an object to control lifecycle. */\n effect(fn: () => EffectResult): EffectObject;\n /** Groups multiple updates into a single synchronous notification cycle. */\n batch(fn: () => void): void;\n /** Executes a function without establishing reactive dependencies. */\n untracked<T>(fn: () => T): T;\n /** Runtime check for Atom instances. */\n isAtom(v: unknown): boolean;\n /** Runtime check for ComputedAtom instances. */\n isComputed(v: unknown): boolean;\n /** Runtime check for any reactive node. */\n isReactive(v: unknown): boolean;\n /** Resolves after the next scheduler flush. */\n nextTick(): Promise<void>;\n /** Initializes the lightweight SPA router. */\n route(config: RouteConfig): Router;\n /** Declarative reactive AJAX primitive. */\n atomFetch<T>(urlOrFn: string | (() => string), options: FetchOptions<T>): ComputedAtom<T>;\n }\n\n interface JQuery {\n /** Binds textContent to a reactive source. */\n atomText<T>(source: ReactiveValue<T>, formatter?: (v: T) => string): this;\n /** Binds innerHTML to a reactive source (sanitized). */\n atomHtml(source: ReactiveValue<string>): this;\n /** Toggles a single CSS class based on a reactive boolean. */\n atomClass(className: string, condition: ReactiveValue<boolean>): this;\n /** Toggles multiple CSS classes from a map of class names to reactive booleans. */\n atomClass(classMap: Record<string, ReactiveValue<boolean>>): this;\n /** Binds a single CSS property to a reactive value, with an optional unit suffix. */\n atomCss(prop: string, source: ReactiveValue<string | number>, unit?: string): this;\n /** Binds multiple CSS properties from a map of property names to reactive values. */\n atomCss(cssMap: CssBindings): this;\n /** Binds a single DOM attribute to a reactive value with security guards. */\n atomAttr(name: string, source: ReactiveValue<PrimitiveValue>): this;\n /** Binds multiple DOM attributes from a map of attribute names to reactive values. */\n atomAttr(attrMap: Record<string, ReactiveValue<PrimitiveValue>>): this;\n /** Binds a single DOM property to a reactive value. */\n atomProp<T>(name: string, source: ReactiveValue<T>): this;\n /** Binds multiple DOM properties from a map of property names to reactive values. */\n atomProp<T>(propMap: Record<string, ReactiveValue<T>>): this;\n /** Controls element visibility (display: none). */\n atomShow(condition: ReactiveValue<boolean>): this;\n /** Inverse of atomShow. */\n atomHide(condition: ReactiveValue<boolean>): this;\n /** Two-way binding for input values. */\n atomVal<T>(atom: WritableAtom<T>, options?: ValOptions<T>): this;\n /** Two-way binding for checkbox/radio checked state. */\n atomChecked(atom: WritableAtom<boolean>): this;\n /** Lifecycle-aware event listener. */\n atomOn(event: string, handler: (e: JQuery.Event) => void): this;\n\n /** Integrated multi-behavior reactive binding. */\n atomBind(options: BindingOptions): this;\n\n /** Reactive list rendering with efficient LIS-based reconciliation. */\n atomList<T>(source: ReadonlyAtom<T[]>, options: ListOptions<T>): this;\n\n /** Mounts a functional component with automatic cleanup. */\n atomMount<P>(component: ComponentFn<P>, props?: P): this;\n /** Unmounts the component and its descendants. */\n atomUnmount(): this;\n\n /** Manually triggers cleanup of all reactive bindings on this element. */\n atomUnbind(): this;\n }\n}\n\n/**\n * Context passed to binding handlers for unified lifecycle management.\n *\n * @internal consumed only by unified.ts and its callers within this package.\n */\nexport interface BindingContext {\n /** The specific jQuery-wrapped element being bound. */\n readonly $el: JQuery;\n /** The raw DOM element. */\n readonly el: HTMLElement;\n /** Registers a cleanup function to be executed when the element is removed. */\n readonly trackCleanup: (fn: EffectCleanup) => void;\n}\n\n// ============================================================================\n// Route types\n// ============================================================================\n\n/**\n * Shared route lifecycle hooks available on every route definition.\n */\nexport interface RouteLifecycle {\n /**\n * Called when entering this route. May return additional params to merge\n * into the params object passed to `render` / `onMount`.\n */\n onEnter?: (params: Record<string, string>) => Record<string, string> | undefined;\n /**\n * Called when leaving this route.\n * Return `false` to block navigation; returning `void` (or nothing) allows it.\n */\n onLeave?: () => boolean | undefined;\n /** Called when the same route is re-activated with new query parameters. */\n onParamsChange?: (params: Record<string, string>) => void;\n}\n\n/**\n * Route that renders content by cloning a `<template>` element.\n */\nexport interface TemplateRoute extends RouteLifecycle {\n /** CSS selector for a `<template>` element (e.g., `'#tmpl-home'`). */\n template: string;\n render?: never;\n /** Called after template content is appended to the container. */\n onMount?: ($content: JQuery) => void;\n}\n\n/**\n * Route that renders content via a custom function.\n */\nexport interface RenderRoute extends RouteLifecycle {\n /** Custom render function providing full control over the container DOM. */\n render: (container: HTMLElement, route: string, params: Record<string, string>) => void;\n template?: never;\n}\n\n/**\n * Route definition for a single route.\n * Exactly one of `template` or `render` must be provided.\n *\n * Use `isTemplateRoute` / `isRenderRoute` from `utils.ts` for safe narrowing\n * instead of direct property access.\n */\nexport type RouteDefinition = TemplateRoute | RenderRoute;\n\n/**\n * Configuration for `$.route()`.\n */\nexport interface RouteConfig {\n /** CSS selector of the element into which route content is rendered. */\n target: string;\n /** Route name used when the URL has no explicit route segment. */\n default: string;\n /** Map of route names to their definitions. */\n routes: Record<string, RouteDefinition>;\n /**\n * Routing strategy. Default: `'hash'`.\n * - `'hash'` — reads/writes `location.hash` (`#routeName`).\n * - `'history'` — reads/writes `location.pathname` via `history.pushState`.\n */\n mode?: 'hash' | 'history';\n /**\n * Path prefix stripped from `location.pathname` in history mode.\n * A trailing slash is normalized away internally.\n * Has no effect in hash mode.\n */\n basePath?: string;\n /** Route name to render when the requested route is not found (404 fallback). */\n notFound?: string;\n /**\n * When `true`, clicks on `[data-route]` elements are intercepted and\n * handled via `navigate()` instead of triggering a full page load.\n * Default: `false`.\n */\n autoBindLinks?: boolean;\n /**\n * CSS class added to `[data-route]` links that match the current route.\n * Also sets `aria-current=\"page\"` on the active link.\n * Default: `'active'`.\n */\n activeClass?: string;\n /**\n * Called before each route transition.\n * `from` is `''` on the very first render (no previous route).\n */\n beforeTransition?: (from: string, to: string) => void;\n /**\n * Called after each route transition completes.\n * `from` is `''` on the very first render (no previous route).\n */\n afterTransition?: (from: string, to: string) => void;\n}\n\n/**\n * Router instance returned by `$.route()`.\n *\n * `currentRoute` and `queryParams` reflect the current URL state reactively:\n * - In `'hash'` mode, `queryParams` is parsed from the query string after `?`\n * in the hash fragment (e.g., `#home?page=2` → `{ page: '2' }`).\n * - In `'history'` mode, `queryParams` is parsed from `location.search`.\n */\nexport interface Router {\n /**\n * Reactive atom containing the current route name.\n * Read-only — use `navigate()` to change routes so that the URL stays in sync.\n */\n currentRoute: ReadonlyAtom<string>;\n /**\n * Reactive atom containing the current query parameters as a plain object.\n * Updated automatically on URL changes; reset to `{}` on programmatic navigation.\n */\n queryParams: ReadonlyAtom<Record<string, string>>;\n /** Navigate programmatically to the named route. */\n navigate: (route: string) => void;\n /** Destroy the router, removing all event listeners and reactive effects. */\n destroy: () => void;\n}\n\nexport type { WritableAtom, ReadonlyAtom, ComputedAtom, EffectObject, ComputedOptions };\n","import { effect, untracked } from '@but212/atom-effect';\nimport { ERROR_MESSAGES, INPUT_DEFAULTS, LOG_PREFIXES } from './constants';\nimport { debug } from './debug';\nimport { INTERNAL_HANDLER } from './jquery-patch';\nimport type { EffectObject, ValOptions, WritableAtom } from './types';\nimport { BindingFlags } from './types';\n\n// Monotonically increasing counter used to generate per-instance event\n// namespaces, preventing cleanup of sibling bindings on the same element.\nlet instanceCounter = 0;\n\ntype InputEl = HTMLInputElement | HTMLTextAreaElement | HTMLSelectElement;\n\nclass InputBinding<T> {\n private readonly $el: JQuery;\n private readonly el: InputEl;\n private readonly atom: WritableAtom<T>;\n private readonly options: Required<ValOptions<T>>;\n\n private flags = 0;\n // undefined instead of null so clearTimeout(this.timeoutId) is always safe\n // without a null-check (clearTimeout(undefined) is a no-op per spec).\n private timeoutId: ReturnType<typeof setTimeout> | undefined = undefined;\n\n /** Per-instance jQuery event namespace — prevents cleanup collisions. */\n private readonly ns = `.atomBind-${++instanceCounter}`;\n\n // Initialized in constructor based on options.debounce decision.\n private readonly handleInput: () => void;\n\n constructor($el: JQuery, atom: WritableAtom<T>, options: ValOptions<T>) {\n this.$el = $el;\n this.el = $el[0] as InputEl;\n this.atom = atom;\n\n const debounce = options.debounce ?? 0;\n this.options = {\n debounce,\n event: options.event ?? INPUT_DEFAULTS.EVENT,\n parse: options.parse ?? ((v: string) => v as unknown as T),\n format: options.format ?? ((v: T) => String(v ?? '')),\n equal: options.equal ?? Object.is,\n };\n\n // Optimization: Pre-bind the appropriate input handler to avoid per-event branching.\n if (debounce > 0) {\n this.handleInput = () => {\n if (this.flags & BindingFlags.Composing) return;\n clearTimeout(this.timeoutId);\n this.timeoutId = setTimeout(() => this.syncAtomFromDom(), debounce);\n };\n } else {\n this.handleInput = () => {\n if (this.flags & BindingFlags.Composing) return;\n this.syncAtomFromDom();\n };\n }\n\n // Mark all internal handlers so the jQuery patch skips batch() wrapping.\n // Inlining markInternal avoids helper call overhead.\n (this.handleFocus as unknown as Record<symbol, boolean>)[INTERNAL_HANDLER] = true;\n (this.handleBlur as unknown as Record<symbol, boolean>)[INTERNAL_HANDLER] = true;\n (this.handleCompositionStart as unknown as Record<symbol, boolean>)[INTERNAL_HANDLER] = true;\n (this.handleCompositionEnd as unknown as Record<symbol, boolean>)[INTERNAL_HANDLER] = true;\n (this.handleInput as unknown as Record<symbol, boolean>)[INTERNAL_HANDLER] = true;\n\n this.bindEvents();\n }\n\n // --- Event Handlers ---\n\n private readonly handleCompositionStart = () => {\n this.flags |= BindingFlags.Composing;\n };\n\n private readonly handleCompositionEnd = () => {\n this.flags &= ~BindingFlags.Composing;\n this.handleInput();\n };\n\n private readonly handleFocus = () => {\n this.flags |= BindingFlags.Focused;\n };\n\n private readonly handleBlur = () => {\n this.flags &= ~BindingFlags.Focused;\n\n // Flush any pending debounce timer on blur.\n if (this.timeoutId !== undefined) {\n clearTimeout(this.timeoutId);\n this.timeoutId = undefined;\n this.syncAtomFromDom();\n }\n\n const formatted = this.options.format(this.atom.peek());\n if (this.el.value !== formatted) {\n this.el.value = formatted;\n }\n };\n\n // --- Sync Logic ---\n\n private syncAtomFromDom(): void {\n // BindingFlags.Busy covers Composing | SyncingToAtom | SyncingToDom.\n // SyncingToDom is included defensively: if a future synchronous code path\n // triggers handleInput during an Atom→DOM write, this guard prevents echo.\n if (this.flags & BindingFlags.Busy) return;\n\n this.flags |= BindingFlags.SyncingToAtom;\n try {\n const parsed = this.options.parse(this.el.value);\n // peek() instead of .value: equality check in an event handler must not\n // register a dependency — only syncDomFromAtom (the effect body) tracks.\n if (!this.options.equal(this.atom.peek(), parsed)) {\n this.atom.value = parsed;\n }\n } catch (e) {\n // parse() threw (e.g. invalid input) — leave the atom unchanged.\n debug.warn(LOG_PREFIXES.BINDING, `${ERROR_MESSAGES.PARSE_ERROR()}:`, e);\n } finally {\n this.flags &= ~BindingFlags.SyncingToAtom;\n }\n }\n\n // --- Public Interface ---\n\n /**\n * Reactive effect body (Atom → DOM).\n * Called by the `effect()` wrapper in `applyInputBinding` whenever the atom\n * value changes. Named `syncDomFromAtom` to distinguish it from the imported\n * `effect` function and to clarify the data-flow direction.\n */\n public readonly syncDomFromAtom = () => {\n // Only this.atom.value is the intended dependency of this effect.\n // Everything else — format(), parse(), equal(), el.value DOM reads —\n // runs untracked so user callbacks cannot accidentally subscribe this\n // effect to extra atoms.\n const val = this.atom.value;\n\n untracked(() => {\n const formatted = this.options.format(val);\n const currentVal = this.el.value;\n\n // Skip if already synchronised.\n if (currentVal === formatted) return;\n\n const isFocused = !!(this.flags & BindingFlags.Focused);\n\n // While focused, skip update if the current raw input already parses to\n // the same logical value — avoids interrupting in-progress user input.\n if (isFocused) {\n try {\n if (this.options.equal(this.options.parse(currentVal), val)) return;\n } catch {\n // parse() threw on the current raw input (e.g. partially typed number).\n // Fall through and apply the formatted value.\n }\n }\n\n this.flags |= BindingFlags.SyncingToDom;\n try {\n if (\n isFocused &&\n (this.el instanceof HTMLInputElement || this.el instanceof HTMLTextAreaElement)\n ) {\n // Preserve cursor position so external atom updates don't jump the caret.\n const start = this.el.selectionStart;\n const end = this.el.selectionEnd;\n\n this.el.value = formatted;\n\n const len = formatted.length;\n if (start !== null && end !== null) {\n this.el.setSelectionRange(Math.min(start, len), Math.min(end, len));\n }\n } else {\n this.el.value = formatted;\n }\n\n debug.domUpdated(this.$el, 'val', formatted);\n } finally {\n this.flags &= ~BindingFlags.SyncingToDom;\n }\n });\n };\n\n public readonly cleanup = () => {\n // Remove only this instance's namespaced events — other bindings on the\n // same element are unaffected.\n this.$el.off(this.ns);\n clearTimeout(this.timeoutId);\n this.timeoutId = undefined;\n };\n\n private bindEvents(): void {\n this.$el\n .on(`focus${this.ns}`, this.handleFocus)\n .on(`blur${this.ns}`, this.handleBlur)\n .on(`compositionstart${this.ns}`, this.handleCompositionStart)\n .on(`compositionend${this.ns}`, this.handleCompositionEnd)\n .on(`${this.options.event}${this.ns}`, this.handleInput);\n }\n}\n\n/**\n * Applies two-way data binding between a writable atom and an input element.\n * Used by both `$.fn.atomVal` (explicit) and `$.fn.atomBind({ val })` (implicit).\n *\n * @param $el - jQuery-wrapped input, textarea, or select element.\n * @param atom - Writable atom to keep in sync with the element's value.\n * @param options - Optional parse/format/debounce/event/equal configuration.\n * @returns `fx` — the registered reactive effect (Atom → DOM),\n * `cleanup` — removes all event listeners and cancels pending timers.\n */\nexport function applyInputBinding<T>(\n $el: JQuery,\n atom: WritableAtom<T>,\n options: ValOptions<T>\n): { fx: EffectObject; cleanup: () => void } {\n const binding = new InputBinding($el, atom, options);\n return { fx: effect(binding.syncDomFromAtom), cleanup: binding.cleanup };\n}\n","import { computed, effect, isAtom, untracked } from '@but212/atom-effect';\nimport $ from 'jquery';\nimport { DANGEROUS_PROPS, ERROR_MESSAGES, LOG_PREFIXES, VALID_INPUT_TAGS } from './constants';\nimport { debug } from './debug';\nimport { type BindingDebugType, registerReactiveEffect } from './effect-factory';\nimport { applyInputBinding } from './input-binding';\nimport { INTERNAL_HANDLER } from './jquery-patch';\nimport { registry } from './registry';\nimport type {\n BindingContext,\n BindingOptions,\n CssValue,\n PrimitiveValue,\n ReactiveValue,\n ValOptions,\n WritableAtom,\n} from './types';\n\nexport type { BindingContext };\n\nimport { isDangerousCssValue, isDangerousUrl, sanitizeHtml } from './utils';\n\n// Cache for CSS property camelization to avoid repeated regex overhead.\n// Uses Map instead of a plain object to avoid prototype pollution risk and\n// for clearer semantics — CSS property names are a small, finite set so the\n// cache is effectively bounded in practice.\nconst camelCache = new Map<string, string>();\nfunction getCamelCase(prop: string): string {\n let cached = camelCache.get(prop);\n if (cached !== undefined) return cached;\n\n cached = prop.includes('-') ? prop.replace(/-./g, (m) => m[1]!.toUpperCase()) : prop;\n camelCache.set(prop, cached);\n return cached;\n}\n\n/**\n * Cache for sanitized versions of reactive strings.\n * Ensures that if 100 elements are bound to the same atom, sanitizeHtml() is\n * called only once per update instead of 100 times.\n */\nconst htmlSanitizeCache = new WeakMap<\n import('@but212/atom-effect').ReadonlyAtom<string>,\n import('@but212/atom-effect').ComputedAtom<string>\n>();\n\nfunction getSanitizedHtml(\n source: import('@but212/atom-effect').ReadonlyAtom<string>\n): import('@but212/atom-effect').ComputedAtom<string> {\n let cached = htmlSanitizeCache.get(source);\n if (!cached) {\n cached = computed(() => sanitizeHtml(source.value));\n htmlSanitizeCache.set(source, cached);\n }\n return cached;\n}\n\n// ============================================================================\n// Binding Context Factory\n// ============================================================================\n\nexport function createContext(el: HTMLElement): BindingContext {\n return {\n $el: $(el),\n el,\n trackCleanup: (fn) => registry.trackCleanup(el, fn),\n };\n}\n\n// ============================================================================\n// One-Way Binding Handlers (Atom → DOM)\n// ============================================================================\n\n/**\n * Updates element text content. Decoupled from generic T for flexibility with any reactive source.\n */\nexport function bindText<T = unknown>(\n ctx: BindingContext,\n value: ReactiveValue<T>,\n formatter?: (val: T) => string\n): void {\n const el = ctx.el;\n registerReactiveEffect(\n el,\n value,\n (val) => {\n const newVal = formatter ? formatter(val) : typeof val === 'string' ? val : String(val ?? '');\n // Guard against redundant DOM writes which trigger browser reflows\n if (el.textContent !== newVal) {\n el.textContent = newVal;\n }\n },\n 'text'\n );\n}\n\n/**\n * Updates element inner HTML with XSS sanitization.\n * Calls `registry.cleanupDescendants` before replacing innerHTML so that any\n * reactive bindings on outgoing child nodes are disposed before they are removed —\n * preventing the MutationObserver auto-cleanup path from firing a redundant cleanup.\n */\nexport function bindHtml(ctx: BindingContext, value: ReactiveValue<string>): void {\n const el = ctx.el;\n\n // Optimization: If the source is reactive, use a cached computed atom to\n // ensure sanitization runs exactly once per atom change for all observers.\n const reactiveSource = isAtom(value)\n ? getSanitizedHtml(value as import('@but212/atom-effect').ReadonlyAtom<string>)\n : value;\n\n registerReactiveEffect(\n el,\n reactiveSource,\n (sanitized) => {\n if (el.innerHTML !== sanitized) {\n // Dispose child bindings before the nodes are removed from the DOM.\n registry.cleanupDescendants(el);\n el.innerHTML = sanitized;\n }\n },\n 'html'\n );\n}\n\n/**\n * Toggles multiple CSS classes based on reactive boolean conditions.\n */\nexport function bindClass(\n ctx: BindingContext,\n classMap: Record<string, ReactiveValue<boolean>>\n): void {\n Object.entries(classMap).forEach(([className, source]) => {\n registerReactiveEffect(\n ctx.el,\n source,\n (val) => {\n ctx.el.classList.toggle(className, !!val);\n },\n `class.${className}`\n );\n });\n}\n\n/**\n * Updates multiple CSS style properties. Supports units (e.g., [source, 'px']).\n */\nexport function bindCss(ctx: BindingContext, cssMap: Record<string, CssValue>): void {\n const el = ctx.el;\n const style = el.style as unknown as Record<string, string>;\n Object.entries(cssMap).forEach(([prop, val]) => {\n const camel = getCamelCase(prop);\n // Destructure the tuple form explicitly so TypeScript can narrow each branch.\n const [source, unit] = Array.isArray(val) ? val : ([val, ''] as const);\n\n registerReactiveEffect(\n el,\n source,\n (v) => {\n const strVal = unit ? `${v}${unit}` : String(v);\n if (isDangerousCssValue(strVal)) {\n return;\n }\n style[camel] = strVal;\n },\n `css.${prop}`\n );\n });\n}\n\n/**\n * Binds DOM attributes with security guards and primitive value constraints.\n */\nexport function bindAttr(\n ctx: BindingContext,\n attrMap: Record<string, ReactiveValue<PrimitiveValue>>\n): void {\n const el = ctx.el;\n Object.keys(attrMap).forEach((name) => {\n // Block event handler attributes (on*) to prevent inline JS injection.\n // Attribute names from the DOM API are lowercase, but user-supplied keys\n // may use mixed case — normalize before the check.\n if (name.toLowerCase().startsWith('on')) {\n return;\n }\n\n registerReactiveEffect(\n el,\n attrMap[name]!,\n (v) => {\n if (v === null || v === undefined || v === false) {\n el.removeAttribute(name);\n return;\n }\n const newVal = v === true ? name : String(v);\n if (isDangerousUrl(name, newVal)) {\n return;\n }\n // Attribute write guard\n if (el.getAttribute(name) !== newVal) {\n el.setAttribute(name, newVal);\n }\n },\n `attr.${name}`\n );\n });\n}\n\n/**\n * Binds DOM properties. Uses strict property write guards.\n */\nexport function bindProp(\n ctx: BindingContext,\n propMap: Record<string, ReactiveValue<unknown>>\n): void {\n const el = ctx.el as unknown as Record<string, unknown>;\n Object.keys(propMap).forEach((name) => {\n // Block dangerous DOM properties that can inject raw HTML (e.g., innerHTML)\n if (DANGEROUS_PROPS.has(name)) {\n return;\n }\n\n registerReactiveEffect(\n ctx.el,\n propMap[name]!,\n (val) => {\n // Redundancy check specifically for DOM properties\n if (el[name] !== val) {\n el[name] = val;\n }\n },\n `prop.${name}`\n );\n });\n}\n\n/**\n * Handles visibility (display: none) toggle.\n */\nexport function bindVisibility(\n ctx: BindingContext,\n condition: ReactiveValue<boolean>,\n invert: boolean\n): void {\n const el = ctx.el;\n const label: BindingDebugType = invert ? 'hide' : 'show';\n registerReactiveEffect(\n el,\n condition,\n (val) => {\n const visible = invert !== !!val;\n el.style.display = visible ? '' : 'none';\n },\n label\n );\n}\n\n/**\n * Two-way value binding with full feature parity to $.fn.atomVal.\n * Supports parse/format options, debouncing, IME composition, and focus-aware updates.\n */\nexport function bindVal(\n ctx: BindingContext,\n atom: WritableAtom<unknown>,\n options: ValOptions<unknown> = {}\n): void {\n const tagName = ctx.el.tagName.toLowerCase();\n if (!VALID_INPUT_TAGS.has(tagName)) {\n console.warn(`${LOG_PREFIXES.BINDING} ${ERROR_MESSAGES.INVALID_INPUT_ELEMENT(tagName)}`);\n return;\n }\n const { fx, cleanup } = applyInputBinding(ctx.$el, atom, options);\n\n registry.trackEffect(ctx.el, fx);\n ctx.trackCleanup(cleanup);\n}\n\n/**\n * Two-way binding for checkbox/radio checked state.\n */\nexport function bindChecked(ctx: BindingContext, atom: WritableAtom<boolean>): void {\n const el = ctx.el as HTMLInputElement;\n const $el = ctx.$el;\n\n // DOM → Atom (jQuery events for .trigger() compatibility)\n // Note: el.checked = x does not fire 'change', so no re-entrancy guard is needed.\n const handler = () => {\n const current = el.checked;\n if (atom.value !== current) {\n atom.value = current;\n }\n };\n // Internal handler — skip batch() wrapping in the jQuery patch.\n (handler as unknown as Record<symbol, boolean>)[INTERNAL_HANDLER] = true;\n\n // DOM → Atom cleanup goes through ctx.trackCleanup (element lifecycle).\n // Atom → DOM cleanup goes through registry.trackEffect (reactive effect lifecycle).\n // The split is intentional: effects are disposed by the registry's effect tracker;\n // plain event listeners have no registry counterpart and need manual teardown.\n $el.on('change', handler);\n ctx.trackCleanup(() => $el.off('change', handler));\n\n // Atom → DOM\n const fx = effect(() => {\n const val = !!atom.value;\n untracked(() => {\n if (el.checked !== val) {\n el.checked = val;\n debug.domUpdated($el, 'checked', val);\n }\n });\n });\n registry.trackEffect(el, fx);\n}\n\n// ============================================================================\n// Event Binding Handler\n// ============================================================================\n\nexport function bindEvents(ctx: BindingContext, eventMap: NonNullable<BindingOptions['on']>): void {\n const $el = ctx.$el;\n $el.on(eventMap);\n ctx.trackCleanup(() => $el.off(eventMap));\n}\n\n/**\n * Binds a single event handler using jQuery's event system for compatibility.\n * Optimized to avoid creating jQuery wrapper objects repeatedly during setup/teardown.\n */\nexport function bindOn(\n ctx: BindingContext,\n event: string,\n handler: (e: JQuery.Event) => void\n): void {\n const $el = ctx.$el;\n $el.on(event, handler);\n ctx.trackCleanup(() => $el.off(event, handler));\n}\n\n/**\n * Disposes all reactive bindings on an element and its descendants.\n * Centralised here so `chainable.ts` does not need to import `registry` directly.\n */\nexport function bindUnbind(el: HTMLElement): void {\n registry.cleanupTree(el);\n}\n","import $ from 'jquery';\nimport { ERROR_MESSAGES, LOG_PREFIXES } from './constants';\nimport type {\n BindingOptions,\n CssBindings,\n PrimitiveValue,\n ReactiveValue,\n ValOptions,\n WritableAtom,\n} from './types';\nimport {\n bindAttr,\n bindChecked,\n bindClass,\n bindCss,\n bindEvents,\n bindHtml,\n bindOn,\n bindProp,\n bindText,\n bindUnbind,\n bindVal,\n bindVisibility,\n createContext,\n} from './unified';\n\n/**\n * Binds element `textContent` to a reactive source.\n *\n * @param source - Reactive or static value to display.\n * @param formatter - Optional function to convert the value to a string.\n * Defaults to `String(val ?? '')`.\n */\n$.fn.atomText = function <T>(source: ReactiveValue<T>, formatter?: (v: T) => string): JQuery {\n return this.each(function () {\n bindText(createContext(this), source, formatter);\n });\n};\n\n/**\n * Binds element `innerHTML` to a reactive string source.\n * The value is automatically sanitized before insertion to prevent XSS.\n */\n$.fn.atomHtml = function (source: ReactiveValue<string>): JQuery {\n return this.each(function () {\n bindHtml(createContext(this), source);\n });\n};\n\n/**\n * Toggles one or more CSS classes based on reactive boolean conditions.\n *\n * @overload Single class: `atomClass(className, condition)`\n * @overload Multiple classes: `atomClass({ active: isActive, disabled: isDisabled })`\n */\n$.fn.atomClass = function (\n classNameOrMap: string | Record<string, ReactiveValue<boolean>>,\n condition?: ReactiveValue<boolean>\n): JQuery {\n // Validate arguments once before iterating — avoids repeated warnings per element.\n if (typeof classNameOrMap === 'string' && condition === undefined) {\n console.warn(`${LOG_PREFIXES.BINDING} ${ERROR_MESSAGES.MISSING_CONDITION('atomClass')}`);\n return this;\n }\n // Hoist: build the map once, not once-per-element inside each().\n const classMap =\n typeof classNameOrMap === 'string' ? { [classNameOrMap]: condition! } : classNameOrMap;\n return this.each(function () {\n bindClass(createContext(this), classMap);\n });\n};\n\n/**\n * Binds one or more CSS style properties to reactive values.\n *\n * @overload Single property: `atomCss(prop, source, unit?)`\n * @overload Multiple properties: `atomCss({ color: colorAtom, opacity: [opacityAtom, 'px'] })`\n */\n$.fn.atomCss = function (\n propOrMap: string | CssBindings,\n source?: ReactiveValue<string | number>,\n unit?: string\n): JQuery {\n // Validate arguments once before iterating — avoids repeated warnings per element.\n if (typeof propOrMap === 'string' && source === undefined) {\n console.warn(`${LOG_PREFIXES.BINDING} ${ERROR_MESSAGES.MISSING_SOURCE('atomCss')}`);\n return this;\n }\n // Hoist: build the map once, not once-per-element inside each().\n const cssMap: CssBindings =\n typeof propOrMap === 'string'\n ? { [propOrMap]: unit ? [source as ReactiveValue<number>, unit] : source! }\n : propOrMap;\n return this.each(function () {\n bindCss(createContext(this), cssMap);\n });\n};\n\n/**\n * Binds one or more HTML attributes to reactive values with security guards.\n * Event handler attributes (`on*`) are blocked. Dangerous URL protocols are blocked.\n *\n * @overload Single attribute: `atomAttr(name, source)`\n * @overload Multiple attributes: `atomAttr({ href: urlAtom, title: titleAtom })`\n */\n$.fn.atomAttr = function (\n nameOrMap: string | Record<string, ReactiveValue<PrimitiveValue>>,\n source?: ReactiveValue<PrimitiveValue>\n): JQuery {\n // Validate arguments once before iterating — avoids repeated warnings per element.\n if (typeof nameOrMap === 'string' && source === undefined) {\n console.warn(`${LOG_PREFIXES.BINDING} ${ERROR_MESSAGES.MISSING_SOURCE('atomAttr')}`);\n return this;\n }\n // Hoist: build the map once, not once-per-element inside each().\n const attrMap: Record<string, ReactiveValue<PrimitiveValue>> = typeof nameOrMap === 'string'\n ? { [nameOrMap]: source! }\n : nameOrMap;\n return this.each(function () {\n bindAttr(createContext(this), attrMap);\n });\n};\n\n/**\n * Binds one or more DOM properties to reactive values.\n * Dangerous properties (`innerHTML`, `outerHTML`, etc.) are blocked.\n *\n * @overload Single property: `atomProp(name, source)`\n * @overload Multiple properties: `atomProp({ disabled: isDisabled, value: valAtom })`\n */\n$.fn.atomProp = function <T>(\n nameOrMap: string | Record<string, ReactiveValue<T>>,\n source?: ReactiveValue<T>\n): JQuery {\n // Validate arguments once before iterating — avoids repeated warnings per element.\n if (typeof nameOrMap === 'string' && source === undefined) {\n console.warn(`${LOG_PREFIXES.BINDING} ${ERROR_MESSAGES.MISSING_SOURCE('atomProp')}`);\n return this;\n }\n // Hoist: build the map once, not once-per-element inside each().\n const propMap: Record<string, ReactiveValue<unknown>> = typeof nameOrMap === 'string'\n ? { [nameOrMap]: source as ReactiveValue<unknown> }\n : (nameOrMap as Record<string, ReactiveValue<unknown>>);\n return this.each(function () {\n bindProp(createContext(this), propMap);\n });\n};\n\n/**\n * Shows the element when `condition` is truthy (`display: ''`).\n */\n$.fn.atomShow = function (condition: ReactiveValue<boolean>): JQuery {\n return this.each(function () {\n bindVisibility(createContext(this), condition, false);\n });\n};\n\n/**\n * Hides the element when `condition` is truthy (`display: 'none'`).\n * Inverse of `atomShow`.\n */\n$.fn.atomHide = function (condition: ReactiveValue<boolean>): JQuery {\n return this.each(function () {\n bindVisibility(createContext(this), condition, true);\n });\n};\n\n/**\n * Two-way binding for `<input>`, `<select>`, and `<textarea>` values.\n * Supports debouncing, IME composition, parse/format, and focus-aware updates.\n *\n * @param atom - Writable atom to sync with the input.\n * @param options - Optional configuration (debounce, event, parse, format, equal).\n * An empty object and an omitted options argument are equivalent — both use defaults.\n */\n$.fn.atomVal = function <T>(atom: WritableAtom<T>, options: ValOptions<T> = {}): JQuery {\n return this.each(function () {\n bindVal(createContext(this), atom as WritableAtom<unknown>, options as ValOptions<unknown>);\n });\n};\n\n/**\n * Two-way binding for checkbox and radio button `checked` state.\n * Uses the jQuery event system (not native `addEventListener`) for `.trigger()` compatibility.\n */\n$.fn.atomChecked = function (atom: WritableAtom<boolean>): JQuery {\n return this.each(function () {\n bindChecked(createContext(this), atom);\n });\n};\n\n/**\n * Attaches a lifecycle-aware event handler using the jQuery event system.\n * The handler is automatically removed when the element is unbound via `atomUnbind`.\n *\n * @param event - jQuery event name (e.g. `'click'`, `'input'`, `'change.myns'`).\n * @param handler - Callback receiving the jQuery event object.\n */\n$.fn.atomOn = function (event: string, handler: (e: JQuery.Event) => void): JQuery {\n return this.each(function () {\n bindOn(createContext(this), event, handler);\n });\n};\n\n/**\n * Integrated multi-behavior reactive binding.\n * Delegates to the focused bind helpers — each option maps 1:1 to a handler.\n *\n * All conditional checks use `!== undefined` consistently so that meaningful\n * falsy values (`show: false`, `hide: false`, `class: {}`) are handled correctly.\n */\n$.fn.atomBind = function (options: BindingOptions): JQuery {\n return this.each(function () {\n const ctx = createContext(this);\n\n if (options.text !== undefined) bindText(ctx, options.text);\n if (options.html !== undefined) bindHtml(ctx, options.html);\n if (options.class !== undefined) bindClass(ctx, options.class);\n if (options.css !== undefined) bindCss(ctx, options.css);\n if (options.attr !== undefined) bindAttr(ctx, options.attr);\n if (options.prop !== undefined) bindProp(ctx, options.prop);\n if (options.show !== undefined) bindVisibility(ctx, options.show, false);\n if (options.hide !== undefined) bindVisibility(ctx, options.hide, true);\n if (options.val !== undefined) {\n if (Array.isArray(options.val)) {\n // BindingOptions.val is typed as WritableAtom | [WritableAtom, ValOptions].\n // Array.isArray narrows to the tuple branch; the cast makes the tuple explicit.\n const [atom, valOpts] = options.val as [WritableAtom<unknown>, ValOptions<unknown>];\n bindVal(ctx, atom, valOpts);\n } else {\n bindVal(ctx, options.val);\n }\n }\n if (options.checked !== undefined) bindChecked(ctx, options.checked);\n if (options.on !== undefined) bindEvents(ctx, options.on);\n });\n};\n\n/**\n * Destroys all reactive bindings on the selected elements **and their descendants**.\n * This calls `registry.cleanupTree` on each element, which disposes effects,\n * cleanup callbacks, and component lifecycle functions recursively.\n *\n * Difference from `atomUnmount`: `atomUnmount` is scoped to components mounted via\n * `atomMount`. `atomUnbind` removes all bindings regardless of how they were created.\n */\n$.fn.atomUnbind = function (): JQuery {\n return this.each(function () {\n bindUnbind(this);\n });\n};\n","import { effect, untracked } from '@but212/atom-effect';\nimport $ from 'jquery';\nimport { ERROR_MESSAGES, LOG_PREFIXES } from './constants';\nimport { debug } from './debug';\nimport { registry } from './registry';\nimport type { ListOptions, ReadonlyAtom } from './types';\nimport { getLIS, getSelector, sanitizeHtml, shallowEqual } from './utils';\n\n// ============================================================================\n// Helpers\n// ============================================================================\n\n/**\n * Inserts `$el` before `nextNode` when `nextNode` is non-null and connected,\n * otherwise appends it to `$container`.\n */\nfunction insertOrAppend($el: JQuery, nextNode: Node | null, $container: JQuery): void {\n if (nextNode?.isConnected) $el.insertBefore(nextNode);\n else $el.appendTo($container);\n}\n\n// ============================================================================\n// atomList\n// ============================================================================\n\n/**\n * Reactive list rendering with LIS-based DOM reconciliation.\n *\n * Note: when `key` is a property name string, the resolved property value is\n * used as the Map key. The property must produce a `string | number` at\n * runtime — boolean or object values will be coerced by the Map and may cause\n * unexpected key collisions.\n */\n$.fn.atomList = function <T>(source: ReadonlyAtom<T[]>, options: ListOptions<T>): JQuery {\n const { key, render, bind, update, onAdd, onRemove, empty } = options;\n\n const getKey =\n typeof key === 'function'\n ? key\n : (item: T, _index: number) => item[key as keyof T] as unknown as string | number;\n\n return this.each(function (this: HTMLElement) {\n const $container = $(this);\n const containerSelector = getSelector(this);\n\n const itemMap = new Map<\n string | number,\n { $el: JQuery; item: T; state?: 'new' | 'replaced' | undefined }\n >();\n const removingKeys = new Set<string | number>();\n let oldKeys: (string | number)[] = [];\n let $emptyEl: JQuery | null = null;\n\n /**\n * Schedules DOM removal after an optional async `onRemove` transition.\n */\n const scheduleRemoval = (k: string | number, entry: { $el: JQuery; item: T }) => {\n const commitRemoval = () => {\n if (fx?.isDisposed) return; // Container already torn down — skip stale DOM work\n entry.$el.remove();\n removingKeys.delete(k);\n debug.log('list', `${containerSelector} removed item:`, k);\n };\n\n if (onRemove) {\n const result = onRemove(entry.$el);\n if (result instanceof Promise) {\n result.then(commitRemoval, commitRemoval);\n } else {\n commitRemoval();\n }\n } else {\n commitRemoval();\n }\n };\n\n const removeItem = (k: string | number, entry: { $el: JQuery; item: T }) => {\n itemMap.delete(k);\n removingKeys.add(k);\n scheduleRemoval(k, entry);\n };\n\n // Declare fx with let so scheduleRemoval's closure can reference it after assignment.\n let fx: ReturnType<typeof effect>;\n\n fx = effect(() => {\n // Only source.value is tracked. All side effects (DOM reads/writes,\n // render calls, bind calls) ran inside untracked() so they cannot\n // accidentally subscribe the list effect to atom reads within user callbacks.\n const items = source.value;\n const itemCount = items.length;\n\n untracked(() => {\n // 1. Handle Empty Template\n if ($emptyEl && itemCount > 0) {\n $emptyEl.remove();\n $emptyEl = null;\n }\n\n if (itemCount === 0) {\n if (empty && !$emptyEl) {\n const safeEmpty = typeof empty === 'string' ? sanitizeHtml(empty) : empty;\n $emptyEl = ($(safeEmpty as string) as JQuery).appendTo($container);\n }\n itemMap.forEach((entry, k) => {\n if (!removingKeys.has(k)) removeItem(k, entry);\n });\n oldKeys = [];\n return;\n }\n\n debug.log('list', `${containerSelector} updating with ${itemCount} items`);\n\n // 2. Build index structures\n const oldIndexMap = new Map<string | number, number>();\n for (let i = 0; i < oldKeys.length; i++) {\n oldIndexMap.set(oldKeys[i]!, i);\n }\n\n const newKeys: (string | number)[] = new Array(itemCount);\n const newKeySet = new Set<string | number>();\n const newIndices = new Int32Array(itemCount);\n // Parallel arrays replace an array-of-objects to reduce GC pressure and\n // improve cache locality when iterating targetsToRender (step 3).\n const trKeys: (string | number)[] = [];\n const trItems: T[] = [];\n const trIdxs: number[] = [];\n\n for (let i = 0; i < itemCount; i++) {\n const item = items[i]!;\n const k = getKey(item, i);\n newKeys[i] = k;\n\n if (newKeySet.has(k)) {\n debug.warn(LOG_PREFIXES.LIST, ERROR_MESSAGES.DUPLICATE_KEY(k, i));\n newIndices[i] = -1;\n continue;\n }\n newKeySet.add(k);\n\n const entry = itemMap.get(k);\n if (entry) {\n const oldItem = entry.item;\n if (!update && oldItem !== item && !shallowEqual(oldItem, item)) {\n trKeys.push(k);\n trItems.push(item);\n trIdxs.push(i);\n }\n newIndices[i] = removingKeys.has(k) ? -1 : (oldIndexMap.get(k) ?? -1);\n } else {\n trKeys.push(k);\n trItems.push(item);\n trIdxs.push(i);\n newIndices[i] = -1;\n }\n }\n\n // 3. Render New/Updated Items (Batch Sanitization)\n const SEPARATOR = '<!--sep-->';\n const renderCount = trKeys.length;\n const renderResults: Array<string | Element | DocumentFragment | JQuery> = new Array(\n renderCount\n );\n const htmlParts: string[] = [];\n\n for (let t = 0; t < renderCount; t++) {\n const raw = render(trItems[t]!, trIdxs[t]!);\n renderResults[t] = raw;\n if (typeof raw === 'string') {\n htmlParts.push(raw);\n }\n }\n\n // Batch sanitize: N calls → 1 call\n let sanitizedFragments: string[] | null = null;\n if (htmlParts.length > 0) {\n const combined = htmlParts.join(SEPARATOR);\n const sanitized = sanitizeHtml(combined);\n sanitizedFragments = sanitized.split(SEPARATOR);\n }\n\n // Create $el for each target\n let fragIdx = 0;\n for (let t = 0; t < renderCount; t++) {\n const raw = renderResults[t]!;\n const $el =\n typeof raw === 'string'\n ? $(sanitizedFragments![fragIdx++]!)\n : ($(raw as never) as JQuery);\n\n const k = trKeys[t]!;\n const entry = itemMap.get(k);\n if (entry) {\n const oldEl = entry.$el[0];\n if (oldEl) registry.cleanupTree(oldEl);\n entry.$el.replaceWith($el);\n entry.$el = $el;\n entry.state = 'replaced';\n } else {\n itemMap.set(k, { $el, item: null as unknown as T, state: 'new' });\n }\n }\n\n // 4. Cleanup Removed Keys\n for (const [k, entry] of itemMap) {\n if (!newKeySet.has(k) && !removingKeys.has(k)) {\n removeItem(k, entry);\n }\n }\n\n // 5. Place and Reorder via LIS\n const lisArr = getLIS(newIndices);\n let lisIdx = lisArr.length - 1;\n let nextNode: Node | null = null;\n const isInitial = oldKeys.length === 0;\n\n // innerHTML fast path: initial render, all string renders, no callbacks,\n // and no elements currently mid-removal (innerHTML would destroy them).\n const useInnerHtml =\n isInitial &&\n sanitizedFragments !== null &&\n fragIdx === renderCount &&\n !bind &&\n !onAdd &&\n !onRemove &&\n removingKeys.size === 0;\n\n if (useInnerHtml) {\n this.innerHTML = sanitizedFragments!.join('');\n\n // Map children back to itemMap entries\n let childIdx = 0;\n for (let i = 0; i < itemCount; i++) {\n const k = newKeys[i]!;\n const item = items[i]!;\n const entry = itemMap.get(k);\n if (!entry) continue;\n\n const el = this.children[childIdx++] as HTMLElement | undefined;\n if (el) {\n entry.$el = $(el);\n entry.item = item;\n entry.state = undefined;\n removingKeys.delete(k);\n debug.domUpdated(entry.$el, 'list.add', item);\n }\n }\n } else {\n const fragment = isInitial ? document.createDocumentFragment() : null;\n\n if (isInitial && fragment) {\n // ── Initial render: accumulate into DocumentFragment ──────────────\n // Loop-invariant branch hoisted out: avoids per-iteration isInitial check.\n for (let i = itemCount - 1; i >= 0; i--) {\n const k = newKeys[i]!;\n const item = items[i]!;\n const entry = itemMap.get(k)!;\n if (!entry) continue;\n\n const state = entry.state;\n const isNewItem = state === 'new';\n const isReplaced = state === 'replaced';\n entry.item = item;\n entry.state = undefined;\n\n if (entry.$el[0]) {\n if (!isNewItem && !isReplaced && update) {\n update(entry.$el, item, i);\n } else if ((isNewItem || isReplaced) && bind) {\n bind(entry.$el, item, i);\n }\n }\n\n for (let j = entry.$el.length - 1; j >= 0; j--) {\n fragment.insertBefore(entry.$el[j]!, fragment.firstChild);\n }\n if (onAdd && isNewItem) onAdd(entry.$el);\n\n if (isNewItem) {\n removingKeys.delete(k);\n debug.domUpdated(entry.$el, 'list.add', item);\n }\n }\n this.appendChild(fragment);\n } else {\n // ── Incremental update: LIS-based reconciliation ──────────────────\n for (let i = itemCount - 1; i >= 0; i--) {\n const k = newKeys[i]!;\n const item = items[i]!;\n const entry = itemMap.get(k)!;\n if (!entry) continue;\n\n const state = entry.state;\n const isNewItem = state === 'new';\n const isReplaced = state === 'replaced';\n entry.item = item;\n entry.state = undefined;\n\n if (entry.$el[0]) {\n if (!isNewItem && !isReplaced && update) {\n update(entry.$el, item, i);\n } else if ((isNewItem || isReplaced) && bind) {\n bind(entry.$el, item, i);\n }\n }\n\n if (lisIdx >= 0 && lisArr[lisIdx] === i) {\n lisIdx--;\n } else {\n insertOrAppend(entry.$el, nextNode, $container);\n }\n if (onAdd && isNewItem) onAdd(entry.$el);\n nextNode = entry.$el[0] ?? null;\n\n if (isNewItem) {\n removingKeys.delete(k);\n debug.domUpdated(entry.$el, 'list.add', item);\n }\n }\n }\n }\n\n oldKeys = newKeys;\n });\n });\n\n registry.trackEffect(this, fx);\n registry.trackCleanup(this, () => {\n itemMap.clear();\n removingKeys.clear();\n oldKeys = [];\n $emptyEl?.remove();\n });\n });\n};\n","import { untracked } from '@but212/atom-effect';\nimport $ from 'jquery';\nimport { ERROR_MESSAGES, LOG_PREFIXES } from './constants';\nimport { debug } from './debug';\nimport { registry } from './registry';\nimport type { ComponentFn } from './types';\nimport { bindUnbind } from './unified';\n\n// ============================================================================\n// Internal helpers\n// ============================================================================\n\nconst EMPTY_PROPS = Object.freeze({});\n\n// ============================================================================\n// jQuery plugin methods\n// ============================================================================\n\n/**\n * Mounts a functional component on each selected element.\n *\n * @param component - Function receiving `($el, props)` and returning an\n * optional cleanup callback. See {@link ComponentFn}.\n * @param props - Props passed to the component. When omitted, `P` must be\n * compatible with an empty object (i.e. all fields optional or\n * `P = object`). Passing no props to a component with required fields is\n * a type error that TypeScript will catch at the call site, but only when\n * `props` is explicitly typed — the `{} as P` fallback is not type-safe\n * for components with required fields.\n */\n$.fn.atomMount = function <P>(component: ComponentFn<P>, props?: P): JQuery {\n // Hoist default props object to avoid allocation in loop\n const p = (props ?? EMPTY_PROPS) as P;\n\n return this.each(function () {\n // Unmount any existing component before mounting the new one.\n registry.cleanupTree(this);\n\n const $el = $(this);\n let teardown: ReturnType<typeof component>;\n try {\n // untracked: component setup code must not register dependencies on any\n // outer reactive context (e.g. if atomMount is called inside an effect).\n teardown = untracked(() => component($el, p));\n } catch (err) {\n debug.error(LOG_PREFIXES.MOUNT, ERROR_MESSAGES.MOUNT_ERROR(), err);\n return;\n }\n\n if (typeof teardown === 'function') {\n registry.setComponentCleanup(this, teardown);\n }\n });\n};\n\n/**\n * Unmounts the component and disposes all reactive bindings on each selected\n * element and its descendants.\n */\n$.fn.atomUnmount = function (): JQuery {\n return this.each(function () {\n bindUnbind(this);\n });\n};\n","import type { ReadonlyAtom } from '@but212/atom-effect';\nimport { computed, atom as createAtom, effect, untracked } from '@but212/atom-effect';\nimport $ from 'jquery';\nimport { ERROR_MESSAGES, LOG_PREFIXES, ROUTE_DEFAULTS } from './constants';\nimport { debug } from './debug';\nimport { registry } from './registry';\nimport type { RouteConfig, RouteDefinition, Router, WritableAtom } from './types';\n\n// --- Helper: Safe History API Wrappers ---\nfunction safePushState(data: unknown, url: string | URL | null): boolean {\n try {\n // Second argument (title) is deprecated in the spec and ignored by all\n // browsers — pass an empty string as required by the signature.\n history.pushState(data, '', url);\n return true;\n } catch (e) {\n debug.warn(\n LOG_PREFIXES.ROUTE,\n 'PushState failed (likely file:// protocol or security restriction). UI will update, but URL will not.',\n e\n );\n return false;\n }\n}\n\nclass RouterImpl implements Router {\n /**\n * Reactive atom containing the current route name.\n * Exposed as ReadonlyAtom so external code cannot mutate route state\n * without going through navigate(), which keeps URL and atom in sync.\n */\n public currentRoute: ReadonlyAtom<string>;\n public queryParams: ReadonlyAtom<Record<string, string>>;\n\n private config: RouteConfig;\n private isDestroyed = false;\n /**\n * Tracks the route name of the last completed transition.\n * Initialized to empty string so beforeTransition/afterTransition always\n * receive a consistent `from` value — never `from === to` on the first render.\n */\n private previousRoute = '';\n /**\n * Mirrors the browser URL after every committed navigation.\n * Used by handleUrlChange to detect real URL changes (vs. our own\n * programmatic updates) and by restoreUrl to roll back blocked transitions.\n */\n private previousUrl: string;\n private cleanups: Array<() => void> = [];\n\n private $target: JQuery;\n private isHistoryMode: boolean;\n private currentRouteAtom: WritableAtom<string>;\n private queryParamsAtom: WritableAtom<Record<string, string>>;\n /** Caches resolved HTMLTemplateElement references to avoid repeated querySelector calls. */\n private templateCache = new Map<string, HTMLTemplateElement>();\n /** Pre-calculated base path with trailing slash stripped for consistent URL building. */\n private normalizedBasePath: string;\n\n constructor(config: RouteConfig) {\n // Destructure configuration with defaults for internal use\n this.config = {\n ...config,\n mode: config.mode ?? ROUTE_DEFAULTS.mode,\n basePath: config.basePath ?? ROUTE_DEFAULTS.basePath,\n autoBindLinks: config.autoBindLinks ?? ROUTE_DEFAULTS.autoBindLinks,\n activeClass: config.activeClass ?? ROUTE_DEFAULTS.activeClass,\n };\n\n this.isHistoryMode = this.config.mode === 'history';\n this.$target = $(this.config.target);\n // Strip trailing slash so URL construction is always `${base}/${route}`.\n this.normalizedBasePath = this.config.basePath?.replace(/\\/$/, '') || '';\n\n // Initialize previousUrl based on current state before setting up atoms.\n // getCurrentUrl() cannot be called yet (method depends on isHistoryMode which is set above).\n this.previousUrl = this.isHistoryMode\n ? window.location.pathname + window.location.search\n : window.location.hash;\n\n // Initialize state atoms; expose via ReadonlyAtom to prevent external mutation.\n this.currentRouteAtom = createAtom(this.getRouteName());\n this.currentRoute = this.currentRouteAtom;\n this.queryParamsAtom = createAtom(this.getQueryParams());\n // Use computed() to ensure queryParams is truly read-only at runtime,\n // as verified by the 'should be read-only (computed)' test.\n this.queryParams = computed(() => this.queryParamsAtom.value);\n\n // Bind methods that are used as callbacks\n this.handleUrlChange = this.handleUrlChange.bind(this);\n this.destroy = this.destroy.bind(this);\n\n // Initialize\n this.init();\n }\n\n private init() {\n // Set up URL change listener\n const eventName = this.isHistoryMode ? 'popstate' : 'hashchange';\n window.addEventListener(eventName, this.handleUrlChange);\n this.cleanups.push(() => window.removeEventListener(eventName, this.handleUrlChange));\n\n // Set up reactive rendering effect.\n // Only currentRouteAtom.value is the intended reactive dependency.\n // renderRoute calls user lifecycle hooks (beforeTransition, onEnter, render,\n // onMount, afterTransition) that may read atoms — those reads must not\n // subscribe this effect to extra dependencies.\n const renderEffect = effect(() => {\n const routeName = this.currentRouteAtom.value; // sole tracked dependency\n untracked(() => this.renderRoute(routeName)); // user hooks run untracked\n });\n this.cleanups.push(() => renderEffect.dispose());\n\n // Auto-bind navigation links\n this.setupAutoBindLinks();\n\n // Auto-cleanup router if target element is removed\n if (this.$target[0]) {\n registry.trackCleanup(this.$target[0], this.destroy);\n }\n }\n\n // --- Mode-abstracted internal methods ---\n\n /**\n * Extracts route name from current URL.\n * Uses `normalizedBasePath` for consistent stripping in history mode.\n */\n private getRouteName(): string {\n const { default: defaultRoute } = this.config;\n\n if (this.isHistoryMode) {\n let pathname = window.location.pathname;\n // Strip the pre-normalized base path prefix.\n if (this.normalizedBasePath && pathname.startsWith(this.normalizedBasePath)) {\n pathname = pathname.substring(this.normalizedBasePath.length);\n }\n // Remove leading slash (optimized: charCodeAt avoids substring allocation)\n if (pathname.charCodeAt(0) === 47) {\n pathname = pathname.slice(1);\n }\n return pathname || defaultRoute;\n }\n // Hash mode\n const hash = window.location.hash;\n const qIndex = hash.indexOf('?');\n const routeName = qIndex === -1 ? hash.substring(1) : hash.substring(1, qIndex);\n return routeName || defaultRoute;\n }\n\n /**\n * Parses query parameters from the current URL.\n *\n * Note: duplicate keys (e.g. `?a=1&a=2`) are collapsed to the last value\n * only (`{ a: '2' }`). This matches `URLSearchParams` → `Object.fromEntries`\n * behaviour. If multi-value keys are needed, access `queryParams` via\n * `new URLSearchParams(window.location.search).getAll('key')` directly.\n */\n private getQueryParams(): Record<string, string> {\n let raw: string;\n\n if (this.isHistoryMode) {\n raw = window.location.search.substring(1); // Remove leading '?'\n if (!raw) return {};\n } else {\n const hash = window.location.hash;\n const qIndex = hash.indexOf('?');\n if (qIndex === -1) return {};\n raw = hash.substring(qIndex + 1);\n }\n\n const sp = new URLSearchParams(raw);\n const params: Record<string, string> = Object.fromEntries(sp);\n\n // Warn about malformed percent-encoded sequences\n if (raw.includes('%')) {\n try {\n decodeURIComponent(raw);\n } catch (_e) {\n debug.warn(LOG_PREFIXES.ROUTE, ERROR_MESSAGES.MALFORMED_URI(raw));\n }\n }\n\n return params;\n }\n\n /**\n * Updates the browser URL to reflect a new route and keeps `previousUrl`\n * in sync so `handleUrlChange` does not re-process our own navigation.\n */\n private setUrl(routeName: string): void {\n if (this.isHistoryMode) {\n const url = `${this.normalizedBasePath}/${routeName}`;\n safePushState(null, url);\n this.previousUrl = url;\n } else {\n const hash = `#${routeName}`;\n window.location.hash = hash;\n this.previousUrl = hash;\n }\n }\n\n /**\n * Restores the URL when a navigation guard blocks the transition.\n * Uses pushState to safely add a new history entry, avoiding \"back button traps\"\n * that occur with replaceState during popstate events.\n */\n private restoreUrl(): void {\n if (this.isHistoryMode) {\n safePushState(null, this.previousUrl);\n } else {\n window.location.hash = this.previousUrl;\n }\n }\n\n /**\n * Returns the current full URL string for comparison purposes.\n */\n private getCurrentUrl(): string {\n if (this.isHistoryMode) {\n return window.location.pathname + window.location.search;\n }\n return window.location.hash;\n }\n\n // --- End mode-abstracted methods ---\n\n /**\n * Resolves route configuration, falling back to notFound route if needed.\n */\n private getRouteConfig(routeName: string): RouteDefinition | null {\n const { routes, notFound } = this.config;\n let routeConfig = routes[routeName];\n\n // Fallback to notFound route if route doesn't exist\n if (!routeConfig && notFound) {\n routeConfig = routes[notFound];\n }\n\n if (!routeConfig) {\n debug.warn(LOG_PREFIXES.ROUTE, ERROR_MESSAGES.ROUTE_NOT_FOUND(routeName));\n return null;\n }\n\n return routeConfig;\n }\n\n /**\n * Appends cloned template content into the target container.\n * Always appends — callers are responsible for calling `$target.empty()`\n * before invoking this method if a clean slate is needed.\n */\n private renderTemplate(templateSelector: string): boolean {\n let template = this.templateCache.get(templateSelector);\n\n if (!template) {\n const el = document.querySelector(templateSelector);\n if (!el || !(el instanceof HTMLTemplateElement)) {\n debug.warn(LOG_PREFIXES.ROUTE, ERROR_MESSAGES.TEMPLATE_NOT_FOUND(templateSelector));\n return false;\n }\n template = el;\n this.templateCache.set(templateSelector, template);\n }\n\n const clonedContent = template.content.cloneNode(true) as DocumentFragment;\n this.$target.append(clonedContent);\n\n return true;\n }\n\n /**\n * Renders the specified route, including lifecycle hooks and content.\n *\n * Called from within a reactive effect, so DOM mutations here run\n * synchronously inside the effect body. `registry.cleanupDescendants` is\n * called before `$target.empty()` to ensure any reactive bindings on\n * outgoing content are disposed before the nodes are removed — preventing\n * the MutationObserver auto-cleanup path from firing a redundant cleanup.\n *\n * If `beforeTransition` throws, the render is aborted and the outgoing\n * content remains in the DOM. This is intentional — a throwing hook signals\n * that the transition should not proceed.\n */\n private renderRoute(routeName: string): void {\n if (this.isDestroyed) return;\n\n // Validate target element exists\n const container = this.$target[0];\n if (!container) {\n debug.warn(LOG_PREFIXES.ROUTE, ERROR_MESSAGES.TARGET_NOT_FOUND(this.config.target));\n return;\n }\n\n // Resolve route configuration\n const routeConfig = this.getRouteConfig(routeName);\n if (!routeConfig) return;\n\n // Parse query parameters\n const params = this.getQueryParams();\n\n // `previousRoute` is '' on first render, so from !== to in all cases.\n const fromRoute = this.previousRoute;\n\n // Call beforeTransition hook.\n // If it throws, the render is aborted — outgoing content stays in the DOM.\n if (this.config.beforeTransition) {\n this.config.beforeTransition(fromRoute, routeName);\n }\n\n // Dispose reactive bindings on outgoing content before clearing the DOM.\n // $.fn.empty() (patched via jquery-patch) handles cleanupDescendants automatically.\n this.$target.empty();\n\n // Call onEnter hook and merge params\n let routeParams = params;\n if (routeConfig.onEnter) {\n const result = routeConfig.onEnter(params);\n if (result !== undefined) {\n routeParams = { ...params, ...result };\n }\n }\n\n // Render content (custom render or template)\n if (routeConfig.render) {\n routeConfig.render(container, routeName, routeParams);\n } else if (routeConfig.template) {\n if (this.renderTemplate(routeConfig.template)) {\n if (routeConfig.onMount) {\n routeConfig.onMount(this.$target.children());\n }\n }\n }\n\n // Call afterTransition hook\n if (this.config.afterTransition) {\n this.config.afterTransition(fromRoute, routeName);\n }\n\n // Update previous route for next transition\n this.previousRoute = routeName;\n }\n\n /**\n * Handles browser URL change events (hashchange or popstate).\n */\n private handleUrlChange(): void {\n if (this.isDestroyed) return;\n\n const currentUrl = this.getCurrentUrl();\n // Early-exit if URL didn't actually change (e.g., called by our own navigate()).\n if (currentUrl === this.previousUrl) return;\n\n const newRoute = this.getRouteName();\n // peek(): event handler path — reading for comparison only, not to subscribe.\n const oldRouteName = this.currentRouteAtom.peek();\n const params = this.getQueryParams();\n\n if (oldRouteName !== newRoute) {\n // Check onLeave guard for user-driven navigation\n const oldRouteConfig = this.config.routes[oldRouteName];\n if (oldRouteConfig?.onLeave) {\n if (oldRouteConfig.onLeave() === false) {\n // Navigation blocked — restore the URL without updating previousUrl,\n // so the next real navigation is still detected correctly.\n this.restoreUrl();\n return;\n }\n }\n // Update route first; the reactive effect will call renderRoute.\n // queryParamsAtom is set here so it is in sync before any subscriber\n // reads it during the same flush — renderRoute reads getQueryParams()\n // directly from the URL so there is no double-write risk.\n this.currentRouteAtom.value = newRoute;\n this.queryParamsAtom.value = params;\n } else {\n // Same route but URL changed (e.g., query params only)\n this.queryParamsAtom.value = params;\n const routeConfig = this.config.routes[oldRouteName];\n if (routeConfig?.onParamsChange) {\n routeConfig.onParamsChange(params);\n } else {\n this.renderRoute(newRoute);\n }\n }\n\n // Commit the new URL only after a successful (unblocked) transition.\n this.previousUrl = currentUrl;\n }\n\n /**\n * Sets up automatic binding for navigation links with data-route attribute.\n *\n * Event delegation is attached to `document` (not `$target`) so that\n * `[data-route]` links anywhere in the page — including outside the router's\n * target container — can trigger navigation. This is intentional: nav links\n * typically live in headers or sidebars, not inside the routed content area.\n *\n * Active-link management uses a reactive effect that re-runs only when\n * `currentRoute` changes — more efficient than a persistent MutationObserver.\n */\n private setupAutoBindLinks(): void {\n if (!this.config.autoBindLinks) return;\n\n // 1. Event delegation on document so nav links outside $target are handled.\n const delegateHandler = (e: JQuery.TriggeredEvent) => {\n e.preventDefault();\n const routeAttr = (e.currentTarget as HTMLElement).dataset.route;\n if (routeAttr != null) this.navigate(routeAttr);\n };\n\n $(document).on('click', '[data-route]', delegateHandler);\n this.cleanups.push(() => {\n $(document).off('click', '[data-route]', delegateHandler);\n });\n\n // 2. Active state management — re-runs only when currentRoute changes.\n // `activeClass` is always set (constructor fills it from ROUTE_DEFAULTS).\n const { activeClass } = this.config;\n\n const activeLinksEffect = effect(() => {\n const current = this.currentRouteAtom.value; // sole tracked dependency\n // DOM queries and class manipulations run untracked: they must not\n // subscribe the effect to anything beyond currentRouteAtom.\n untracked(() => {\n const links = document.querySelectorAll<HTMLElement>('[data-route]');\n\n for (const el of links) {\n const routeAttr = el.dataset.route!;\n const isActive = current === routeAttr;\n\n el.classList.toggle(activeClass as string, isActive);\n if (isActive) {\n el.setAttribute('aria-current', 'page');\n } else {\n el.removeAttribute('aria-current');\n }\n }\n });\n });\n\n this.cleanups.push(() => activeLinksEffect.dispose());\n }\n\n /**\n * Navigates to the specified route programmatically.\n *\n * If `routeName` resolves to an empty string after falling back to\n * `config.default`, `setUrl` will be called with an empty string, producing\n * a URL of `${basePath}/` in history mode. Callers should ensure\n * `config.default` is always a non-empty route name.\n */\n public navigate(routeName: string): void {\n if (this.isDestroyed) return;\n\n // peek(): navigate() is called imperatively (not inside an effect), so\n // reading the current route must not register a reactive dependency.\n const currentRouteName = this.currentRouteAtom.peek();\n const currentRouteConfig = this.config.routes[currentRouteName];\n\n if (currentRouteConfig?.onLeave) {\n const canLeave = currentRouteConfig.onLeave();\n if (canLeave === false) return; // Navigation blocked\n }\n\n // Resolve empty route name to default route, matching getRouteName behavior\n const resolved = routeName || this.config.default;\n if (!resolved) {\n debug.warn(\n LOG_PREFIXES.ROUTE,\n 'navigate() called with empty routeName and no default configured.'\n );\n return;\n }\n\n this.setUrl(resolved);\n // Clear stale query params when navigating to a new route.\n this.queryParamsAtom.value = {};\n this.currentRouteAtom.value = resolved;\n }\n\n /**\n * Cleans up all event listeners and effects, and releases the template cache.\n * Each cleanup function is called in a try/catch so that a single failing\n * cleanup does not prevent the remaining ones from running.\n */\n public destroy(): void {\n if (this.isDestroyed) return;\n this.isDestroyed = true;\n\n this.cleanups.forEach((fn) => {\n try {\n fn();\n } catch (e) {\n debug.warn(LOG_PREFIXES.ROUTE, 'Cleanup error during destroy:', e);\n }\n });\n this.cleanups.length = 0;\n\n // Release cached template references to allow GC.\n this.templateCache.clear();\n }\n}\n\n/**\n * Creates an SPA router with reactive state management.\n * Supports both hash-based and pushState-based (history) routing.\n *\n * This removes boilerplate from manual route handling by:\n * - Automatically tracking URL changes and updating the UI\n * - Managing template rendering with lifecycle hooks\n * - Handling active link states reactively\n * - Providing navigation guard support (onLeave)\n *\n * @param config - Router configuration\n * @returns Router instance with navigate, destroy methods and currentRoute atom\n *\n * @example\n * ```ts\n * const router = $.route({\n * target: '#app',\n * default: 'home',\n * routes: {\n * home: { template: '#tmpl-home' },\n * about: { template: '#tmpl-about' }\n * }\n * });\n * ```\n */\nexport function route(config: RouteConfig): Router {\n return new RouterImpl(config);\n}\n\n/**\n * Register as jQuery static method.\n * `$.extend(obj)` merges into JQueryStatic; use `$.fn.extend(obj)` for instance methods.\n */\n$.extend({\n route,\n});\n","import { computed } from '@but212/atom-effect';\nimport $ from 'jquery';\nimport type { ComputedAtom, FetchOptions } from './types';\n\n/**\n * A Promise that never settles, used to keep a computed atom in its pending\n * state after an aborted request — until the next reactive run supersedes it.\n *\n * When the async computed fn returns this value, core treats the run as still\n * in-flight (pending flag stays set) without resolving or rejecting. The next\n * run (triggered by invalidate() or a dependency change) replaces this state.\n *\n * Typed as `Promise<never>` so it can be widened to `Promise<T>` at the call\n * site without an `as unknown` double-cast — `never` is assignable to any `T`.\n *\n * Intentional module-level singleton: the Promise executor never resolves or\n * rejects, so the object is permanently live. This is expected and safe —\n * there are no closures over external references that would prevent GC of other\n * objects.\n */\nconst NEVER_SETTLE = new Promise<never>(() => {});\n\n// ============================================================================\n// atomFetch\n// ============================================================================\n\n$.extend({\n atomFetch<T>(urlOrFn: string | (() => string), options: FetchOptions<T>): ComputedAtom<T> {\n const { defaultValue, transform, method, headers, ajaxOptions, onError, eager } = options;\n\n // Hoist 1: Determine URL getter once.\n const getUrl = typeof urlOrFn === 'function' ? urlOrFn : null;\n const staticUrl = typeof urlOrFn === 'string' ? urlOrFn : undefined;\n\n // Hoist 2: Pre-merge static options to avoid repeated object spreads per request.\n const baseOptions = {\n ...ajaxOptions,\n ...(method !== undefined && { method }),\n ...(headers !== undefined && { headers }),\n };\n\n let abortController: AbortController | null = null;\n\n return computed(\n async () => {\n abortController?.abort();\n abortController = new AbortController();\n const signal = abortController.signal;\n\n const reqOptions = staticUrl\n ? { ...baseOptions, url: staticUrl }\n : { ...baseOptions, url: getUrl!() };\n\n const xhr = $.ajax(reqOptions);\n\n signal.onabort = () => xhr.abort();\n if (signal.aborted) xhr.abort();\n\n try {\n const raw = await xhr;\n return transform ? transform(raw) : (raw as T);\n } catch (err) {\n if (signal.aborted) {\n return NEVER_SETTLE as Promise<T>;\n }\n try {\n onError?.(err);\n } catch {\n // Ignore\n }\n throw err;\n } finally {\n signal.onabort = null;\n if (abortController.signal === signal) abortController = null;\n }\n },\n { defaultValue, lazy: !(eager ?? true) }\n );\n },\n});\n","/**\n * atom-effect-jquery\n *\n * Brings reactivity to jQuery.\n *\n * Features:\n * - Full CJK IME Support (Input Method Editor).\n * - Auto-cleanup via MutationObserver (No memory leaks).\n * - Debug Mode: Console logging + Visual Highlighting.\n *\n * Type augmentation note:\n * This package extends both `JQuery` and `JQueryStatic` via global interface\n * merging in `types.ts`. Consumers using the `export default $` path will\n * receive the augmented type automatically because the module's side-effect\n * imports apply the augmentation at import time.\n */\n\nimport $ from 'jquery';\n\n// ============================================================================\n// Plugin registrations (order matters — namespace must come first)\n// ============================================================================\n\n// Registers $.atom, $.computed, $.effect, $.batch, $.untracked,\n// $.isAtom, $.isComputed, $.isReactive, $.nextTick\nimport './namespace';\n\n// Registers $.fn.atomText/Html/Class/Css/Attr/Prop/Show/Hide/Val/Checked/On/Bind/Unbind.\nimport './chainable';\n\n// Registers $.fn.atomList\nimport './list';\n\n// Registers $.fn.atomMount / $.fn.atomUnmount\nimport './mount';\n\n// Registers $.route\nimport './route';\n\n// Registers $.atomFetch\nimport './fetch';\n\n// ============================================================================\n// Runtime initialisation (browser only)\n// ============================================================================\n\nimport { enablejQueryOverrides } from './jquery-patch';\nimport { disableAutoCleanup, enableAutoCleanup, registry } from './registry';\n\n// $() runs after DOMContentLoaded, so document.body is guaranteed non-null here.\n// In JSDOM/test environments jQuery calls the callback synchronously.\n$(() => {\n // Wraps jQuery event dispatch in batch() so that rapid user interactions\n // (e.g. typing in an input) batch atom writes into a single reactive flush.\n enablejQueryOverrides();\n\n // Watches document.body for removed elements and disposes their reactive\n // bindings automatically, preventing memory leaks without manual cleanup.\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n enableAutoCleanup(document.body!);\n});\n\n// ============================================================================\n// ESM exports — values\n// ============================================================================\n\n// Core primitives — re-exported so consumers do not need to depend on\n// @but212/atom-effect directly.\nexport {\n atom,\n batch,\n computed,\n effect,\n isAtom,\n isComputed,\n untracked,\n} from '@but212/atom-effect';\n\n// jQuery override controls — called automatically on DOM ready, but exposed\n// here for consumers who manage initialisation themselves (e.g. custom roots,\n// shadow DOMs, or environments where the automatic call is not appropriate).\nexport { disablejQueryOverrides, enablejQueryOverrides } from './jquery-patch';\n\n// nextTick is registered on $ via namespace.ts and exported here so ESM\n// consumers can import it without touching $.\n// isReactive is defined in utils.ts and also registered on $ via namespace.ts.\nexport { nextTick } from './namespace';\nexport { isReactive } from './utils';\n\n// Registry API — for advanced lifecycle control (custom roots, manual cleanup).\n// Note: enableAutoCleanup is called automatically on DOM ready with document.body.\n// Call it again only if you need a different root or want to re-initialise.\nexport { registry, enableAutoCleanup, disableAutoCleanup };\n\n// ============================================================================\n// ESM exports — types\n// ============================================================================\n\n// Public-facing types — includes everything needed to fully type-check calls\n// to every exported function and jQuery plugin method.\nexport type {\n // Binding authoring\n BindingOptions,\n ComponentFn,\n // Reactive primitives (core)\n ComputedAtom,\n CssBindings,\n CssValue,\n EffectCleanup,\n EffectResult,\n EqualFn,\n // Fetch\n FetchOptions,\n // List\n ListOptions,\n PrimitiveValue,\n ReactiveValue,\n ReadonlyAtom,\n // Routing\n RenderRoute,\n RouteConfig,\n RouteDefinition,\n RouteLifecycle,\n Router,\n TemplateRoute,\n ValOptions,\n WritableAtom,\n} from './types';\n\n// The augmented jQuery object. Consumers importing this receive a $ with all\n// atom-effect plugin methods already typed via global interface merging.\nexport default $;\n"],"names":["b","u","$","a","d","rt","H","L","W","ot","D","e","s","f","I","m","ht","ct","x","F","i","ut","_t","K","n","P","V","v","h","S","O","J","Z","r","k","w","M","B","R","tt","et","X","G","at","lt","T","z","st","it","_","Ct","Q","ft","gt","Et","c","l","Tt","Ot","nt","Y","q","A","p","N","E","g","y","C","U","dt","pt","It","o","At","j","St","yt","Nt","LOG_PREFIXES","ROUTE_DEFAULTS","INPUT_DEFAULTS","VALID_INPUT_TAGS","DANGEROUS_PROPS","ERROR_MESSAGES","name","selector","raw","prop","tagName","method","key","index","debugType","isReactive","value","isAtom","getSelector","el","list","len","URL_ATTRS","hasOwn","DANGEROUS_PROTOCOL_RE","DANGEROUS_CSS_RE","DANGEROUS_CSS_URL_RE","STRIP_CTRL_RE","STRIP_XML_RE","DANGEROUS_TAG_RE","DANGEROUS_PROTOCOL_GLOBAL_RE","DANGEROUS_DATA_URI_RE","UNSAFE_ATTR_RE","DANGEROUS_CSS_GLOBAL_RE","sanitizeHtml","html","safe","prev","isDangerousUrl","attrName","isDangerousCssValue","shallowEqual","keysA","keysB","objA","objB","getLIS","arr","predecessors","result","resultLen","val","lastIdx","left","right","mid","midIdx","leftIdx","lis","curr","HIGHLIGHT_DURATION_MS","HIGHLIGHT_TRANSITION","getInitialDebugState","flag","__vite_import_meta_env__","debugEnabled","debug","type","args","oldVal","newVal","target","highlightElement","prefix","message","rest","cause","HIGHLIGHT_CLASS","HIGHLIGHT_STYLE_ATTR","_highlightStyleRef","injectHighlightStyle","style","highlightTimers","highlightRafs","existingRaf","existingTimer","rafId","atom","initialValue","options","createAtom","nextTick","resolve","staticExtensions","computed","effect","batch","untracked","isComputed","AES_BOUND","BindingRegistry","node","res","fx","record","fn","descendants","child","registry","observer","observedRoot","enableAutoCleanup","root","mutations","mutation","disableAutoCleanup","registerReactiveEffect","source","updater","reactiveSource","INTERNAL_HANDLER","handlerMap","originals","getWrappedHandler","wrapped","wrapEventMap","map","newMap","handler","resolveOffEventMap","enablejQueryOverrides","orig","targets","types","disablejQueryOverrides","BindingFlags","instanceCounter","InputBinding","$el","formatted","currentVal","isFocused","start","end","debounce","parsed","applyInputBinding","binding","camelCache","getCamelCase","cached","htmlSanitizeCache","getSanitizedHtml","createContext","bindText","ctx","formatter","bindHtml","sanitized","bindClass","classMap","className","bindCss","cssMap","camel","unit","strVal","bindAttr","attrMap","bindProp","propMap","bindVisibility","condition","invert","visible","bindVal","cleanup","bindChecked","current","bindEvents","eventMap","bindOn","event","bindUnbind","classNameOrMap","propOrMap","nameOrMap","valOpts","insertOrAppend","nextNode","$container","render","bind","update","onAdd","onRemove","empty","getKey","item","_index","containerSelector","itemMap","removingKeys","oldKeys","$emptyEl","scheduleRemoval","entry","commitRemoval","removeItem","items","itemCount","safeEmpty","oldIndexMap","newKeys","newKeySet","newIndices","trKeys","trItems","trIdxs","oldItem","SEPARATOR","renderCount","renderResults","htmlParts","t","sanitizedFragments","combined","fragIdx","oldEl","lisArr","lisIdx","isInitial","childIdx","fragment","state","isNewItem","isReplaced","EMPTY_PROPS","component","props","teardown","err","safePushState","data","url","RouterImpl","config","eventName","renderEffect","routeName","defaultRoute","pathname","hash","qIndex","sp","params","routes","notFound","routeConfig","templateSelector","template","clonedContent","container","fromRoute","routeParams","currentUrl","newRoute","oldRouteName","oldRouteConfig","delegateHandler","routeAttr","activeClass","activeLinksEffect","links","isActive","currentRouteName","currentRouteConfig","resolved","route","NEVER_SETTLE","urlOrFn","defaultValue","transform","headers","ajaxOptions","onError","eager","getUrl","staticUrl","baseOptions","abortController","signal","reqOptions","xhr"],"mappings":";;AAAK,MAACA,KAAI;AAAA,EACR,MAAM;AAAA,EACN,SAAS;AAAA,EACT,UAAU;AAAA,EACV,UAAU;AACZ,GAAGC,IAAI;AAAA,EACL,UAAU;AAAA,EACV,WAAW;AACb,G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O,IAA0C;AAE9C,WAAOpM;AAAAA,MACL,YAAY;AACV,QAAAoM,GAAiB,MAAA,GACjBA,IAAkB,IAAI,gBAAA;AACtB,cAAMC,IAASD,EAAgB,QAEzBE,IAAaJ,IACf,EAAE,GAAGC,GAAa,KAAKD,EAAA,IACvB,EAAE,GAAGC,GAAa,KAAKF,IAAQ,GAE7BM,IAAMlX,EAAE,KAAKiX,CAAU;AAE7B,QAAAD,EAAO,UAAU,MAAME,EAAI,MAAA,GACvBF,EAAO,WAASE,EAAI,MAAA;AAExB,YAAI;AACF,gBAAM7R,IAAM,MAAM6R;AAClB,iBAAOX,IAAYA,EAAUlR,CAAG,IAAKA;AAAA,QACvC,SAASyO,GAAK;AACZ,cAAIkD,EAAO;AACT,mBAAOZ;AAET,cAAI;AACF,YAAAM,IAAU5C,CAAG;AAAA,UACf,QAAQ;AAAA,UAER;AACA,gBAAMA;AAAA,QACR,UAAA;AACE,UAAAkD,EAAO,UAAU,MACbD,EAAgB,WAAWC,MAAQD,IAAkB;AAAA,QAC3D;AAAA,MACF;AAAA,MACA,EAAE,cAAAT,GAAc,MAAM,EAAEK,KAAS,IAAA;AAAA,IAAM;AAAA,EAE3C;AACF,CAAC;AC5BD3W,EAAE,MAAM;AAGN,EAAA+M,GAAA,GAKAnB,GAAkB,SAAS,IAAK;AAClC,CAAC;"}
|
|
1
|
+
{"version":3,"file":"index.mjs","sources":["../../core/dist/index.mjs","../src/constants.ts","../src/utils.ts","../src/debug.ts","../src/namespace.ts","../src/registry.ts","../src/effect-factory.ts","../src/jquery-patch.ts","../src/types.ts","../src/input-binding.ts","../src/sanitize.ts","../src/unified.ts","../src/chainable.ts","../src/list.ts","../src/mount.ts","../src/route.ts","../src/fetch.ts","../src/index.ts"],"sourcesContent":["const N = {\n IDLE: \"idle\",\n PENDING: \"pending\",\n RESOLVED: \"resolved\",\n REJECTED: \"rejected\"\n}, _ = {\n DISPOSED: 1,\n EXECUTING: 8\n}, W = {\n DISPOSED: 1,\n /** Marker bit: identifies this node as a computed. */\n IS_COMPUTED: 2,\n DIRTY: 8,\n IDLE: 16,\n PENDING: 32,\n RESOLVED: 64,\n REJECTED: 128,\n RECOMPUTING: 256,\n HAS_ERROR: 512\n}, a = {\n DISPOSED: 1,\n SYNC: 8,\n NOTIFICATION_SCHEDULED: 16\n}, d = {\n // Infinite loop protection\n MAX_EXECUTIONS_PER_SECOND: 1e3,\n MAX_EXECUTIONS_PER_EFFECT: 100,\n // Batch processing limits to prevent blocking the main thread for too long\n MAX_EXECUTIONS_PER_FLUSH: 1e4,\n MAX_FLUSH_ITERATIONS: 1e3,\n MIN_FLUSH_ITERATIONS: 10,\n // Memory management\n BATCH_QUEUE_SHRINK_THRESHOLD: 1e3\n}, ht = {\n WARN_INFINITE_LOOP: !0,\n EFFECT_FREQUENCY_WINDOW: 1e3\n}, V = {\n MAX_ASYNC_RETRIES: 3,\n MAX_PROMISE_ID: Number.MAX_SAFE_INTEGER - 1\n}, g = {\n /** Uninitialized epoch marker. Used as initial value before any flush has occurred. */\n UNINITIALIZED: -1\n}, F = 1073741823, Z = typeof process < \"u\" && process.env && !1 || !1, ot = Object.freeze([]);\nfunction X(n, t, s) {\n const e = /* @__PURE__ */ new Map();\n for (let i = 0; i < t.length; i++) {\n const r = t[i];\n r?.unsub && e.set(r.node, r.unsub);\n }\n for (let i = 0; i < n.length; i++) {\n const r = n[i];\n if (!r) continue;\n const h = r.node, o = e.get(h);\n o !== void 0 ? (r.unsub = o, e.delete(h)) : r.unsub || (r.unsub = h.subscribe(s));\n }\n for (const i of e.values())\n i();\n}\nclass y {\n constructor(t, s, e = void 0) {\n this.node = t, this.version = s, this.unsub = e;\n }\n}\nclass ct {\n constructor(t, s) {\n this.fn = t, this.sub = s;\n }\n notify(t, s) {\n this.fn ? this.fn(t, s) : this.sub && this.sub.execute();\n }\n}\nclass k extends Error {\n constructor(t, s = null, e = !0) {\n super(t), this.cause = s, this.recoverable = e, this.name = \"AtomError\";\n }\n}\nclass I extends k {\n constructor(t, s = null) {\n super(t, s, !0), this.name = \"ComputedError\";\n }\n}\nclass C extends k {\n constructor(t, s = null) {\n super(t, s, !1), this.name = \"EffectError\";\n }\n}\nclass m extends k {\n constructor(t, s = null) {\n super(t, s, !1), this.name = \"SchedulerError\";\n }\n}\nconst c = {\n // Computed Errors\n COMPUTED_MUST_BE_FUNCTION: \"Computed target must be a function\",\n COMPUTED_ASYNC_PENDING_NO_DEFAULT: \"Async computation pending with no default value\",\n COMPUTED_COMPUTATION_FAILED: \"Computation execution failed\",\n COMPUTED_ASYNC_COMPUTATION_FAILED: \"Async computation execution failed\",\n COMPUTED_CIRCULAR_DEPENDENCY: \"Circular dependency detected\",\n COMPUTED_DISPOSED: \"Attempted to access disposed computed\",\n // Atom Errors\n ATOM_SUBSCRIBER_MUST_BE_FUNCTION: \"Subscriber must be a function or Subscriber object\",\n ATOM_INDIVIDUAL_SUBSCRIBER_FAILED: \"Subscriber execution failed\",\n // Effect Errors\n EFFECT_MUST_BE_FUNCTION: \"Effect target must be a function\",\n EFFECT_EXECUTION_FAILED: \"Effect execution failed\",\n EFFECT_CLEANUP_FAILED: \"Effect cleanup failed\",\n EFFECT_DISPOSED: \"Attempted to run disposed effect\",\n // Scheduler Errors\n SCHEDULER_FLUSH_OVERFLOW: (n, t) => `Maximum flush iterations (${n}) exceeded. ${t} jobs dropped. Possible infinite loop.`,\n // System / Debug\n CALLBACK_ERROR_IN_ERROR_HANDLER: \"Exception encountered in onError handler\",\n // Effect frequency\n EFFECT_FREQUENCY_LIMIT_EXCEEDED: \"Effect executed too frequently within 1 second. Suspected infinite loop.\",\n SCHEDULER_CALLBACK_MUST_BE_FUNCTION: \"Scheduler callback must be a function\",\n SCHEDULER_END_BATCH_WITHOUT_START: \"endBatch() called without matching startBatch(). Ignoring.\",\n BATCH_CALLBACK_MUST_BE_FUNCTION: \"Batch callback must be a function\"\n}, ut = /* @__PURE__ */ Symbol(\"AtomEffect.DebugName\"), _t = /* @__PURE__ */ Symbol(\"AtomEffect.Type\"), x = /* @__PURE__ */ Symbol(\"AtomEffect.NoDefaultValue\"), B = {\n // Dev mode flag\n enabled: Z,\n warnInfiniteLoop: ht.WARN_INFINITE_LOOP,\n warn(n, t) {\n },\n attachDebugInfo(n, t, s) {\n },\n getDebugName: (n) => n?.[ut],\n getDebugType: (n) => n?.[_t]\n};\nlet lt = 1;\nconst at = () => lt++;\nfunction S(n, t, s) {\n if (n instanceof k)\n return n;\n const e = n instanceof Error, i = e ? n.message : String(n), r = e ? n : void 0, o = `${e ? n.constructor.name : \"Unexpected error\"} (${s}): ${i}`;\n return new t(o, r);\n}\nclass J {\n constructor() {\n this.flags = 0, this.version = 0, this._lastSeenEpoch = g.UNINITIALIZED, this.id = at() & F;\n }\n}\nclass tt extends J {\n constructor() {\n super(...arguments), this._notifying = 0;\n }\n /**\n * Adds subscriber.\n */\n subscribe(t) {\n const s = typeof t == \"function\";\n if (!s && (!t || typeof t.execute != \"function\"))\n throw S(\n new TypeError(\"Invalid subscriber\"),\n k,\n c.ATOM_SUBSCRIBER_MUST_BE_FUNCTION\n );\n const e = this._subscribers, i = e.length;\n let r = !1;\n for (let o = 0; o < i; o++) {\n const U = e[o];\n if (U != null && (s ? U.fn === t : U.sub === t)) {\n r = !0;\n break;\n }\n }\n if (r)\n return () => {\n };\n const h = new ct(\n s ? t : void 0,\n s ? void 0 : t\n );\n return e.push(h), () => this._unsubscribe(h);\n }\n _unsubscribe(t) {\n const s = this._subscribers;\n let e = -1;\n for (let r = 0; r < s.length; r++)\n if (s[r] === t) {\n e = r;\n break;\n }\n if (e === -1) return;\n if (this._notifying > 0) {\n s[e] = null;\n return;\n }\n const i = s.pop();\n e < s.length && i !== void 0 && (s[e] = i);\n }\n subscriberCount() {\n let t = 0;\n const s = this._subscribers;\n for (let e = 0; e < s.length; e++)\n s[e] != null && t++;\n return t;\n }\n _notifySubscribers(t, s) {\n const e = this._subscribers, i = e.length;\n if (i !== 0) {\n this._notifying++;\n try {\n for (let r = 0; r < i; r++) {\n const h = e[r];\n if (h != null)\n try {\n h.notify(t, s);\n } catch (o) {\n this._handleNotifyError(o);\n }\n }\n } finally {\n this._notifying--, this._notifying === 0 && this._cleanupTombstones();\n }\n }\n }\n _cleanupTombstones() {\n const t = this._subscribers;\n let s = 0;\n for (; s < t.length; )\n if (t[s] === null) {\n const e = t.pop();\n s < t.length && e !== void 0 && (t[s] = e);\n } else\n s++;\n }\n _handleNotifyError(t) {\n console.error(S(t, k, c.ATOM_INDIVIDUAL_SUBSCRIBER_FAILED));\n }\n}\nlet v = 0;\nconst w = () => (v = v + 1 & F || 1, v), M = (n) => n + 1 & F;\nlet z = 0, R = !1, st = 0;\nconst et = () => st;\nfunction G() {\n return R ? !1 : (R = !0, st = w(), z = 0, !0);\n}\nconst Q = () => {\n R = !1;\n}, ft = () => R ? ++z : 0;\nclass Et {\n constructor() {\n this._queueBuffer = [[], []], this._bufferIndex = 0, this._size = 0, this._epoch = 0, this._isProcessing = !1, this._isBatching = !1, this._isFlushingSync = !1, this._batchDepth = 0, this._batchQueue = [], this._batchQueueSize = 0, this._maxFlushIterations = d.MAX_FLUSH_ITERATIONS, this.onOverflow = null, this._boundRunLoop = this._runLoop.bind(this);\n }\n get phase() {\n return this._isProcessing || this._isFlushingSync ? 2 : this._isBatching ? 1 : 0;\n }\n get queueSize() {\n return this._size;\n }\n get isBatching() {\n return this._isBatching;\n }\n /**\n * Schedules job.\n */\n schedule(t) {\n if (t._nextEpoch !== this._epoch) {\n if (t._nextEpoch = this._epoch, this._isBatching || this._isFlushingSync) {\n this._batchQueue[this._batchQueueSize++] = t;\n return;\n }\n this._queueBuffer[this._bufferIndex][this._size++] = t, this._isProcessing || this._flush();\n }\n }\n /**\n * Triggers flush.\n */\n _flush() {\n this._isProcessing || this._size === 0 || (this._isProcessing = !0, queueMicrotask(this._boundRunLoop));\n }\n /**\n * Scheduler loop.\n */\n _runLoop() {\n try {\n if (this._size === 0) return;\n const t = G();\n this._drainQueue(), t && Q();\n } finally {\n this._isProcessing = !1, this._size > 0 && !this._isBatching && this._flush();\n }\n }\n _flushSync() {\n this._isFlushingSync = !0;\n const t = G();\n try {\n this._mergeBatchQueue(), this._drainQueue();\n } finally {\n this._isFlushingSync = !1, t && Q();\n }\n }\n _mergeBatchQueue() {\n if (this._batchQueueSize === 0) return;\n const t = ++this._epoch, s = this._batchQueue, e = this._queueBuffer[this._bufferIndex];\n let i = this._size;\n s.slice(0, this._batchQueueSize).forEach((r) => {\n r._nextEpoch !== t && (r._nextEpoch = t, e[i++] = r);\n }), this._size = i, this._batchQueueSize = 0, s.length > d.BATCH_QUEUE_SHRINK_THRESHOLD && (s.length = 0);\n }\n _drainQueue() {\n let t = 0;\n for (; this._size > 0; ) {\n if (++t > this._maxFlushIterations) {\n this._handleFlushOverflow();\n return;\n }\n this._processQueue(), this._mergeBatchQueue();\n }\n }\n _processQueue() {\n const t = this._bufferIndex, s = this._queueBuffer[t], e = this._size;\n this._bufferIndex = t ^ 1, this._size = 0, this._epoch++;\n for (let i = 0; i < e; i++)\n try {\n const r = s[i];\n typeof r == \"function\" ? r() : r.execute();\n } catch (r) {\n console.error(new m(\"Error occurred during scheduler execution\", r));\n }\n s.length = 0;\n }\n _handleFlushOverflow() {\n const t = this._size + this._batchQueueSize;\n if (console.error(\n new m(\n c.SCHEDULER_FLUSH_OVERFLOW(this._maxFlushIterations, t)\n )\n ), this._size = 0, this._queueBuffer[this._bufferIndex].length = 0, this._batchQueueSize = 0, this.onOverflow)\n try {\n this.onOverflow(t);\n } catch {\n }\n }\n startBatch() {\n this._batchDepth++, this._isBatching = !0;\n }\n endBatch() {\n this._batchDepth !== 0 && --this._batchDepth === 0 && (this._flushSync(), this._isBatching = !1);\n }\n setMaxFlushIterations(t) {\n if (t < d.MIN_FLUSH_ITERATIONS)\n throw new m(\n `Max flush iterations must be at least ${d.MIN_FLUSH_ITERATIONS}`\n );\n this._maxFlushIterations = t;\n }\n}\nconst T = new Et(), H = /* @__PURE__ */ Symbol.for(\"atom-effect/atom\"), it = /* @__PURE__ */ Symbol.for(\"atom-effect/computed\"), nt = /* @__PURE__ */ Symbol.for(\"atom-effect/effect\"), dt = /* @__PURE__ */ Symbol.for(\"atom-effect/writable\"), l = {\n /** Active listener. */\n current: null,\n /**\n * Executes in context.\n *\n * @param listener - The subscriber.\n * @param fn - The logic to execute.\n * @returns The result of `fn`.\n */\n run(n, t) {\n const s = this.current;\n this.current = n;\n try {\n return t();\n } finally {\n this.current = s;\n }\n }\n};\nfunction Dt(n) {\n const t = l.current;\n if (t === null) return n();\n l.current = null;\n try {\n return n();\n } finally {\n l.current = t;\n }\n}\nvar Y, q;\nclass It extends tt {\n constructor(t, s) {\n super(), this._pendingOldValue = void 0, this._subscribers = [], this[q] = !0, this[Y] = !0, this._value = t, s && (this.flags |= a.SYNC), B.attachDebugInfo(this, \"atom\", this.id);\n }\n get value() {\n return l.current?.addDependency(this), this._value;\n }\n set value(t) {\n const s = this._value;\n if (Object.is(s, t)) return;\n this._value = t, this.version = M(this.version);\n const e = this.flags;\n if (!(this._subscribers.length === 0 || e & a.NOTIFICATION_SCHEDULED)) {\n if (this._pendingOldValue = s, this.flags = e | a.NOTIFICATION_SCHEDULED, e & a.SYNC && !T.isBatching) {\n this._flushNotifications();\n return;\n }\n T.schedule(this);\n }\n }\n /**\n * Executes scheduled notification.\n * @internal\n */\n execute() {\n this._flushNotifications();\n }\n /**\n * Triggers subscribers.\n */\n _flushNotifications() {\n const t = this.flags;\n if (!(t & a.NOTIFICATION_SCHEDULED) || t & a.DISPOSED)\n return;\n const s = this._pendingOldValue;\n this._pendingOldValue = void 0, this.flags &= -17, this._notifySubscribers(this._value, s);\n }\n peek() {\n return this._value;\n }\n dispose() {\n this.flags & a.DISPOSED || (this._subscribers.length = 0, this.flags |= a.DISPOSED, this._value = void 0, this._pendingOldValue = void 0);\n }\n [(q = H, Y = dt, Symbol.dispose)]() {\n this.dispose();\n }\n}\nfunction bt(n, t = {}) {\n return new It(n, t.sync ?? !1);\n}\nclass pt {\n /**\n * @param limit - Max unique arrays to hold (default: 50). Prevents the pool itself from consuming too much memory.\n * @param capacity - Max length of an array to accept (default: 256).\n * @param enableStats - Force-enable stats even in production (default: false).\n */\n constructor(t = 50, s = 256, e = !1) {\n this.limit = t, this.capacity = s, this.pool = [], this.stats = null, this.stats = e ? {\n acquired: 0,\n released: 0,\n rejected: { frozen: 0, tooLarge: 0, poolFull: 0 }\n } : null;\n }\n /**\n * Acquires array.\n */\n acquire() {\n return this.stats && this.stats.acquired++, this.pool.pop() ?? [];\n }\n /**\n * Releases array.\n *\n * @param arr - Array to release.\n * @param emptyConst - Optional empty constant.\n */\n release(t, s) {\n if (!(s && t === s)) {\n if (t.length > this.capacity) {\n this.stats && this.stats.rejected.tooLarge++;\n return;\n }\n if (this.pool.length >= this.limit) {\n this.stats && this.stats.rejected.poolFull++;\n return;\n }\n if (Object.isFrozen(t)) {\n this.stats && this.stats.rejected.frozen++;\n return;\n }\n t.length = 0, this.pool.push(t), this.stats && this.stats.released++;\n }\n }\n /**\n * Pool stats.\n */\n getStats() {\n if (!this.stats) return null;\n const { acquired: t, released: s, rejected: e } = this.stats, i = t - s - (e.frozen + e.tooLarge + e.poolFull);\n return {\n acquired: t,\n released: s,\n rejected: { ...e },\n leaked: i,\n poolSize: this.pool.length\n };\n }\n /**\n * Resets pool.\n */\n reset() {\n this.pool.length = 0, this.stats && (this.stats = {\n acquired: 0,\n released: 0,\n rejected: { frozen: 0, tooLarge: 0, poolFull: 0 }\n });\n }\n}\nconst u = Object.freeze(\n []\n), f = new pt();\nfunction Tt(n) {\n return n !== null && typeof n == \"object\" && H in n;\n}\nfunction Nt(n) {\n return n !== null && typeof n == \"object\" && it in n;\n}\nfunction Lt(n) {\n return n !== null && typeof n == \"object\" && nt in n;\n}\nfunction rt(n) {\n return n !== null && typeof n == \"object\" && typeof n.then == \"function\";\n}\nvar j, $;\nconst { IDLE: L, DIRTY: p, PENDING: O, RESOLVED: E, REJECTED: b, HAS_ERROR: A, RECOMPUTING: D, DISPOSED: P, IS_COMPUTED: Ct } = W;\nfunction gt(n) {\n return n & E ? N.RESOLVED : n & O ? N.PENDING : n & b ? N.REJECTED : N.IDLE;\n}\nclass St extends tt {\n constructor(t, s = {}) {\n if (typeof t != \"function\") throw new I(c.COMPUTED_MUST_BE_FUNCTION);\n super(), this[$] = !0, this[j] = !0, this._error = null, this._promiseId = 0, this._subscribers = [], this._links = u, this._asyncStartAggregateVersion = 0, this._asyncRetryCount = 0, this._lastDriftEpoch = g.UNINITIALIZED, this._trackEpoch = g.UNINITIALIZED, this._trackLinks = u, this._trackCount = 0, this._value = void 0, this.flags = Ct | p | L, this._equal = s.equal ?? Object.is, this._fn = t, this._defaultValue = \"defaultValue\" in s ? s.defaultValue : x, this._onError = s.onError ?? null;\n const e = s.maxAsyncRetries;\n if (this._maxAsyncRetries = (e ?? V.MAX_ASYNC_RETRIES) & F, B.attachDebugInfo(this, \"computed\", this.id), s.lazy === !1)\n try {\n this._recompute();\n } catch {\n }\n }\n _track() {\n l.current?.addDependency(this);\n }\n get value() {\n this._track();\n const t = this.flags;\n if ((t & (E | p | L)) === E)\n return this._value;\n if (t & P)\n throw new I(c.COMPUTED_DISPOSED);\n if (t & D) {\n if (this._defaultValue !== x) return this._defaultValue;\n throw new I(c.COMPUTED_CIRCULAR_DEPENDENCY);\n }\n if (t & (p | L) && (this._recompute(), this.flags & E))\n return this._value;\n const s = this._defaultValue, e = s !== x;\n if (this.flags & O) {\n if (e) return s;\n throw new I(c.COMPUTED_ASYNC_PENDING_NO_DEFAULT);\n }\n if (this.flags & b) {\n if (e) return s;\n throw this._error;\n }\n return this._value;\n }\n peek() {\n return this._value;\n }\n get state() {\n return this._track(), gt(this.flags);\n }\n get hasError() {\n return this._track(), this.flags & (b | A) ? !0 : this._links.some((t) => t?.node?.flags & A);\n }\n get isValid() {\n return !this.hasError;\n }\n get errors() {\n if (this._track(), !this.hasError) return ot;\n const t = [];\n return this._error && t.push(this._error), this._links.forEach((e) => {\n const i = e.node;\n i.flags & A && i.errors.forEach((h) => {\n h && !t.includes(h) && t.push(h);\n });\n }), Object.freeze(t);\n }\n get lastError() {\n return this._track(), this._error;\n }\n get isPending() {\n return this._track(), (this.flags & O) !== 0;\n }\n get isResolved() {\n return this._track(), (this.flags & E) !== 0;\n }\n invalidate() {\n this._markDirty();\n }\n dispose() {\n if (this.flags & P) return;\n const t = this._links;\n t !== u && (t.forEach((s) => s.unsub?.()), f.release(t), this._links = u), this._subscribers.length = 0, this.flags = P | p | L, this._error = null, this._value = void 0;\n }\n [($ = H, j = it, Symbol.dispose)]() {\n this.dispose();\n }\n addDependency(t) {\n if (t._lastSeenEpoch !== this._trackEpoch) {\n if (t._lastSeenEpoch = this._trackEpoch, this._trackLinks === this._links && this._trackCount < this._links.length && this._links[this._trackCount].node === t) {\n this._links[this._trackCount].version = t.version, this._trackCount++;\n return;\n }\n if (this._trackLinks === this._links) {\n const s = f.acquire();\n for (let e = 0; e < this._trackCount; e++)\n s[e] = this._links[e];\n this._trackLinks = s;\n }\n this._trackCount < this._trackLinks.length ? this._trackLinks[this._trackCount] = new y(t, t.version) : this._trackLinks.push(new y(t, t.version)), this._trackCount++;\n }\n }\n _recompute() {\n if (this.flags & D) return;\n this.flags |= D;\n const t = this._links;\n this._trackEpoch = w(), this._trackLinks = t, this._trackCount = 0;\n let s = !1;\n try {\n const e = l.run(this, this._fn);\n if (this._trackLinks === t)\n if (this._trackCount === t.length)\n s = !0;\n else {\n for (let i = this._trackCount; i < t.length; i++)\n t[i].unsub?.();\n t.length = this._trackCount, s = !0;\n }\n else\n this._trackLinks.length = this._trackCount, X(this._trackLinks, t, this), this._links = this._trackLinks, s = !0;\n rt(e) ? this._handleAsyncComputation(e) : this._finalizeResolution(e);\n } catch (e) {\n if (!s)\n try {\n if (this._trackLinks === t) {\n for (let i = this._trackCount; i < t.length; i++)\n t[i].unsub?.();\n t.length = this._trackCount, s = !0;\n } else\n this._trackLinks.length = this._trackCount, X(this._trackLinks, t, this), this._links = this._trackLinks, s = !0;\n } catch {\n }\n this._handleError(e, c.COMPUTED_COMPUTATION_FAILED, !0);\n } finally {\n s ? this._links !== t && t !== u && f.release(t) : this._trackLinks !== t && this._trackLinks !== u && f.release(this._trackLinks), this._trackEpoch = g.UNINITIALIZED, this._trackLinks = u, this._trackCount = 0, this.flags &= ~D;\n }\n }\n _handleAsyncComputation(t) {\n this.flags = (this.flags | O) & -217, this._notifySubscribers(void 0, void 0), this._asyncStartAggregateVersion = this._captureVersionSnapshot(), this._asyncRetryCount = 0, this._promiseId = (this._promiseId + 1) % V.MAX_PROMISE_ID;\n const s = this._promiseId;\n t.then(\n (e) => {\n if (s === this._promiseId) {\n if (this._captureVersionSnapshot() !== this._asyncStartAggregateVersion) {\n const i = et();\n return this._lastDriftEpoch !== i && (this._lastDriftEpoch = i, this._asyncRetryCount = 0), this._asyncRetryCount++ < this._maxAsyncRetries ? this._markDirty() : this._handleError(\n new I(\n `Async drift threshold exceeded after ${this._maxAsyncRetries} retries.`\n ),\n c.COMPUTED_ASYNC_COMPUTATION_FAILED\n );\n }\n this._finalizeResolution(e), this._notifySubscribers(e, void 0);\n }\n },\n (e) => s === this._promiseId && this._handleError(e, c.COMPUTED_ASYNC_COMPUTATION_FAILED)\n );\n }\n _captureVersionSnapshot() {\n let t = 0;\n const s = this._links;\n for (let e = 0, i = s.length; e < i; e++)\n t = (t << 5) - t + s[e].node.version | 0;\n return t;\n }\n _handleError(t, s, e = !1) {\n const i = S(t, I, s);\n if (!e && !(this.flags & b) && (this.version = M(this.version)), this._error = i, this.flags = this.flags & -121 | b | A, this._onError)\n try {\n this._onError(i);\n } catch (r) {\n console.error(c.CALLBACK_ERROR_IN_ERROR_HANDLER, r);\n }\n if (e) throw i;\n this._notifySubscribers(void 0, void 0);\n }\n _finalizeResolution(t) {\n (!(this.flags & E) || !this._equal(this._value, t)) && (this.version = M(this.version)), this._value = t, this._error = null, this.flags = (this.flags | E) & -697;\n }\n execute() {\n this._markDirty();\n }\n /** @internal */\n _markDirty() {\n this.flags & (D | p) || (this.flags |= p, this._notifySubscribers(void 0, void 0));\n }\n}\nfunction At(n, t = {}) {\n return new St(n, t);\n}\nvar K;\nclass kt extends J {\n constructor(t, s = {}) {\n super(), this[K] = !0, this._cleanup = null, this._links = u, this._nextLinks = null, this._prevLinks = u, this._currentEpoch = g.UNINITIALIZED, this._lastFlushEpoch = g.UNINITIALIZED, this._executionsInEpoch = 0, this._executionCount = 0, this._windowStart = 0, this._windowCount = 0, this._execId = 0, this._trackCount = 0, this._fn = t, this._onError = s.onError ?? null, this._sync = s.sync ?? !1, this._maxExecutions = s.maxExecutionsPerSecond ?? d.MAX_EXECUTIONS_PER_SECOND, this._maxExecutionsPerFlush = s.maxExecutionsPerFlush ?? d.MAX_EXECUTIONS_PER_EFFECT, this._sync ? this._notifyCallback = () => this.execute() : this._notifyCallback = () => T.schedule(this), B.attachDebugInfo(this, \"effect\", this.id);\n }\n run() {\n if (this.flags & _.DISPOSED)\n throw new C(c.EFFECT_DISPOSED);\n this.execute(!0);\n }\n dispose() {\n this.flags & _.DISPOSED || (this.flags |= _.DISPOSED, this._execCleanup(), this._unsubLinks(this._links), this._links !== u && f.release(this._links), this._links = u, this._prevLinks = u);\n }\n [(K = nt, Symbol.dispose)]() {\n this.dispose();\n }\n addDependency(t) {\n if (!(this.flags & _.EXECUTING)) return;\n const s = this._currentEpoch;\n if (t._lastSeenEpoch === s) return;\n t._lastSeenEpoch = s;\n const e = this._prevLinks;\n if (this._nextLinks === e && this._trackCount < e.length && e[this._trackCount].node === t) {\n e[this._trackCount].version = t.version, this._trackCount++;\n return;\n }\n if (this._nextLinks === e) {\n const h = f.acquire();\n for (let o = 0; o < this._trackCount; o++)\n h[o] = e[o];\n this._nextLinks = h;\n }\n const i = this._nextLinks;\n let r = -1;\n for (let h = this._trackCount; h < e.length; h++) {\n const o = e[h];\n if (o && o.node === t && o.unsub) {\n r = h;\n break;\n }\n }\n if (r !== -1) {\n const h = e[r];\n h.version = t.version, i[this._trackCount] = h, e[r] = null;\n } else\n try {\n const h = t.subscribe(this._notifyCallback);\n i[this._trackCount] = new y(t, t.version, h);\n } catch (h) {\n const o = S(h, C, c.EFFECT_EXECUTION_FAILED);\n if (console.error(o), this._onError)\n try {\n this._onError(o);\n } catch {\n }\n i[this._trackCount] = new y(t, t.version, void 0);\n }\n this._trackCount++;\n }\n /**\n * Executes effect with tracking.\n */\n execute(t = !1) {\n if (this.flags & (_.DISPOSED | _.EXECUTING) || !t && this._links.length > 0 && !this._isDirty()) return;\n this._checkInfiniteLoops(), this.flags |= _.EXECUTING, this._execCleanup(), this._prevLinks = this._links, this._nextLinks = this._links, this._currentEpoch = w(), this._trackCount = 0;\n let s = !1;\n try {\n const e = l.run(this, this._fn);\n if (this._nextLinks === this._prevLinks)\n if (this._trackCount === this._prevLinks.length)\n s = !0;\n else {\n for (let i = this._trackCount; i < this._prevLinks.length; i++)\n this._prevLinks[i]?.unsub?.();\n this._prevLinks.length = this._trackCount, s = !0;\n }\n else\n this._nextLinks.length = this._trackCount, s = !0;\n this._links = this._nextLinks, rt(e) ? this._handleAsyncResult(e) : this._cleanup = typeof e == \"function\" ? e : null;\n } catch (e) {\n if (!s)\n if (this._nextLinks === this._prevLinks) {\n for (let i = this._trackCount; i < this._prevLinks.length; i++)\n this._prevLinks[i]?.unsub?.();\n this._prevLinks.length = this._trackCount, s = !0;\n } else\n this._nextLinks.length = this._trackCount, s = !0;\n this._links = this._nextLinks, this._handleExecutionError(e), this._cleanup = null;\n } finally {\n this._finalizeDependencies(s, this._prevLinks, this._nextLinks), this.flags &= -9;\n }\n }\n _handleAsyncResult(t) {\n const s = ++this._execId;\n t.then(\n (e) => {\n if (s !== this._execId || this.flags & _.DISPOSED) {\n if (typeof e == \"function\")\n try {\n e();\n } catch (i) {\n this._handleExecutionError(i, c.EFFECT_CLEANUP_FAILED);\n }\n return;\n }\n typeof e == \"function\" && (this._cleanup = e);\n },\n (e) => s === this._execId && this._handleExecutionError(e)\n );\n }\n _finalizeDependencies(t, s, e) {\n this._nextLinks = null, this._prevLinks = u, t ? e !== s && s !== u && (s.forEach((i) => i?.unsub?.()), f.release(s)) : e !== s && e !== u && e && (this._unsubLinks(e), f.release(e));\n }\n _unsubLinks(t) {\n t.forEach((s) => s?.unsub?.());\n }\n _isDirty() {\n const t = this._links, s = l.current;\n l.current = null;\n try {\n return t.some((e) => {\n const i = e.node;\n if (i.flags & W.IS_COMPUTED)\n try {\n i.value;\n } catch {\n return !0;\n }\n return i.version !== e.version;\n });\n } finally {\n l.current = s;\n }\n }\n _execCleanup() {\n if (this._cleanup) {\n try {\n this._cleanup();\n } catch (t) {\n this._handleExecutionError(t, c.EFFECT_CLEANUP_FAILED);\n }\n this._cleanup = null;\n }\n }\n _checkInfiniteLoops() {\n const t = et();\n this._lastFlushEpoch !== t && (this._lastFlushEpoch = t, this._executionsInEpoch = 0), ++this._executionsInEpoch > this._maxExecutionsPerFlush && this._throwInfiniteLoopError(\"per-effect\"), ft() > d.MAX_EXECUTIONS_PER_FLUSH && this._throwInfiniteLoopError(\"global\"), this._executionCount++;\n }\n get isDisposed() {\n return (this.flags & _.DISPOSED) !== 0;\n }\n get executionCount() {\n return this._executionCount;\n }\n get isExecuting() {\n return (this.flags & _.EXECUTING) !== 0;\n }\n _throwInfiniteLoopError(t) {\n const s = new C(\n `Infinite loop detected (${t}): effect executed ${this._executionsInEpoch} times in current flush. Total executions in flush: ${z}`\n );\n throw this.dispose(), console.error(s), s;\n }\n _handleExecutionError(t, s = c.EFFECT_EXECUTION_FAILED) {\n const e = S(t, C, s);\n if (console.error(e), this._onError)\n try {\n this._onError(e);\n } catch (i) {\n console.error(S(i, C, c.CALLBACK_ERROR_IN_ERROR_HANDLER));\n }\n }\n}\nfunction Ot(n, t = {}) {\n if (typeof n != \"function\")\n throw new C(c.EFFECT_MUST_BE_FUNCTION);\n const s = new kt(n, t);\n return s.execute(), s;\n}\nfunction yt(n) {\n if (typeof n != \"function\")\n throw new TypeError(c.BATCH_CALLBACK_MUST_BE_FUNCTION);\n T.startBatch();\n try {\n return n();\n } finally {\n T.endBatch();\n }\n}\nexport {\n N as AsyncState,\n k as AtomError,\n I as ComputedError,\n ht as DEBUG_CONFIG,\n B as DEBUG_RUNTIME,\n C as EffectError,\n d as SCHEDULER_CONFIG,\n m as SchedulerError,\n bt as atom,\n yt as batch,\n At as computed,\n Ot as effect,\n Tt as isAtom,\n Nt as isComputed,\n Lt as isEffect,\n T as scheduler,\n Dt as untracked\n};\n//# sourceMappingURL=index.mjs.map\n","/**\n * Constants for atom-effect-jquery\n */\n\nimport type { RouteConfig } from './types';\n\n// ============================================================================\n// Log Prefixes\n// ============================================================================\n\n/**\n * Log prefixes keyed by subsystem.\n * Each prefix names the specific subsystem that emitted the message so that\n * console output is unambiguous regardless of which binding triggered it.\n */\nexport const LOG_PREFIXES = {\n /** Used by the SPA router ($.route). */\n ROUTE: '[atom-route]',\n /** Used by all reactive binding helpers (bindText, bindCss, bindAttr, …). */\n BINDING: '[atom-binding]',\n /** Used by atomList reactive list rendering. */\n LIST: '[atom-list]',\n /** Used by mount/unmount lifecycle helpers. */\n MOUNT: '[atom-mount]',\n} as const;\n\n// ============================================================================\n// Route Defaults\n// ============================================================================\n\n/**\n * Subset of RouteConfig fields that have default values.\n * Extracted as a named type so the annotation on ROUTE_DEFAULTS stays concise.\n */\ntype RouteDefaults = Readonly<\n Required<Pick<RouteConfig, 'mode' | 'basePath' | 'autoBindLinks' | 'activeClass'>>\n>;\n\n/**\n * Default values for RouteConfig optional fields.\n */\nexport const ROUTE_DEFAULTS: RouteDefaults = Object.freeze({\n mode: 'hash',\n basePath: '',\n autoBindLinks: false,\n activeClass: 'active',\n});\n\n// ============================================================================\n// Input & Binding Defaults\n// ============================================================================\n\n/**\n * Default values for input binding options.\n */\nexport const INPUT_DEFAULTS = {\n /** Default DOM event to trigger synchronization. */\n EVENT: 'input',\n /** Default debounce delay in milliseconds. */\n DEBOUNCE: 0,\n} as const;\n\n// ============================================================================\n// Debug Defaults\n// ============================================================================\n\n/**\n * Default values for debug mode.\n */\nexport const DEBUG_DEFAULTS = {\n /** Default duration in ms for visual highlighting during DOM updates. */\n HIGHLIGHT_DURATION_MS: 500,\n} as const;\n\n// ============================================================================\n// Security-Sensitive DOM Elements & Properties\n// ============================================================================\n\n/**\n * Valid input-like tag names for val binding.\n * Internal comparisons MUST use `.toLowerCase()` on the element's tagName.\n */\nexport const VALID_INPUT_TAGS: ReadonlySet<string> = new Set(['input', 'select', 'textarea']);\n\n/**\n * DOM properties that carry URL values.\n *\n * Even when using `bindProp` (Property binding) instead of `bindAttr` (Attribute\n * binding), these properties must be guarded for dangerous protocols\n * (e.g. `javascript:`) to prevent bypasses.\n */\nexport const URL_PROPS: ReadonlySet<string> = new Set([\n 'src',\n 'href',\n 'action',\n 'formaction',\n 'data',\n 'poster',\n 'background',\n 'cite',\n 'longdesc',\n 'profile',\n 'usemap',\n 'classid',\n 'codebase',\n 'xlink:href',\n]);\n\n/**\n * DOM properties blocked by `bindProp` to prevent HTML injection and\n * prototype pollution attacks.\n *\n * ⚠ Note: `on*` event handler properties are blocked by logic in `bindProp`,\n * not by this static list, to cover all possible event types (onclick, etc.).\n */\nexport const DANGEROUS_PROPS: ReadonlySet<string> = new Set([\n 'innerHTML',\n 'outerHTML',\n 'srcdoc',\n '__proto__',\n 'constructor',\n 'prototype',\n]);\n\n// ============================================================================\n// Error & Warning Messages\n// ============================================================================\n\n/**\n * Canonical error and warning messages for all subsystems.\n *\n * Every entry is a function providing consistent caller-side context.\n */\nexport const ERROR_MESSAGES = {\n ROUTE: {\n NOT_FOUND: (name: string) => `Route \"${name}\" not found and no notFound route configured`,\n TEMPLATE_NOT_FOUND: (selector: string) => `Template \"${selector}\" not found`,\n TARGET_NOT_FOUND: (selector: string) => `Target element \"${selector}\" not found`,\n MALFORMED_URI: (raw: string) => `Malformed URI component: ${raw}`,\n },\n SECURITY: {\n /** Emitted when sanitizeHtml modifies the input. */\n UNSAFE_CONTENT: () => 'Unsafe content neutralized during sanitization.',\n /** Emitted when a CSS style property value contains a dangerous protocol. */\n BLOCKED_CSS_VALUE: (prop: string) => `Blocked dangerous value in CSS style property \"${prop}\".`,\n BLOCKED_EVENT_HANDLER: (name: string) =>\n `Blocked setting dangerous event handler attribute/property \"${name}\".`,\n BLOCKED_PROTOCOL: (name: string) => `Blocked dangerous protocol in \"${name}\".`,\n BLOCKED_PROP: (name: string) =>\n `Blocked setting dangerous property \"${name}\". Use html binding for sanitized HTML.`,\n },\n BINDING: {\n INVALID_INPUT_ELEMENT: (tagName: string) =>\n `Val binding used on non-input element <${tagName}>.`,\n MISSING_SOURCE: (method: string) =>\n `[${method}] source is required when prop/name is a string.`,\n MISSING_CONDITION: (method: string) =>\n `[${method}] condition is required when className is a string.`,\n UPDATER_ERROR: (debugType: string, isStatic?: boolean) =>\n `Updater threw in binding \"${debugType}\"${isStatic ? ' (static)' : ''}`,\n CLEANUP_ERROR: (info?: string) => `Binding cleanup error${info ? `: ${info}` : ''}`,\n PARSE_ERROR: (details?: string) =>\n `parse() threw during DOM→Atom sync${details ? `: ${details}` : ''}`,\n },\n LIST: {\n DUPLICATE_KEY: (key: string | number, index: number, container: string) =>\n `Duplicate key \"${key}\" at index ${index} in atomList <${container}>.`,\n },\n MOUNT: {\n ERROR: (name?: string) => `Mount error${name ? ` in component <${name}>` : ''}`,\n CLEANUP_ERROR: (name?: string) => `Cleanup error${name ? ` in component <${name}>` : ''}`,\n },\n CORE: {\n EFFECT_DISPOSE_ERROR: (info?: string) => `Effect dispose error${info ? `: ${info}` : ''}`,\n },\n} as const;\n","import type { ReadonlyAtom } from '@but212/atom-effect';\nimport { isAtom } from '@but212/atom-effect';\nimport type { RenderRoute, RouteDefinition, TemplateRoute } from './types';\n\n// ============================================================================\n// Reactive helpers\n// ============================================================================\n\n/**\n * Checks if a given value is a reactive node (Atom or Computed).\n *\n * `isAtom` returns `true` for both plain atoms and computed atoms because\n * `ComputedAtomImpl` carries `ATOM_BRAND` in addition to `COMPUTED_BRAND`.\n * A separate `isComputed` check would therefore be redundant.\n */\nexport function isReactive(value: unknown): value is ReadonlyAtom<unknown> {\n return isAtom(value);\n}\n\n// ============================================================================\n// DOM helpers\n// ============================================================================\n\n/**\n * Generates a CSS selector-like string for a DOM element, suitable for debug\n * output. Returns `tagName#id` when an id is present, otherwise\n * `tagName.class1.class2…`.\n *\n * ⚠ Not a valid CSS selector — do NOT pass this to `querySelector()`.\n * Element IDs and class names may contain characters with special meaning in\n * CSS selectors (e.g. `.`, `[`, `(`). This helper is intended solely for\n * human-readable console/log messages.\n */\nexport function getSelector(el: Element): string {\n const tagName = el.tagName.toLowerCase();\n if (el.id) return `${tagName}#${el.id}`;\n\n const list = el.classList;\n const len = list.length;\n if (len === 0) return tagName;\n\n let selector = tagName;\n for (let i = 0; i < len; i++) {\n selector += `.${list[i]!}`;\n }\n return selector;\n}\n\n// ============================================================================\n// Shared low-level helpers\n// ============================================================================\n\n/** Portable own-property check. Prefer over `in` to exclude prototype keys. */\nexport const hasOwn = Object.prototype.hasOwnProperty;\n\n// ============================================================================\n// Route type guards\n// ============================================================================\n\n/** Narrows a `RouteDefinition` to `TemplateRoute`. */\nexport function isTemplateRoute(r: RouteDefinition): r is TemplateRoute {\n return typeof (r as TemplateRoute).template === 'string';\n}\n\n/** Narrows a `RouteDefinition` to `RenderRoute`. */\nexport function isRenderRoute(r: RouteDefinition): r is RenderRoute {\n return typeof (r as RenderRoute).render === 'function';\n}\n\n// ============================================================================\n// General utilities\n// ============================================================================\n\n/**\n * Shallow equality check for plain objects.\n * Returns `true` if both objects have the same own keys with identical (`===`) values.\n */\nexport function shallowEqual(a: unknown, b: unknown): boolean {\n if (a === b) return true;\n if (a === null || b === null || typeof a !== 'object' || typeof b !== 'object') return false;\n\n const keysA = Object.keys(a);\n const keysB = Object.keys(b);\n if (keysA.length !== keysB.length) return false;\n\n const objA = a as Record<string, unknown>;\n const objB = b as Record<string, unknown>;\n\n for (let i = 0; i < keysA.length; i++) {\n const key = keysA[i]!;\n if (!hasOwn.call(objB, key) || objA[key] !== objB[key]) {\n return false;\n }\n }\n return true;\n}\n\n// ============================================================================\n// DOM reconciliation algorithm\n// ============================================================================\n\n/**\n * Computes the Longest Increasing Subsequence (LIS) of old-position indices.\n *\n * Used by `atomList` to minimise DOM moves during reconciliation: items whose\n * old-position index appears in the LIS are already in the correct relative\n * order and do not need to be moved.\n *\n * Sentinel value: `-1` means \"not present in the old list\" and is skipped.\n *\n * Time complexity: O(N log N). Space complexity: O(N).\n */\nexport function getLIS(arr: Int32Array | number[]): Int32Array {\n const len = arr.length;\n if (len === 0) return new Int32Array(0);\n\n // predecessors[i] records the index in `arr` that preceded i in the LIS,\n // or -1 if i was the first element. Initialised to -1 so unvisited slots\n // are distinguishable from a valid predecessor at index 0.\n const predecessors = new Int32Array(len).fill(-1);\n const result = new Int32Array(len);\n let resultLen = 0;\n\n for (let i = 0; i < len; i++) {\n const val = arr[i];\n // `undefined` can only occur for a plain `number[]` under noUncheckedIndexedAccess;\n // Int32Array always returns a number. Both cases are treated as absent.\n if (val === undefined || val === -1) continue;\n\n const lastIdx = resultLen > 0 ? result[resultLen - 1] : undefined;\n if (resultLen === 0 || (lastIdx !== undefined && (arr[lastIdx] ?? -1) < val)) {\n predecessors[i] = lastIdx ?? -1;\n result[resultLen++] = i;\n continue;\n }\n\n // Binary search for the leftmost result position whose value >= val\n let left = 0;\n let right = resultLen - 1;\n while (left < right) {\n const mid = (left + right) >>> 1;\n const midIdx = result[mid];\n if (midIdx !== undefined && (arr[midIdx] ?? -1) < val) {\n left = mid + 1;\n } else {\n right = mid;\n }\n }\n\n const leftIdx = result[left];\n if (leftIdx !== undefined && val < (arr[leftIdx] ?? Number.MAX_SAFE_INTEGER)) {\n if (left > 0) {\n predecessors[i] = result[left - 1] ?? -1;\n }\n result[left] = i;\n }\n }\n\n // Back-track through predecessors to reconstruct the LIS indices.\n const lis = new Int32Array(resultLen);\n if (resultLen > 0) {\n let curr: number | undefined = result[resultLen - 1];\n for (let i = resultLen - 1; i >= 0 && curr !== undefined && curr !== -1; i--) {\n lis[i] = curr;\n curr = predecessors[curr];\n }\n }\n\n return lis;\n}\n","/**\n * Debug Mode\n *\n * When $.atom.debug = true is enabled:\n * 1. Logs state changes to the console.\n * 2. Visually highlights DOM updates (red border flash).\n *\n * Debug mode can be enabled in two ways:\n * 1. Build-time: VITE_ATOM_DEBUG=true (opt-in via env var)\n * 2. Runtime: $.atom.debug = true or window.__ATOM_DEBUG__ = true\n *\n * NOTE: debug mode is NOT enabled automatically in DEV builds to avoid\n * polluting the console without explicit opt-in.\n */\n\nimport { DEBUG_DEFAULTS } from './constants';\nimport { getSelector } from './utils';\n\n// ============================================================================\n// Timing constants — HIGHLIGHT_TRANSITION is derived from HIGHLIGHT_DEFAULTS\n// so the two values stay in sync automatically.\n// ============================================================================\n\n/** CSS transition duration derived from DEBUG_DEFAULTS.HIGHLIGHT_DURATION_MS. */\nconst HIGHLIGHT_TRANSITION = `${DEBUG_DEFAULTS.HIGHLIGHT_DURATION_MS / 1000}s`;\n\n// ============================================================================\n// Initial state\n// ============================================================================\n\n/**\n * Determines the initial debug state.\n * Priority: window.__ATOM_DEBUG__ > explicit VITE_ATOM_DEBUG env var.\n * DEV mode alone does NOT enable debug to avoid silent console pollution.\n */\nfunction getInitialDebugState(): boolean {\n if (typeof window !== 'undefined') {\n const flag = (window as Window & { __ATOM_DEBUG__?: boolean }).__ATOM_DEBUG__;\n if (typeof flag === 'boolean') return flag;\n }\n\n // Vite inlines import.meta.env at build time; guard for non-Vite environments.\n // We also check for process.env as a fallback for other build tools.\n try {\n if (import.meta.env?.VITE_ATOM_DEBUG === 'true') return true;\n } catch {\n /* ignore if import.meta is unavailable */\n }\n\n try {\n // Cast globalThis to include optional process.env for environment detection\n const env = (\n globalThis as typeof globalThis & {\n process?: { env?: Record<string, string | undefined> };\n }\n ).process?.env;\n\n if (env?.VITE_ATOM_DEBUG === 'true') {\n return true;\n }\n } catch {\n /* ignore */\n }\n\n return false;\n}\n\nlet debugEnabled = getInitialDebugState();\n\n// ============================================================================\n// Debug object\n// ============================================================================\n\nexport const debug = {\n get enabled() {\n // Check global flag at runtime to allow dynamic toggling via console.\n if (typeof window !== 'undefined') {\n const globalFlag = (window as Window & { __ATOM_DEBUG__?: boolean }).__ATOM_DEBUG__;\n if (typeof globalFlag === 'boolean') return globalFlag;\n }\n return debugEnabled;\n },\n set enabled(value: boolean) {\n debugEnabled = value;\n },\n\n /**\n * Logs a message only when debug mode is active.\n */\n log(prefix: string, ...args: unknown[]) {\n if (this.enabled) {\n console.log(`${prefix}`, ...args);\n }\n },\n\n /**\n * Logs an atom value change only when debug mode is active.\n */\n atomChanged(prefix: string, name: string | undefined, oldVal: unknown, newVal: unknown) {\n if (this.enabled) {\n console.log(`${prefix} Atom \"${name ?? 'anonymous'}\" changed:`, oldVal, '→', newVal);\n }\n },\n\n /**\n * Logs a DOM update and triggers a visual highlight flash.\n */\n domUpdated(prefix: string, target: Element | JQuery, type: string, value: unknown) {\n if (!this.enabled) return;\n\n const el: Element | undefined =\n target instanceof Element ? target : (target[0] as Element | undefined);\n\n // SVG elements also support classList, so we relax the check to Element.\n if (!el) return;\n\n console.log(`${prefix} DOM updated: ${getSelector(el)}.${type} =`, value);\n highlightElement(el);\n },\n\n /**\n * Logs a cleanup event only when debug mode is active.\n */\n cleanup(prefix: string, selector: string) {\n if (this.enabled) {\n console.log(`${prefix} Cleanup: ${selector}`);\n }\n },\n\n /**\n * Unconditional warning for runtime errors.\n */\n warn(prefix: string, message: string, ...rest: unknown[]) {\n console.warn(`${prefix} ${message}`, ...rest);\n },\n\n /**\n * Unconditional error for binding failures.\n */\n error(prefix: string, message: string, cause: unknown) {\n console.error(`${prefix} ${message}`, cause);\n },\n};\n\n// ============================================================================\n// Visual highlight\n// ============================================================================\n\nconst HIGHLIGHT_CLASS = 'atom-debug-highlight';\nconst HIGHLIGHT_STYLE_ATTR = 'data-atom-debug';\n\n/**\n * Injects the highlight CSS once per document lifetime.\n * Uses a WeakRef with a plain fallback to handle both test resets and old environments.\n */\nlet highlightStyleRef: WeakRef<HTMLStyleElement> | HTMLStyleElement | undefined;\nfunction injectHighlightStyle(): void {\n const current =\n highlightStyleRef instanceof HTMLStyleElement ? highlightStyleRef : highlightStyleRef?.deref();\n\n if (current?.isConnected) return;\n\n // Final guard: check if the style already exists in the document (e.g. from a previous session)\n if (document.querySelector(`style[${HIGHLIGHT_STYLE_ATTR}]`)) return;\n\n const style = document.createElement('style');\n style.setAttribute(HIGHLIGHT_STYLE_ATTR, '');\n style.textContent =\n `.${HIGHLIGHT_CLASS}{` +\n `outline:2px solid rgba(255,68,68,0.8);` +\n `outline-offset:1px;` +\n `transition:outline ${HIGHLIGHT_TRANSITION} ease-out` +\n `}`;\n document.head.appendChild(style);\n\n // Use WeakRef only if available (ES2021)\n if (typeof WeakRef !== 'undefined') {\n highlightStyleRef = new WeakRef(style);\n } else {\n highlightStyleRef = style;\n }\n}\n\n// Tracks pending operations per element.\nconst highlightTimers = new WeakMap<Element, ReturnType<typeof setTimeout>>();\nconst highlightRafs = new WeakMap<Element, ReturnType<typeof requestAnimationFrame>>();\n\n/**\n * Flashes a red outline on an element to indicate a reactive DOM update.\n * Supports both HTML and SVG elements via classList manipulation.\n */\nfunction highlightElement(el: Element): void {\n // Re-check debug state and connection.\n if (!debug.enabled || !el.isConnected) return;\n\n injectHighlightStyle();\n\n // Cancel any pending rAF.\n const existingRaf = highlightRafs.get(el);\n if (existingRaf !== undefined) {\n cancelAnimationFrame(existingRaf);\n }\n\n // Cancel any pending timeout.\n const existingTimer = highlightTimers.get(el);\n if (existingTimer !== undefined) {\n clearTimeout(existingTimer);\n }\n\n const rafId = requestAnimationFrame(() => {\n highlightRafs.delete(el);\n\n // Re-verify connection inside rAF as the node might have been removed\n // between the scheduling and execution of the frame.\n if (!el.isConnected) return;\n\n el.classList.add(HIGHLIGHT_CLASS);\n\n highlightTimers.set(\n el,\n setTimeout(() => {\n // Re-verify connection again before trying to remove class.\n if (el.isConnected) {\n el.classList.remove(HIGHLIGHT_CLASS);\n }\n highlightTimers.delete(el);\n }, DEBUG_DEFAULTS.HIGHLIGHT_DURATION_MS)\n );\n });\n\n highlightRafs.set(el, rafId);\n}\n","import {\n batch,\n computed,\n atom as createAtom,\n effect,\n isAtom,\n isComputed,\n untracked,\n} from '@but212/atom-effect';\nimport $ from 'jquery';\nimport { debug } from './debug';\nimport type { AtomOptions, WritableAtom } from './types';\n// isReactive is defined in utils.ts because core's isAtom already covers computed\n// atoms (ComputedAtom carries ATOM_BRAND), making a separate isComputed check redundant.\nimport { isReactive } from './utils';\n\n// ============================================================================\n// atom factory + debug namespace\n// ============================================================================\n\n/**\n * Local wrapper around core's `atom` factory.\n *\n * This wrapper exists to attach the `$.atom.debug` accessor directly to the\n * function object at runtime. TypeScript requires a double cast for this\n * augmentation, but `NamespaceExtensions` ensures all other fields are type-safe.\n *\n * `options` is not defaulted here — core's `atom` defaults `options` to `{}`\n * internally, so passing `undefined` is safe and avoids an extra allocation\n * per call.\n */\nfunction atom<T>(initialValue: T, options?: AtomOptions): WritableAtom<T> {\n return createAtom(initialValue, options);\n}\n\nObject.defineProperty(atom, 'debug', {\n enumerable: true,\n // configurable: true allows tests and advanced consumers to redefine or\n // delete the accessor if needed. The default (false) would permanently lock\n // the property on the function object.\n configurable: true,\n get(): boolean {\n return debug.enabled;\n },\n set(value: boolean) {\n debug.enabled = value;\n },\n});\n\n// ============================================================================\n// nextTick\n// ============================================================================\n\n/**\n * Resolves after all pending microtask-scheduled reactive effects have flushed.\n *\n * Implementation uses `setTimeout(0)` (a macrotask) which always runs after\n * the current microtask queue is drained. This is intentional: core's\n * scheduler enqueues effects as microtasks, so by the time the macrotask\n * fires, all pending reactive propagation for the current turn is complete.\n *\n * Note: browsers may enforce a minimum 4 ms delay for nested `setTimeout`\n * calls. For unit tests this is typically not an issue. If sub-millisecond\n * resolution is needed, use `Promise.resolve()` directly to wait for a single\n * microtask tick instead.\n *\n * **Caveats**: A single `await nextTick()` covers one reactive propagation\n * wave. Chains of computed → effect → atom → effect may require multiple\n * awaits — one per propagation step.\n */\nexport function nextTick(): Promise<void> {\n return new Promise<void>((resolve) => setTimeout(resolve, 0));\n}\n\n// ============================================================================\n// Static extension registration\n// ============================================================================\n\n/**\n * The subset of `JQueryStatic` that this module registers.\n *\n * Typed as `Pick<JQueryStatic, ...>` so that the compiler verifies:\n * 1. Every key listed here actually exists on `JQueryStatic`.\n * 2. Every value's type is assignable to the declared `JQueryStatic` member.\n *\n * Adding or removing a key in either `JQueryStatic` or this object without\n * updating the other produces a compile-time error.\n *\n * Dependency direction note: `nextTick` is defined locally in this file, so\n * `JQueryStatic['nextTick']` is validated against its signature. For most other\n * keys, `JQueryStatic` serves as the source of truth for typing.\n *\n * Note: `$.extend(staticExtensions)` merges the fields into `$` at runtime.\n * TypeScript does not model this mutation on the `$` type — the augmented\n * types are declared separately via global interface merging in `types.ts`.\n */\ntype NamespaceExtensions = Pick<\n JQueryStatic,\n | 'atom'\n | 'computed'\n | 'effect'\n | 'batch'\n | 'untracked'\n | 'isAtom'\n | 'isComputed'\n | 'isReactive'\n | 'nextTick'\n>;\n\nconst staticExtensions: NamespaceExtensions = {\n // Double cast required for the `atom` function due to its runtime `debug`\n // accessor (see JSDoc for `function atom` above). All other fields are\n // fully verified by `NamespaceExtensions`.\n atom: atom as unknown as JQueryStatic['atom'],\n computed,\n effect,\n batch,\n untracked,\n isAtom,\n isComputed,\n isReactive,\n nextTick,\n};\n\n// $.extend(obj) merges into JQueryStatic (i.e. the $ function itself).\n// Use $.fn.extend(obj) instead to add instance methods on jQuery collections.\n$.extend(staticExtensions);\n","import { ERROR_MESSAGES, LOG_PREFIXES } from './constants';\nimport { debug } from './debug';\nimport type { EffectObject } from './types';\nimport { getSelector } from './utils';\n\n/**\n * CSS class added to every element that has at least one active binding.\n * Used by `querySelectorAll` in `cleanupDescendants` for efficient subtree traversal.\n * Internal use only.\n */\nconst AES_BOUND = '_aes-bound';\n\n/**\n * Per-element record of all reactive resources that must be released on cleanup.\n * Fields are optional to avoid allocating arrays for the common case where only\n * one resource type is used.\n */\ninterface BindingRecord {\n effects?: EffectObject[] | undefined;\n cleanups?: Array<() => void> | undefined;\n componentCleanup?: (() => void) | undefined;\n}\n\n// ============================================================================\n// BindingRegistry\n// ============================================================================\n\n/**\n * Central registry mapping DOM elements to their reactive binding records.\n *\n * Design goals:\n * - Zero memory leaks: all collections use WeakMap/WeakSet keyed by Element.\n * - Minimal allocations in the hot tracking path.\n * - O(bound-descendants) cleanup via a single querySelectorAll pass.\n */\nclass BindingRegistry {\n private records = new WeakMap<Element, BindingRecord>();\n\n // boundElements removed: records is now the Single Source of Truth.\n // WeakMap.has() provides the existence check.\n\n private preservedNodes = new WeakSet<Node>();\n private ignoredNodes = new WeakSet<Node>();\n\n // --------------------------------------------------------------------------\n // Lifecycle flags\n // --------------------------------------------------------------------------\n\n keep(node: Node): void {\n this.preservedNodes.add(node);\n }\n\n isKept(node: Node): boolean {\n return this.preservedNodes.has(node);\n }\n\n markIgnored(node: Node): void {\n this.ignoredNodes.add(node);\n }\n\n isIgnored(node: Node): boolean {\n return this.ignoredNodes.has(node);\n }\n\n // --------------------------------------------------------------------------\n // Tracking\n // --------------------------------------------------------------------------\n\n private getOrCreateRecord(el: Element): BindingRecord {\n let res = this.records.get(el);\n if (!res) {\n // V8 Optimization: Enforce monomorphic object shape from creation time.\n res = { effects: undefined, cleanups: undefined, componentCleanup: undefined };\n this.records.set(el, res);\n el.classList.add(AES_BOUND);\n }\n return res;\n }\n\n trackEffect(el: Element, fx: EffectObject): void {\n const record = this.getOrCreateRecord(el);\n record.effects ??= [];\n record.effects.push(fx);\n }\n\n trackCleanup(el: Element, fn: () => void): void {\n const record = this.getOrCreateRecord(el);\n record.cleanups ??= [];\n record.cleanups.push(fn);\n }\n\n setComponentCleanup(el: Element, fn: (() => void) | undefined): void {\n const record = this.getOrCreateRecord(el);\n record.componentCleanup = fn;\n }\n\n hasBind(el: Element): boolean {\n return this.records.has(el);\n }\n\n // --------------------------------------------------------------------------\n // Cleanup\n // --------------------------------------------------------------------------\n\n cleanup(el: Element | Node): void {\n // Optimization: Single lookup + delete.\n const record = this.records.get(el as Element);\n if (!record) {\n // Already cleaned up or never bound.\n // Ensure specific class is removed unconditionally just in case of stale DOM state\n // (e.g. detached node being re-inserted).\n if (el.nodeType === 1) (el as Element).classList.remove(AES_BOUND);\n this.preservedNodes.delete(el);\n this.ignoredNodes.delete(el);\n return;\n }\n\n // Atomic deletion doubles as a re-entry guard.\n this.records.delete(el as Element);\n this.preservedNodes.delete(el);\n this.ignoredNodes.delete(el);\n\n // Unconditionally remove the class to prevent \"zombie markers\".\n // If a detached node is cached by the user and re-inserted into the DOM later,\n // leaving the class would cause false-positive lookups during subtree cleanups.\n // (classList.remove on detached nodes is virtually free).\n if (el.nodeType === 1) (el as Element).classList.remove(AES_BOUND);\n\n if (debug.enabled) {\n const info = el.nodeType === 1 ? getSelector(el as Element) : el.nodeName || 'Node';\n debug.cleanup(LOG_PREFIXES.BINDING, info);\n }\n\n // Step 0 — Component cleanup runs first so the component can unmount\n // gracefully before its reactive effects are severed.\n if (record.componentCleanup) {\n try {\n record.componentCleanup();\n } catch (e) {\n const selector = el.nodeType === 1 ? getSelector(el as Element) : 'Node';\n debug.error(LOG_PREFIXES.MOUNT, ERROR_MESSAGES.MOUNT.CLEANUP_ERROR(selector), e);\n }\n }\n\n // Step 1 — Sever atom → effect subscriptions.\n if (record.effects) {\n const effects = record.effects;\n for (let i = 0, len = effects.length; i < len; i++) {\n try {\n effects[i]!.dispose();\n } catch (e) {\n const selector = el.nodeType === 1 ? getSelector(el as Element) : 'Node';\n debug.error(LOG_PREFIXES.BINDING, ERROR_MESSAGES.CORE.EFFECT_DISPOSE_ERROR(selector), e);\n }\n }\n }\n\n // Step 2 — Run general-purpose cleanup callbacks.\n if (record.cleanups) {\n const cleanups = record.cleanups;\n for (let i = 0, len = cleanups.length; i < len; i++) {\n try {\n cleanups[i]!();\n } catch (e) {\n const selector = el.nodeType === 1 ? getSelector(el as Element) : 'Node';\n debug.error(LOG_PREFIXES.BINDING, ERROR_MESSAGES.BINDING.CLEANUP_ERROR(selector), e);\n }\n }\n }\n }\n\n cleanupDescendants(el: Element | DocumentFragment | ShadowRoot): void {\n // ⚠ Blind Spot Notice: Web Components & Shadow DOM\n // getElementsByClassName only traverses the Light DOM. If reactive elements\n // are placed inside a ShadowRoot, they will NOT be discovered or cleaned up\n // automatically by a parent's removal. Users must explicitly track and call\n // `registry.cleanupTree(shadowRoot)` to avoid memory leaks in Shadow DOMs.\n\n // is not available on ShadowRoot.\n const descendants =\n 'getElementsByClassName' in el && typeof el.getElementsByClassName === 'function'\n ? el.getElementsByClassName(AES_BOUND)\n : el.querySelectorAll(`.${AES_BOUND}`);\n for (let i = descendants.length - 1; i >= 0; i--) {\n const child = descendants[i];\n if (!child) continue;\n\n if (this.records.has(child)) {\n this.cleanup(child);\n } else {\n // The AES_BOUND class is present but the registry has no record.\n // Remove the stale class and warn so it surfaces in debug mode.\n child.classList.remove(AES_BOUND);\n if (debug.enabled) {\n debug.warn(\n LOG_PREFIXES.BINDING,\n `${AES_BOUND} class found on unregistered element:`,\n child\n );\n }\n }\n }\n }\n\n cleanupTree(el: Element | Node): void {\n // 1: Element, 11: DocumentFragment or ShadowRoot\n if (el.nodeType === 1 || el.nodeType === 11) {\n this.cleanupDescendants(el as Element | DocumentFragment | ShadowRoot);\n }\n this.cleanup(el);\n }\n}\n\n// ============================================================================\n// Singleton + auto-cleanup\n// ============================================================================\n\nexport const registry = new BindingRegistry();\n\nconst observers = new Map<Element, MutationObserver>();\n\n/**\n * Starts observing `root` for removed elements and automatically disposes\n * their reactive bindings when they leave the DOM.\n *\n * Multiple roots can be observed concurrently (e.g. for Micro-Frontends).\n * The `root` parameter is required (no default) to make the caller explicit\n * about which subtree is being observed.\n *\n * Idempotent: calling more than once with the same root has no effect.\n */\nexport function enableAutoCleanup(root: Element): void {\n // Support independent multiple roots for Micro-Frontend architectures.\n if (observers.has(root)) {\n return;\n }\n\n const observer = new MutationObserver((mutations) => {\n // Optimization: raw for-loop avoids iterator allocations.\n for (let i = 0, mLen = mutations.length; i < mLen; i++) {\n const removedNodes = mutations[i]!.removedNodes;\n for (let j = 0, rLen = removedNodes.length; j < rLen; j++) {\n const node = removedNodes[j]!;\n\n // Only Element nodes can carry AES_BOUND bindings.\n // 1 === Node.ELEMENT_NODE\n if (node.nodeType !== 1) continue;\n\n // isConnected handles the move case.\n // isKept handles explicit .detach().\n // isIgnored handles .remove().\n if (node.isConnected || registry.isKept(node) || registry.isIgnored(node)) {\n continue;\n }\n\n registry.cleanupTree(node as Element);\n }\n }\n });\n\n observer.observe(root, { childList: true, subtree: true });\n observers.set(root, observer);\n}\n\n/**\n * Stops all MutationObservers started by `enableAutoCleanup`.\n */\nexport function disableAutoCleanup(): void {\n observers.forEach((obs) => obs.disconnect());\n observers.clear();\n}\n","import { effect, type ReadonlyAtom, untracked } from '@but212/atom-effect';\nimport { ERROR_MESSAGES, LOG_PREFIXES } from './constants';\nimport { debug } from './debug';\nimport { registry } from './registry';\nimport type { ReactiveValue } from './types';\nimport { isReactive } from './utils';\n\n// ============================================================================\n// Debug type\n// ============================================================================\n\n/**\n * Structured label identifying which binding produced a debug log entry.\n * Fixed bindings use a plain literal; per-key bindings use a `prefix.key` form\n * where the key portion must be non-empty.\n *\n * Note: the trailing `(string & {})` member makes this type accept any string\n * at runtime while still surfacing the named literals as IDE autocomplete\n * suggestions. It does NOT enforce that only the listed values are used —\n * TypeScript absorbs all narrower literal members into `string & {}`, so there\n * is no compile-time restriction beyond `string`.\n */\nexport type BindingDebugType =\n | 'text'\n | 'html'\n | 'show'\n | 'hide'\n | 'checked'\n | `class.${string & {}}`\n | `css.${string & {}}`\n | `attr.${string & {}}`\n | `prop.${string & {}}`\n | (string & {});\n\n// ============================================================================\n// Core factory\n// ============================================================================\n\n/**\n * Registers a reactive effect that calls `updater` whenever `source` changes,\n * or calls `updater` once immediately if `source` is a static value.\n *\n * Responsibilities:\n * - Reactive path: wraps `updater` in an `effect`, tracks it on the registry.\n * - Static path: applies the value once; no effect is registered.\n * - Debug path: logs both the static initial bind and reactive updates via\n * `debug.domUpdated` so that all DOM writes appear in a uniform format.\n * - Error path: catches `updater` exceptions and surfaces them via `console.error`\n * so that a broken binding does not silently kill the effect loop.\n * Both the reactive and static paths are guarded consistently with `untracked`.\n *\n * @param el DOM element or SVG element to associate the effect with.\n * @param source Reactive or static value source.\n * @param updater Function that writes the value to the DOM.\n * @param debugType Structured label used in debug log output and effect naming.\n */\nexport function registerReactiveEffect<T>(\n el: Element,\n source: ReactiveValue<T>,\n updater: (value: T) => void,\n debugType: BindingDebugType\n): void {\n if (isReactive(source)) {\n const reactiveSource = source as ReadonlyAtom<T>;\n registry.trackEffect(\n el,\n effect(\n () => {\n // Read the source value inside the tracking context — this is the\n // ONLY dependency this effect should subscribe to.\n const value = reactiveSource.value;\n\n // Run the updater untracked so that any atom reads inside updater\n // (user formatters, guards, computed lookups) cannot accidentally\n // add extra subscriptions to this effect.\n untracked(() => {\n // The effect continues running on future source changes regardless of\n // whether updater throws — the catch here is purely for error surfacing.\n try {\n updater(value);\n } catch (e) {\n debug.error(LOG_PREFIXES.BINDING, ERROR_MESSAGES.BINDING.UPDATER_ERROR(debugType), e);\n return;\n }\n // debug.domUpdated already guards on debug.enabled internally, but\n // skipping the call entirely avoids a function-call overhead on every\n // atom update in production (debug disabled).\n if (debug.enabled) debug.domUpdated(LOG_PREFIXES.BINDING, el, debugType, value);\n });\n },\n { name: debugType }\n )\n );\n } else {\n // Static path: apply once within untracked() to prevent dependency leak\n // if registerReactiveEffect is called inside an outer reactive context.\n untracked(() => {\n try {\n updater(source);\n } catch (e) {\n debug.error(LOG_PREFIXES.BINDING, ERROR_MESSAGES.BINDING.UPDATER_ERROR(debugType, true), e);\n return;\n }\n if (debug.enabled) debug.domUpdated(LOG_PREFIXES.BINDING, el, debugType, source);\n });\n }\n}\n","import { batch } from '@but212/atom-effect';\nimport $ from 'jquery';\nimport { registry } from './registry';\n\n/** Generic event handler type matching jQuery's internal handler signature. */\ntype EventHandler = JQuery.EventHandlerBase<unknown, JQuery.TriggeredEvent>;\n\n/**\n * Symbol marker attached to handlers registered by this library's internals.\n * Handlers carrying this marker are NOT wrapped in batch() — they already\n * manage atom writes directly and do not need an extra reactive flush.\n */\nexport const INTERNAL_HANDLER = Symbol('atom-effect-internal');\n\n/**\n * WeakMap from original handler function → batch-wrapped handler function.\n * Keys are functions (held alive by jQuery's internal event store for as long\n * as the handler is registered), so entries are naturally released when the\n * handler is removed via .off() and jQuery drops its reference.\n */\nconst handlerMap = new WeakMap<EventHandler, EventHandler>();\n\n// ============================================================================\n// Originals store\n// ============================================================================\n\n/**\n * Snapshot of jQuery prototype methods captured at `enablejQueryOverrides()`\n * time and restored by `disablejQueryOverrides()`.\n *\n * Stored as a typed object and captured into `orig` (a local const) inside\n * `enablejQueryOverrides` so that the override closures always reference the\n * pre-patch methods even if `disablejQueryOverrides()` later resets the\n * module-level `originals` variable to null.\n */\ntype OriginalMethods = {\n on: typeof $.fn.on;\n off: typeof $.fn.off;\n remove: typeof $.fn.remove;\n empty: typeof $.fn.empty;\n detach: typeof $.fn.detach;\n};\n\nlet originals: OriginalMethods | null = null;\n\n// ============================================================================\n// Internal helpers\n// ============================================================================\n\nconst getWrappedHandler = (fn: EventHandler): EventHandler => {\n // Skip wrapping for library-internal handlers.\n if ((fn as unknown as Record<symbol, true>)[INTERNAL_HANDLER]) return fn;\n\n let wrapped = handlerMap.get(fn);\n if (!wrapped) {\n // `function` (not arrow) to preserve the jQuery-provided `this` context.\n // Double cast via `unknown` is required because the rest-args signature\n // `(...args: unknown[])` is not directly assignable to `EventHandler`.\n wrapped = function (this: unknown, ...args: unknown[]) {\n return batch(() => fn.apply(this, args as Parameters<EventHandler>));\n } as unknown as EventHandler;\n // Mark the wrapper itself as internal so it isn't double-wrapped if passed again.\n (wrapped as unknown as Record<symbol, true>)[INTERNAL_HANDLER] = true;\n handlerMap.set(fn, wrapped);\n }\n return wrapped;\n};\n\n/**\n * Wraps each handler in an `.on()` event-map with `getWrappedHandler`.\n * Skips keys whose value is falsy — mirrors jQuery's own behaviour of ignoring\n * undefined handlers in event-maps.\n * Uses `for...in` with `hasOwnProperty` guard to iterate own properties only,\n * consistent with the `for` loops used elsewhere in this file.\n */\nfunction wrapEventMap(map: Record<string, EventHandler>): Record<string, EventHandler> {\n const newMap: Record<string, EventHandler> = {};\n const entries = Object.entries(map);\n for (let i = 0, len = entries.length; i < len; i++) {\n const entry = entries[i]!;\n const key = entry[0];\n const handler = entry[1];\n if (handler) {\n newMap[key] = getWrappedHandler(handler);\n }\n }\n return newMap;\n}\n\n/**\n * Resolves the wrapped counterpart for each handler in an `.off()` event-map.\n * Preserves `undefined` values — `.off({ click: undefined })` is a valid\n * jQuery call that removes ALL listeners for that event type.\n * Uses `for...in` with `hasOwnProperty` guard, consistent with `wrapEventMap`.\n */\nfunction resolveOffEventMap(\n map: Record<string, EventHandler | undefined>\n): Record<string, EventHandler | undefined> {\n const newMap: Record<string, EventHandler | undefined> = {};\n const entries = Object.entries(map);\n for (let i = 0, len = entries.length; i < len; i++) {\n const entry = entries[i]!;\n const key = entry[0];\n const handler = entry[1];\n newMap[key] = handler ? (handlerMap.get(handler) ?? handler) : undefined;\n }\n return newMap;\n}\n\n// ============================================================================\n// Public API\n// ============================================================================\n\n/**\n * Patches jQuery's `.on()`, `.off()`, `.remove()`, `.empty()`, and `.detach()`\n * to integrate with the reactive system:\n * - Event handlers are wrapped in `batch()` for efficient atom flushing.\n * - DOM removal triggers reactive binding cleanup.\n * - `.detach()` preserves bindings for re-attachment.\n *\n * Idempotent — calling more than once has no effect.\n * Call `disablejQueryOverrides()` to restore original methods.\n */\nexport function enablejQueryOverrides(): void {\n if (originals !== null) return;\n\n originals = {\n on: $.fn.on,\n off: $.fn.off,\n remove: $.fn.remove,\n empty: $.fn.empty,\n detach: $.fn.detach,\n };\n\n // Capture into a local const so the closures below always hold a stable\n // reference to the originals even after disablejQueryOverrides() resets\n // the module-level `originals` variable to null.\n const orig = originals;\n\n // --- Lifecycle overrides ---\n\n // .remove() — clean up bindings on the matching elements, then delegate.\n // Only elements matched by `selector` (or all elements when selector is\n // omitted) are cleaned up — other elements in `this` are not affected,\n // mirroring jQuery's own selector-scoped remove behaviour.\n $.fn.remove = function (this: JQuery, selector?: string) {\n const targets = selector ? this.filter(selector) : this;\n for (let i = 0, len = targets.length; i < len; i++) {\n const el = targets[i];\n if (el) {\n // markIgnored BEFORE cleanupTree: a MutationObserver callback that\n // fires synchronously during removal will see the ignored flag and\n // skip the redundant second cleanup pass.\n registry.markIgnored(el);\n registry.cleanupTree(el);\n }\n }\n const result = orig.remove.call(this, selector);\n // Ensure chaining is definitively unbroken even if original was sub-patched\n return result !== undefined ? (result as JQuery) : this;\n };\n\n // .empty() — recursively clean up descendants, then delegate.\n $.fn.empty = function (this: JQuery) {\n for (let i = 0, len = this.length; i < len; i++) {\n const el = this[i];\n // Fast path: Avoid expensive DOM queries if the element has no children at all.\n // E.g. .empty() called on a text-only or already-empty element.\n if (el?.hasChildNodes()) {\n registry.cleanupDescendants(el);\n }\n }\n const result = orig.empty.call(this);\n return result !== undefined ? (result as JQuery) : this;\n };\n\n // .detach() — mark elements as kept so the MutationObserver does not\n // dispose their bindings while they are temporarily out of the DOM.\n $.fn.detach = function (this: JQuery, selector?: string) {\n const targets = selector ? this.filter(selector) : this;\n for (let i = 0, len = targets.length; i < len; i++) {\n const el = targets[i];\n if (el) registry.keep(el);\n }\n const result = orig.detach.call(this, selector);\n return result !== undefined ? (result as JQuery) : this;\n };\n\n // --- Event overrides ---\n\n // .on() — wrap the handler argument in batch().\n //\n // jQuery's full signature is: .on(events, selector?, data?, handler)\n // When the first arg is an object it is an event-map; otherwise the handler\n // is always the LAST argument (position 1, 2, or 3 depending on overload).\n // Iterating from the end and stopping at the first function is therefore\n // correct for the positional form, because `data` is never a function in\n // jQuery's documented API.\n // `...args: unknown[]` is used instead of jQuery's overloaded signature\n // because TypeScript cannot unify the 4+ overloads into a single rest type.\n // The casts at args[0] and the apply call site are therefore unavoidable.\n $.fn.on = function (this: JQuery, ...args: unknown[]) {\n const types = args[0];\n\n if (types && typeof types === 'object') {\n args[0] = wrapEventMap(types as Record<string, EventHandler>);\n } else {\n // In jQuery signature .on(events, [selector], [data], handler), the handler\n // is always the last argument provided. We inspect the exact last element\n // to avoid wrapping a function that is actually passed as 'data'.\n const lastIndex = args.length - 1;\n if (lastIndex >= 0 && typeof args[lastIndex] === 'function') {\n args[lastIndex] = getWrappedHandler(args[lastIndex] as EventHandler);\n }\n }\n\n const result = orig.on.apply(this, args as Parameters<typeof $.fn.on>);\n return result !== undefined ? (result as JQuery) : this;\n };\n\n // .off() — resolve the original handler back to its wrapped counterpart so\n // jQuery can find and remove the correct internal listener.\n $.fn.off = function (this: JQuery, ...args: unknown[]) {\n const types = args[0];\n\n if (types && typeof types === 'object') {\n args[0] = resolveOffEventMap(types as Record<string, EventHandler | undefined>);\n } else {\n // Like .on(), only unwrap if the last provided argument is a function.\n const lastIndex = args.length - 1;\n if (lastIndex >= 0 && typeof args[lastIndex] === 'function') {\n const fn = args[lastIndex] as EventHandler;\n args[lastIndex] = handlerMap.get(fn) ?? fn;\n }\n }\n\n const result = orig.off.apply(this, args as Parameters<typeof $.fn.off>);\n return result !== undefined ? (result as JQuery) : this;\n };\n}\n\n/**\n * Restores all jQuery methods patched by `enablejQueryOverrides()`.\n * Primarily useful in test environments to reset state between suites.\n */\nexport function disablejQueryOverrides(): void {\n if (originals === null) return;\n\n $.fn.on = originals.on;\n $.fn.off = originals.off;\n $.fn.remove = originals.remove;\n $.fn.empty = originals.empty;\n $.fn.detach = originals.detach;\n\n originals = null;\n}\n","import type {\n AtomOptions as BaseAtomOptions,\n ComputedAtom,\n ComputedOptions,\n EffectObject,\n ReadonlyAtom,\n WritableAtom,\n} from '@but212/atom-effect';\n\n// ============================================================================\n// Shared API Types\n// ============================================================================\n\n/**\n * Cleanup function returned by effects or components.\n */\nexport type EffectCleanup = () => void;\n\n/**\n * Result of a reactive factory or component mount.\n * Returns `void` (no cleanup) or an `EffectCleanup` function.\n */\nexport type EffectResult = undefined | EffectCleanup;\n\n/**\n * Generic equality predicate shared by `ValOptions` and any future consumer.\n * Extracted as a named type to avoid duplicating the inline function signature.\n */\nexport type EqualFn<T> = (a: T, b: T) => boolean;\n\n/**\n * Extended options for Atom creation.\n */\nexport interface AtomOptions extends BaseAtomOptions {\n /** Name for debugging purposes */\n name?: string;\n}\n\n/**\n * Represents a value that can be either a reactive node (Atom or Computed)\n * or a plain static value of the same type.\n *\n * `ComputedAtom<T>` is a structural sub-type of `ReadonlyAtom<T>`, so it is\n * already covered by `ReadonlyAtom<T>`.\n */\nexport type ReactiveValue<T> = T | ReadonlyAtom<T>;\n\n/**\n * Values allowed for DOM properties and attributes.\n */\nexport type PrimitiveValue = string | number | boolean | null | undefined;\n\n/**\n * Helper to extract keys of T whose values extend V.\n * Used to ensure `key` property refers to valid ID-like values.\n */\ntype KeysOfType<T, V> = { [K in keyof T]: T[K] extends V ? K : never }[keyof T];\n\n/**\n * CSS value: either a direct reactive value or a numeric tuple of [source, unit].\n */\nexport type CssValue =\n | ReactiveValue<string | number>\n | [source: ReactiveValue<number>, unit: string];\n\n/**\n * CSS bindings map property names to CSS values.\n */\nexport type CssBindings = Record<string, CssValue>;\n\n/**\n * Configuration options for `atomBind`.\n * @template T Type of the value for two-way binding (`val` field).\n */\nexport interface BindingOptions<T = unknown> {\n /** Binds textContent to any reactive source. */\n text?: ReactiveValue<unknown>;\n /** Binds innerHTML to a reactive string source (sanitized). */\n html?: ReactiveValue<string>;\n /** Map of class names to reactive boolean conditions. */\n class?: Record<string, ReactiveValue<boolean>>;\n /** Map of CSS properties to reactive values or [value, unit] tuples. */\n css?: CssBindings;\n /** Binds attributes with consistent primitive constraints. */\n attr?: Record<string, ReactiveValue<PrimitiveValue>>;\n /** Binds DOM properties. */\n prop?: Record<string, ReactiveValue<unknown>>;\n /** Direct visibility control (display: none). */\n show?: ReactiveValue<boolean>;\n /** Inverse visibility control. */\n hide?: ReactiveValue<boolean>;\n /**\n * Two-way binding for input values.\n * Pass an atom or a `[atom, options]` tuple.\n */\n val?: WritableAtom<T> | [atom: WritableAtom<T>, options: ValOptions<T>];\n /** Two-way binding for checkboxes and radio buttons. */\n checked?: WritableAtom<boolean>;\n /** Event listeners with automatic batched execution and lifecycle-bound cleanup. */\n on?: Record<string, (e: JQuery.Event) => void>;\n}\n\n// ============================================================================\n// List API Types\n// ============================================================================\n\n/** Key type for Map/Set inside list.ts */\nexport type ListKey = string | number;\n\n/** Lifecycle state of the itemMap entry */\nexport type ListItemState = 'new' | 'replaced';\n\n/** Possible return types for render() / empty */\nexport type ListRenderResult = string | Element | DocumentFragment | JQuery;\n\n/** Key extractor function signature. */\nexport type ListKeyFn<T> = (item: T, index: number) => ListKey;\n\n/**\n * Configuration options for `atomList`.\n */\nexport interface ListOptions<T> {\n /**\n * Key to track items. Must be a property name whose value is a string|number,\n * or a key extractor function.\n */\n key: KeysOfType<T, ListKey> | ListKeyFn<T>;\n /** Render function for each item. */\n render: (item: T, index: number) => ListRenderResult;\n /** Optional post-render binding logic. */\n bind?: ($el: JQuery, item: T, index: number) => void;\n /** Optional update logic when item data changes but DOM is reused. */\n update?: ($el: JQuery, item: T, index: number) => void;\n /** Lifecycle hook: called when an element is added to the list. */\n onAdd?: ($el: JQuery) => void;\n /** Lifecycle hook: called when an element is about to be removed. */\n onRemove?: ($el: JQuery) => Promise<void> | void;\n /** Content to show when the list is empty. */\n empty?: ListRenderResult;\n /** Delegated event handlers attached to the container. */\n events?: Record<string, (item: T, index: number, e: JQuery.TriggeredEvent) => void>;\n}\n\n// ============================================================================\n// Form & Input Types\n// ============================================================================\n\n/**\n * Configuration options for `atomVal`.\n */\nexport interface ValOptions<T> {\n /** Delay in milliseconds before syncing DOM input to Atom. */\n debounce?: number;\n /** DOM event to trigger sync (default: 'input'). */\n event?: string;\n /** Parser to convert string input to Atom type T. */\n parse?: (v: string) => T;\n /** Formatter to convert Atom type T to string for DOM display. */\n format?: (v: T) => string;\n /** Custom equality check for comparing parsed values. Defaults to Object.is. */\n equal?: EqualFn<T>;\n}\n\n// ============================================================================\n// Fetch API Types\n// ============================================================================\n\n/**\n * Configuration options for `atomFetch`.\n */\nexport interface FetchOptions<T> {\n /** Initial value before the first fetch resolves. */\n defaultValue: T;\n /** HTTP method (default: 'GET'). */\n method?: 'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE' | 'HEAD' | 'OPTIONS' | (string & {});\n /** HTTP headers. */\n headers?: Record<string, string>;\n /** Transforms the raw response into T. */\n transform?: (raw: unknown) => T;\n /** Additional `$.ajax` settings. Can be a getter function for reactive data tracking. */\n ajaxOptions?: JQuery.AjaxSettings | (() => JQuery.AjaxSettings);\n /** Error callback. */\n onError?: (err: unknown) => void;\n /** Whether to fetch immediately (default: true). */\n eager?: boolean;\n}\n\n/** Error payload for atomFetch. */\nexport interface FetchError extends Error {\n /** The original jQuery XHR object. */\n jqXHR?: JQuery.jqXHR;\n}\n\n// ============================================================================\n// Component & Router Types\n// ============================================================================\n\n/**\n * A function that initializes logic on a jQuery element and returns an optional cleanup function.\n * `P` defaults to `Record<string, unknown>` for convenience. Use `P = Record<string, never>`\n * for strictly no-props components.\n */\nexport type ComponentFn<P = Record<string, unknown>> = ($el: JQuery, props: P) => EffectResult;\n\n/** Shared route lifecycle hooks. */\nexport interface RouteLifecycle {\n onEnter?: (params: Record<string, string>) => Record<string, string> | undefined;\n onLeave?: () => boolean | undefined;\n onParamsChange?: (params: Record<string, string>) => void;\n}\n\nexport interface TemplateRoute extends RouteLifecycle {\n template: string;\n render?: never;\n onMount?: ($content: JQuery) => void;\n}\n\nexport interface RenderRoute extends RouteLifecycle {\n render: (container: HTMLElement, route: string, params: Record<string, string>) => void;\n template?: never;\n}\n\nexport type RouteDefinition = TemplateRoute | RenderRoute;\n\nexport interface RouteConfig {\n target: string;\n default: string;\n routes: Record<string, RouteDefinition>;\n mode?: 'hash' | 'history';\n basePath?: string;\n notFound?: string;\n autoBindLinks?: boolean;\n activeClass?: string;\n beforeTransition?: (from: string, to: string) => void;\n afterTransition?: (from: string, to: string) => void;\n}\n\nexport interface Router {\n currentRoute: ReadonlyAtom<string>;\n queryParams: ReadonlyAtom<Record<string, string>>;\n navigate: (route: string) => void;\n destroy: () => void;\n}\n\n// ============================================================================\n// Internal Types (Implementation Details)\n// ============================================================================\n\n/**\n * Bit flags for input binding state management.\n * @internal\n */\nexport enum BindingFlags {\n None = 0,\n Focused = 1 << 0,\n Composing = 1 << 1,\n SyncingToAtom = 1 << 2,\n SyncingToDom = 1 << 3,\n Busy = Composing | SyncingToAtom | SyncingToDom,\n}\n\n/**\n * Context passed to binding handlers for unified lifecycle management.\n * @internal\n */\nexport interface BindingContext {\n readonly $el: JQuery;\n readonly el: HTMLElement;\n readonly trackCleanup: (fn: EffectCleanup) => void;\n}\n\n/**\n * Item record stored in itemMap.\n * @internal\n */\nexport interface ListItemEntry<T> {\n $el: JQuery;\n item: T;\n state?: ListItemState | undefined;\n}\n\n// ============================================================================\n// JQuery Global Augmentation\n// ============================================================================\n\ndeclare global {\n interface JQueryStatic {\n atom: {\n <T>(initialValue: T, options?: AtomOptions): WritableAtom<T>;\n debug: boolean;\n };\n computed<T>(fn: () => T, options?: ComputedOptions<T>): ComputedAtom<T>;\n computed<T>(\n fn: () => Promise<T>,\n options: ComputedOptions<T> & { defaultValue: T }\n ): ComputedAtom<T>;\n effect(fn: () => EffectResult): EffectObject;\n batch(fn: () => void): void;\n untracked<T>(fn: () => T): T;\n isAtom(v: unknown): boolean;\n isComputed(v: unknown): boolean;\n isReactive(v: unknown): boolean;\n nextTick(): Promise<void>;\n route(config: RouteConfig): Router;\n atomFetch<T>(\n urlOrFn: string | (() => string),\n options: FetchOptions<T>\n ): ComputedAtom<T> & { abort: () => void };\n }\n\n interface JQuery {\n atomText<T>(source: ReactiveValue<T>, formatter?: (v: T) => string): this;\n atomHtml(source: ReactiveValue<string>): this;\n atomClass(className: string, condition: ReactiveValue<boolean>): this;\n atomClass(classMap: Record<string, ReactiveValue<boolean>>): this;\n atomCss(prop: string, source: ReactiveValue<string | number>, unit?: string): this;\n atomCss(cssMap: CssBindings): this;\n atomAttr(name: string, source: ReactiveValue<PrimitiveValue>): this;\n atomAttr(attrMap: Record<string, ReactiveValue<PrimitiveValue>>): this;\n atomProp<T>(name: string, source: ReactiveValue<T>): this;\n atomProp<T>(propMap: Record<string, ReactiveValue<T>>): this;\n atomShow(condition: ReactiveValue<boolean>): this;\n atomHide(condition: ReactiveValue<boolean>): this;\n atomVal<T>(atom: WritableAtom<T>, options?: ValOptions<T>): this;\n atomChecked(atom: WritableAtom<boolean>): this;\n atomOn(event: string, handler: (e: JQuery.Event) => void): this;\n\n atomBind<T = unknown>(options: BindingOptions<T>): this;\n atomList<T>(source: ReadonlyAtom<T[]>, options: ListOptions<T>): this;\n\n atomMount<P>(component: ComponentFn<P>, props?: P): this;\n atomUnmount(): this;\n atomUnbind(): this;\n }\n}\n\nexport type { WritableAtom, ReadonlyAtom, ComputedAtom, EffectObject, ComputedOptions };\n","import { effect, untracked } from '@but212/atom-effect';\nimport { ERROR_MESSAGES, INPUT_DEFAULTS, LOG_PREFIXES } from './constants';\nimport { debug } from './debug';\nimport { INTERNAL_HANDLER } from './jquery-patch';\nimport type { EffectObject, ValOptions, WritableAtom } from './types';\nimport { BindingFlags } from './types';\n\n// Monotonically increasing counter used to generate per-instance event\n// namespaces, preventing cleanup of sibling bindings on the same element.\nlet instanceCounter = 0;\n\ntype InputEl = HTMLInputElement | HTMLTextAreaElement | HTMLSelectElement;\n\n/**\n * Marks a handler as library-internal so the jQuery patch skips batch() wrapping.\n * All handlers registered by InputBinding must be marked — unmarked handlers are\n * wrapped in batch() by the jQuery override, which is redundant and potentially\n * harmful here since InputBinding manages atom writes directly.\n */\nfunction markInternal(fn: Function): void {\n (fn as unknown as Record<symbol, true>)[INTERNAL_HANDLER] = true;\n}\n\nclass InputBinding<T> {\n // $el: used only for jQuery event binding and debug.domUpdated — kept as a\n // field to avoid re-wrapping $el[0] on every call.\n // el: raw DOM reference for hot-path property access (value, selectionStart,\n // etc.) — avoids jQuery wrapper overhead on every input event.\n private readonly $el: JQuery;\n private readonly el: InputEl;\n private readonly atom: WritableAtom<T>;\n private readonly isMultipleSelect: boolean;\n\n // Hoisted fast local properties vs deep this.options.x lookups for hot paths.\n private readonly parse: (v: string) => T;\n private readonly format: (v: T) => string;\n private readonly equal: (a: T, b: T) => boolean;\n\n private flags = 0;\n // undefined instead of null so clearTimeout(this.timeoutId) is always safe\n // without a null-check (clearTimeout(undefined) is a no-op per spec).\n private timeoutId: ReturnType<typeof setTimeout> | undefined = undefined;\n\n /** Per-instance jQuery event namespace — prevents cleanup collisions. */\n private readonly ns: string;\n\n // Declared here so TypeScript knows the field exists; assigned in the\n // constructor where the debounce branch decides which closure to use.\n // Must be readonly after construction — markInternal relies on the final\n // function reference being stable, which is ensured by calling it after\n // all handler assignments are complete.\n private readonly handleInput: () => void;\n\n constructor($el: JQuery, atom: WritableAtom<T>, options: ValOptions<T>) {\n this.$el = $el;\n this.el = $el[0] as InputEl;\n this.atom = atom;\n this.isMultipleSelect = this.el.tagName === 'SELECT' && (this.el as HTMLSelectElement).multiple;\n this.ns = `.atomBind-${++instanceCounter}`;\n\n const debounce = options.debounce ?? 0;\n const eventName = options.event ?? INPUT_DEFAULTS.EVENT;\n\n this.parse = options.parse ?? ((v: string) => v as unknown as T);\n this.format =\n options.format ??\n ((v: T) => {\n // Return array directly for <select multiple> instead of stringifying\n if (this.isMultipleSelect) {\n return (Array.isArray(v) ? v : v ? [String(v)] : []).join(',');\n }\n return String(v ?? '');\n });\n\n // Wrap user-provided or default equality with shallow array comparison\n // to support <select multiple> without leaking `unknown` into the public type.\n const baseEqual = options.equal ?? Object.is;\n this.equal = (a: T, b: T): boolean => {\n if (baseEqual(a, b)) return true;\n if (Array.isArray(a) && Array.isArray(b)) {\n return a.length === b.length && a.every((val, i) => Object.is(val, b[i]));\n }\n return false;\n };\n\n // Optimization: pre-bind the appropriate input handler to avoid per-event\n // branching at runtime. The debounce branch produces a closure that clears\n // and resets a timer; the no-debounce branch calls syncAtomFromDom directly.\n if (debounce > 0) {\n this.handleInput = () => {\n if (this.flags & BindingFlags.Composing) return;\n clearTimeout(this.timeoutId);\n this.timeoutId = setTimeout(() => this.syncAtomFromDom(), debounce);\n };\n } else {\n this.handleInput = () => {\n if (this.flags & BindingFlags.Composing) return;\n this.syncAtomFromDom();\n };\n }\n\n // Mark all handlers so the jQuery patch skips batch() wrapping.\n // Done after all handler references are finalized (handleInput is assigned\n // above; the others are class-field arrow functions initialized before the\n // constructor body runs).\n markInternal(this.handleFocus);\n markInternal(this.handleBlur);\n markInternal(this.handleCompositionStart);\n markInternal(this.handleCompositionEnd);\n markInternal(this.handleInput);\n\n this.bindEvents(eventName);\n }\n\n // --- Event Handlers ---\n\n private readonly handleCompositionStart = () => {\n this.flags |= BindingFlags.Composing;\n };\n\n private readonly handleCompositionEnd = () => {\n this.flags &= ~BindingFlags.Composing;\n this.handleInput();\n };\n\n private readonly handleFocus = () => {\n this.flags |= BindingFlags.Focused;\n };\n\n private readonly handleBlur = () => {\n this.flags &= ~BindingFlags.Focused;\n\n // FIX 4: Clear composing state securely when an element is unexpectedly blurred\n // while composition was active (e.g., click away during IME typing).\n const wasComposing = !!(this.flags & BindingFlags.Composing);\n this.flags &= ~BindingFlags.Composing;\n\n // Order matters: flush the pending debounce write BEFORE normalizing the\n // display value so that normalizeDomValue reads the atom state that\n // includes any value the user was typing.\n this.flushPendingDebounce();\n\n // If debounce === 0 and was composing, flushPendingDebounce wouldn't have synced Atom\n // (since timeoutId is undefined), so we must manually sync to prevent typed text from evaporating.\n if (wasComposing && this.timeoutId === undefined) {\n this.syncAtomFromDom();\n }\n\n this.normalizeDomValue();\n };\n\n // --- Blur helpers ---\n\n /**\n * Flushes any pending debounce timer immediately.\n * Called on blur so that a value the user finished typing is not lost\n * when focus moves away before the debounce delay expires.\n */\n private flushPendingDebounce(): void {\n if (this.timeoutId !== undefined) {\n clearTimeout(this.timeoutId);\n this.timeoutId = undefined;\n this.syncAtomFromDom();\n }\n }\n\n /**\n * Re-formats the current atom value into the input element on blur.\n * Ensures the displayed text matches the canonical format (e.g. trims trailing\n * spaces, applies number formatting) after the user finishes editing.\n */\n private normalizeDomValue(): void {\n const formatted = this.format(this.atom.peek());\n\n if (this.isMultipleSelect) {\n const currentVal = (this.$el.val() as string[] | null) || [];\n const formattedArr = Array.isArray(this.atom.peek()) ? this.atom.peek() : [];\n if (!this.equal(currentVal as unknown as T, formattedArr as unknown as T)) {\n this.$el.val(formattedArr as unknown as string[]);\n }\n } else if (this.el.value !== formatted) {\n this.el.value = formatted;\n }\n }\n\n // --- Sync Logic ---\n\n private syncAtomFromDom(): void {\n // BindingFlags.Busy covers Composing | SyncingToAtom | SyncingToDom.\n // SyncingToDom is included defensively: if a future synchronous code path\n // triggers handleInput during an Atom→DOM write, this guard prevents echo.\n if (this.flags & BindingFlags.Busy) return;\n\n this.flags |= BindingFlags.SyncingToAtom;\n try {\n // FIX 3: Support <select multiple> arrays\n let rawValue: string;\n if (this.isMultipleSelect) {\n rawValue = ((this.$el.val() as string[] | null) || []) as unknown as string;\n } else {\n rawValue = this.el.value;\n }\n\n const parsed = this.parse(rawValue);\n // peek() instead of .value: equality check in an event handler must not\n // register a dependency — only syncDomFromAtom (the effect body) tracks.\n if (!this.equal(this.atom.peek(), parsed)) {\n this.atom.value = parsed;\n }\n } catch (e) {\n // parse() threw (e.g. invalid input) — leave the atom unchanged.\n debug.warn(\n LOG_PREFIXES.BINDING,\n ERROR_MESSAGES.BINDING.PARSE_ERROR(e instanceof Error ? e.message : String(e)),\n e\n );\n } finally {\n this.flags &= ~BindingFlags.SyncingToAtom;\n }\n }\n\n // --- Public Interface ---\n\n /**\n * Reactive effect body (Atom → DOM).\n * Called by the `effect()` wrapper in `applyInputBinding` whenever the atom\n * value changes. Named `syncDomFromAtom` to distinguish it from the imported\n * `effect` function and to clarify the data-flow direction.\n *\n * TRACKING NOTE: only `this.atom.value` is intentionally tracked as a\n * reactive dependency. `format()`, `parse()`, and `equal()` run inside\n * `untracked()` so that user-supplied callbacks cannot accidentally subscribe\n * this effect to additional atoms — even if those callbacks internally read\n * reactive state.\n */\n public readonly syncDomFromAtom = () => {\n const val = this.atom.value;\n\n untracked(() => {\n const formatted = this.format(val);\n\n let currentVal: T;\n if (this.isMultipleSelect) {\n currentVal = ((this.$el.val() as string[] | null) || []) as unknown as T;\n } else {\n currentVal = this.el.value as unknown as T;\n }\n\n // Skip if already synchronised.\n if (this.equal(currentVal, val)) return;\n\n const isFocused = !!(this.flags & BindingFlags.Focused);\n\n // While focused, skip update if the current raw input already parses to\n // the same logical value — avoids interrupting in-progress user input.\n if (isFocused) {\n try {\n const parsedCurrent = this.isMultipleSelect\n ? currentVal // already T (string[]) from DOM\n : this.parse(this.el.value);\n if (this.equal(parsedCurrent, val)) return;\n } catch {\n // parse() threw on the current raw input (e.g. partially typed number).\n // Fall through and apply the formatted value.\n }\n }\n\n this.flags |= BindingFlags.SyncingToDom;\n try {\n if (this.isMultipleSelect) {\n this.$el.val(val as unknown as string[]);\n } else if (\n isFocused &&\n (this.el instanceof HTMLInputElement || this.el instanceof HTMLTextAreaElement)\n ) {\n // Preserve cursor position so external atom updates don't jump the caret.\n try {\n const start = this.el.selectionStart;\n const end = this.el.selectionEnd;\n\n this.el.value = formatted;\n const len = formatted.length;\n\n if (start !== null && end !== null) {\n this.el.setSelectionRange(start < len ? start : len, end < len ? end : len);\n }\n } catch (_e) {\n // FIX 1: Accessing selectionStart on types like 'number' throws an InvalidStateError DOMException.\n this.el.value = formatted;\n }\n } else {\n this.el.value = formatted;\n }\n\n if (debug.enabled) debug.domUpdated(LOG_PREFIXES.BINDING, this.$el, 'val', formatted);\n } finally {\n this.flags &= ~BindingFlags.SyncingToDom;\n }\n });\n };\n\n public readonly cleanup = () => {\n // Remove only this instance's namespaced events — other bindings on the\n // same element are unaffected.\n this.$el.off(this.ns);\n clearTimeout(this.timeoutId);\n this.timeoutId = undefined;\n };\n\n private bindEvents(eventName: string): void {\n const ns = this.ns;\n // FIX 2: Apply namespace to every space-separated event type.\n const namespacedEvents = eventName\n .trim()\n .split(/\\s+/)\n .map((e) => `${e}${ns}`)\n .join(' ');\n\n this.$el\n .on(`focus${ns}`, this.handleFocus)\n .on(`blur${ns}`, this.handleBlur)\n .on(`compositionstart${ns}`, this.handleCompositionStart)\n .on(`compositionend${ns}`, this.handleCompositionEnd)\n .on(namespacedEvents, this.handleInput);\n }\n}\n\n/**\n * Applies two-way data binding between a writable atom and an input element.\n * Used by both `$.fn.atomVal` (explicit) and `$.fn.atomBind({ val })` (implicit).\n *\n * @param $el - jQuery-wrapped input, textarea, or select element.\n * @param atom - Writable atom to keep in sync with the element's value.\n * @param options - Optional parse/format/debounce/event/equal configuration.\n * @returns `fx` — the registered reactive effect (Atom → DOM),\n * `cleanup` — removes all event listeners and cancels pending timers.\n */\nexport function applyInputBinding<T>(\n $el: JQuery,\n atom: WritableAtom<T>,\n options: ValOptions<T>\n): { fx: EffectObject; cleanup: () => void } {\n const binding = new InputBinding($el, atom, options);\n return { fx: effect(binding.syncDomFromAtom), cleanup: binding.cleanup };\n}\n","/**\n * HTML sanitization and security guards for XSS mitigation.\n *\n * This module is the **sole** sanitization layer — there is no downstream\n * sanitizer (e.g. DOMPurify) applied automatically. All regex-based\n * filtering happens here before content reaches the DOM.\n *\n * **Threat model:** best-effort defence for developer-authored templates and\n * reactive string bindings. For user-controlled rich text (e.g. a WYSIWYG\n * editor), replace or supplement this with DOMPurify.\n */\n\n// ============================================================================\n// URL attribute registry\n// ============================================================================\n\n/**\n * Attributes that carry a single URL value.\n *\n * `srcset` is intentionally excluded: its value is a comma-separated list of\n * URLs (e.g. `\"img.png 1x, img@2x.png 2x\"`), so a start-anchored regex cannot\n * reliably detect a dangerous protocol buried after the first comma. Callers\n * that need to validate srcset should parse each URL individually.\n */\nconst URL_ATTRS = new Set([\n 'href',\n 'src',\n 'action',\n 'formaction',\n 'xlink:href',\n 'data',\n 'poster',\n 'background',\n 'cite',\n 'longdesc',\n 'profile',\n 'usemap',\n 'classid',\n 'codebase',\n]);\n\n// ============================================================================\n// Pre-compiled regex constants\n// ============================================================================\n\nconst DANGEROUS_PROTOCOL_RE = /^\\s*(?:javascript|vbscript)\\s*:/i;\n\nconst DANGEROUS_CSS_RE =\n // biome-ignore lint/suspicious/noControlCharactersInRegex: Intentionally matching control characters for XSS sanitization\n /(?:expression\\s*\\(|behavior\\s*:|-moz-binding\\s*:|(?:\\\\[0-9a-f]{1,6}\\s*|[\\s\\x00-\\x20/'\"])*(?:j\\s*a\\s*v\\s*a\\s*s\\s*c\\s*r\\s*i\\s*p\\s*t|v\\s*b\\s*s\\s*c\\s*r\\s*i\\s*p\\s*t|d\\s*a\\s*t\\s*a)\\s*:(?!image\\/))/i;\n\n/** Detects `javascript:` / `vbscript:` inside a CSS `url()` function. Non-global — no `lastIndex` state. */\nconst DANGEROUS_CSS_URL_RE = /url\\s*\\(\\s*(?:[\"']?\\s*)?(?:javascript|vbscript)\\s*:/i;\n\n// biome-ignore lint/suspicious/noControlCharactersInRegex: Intentionally matching control characters\nconst STRIP_CTRL_RE = /[\\x00-\\x08\\x0b\\x0c\\x0e-\\x1f\\x7f]/g;\n\n/**\n * Numeric HTML entity decoder: &#NNN; and &#xHH; forms.\n *\n * Runs before protocol/tag checks so entity-encoded bypass vectors like\n * \"javascript:\" (j=106) are normalised to their literal characters.\n * Safe structural entities (& < > ") are intentionally left\n * encoded — they produce inert text when re-inserted via innerHTML and must\n * remain escaped for correct HTML rendering.\n *\n * The semicolon is optional (`?`) to catch unterminated references such as\n * \"javascript:\" which some parsers still decode.\n */\nconst DECODE_NUMERIC_ENTITY_RE = /&#x([0-9a-f]+);?|&#([0-9]+);?/gi;\n\n/**\n * Named-entity decoder for the small set of entities relevant to protocol\n * smuggling (colon, Tab, NewLine).\n *\n * HTML5 named character references are **case-sensitive** — `	` exists,\n * `&tab;` does not. Do NOT add the `i` flag: it would incorrectly decode\n * non-existent variants and widen the attack surface.\n */\nconst NAMED_ENTITY_MAP: Record<string, string> = {\n colon: ':',\n Tab: '\\t',\n NewLine: '\\n',\n};\nconst DECODE_NAMED_ENTITY_RE = /&(colon|Tab|NewLine);/g;\n\nconst STRIP_XML_RE = /<\\?[\\s\\S]*?\\?>/g;\n\nconst DANGEROUS_TAG_RE =\n /(<(script|iframe|object|embed|base|meta|applet|noscript|form|style|link)\\b[^>]*>([\\s\\S]*?)<\\/\\2>|<(script|iframe|object|embed|base|meta|applet|noscript|form|style|link)\\b[^>]*\\/?>)/gi;\n\nconst DANGEROUS_PROTOCOL_GLOBAL_RE =\n /(j\\s*a\\s*v\\s*a\\s*s\\s*c\\s*r\\s*i\\s*p\\s*t|v\\s*b\\s*s\\s*c\\s*r\\s*i\\s*p\\s*t)\\s*:/gi;\n\nconst DANGEROUS_DATA_URI_RE =\n /data\\s*:\\s*(?:text\\/(?:html|javascript|vbscript|xml)|application\\/(?:javascript|xhtml\\+xml|xml|x-shockwave-flash)|image\\/svg\\+xml)/gi;\n\nconst UNSAFE_ATTR_RE = /\\bon\\w+\\s*=/gim;\n\n/** Global variant of DANGEROUS_CSS_RE for use inside sanitizeHtml. */\nconst DANGEROUS_CSS_GLOBAL_RE = new RegExp(DANGEROUS_CSS_RE.source, 'gim');\n\n// ============================================================================\n// sanitizeHtml\n// ============================================================================\n\n/**\n * HTML sanitization for XSS mitigation using regex-based filtering.\n *\n * Faster than DOMParser but relies on pattern matching.\n * Neutralizes dangerous attributes (`on*`, protocols) instead of removing\n * them entirely, so the surrounding markup structure is preserved.\n *\n * **This is the final sanitization layer.** No additional sanitizer runs\n * downstream. For user-controlled rich text (WYSIWYG, markdown output, etc.)\n * use a dedicated library such as DOMPurify instead of or on top of this.\n */\nexport function sanitizeHtml(html: string | null | undefined): string {\n let safe = String(html ?? '');\n\n // 0. Pre-process: Remove null bytes and control characters (bypass vectors)\n // These are often used to bypass regex filters while browsers ignore them.\n safe = safe.replace(STRIP_CTRL_RE, '');\n\n // 0b. Decode numeric HTML entities (&#NNN; / &#xHH;) and dangerous named\n // entities so that protocol-bypass vectors like \"javascript:\" are\n // normalised to their literal characters before the dangerous-tag and\n // dangerous-protocol regexes run.\n safe = safe.replace(DECODE_NUMERIC_ENTITY_RE, (_, hex, dec) =>\n String.fromCodePoint(hex ? parseInt(hex, 16) : parseInt(dec, 10))\n );\n safe = safe.replace(DECODE_NAMED_ENTITY_RE, (_, name) => NAMED_ENTITY_MAP[name] ?? '');\n\n // 1. Remove dangerous tags (script, iframe, style, etc.) and their content.\n // Note: <svg> and <math> are intentionally kept — they have legitimate uses\n // (icons, equations). Their event handlers (on*) are neutralized in step 3.\n // Also strip XML processing instructions <?...?> (abused in some parsers).\n safe = safe.replace(STRIP_XML_RE, '');\n\n // Loop tag removal to prevent nested reassembly bypass (e.g. \"<scr<script>ipt>\").\n let prev: string;\n do {\n prev = safe;\n safe = safe.replace(DANGEROUS_TAG_RE, '');\n } while (safe !== prev);\n\n // 2. Neutralize dangerous protocols (javascript:, vbscript:).\n // Whitespace-tolerant regex handles obfuscation like \"j a v a s c r i p t:\".\n safe = safe.replace(DANGEROUS_PROTOCOL_GLOBAL_RE, 'data-unsafe-protocol:');\n\n // Neutralize dangerous data URIs (text/html, application/javascript, image/svg+xml, etc.).\n // Common inline images (data:image/png, data:image/jpeg, etc.) are preserved.\n safe = safe.replace(DANGEROUS_DATA_URI_RE, 'data-unsafe-protocol:');\n\n // 3. Neutralize event handler attributes (on* = → data-unsafe-attr=).\n safe = safe.replace(UNSAFE_ATTR_RE, 'data-unsafe-attr=');\n\n // 4. Neutralize CSS expressions (IE legacy) and -moz-binding.\n safe = safe.replace(DANGEROUS_CSS_GLOBAL_RE, 'data-unsafe-css:');\n\n return safe;\n}\n\n// ============================================================================\n// Security guards (used by the binding layer)\n// ============================================================================\n\n/**\n * Returns `true` when `attrName` is a URL-bearing attribute and `value`\n * contains a `javascript:` or `vbscript:` protocol.\n *\n * Only single-URL attributes are checked (see `URL_ATTRS`). `srcset` is\n * excluded because its comma-separated format requires per-URL parsing that\n * this function does not perform.\n *\n * Used by `bindAttr` to guard URL-bearing attributes.\n */\nexport function isDangerousUrl(attrName: string, value: string): boolean {\n if (!URL_ATTRS.has(attrName.toLowerCase())) return false;\n return DANGEROUS_PROTOCOL_RE.test(value);\n}\n\n/**\n * Returns `true` when a CSS property value contains a dangerous protocol\n * inside a `url()` function (e.g. `background-image: url(\"javascript:…\")`).\n *\n * Uses a non-global regex to avoid `lastIndex` statefulness between calls.\n */\nexport function isDangerousCssValue(value: string): boolean {\n // Fast pre-check avoids running the full regex on every CSS value.\n if (!value.toLowerCase().includes('url(')) return false;\n return DANGEROUS_CSS_URL_RE.test(value);\n}\n","import { computed, effect, isAtom, untracked } from '@but212/atom-effect';\nimport $ from 'jquery';\nimport {\n DANGEROUS_PROPS,\n ERROR_MESSAGES,\n LOG_PREFIXES,\n URL_PROPS,\n VALID_INPUT_TAGS,\n} from './constants';\nimport { debug } from './debug';\nimport { type BindingDebugType, registerReactiveEffect } from './effect-factory';\nimport { applyInputBinding } from './input-binding';\nimport { INTERNAL_HANDLER } from './jquery-patch';\nimport { registry } from './registry';\nimport type {\n BindingContext,\n BindingOptions,\n CssValue,\n PrimitiveValue,\n ReactiveValue,\n ValOptions,\n WritableAtom,\n} from './types';\n\nexport type { BindingContext };\n\nimport { isDangerousCssValue, isDangerousUrl, sanitizeHtml } from './sanitize';\nimport { hasOwn } from './utils';\n\n// Cache for CSS property camelization to avoid repeated regex overhead.\n// Uses Map instead of a plain object to avoid prototype pollution risk and\n// for clearer semantics — CSS property names are a small, finite set so the\n// cache is effectively bounded in practice.\nconst camelCache = new Map<string, string>();\nfunction getCamelCase(prop: string): string {\n let cached = camelCache.get(prop);\n if (cached !== undefined) return cached;\n\n cached = prop.includes('-') ? prop.replace(/-./g, (m) => m[1]!.toUpperCase()) : prop;\n camelCache.set(prop, cached);\n return cached;\n}\n\n/**\n * Cache for sanitized versions of reactive strings.\n * Ensures that if 100 elements are bound to the same atom, sanitizeHtml() is\n * called only once per update instead of 100 times.\n */\nconst htmlSanitizeCache = new WeakMap<\n import('@but212/atom-effect').ReadonlyAtom<string>,\n import('@but212/atom-effect').ComputedAtom<string>\n>();\n\nfunction getSanitizedHtml(\n source: import('@but212/atom-effect').ReadonlyAtom<string>\n): import('@but212/atom-effect').ComputedAtom<string> {\n let cached = htmlSanitizeCache.get(source);\n if (!cached) {\n cached = computed(() => sanitizeHtml(source.value));\n htmlSanitizeCache.set(source, cached);\n }\n return cached;\n}\n\n// ============================================================================\n// Binding Context Factory\n// ============================================================================\n\nexport function createContext(el: HTMLElement): BindingContext {\n return {\n $el: $(el),\n el,\n trackCleanup: (fn) => registry.trackCleanup(el, fn),\n };\n}\n\n// ============================================================================\n// One-Way Binding Handlers (Atom → DOM)\n// ============================================================================\n\n/**\n * Updates element text content. Decoupled from generic T for flexibility with any reactive source.\n */\nexport function bindText<T = unknown>(\n ctx: BindingContext,\n value: ReactiveValue<T>,\n formatter?: (val: T) => string\n): void {\n const el = ctx.el;\n registerReactiveEffect(\n el,\n value,\n (val) => {\n const newVal = formatter ? formatter(val) : typeof val === 'string' ? val : String(val ?? '');\n // Guard against redundant DOM writes which trigger browser reflows\n if (el.textContent !== newVal) {\n el.textContent = newVal;\n }\n },\n 'text'\n );\n}\n\n/**\n * Updates element inner HTML with XSS sanitization.\n * Calls `registry.cleanupDescendants` before replacing innerHTML so that any\n * reactive bindings on outgoing child nodes are disposed before they are removed —\n * preventing the MutationObserver auto-cleanup path from firing a redundant cleanup.\n */\nexport function bindHtml(ctx: BindingContext, value: ReactiveValue<string>): void {\n const el = ctx.el;\n\n // Optimization: If the source is reactive, use a cached computed atom to\n // ensure sanitization runs exactly once per atom change for all observers.\n const reactiveSource = isAtom(value)\n ? getSanitizedHtml(value as import('@but212/atom-effect').ReadonlyAtom<string>)\n : value;\n\n registerReactiveEffect(\n el,\n reactiveSource,\n (sanitized) => {\n if (el.innerHTML !== sanitized) {\n // Dispose child bindings before the nodes are removed from the DOM.\n registry.cleanupDescendants(el);\n el.innerHTML = sanitized;\n }\n },\n 'html'\n );\n}\n\n/**\n * Toggles multiple CSS classes based on reactive boolean conditions.\n */\nexport function bindClass(\n ctx: BindingContext,\n classMap: Record<string, ReactiveValue<boolean>>\n): void {\n for (const className in classMap) {\n if (hasOwn.call(classMap, className)) {\n const source = classMap[className]!;\n // FIX 1: Support space-separated multiple classes (e.g. Tailwind) without DOMException\n const tokens = className.trim().split(/\\s+/).filter(Boolean);\n\n if (tokens.length > 1) {\n registerReactiveEffect(\n ctx.el,\n source,\n (val) => {\n if (val) {\n ctx.el.classList.add(...tokens);\n } else {\n ctx.el.classList.remove(...tokens);\n }\n },\n `class.${className}`\n );\n } else if (tokens.length === 1) {\n registerReactiveEffect(\n ctx.el,\n source,\n (val) => {\n ctx.el.classList.toggle(tokens[0]!, !!val);\n },\n `class.${className}`\n );\n }\n }\n }\n}\n\n/**\n * Updates multiple CSS style properties. Supports units (e.g., [source, 'px']).\n */\nexport function bindCss(ctx: BindingContext, cssMap: Record<string, CssValue>): void {\n const el = ctx.el;\n const style = el.style as unknown as Record<string, string>;\n for (const prop in cssMap) {\n if (hasOwn.call(cssMap, prop)) {\n const val = cssMap[prop]!;\n const camel = getCamelCase(prop);\n // Destructure the tuple form explicitly so TypeScript can narrow each branch.\n const [source, unit] = Array.isArray(val) ? val : ([val, ''] as const);\n\n registerReactiveEffect(\n el,\n source,\n (v) => {\n const strVal = unit ? String(v) + unit : String(v);\n if (!isDangerousCssValue(strVal)) {\n style[camel] = strVal;\n }\n },\n `css.${prop}`\n );\n }\n }\n}\n\n/**\n * Binds DOM attributes with security guards and primitive value constraints.\n */\nexport function bindAttr(\n ctx: BindingContext,\n attrMap: Record<string, ReactiveValue<PrimitiveValue>>\n): void {\n const el = ctx.el;\n for (const name in attrMap) {\n if (hasOwn.call(attrMap, name)) {\n const lowerName = name.toLowerCase();\n // Block event handler attributes (on*) to prevent inline JS injection.\n if (lowerName.startsWith('on')) {\n console.warn(\n `${LOG_PREFIXES.BINDING} ${ERROR_MESSAGES.SECURITY.BLOCKED_EVENT_HANDLER(name)}`\n );\n continue;\n }\n\n const isAria = lowerName.startsWith('aria-');\n\n registerReactiveEffect(\n el,\n attrMap[name]!,\n (v) => {\n if (v == null) {\n el.removeAttribute(name);\n return;\n }\n // FIX 3: Preserve boolean 'false' for ARIA attributes instead of removing them.\n if (v === false && !isAria) {\n el.removeAttribute(name);\n return;\n }\n const newVal = v === true ? (isAria ? 'true' : name) : String(v);\n if (isDangerousUrl(name, newVal)) {\n console.warn(\n `${LOG_PREFIXES.BINDING} ${ERROR_MESSAGES.SECURITY.BLOCKED_PROTOCOL(name)}`\n );\n return;\n }\n // Attribute write guard\n if (el.getAttribute(name) !== newVal) {\n el.setAttribute(name, newVal);\n }\n },\n `attr.${name}`\n );\n }\n }\n}\n\n/**\n * Binds DOM properties. Uses strict property write guards and security filters.\n */\nexport function bindProp(\n ctx: BindingContext,\n propMap: Record<string, ReactiveValue<unknown>>\n): void {\n const el = ctx.el as unknown as Record<string, unknown>;\n for (const name in propMap) {\n if (hasOwn.call(propMap, name)) {\n const lowerName = name.toLowerCase();\n\n // Block dangerous event handler properties.\n if (lowerName.startsWith('on')) {\n console.warn(\n `${LOG_PREFIXES.BINDING} ${ERROR_MESSAGES.SECURITY.BLOCKED_EVENT_HANDLER(name)}`\n );\n continue;\n }\n\n // Block dangerous DOM properties that can inject raw HTML (e.g., innerHTML)\n if (DANGEROUS_PROPS.has(name)) {\n console.warn(`${LOG_PREFIXES.BINDING} ${ERROR_MESSAGES.SECURITY.BLOCKED_PROP(name)}`);\n continue;\n }\n\n const isUrlProp = URL_PROPS.has(lowerName);\n\n registerReactiveEffect(\n ctx.el,\n propMap[name]!,\n (val) => {\n // Block dangerous protocols in property values (src, href, etc.).\n if (isUrlProp && typeof val === 'string' && isDangerousUrl(name, val)) {\n console.warn(\n `${LOG_PREFIXES.BINDING} ${ERROR_MESSAGES.SECURITY.BLOCKED_PROTOCOL(name)}`\n );\n return;\n }\n\n // Redundancy check specifically for DOM properties\n if (el[name] !== val) {\n el[name] = val;\n }\n },\n `prop.${name}`\n );\n }\n }\n}\n\n/**\n * Handles visibility (display: none) toggle.\n */\nexport function bindVisibility(\n ctx: BindingContext,\n condition: ReactiveValue<boolean>,\n invert: boolean\n): void {\n const el = ctx.el;\n const label: BindingDebugType = invert ? 'hide' : 'show';\n const originalDisplay = el.style.display;\n const showDisplay = originalDisplay === 'none' ? '' : originalDisplay;\n\n registerReactiveEffect(\n el,\n condition,\n (val) => {\n el.style.display = invert !== !!val ? showDisplay : 'none';\n },\n label\n );\n}\n\n/**\n * Two-way value binding with full feature parity to $.fn.atomVal.\n * Supports parse/format options, debouncing, IME composition, and focus-aware updates.\n */\nexport function bindVal(\n ctx: BindingContext,\n atom: WritableAtom<unknown>,\n options: ValOptions<unknown> = {}\n): void {\n const tagName = ctx.el.tagName.toLowerCase();\n if (!VALID_INPUT_TAGS.has(tagName)) {\n console.warn(\n `${LOG_PREFIXES.BINDING} ${ERROR_MESSAGES.BINDING.INVALID_INPUT_ELEMENT(tagName)}`\n );\n return;\n }\n const { fx, cleanup } = applyInputBinding(ctx.$el, atom, options);\n\n registry.trackEffect(ctx.el, fx);\n ctx.trackCleanup(cleanup);\n}\n\n/**\n * Two-way binding for checkbox/radio checked state.\n */\nexport function bindChecked(ctx: BindingContext, atom: WritableAtom<boolean>): void {\n const el = ctx.el as HTMLInputElement;\n const $el = ctx.$el;\n const isRadio = el.type === 'radio';\n\n // DOM → Atom (jQuery events for .trigger() compatibility)\n const handler = () => {\n const current = el.checked;\n if (atom.value !== current) {\n atom.value = current;\n // FIX 2: Radio buttons do not fire 'change' when unchecked by selecting another radio.\n // Trigger a custom event on sibling radios so they can sync their newly unchecked state.\n // FIX 2 follow-up: Scope to the containing <form> to avoid cross-form interference.\n // Falls back to document for radios outside any form.\n if (isRadio && current && el.name) {\n const escapedName = el.name.replace(/\"/g, '\\\\\"');\n const $scope = el.form ? $(el.form) : $(document);\n $scope\n .find(`input[type=\"radio\"][name=\"${escapedName}\"]`)\n .not(el)\n .trigger('change.atomRadioSync');\n }\n }\n };\n // Internal handler — skip batch() wrapping in the jQuery patch.\n (handler as unknown as Record<symbol, true>)[INTERNAL_HANDLER] = true;\n\n // DOM → Atom cleanup goes through ctx.trackCleanup (element lifecycle).\n // Atom → DOM cleanup goes through registry.trackEffect (reactive effect lifecycle).\n // The split is intentional: effects are disposed by the registry's effect tracker;\n // plain event listeners have no registry counterpart and need manual teardown.\n $el.on('change change.atomRadioSync', handler);\n ctx.trackCleanup(() => $el.off('change change.atomRadioSync', handler));\n\n // Atom → DOM\n const fx = effect(() => {\n const val = !!atom.value;\n untracked(() => {\n if (el.checked !== val) {\n el.checked = val;\n if (debug.enabled) debug.domUpdated(LOG_PREFIXES.BINDING, $el, 'checked', val);\n }\n });\n });\n registry.trackEffect(el, fx);\n}\n\n// ============================================================================\n// Event Binding Handler\n// ============================================================================\n\nexport function bindEvents(ctx: BindingContext, eventMap: NonNullable<BindingOptions['on']>): void {\n const $el = ctx.$el;\n $el.on(eventMap);\n ctx.trackCleanup(() => $el.off(eventMap));\n}\n\n/**\n * Binds a single event handler using jQuery's event system for compatibility.\n * Optimized to avoid creating jQuery wrapper objects repeatedly during setup/teardown.\n */\nexport function bindOn(\n ctx: BindingContext,\n event: string,\n handler: (e: JQuery.Event) => void\n): void {\n const $el = ctx.$el;\n $el.on(event, handler);\n ctx.trackCleanup(() => $el.off(event, handler));\n}\n\n/**\n * Disposes all reactive bindings on an element and its descendants.\n * Centralised here so `chainable.ts` does not need to import `registry` directly.\n */\nexport function bindUnbind(el: HTMLElement): void {\n registry.cleanupTree(el);\n}\n","import $ from 'jquery';\nimport { ERROR_MESSAGES, LOG_PREFIXES } from './constants';\nimport { debug } from './debug';\nimport type {\n BindingOptions,\n CssBindings,\n PrimitiveValue,\n ReactiveValue,\n ValOptions,\n WritableAtom,\n} from './types';\nimport {\n bindAttr,\n bindChecked,\n bindClass,\n bindCss,\n bindEvents,\n bindHtml,\n bindOn,\n bindProp,\n bindText,\n bindUnbind,\n bindVal,\n bindVisibility,\n createContext,\n} from './unified';\n\n/**\n * Logs a debug-mode warning when a non-Element node is encountered\n * in a jQuery set during a binding call. Completely inert in production.\n */\nfunction warnNonElement(nodeType: number): void {\n if (debug.enabled) {\n debug.log(LOG_PREFIXES.BINDING, `Skipping non-Element node (nodeType=${nodeType})`);\n }\n}\n\n/**\n * Binds element `textContent` to a reactive source.\n *\n * @param source - Reactive or static value to display.\n * @param formatter - Optional function to convert the value to a string.\n * Defaults to `String(val ?? '')`.\n */\n$.fn.atomText = function <T>(source: ReactiveValue<T>, formatter?: (v: T) => string): JQuery {\n for (let i = 0, len = this.length; i < len; i++) {\n const el = this[i]!;\n if (el.nodeType === 1) bindText(createContext(el as HTMLElement), source, formatter);\n else warnNonElement(el.nodeType);\n }\n return this;\n};\n\n/**\n * Binds element `innerHTML` to a reactive string source.\n * The value is automatically sanitized before insertion to prevent XSS.\n */\n$.fn.atomHtml = function (source: ReactiveValue<string>): JQuery {\n for (let i = 0, len = this.length; i < len; i++) {\n const el = this[i]!;\n if (el.nodeType === 1) bindHtml(createContext(el as HTMLElement), source);\n else warnNonElement(el.nodeType);\n }\n return this;\n};\n\n/**\n * Toggles one or more CSS classes based on reactive boolean conditions.\n *\n * @overload Single class: `atomClass(className, condition)`\n * @overload Multiple classes: `atomClass({ active: isActive, disabled: isDisabled })`\n */\n$.fn.atomClass = function (\n classNameOrMap: string | Record<string, ReactiveValue<boolean>>,\n condition?: ReactiveValue<boolean>\n): JQuery {\n // Validate arguments once before iterating — avoids repeated warnings per element.\n if (typeof classNameOrMap === 'string' && condition === undefined) {\n console.warn(\n `${LOG_PREFIXES.BINDING} ${ERROR_MESSAGES.BINDING.MISSING_CONDITION('atomClass')}`\n );\n return this;\n }\n // Hoist: build the map once, not once-per-element inside each().\n const classMap =\n typeof classNameOrMap === 'string' ? { [classNameOrMap]: condition! } : classNameOrMap;\n for (let i = 0, len = this.length; i < len; i++) {\n const el = this[i]!;\n if (el.nodeType === 1) bindClass(createContext(el as HTMLElement), classMap);\n else warnNonElement(el.nodeType);\n }\n return this;\n};\n\n/**\n * Binds one or more CSS style properties to reactive values.\n *\n * @overload Single property: `atomCss(prop, source, unit?)`\n * @overload Multiple properties: `atomCss({ color: colorAtom, opacity: [opacityAtom, 'px'] })`\n */\n$.fn.atomCss = function (\n propOrMap: string | CssBindings,\n source?: ReactiveValue<string | number>,\n unit?: string\n): JQuery {\n // Validate arguments once before iterating — avoids repeated warnings per element.\n if (typeof propOrMap === 'string' && source === undefined) {\n console.warn(`${LOG_PREFIXES.BINDING} ${ERROR_MESSAGES.BINDING.MISSING_SOURCE('atomCss')}`);\n return this;\n }\n // Hoist: build the map once, not once-per-element inside each().\n const cssMap: CssBindings =\n typeof propOrMap === 'string'\n ? { [propOrMap]: unit ? [source as ReactiveValue<number>, unit] : source! }\n : propOrMap;\n for (let i = 0, len = this.length; i < len; i++) {\n const el = this[i]!;\n if (el.nodeType === 1) bindCss(createContext(el as HTMLElement), cssMap);\n else warnNonElement(el.nodeType);\n }\n return this;\n};\n\n/**\n * Binds one or more HTML attributes to reactive values with security guards.\n * Event handler attributes (`on*`) are blocked. Dangerous URL protocols are blocked.\n *\n * @overload Single attribute: `atomAttr(name, source)`\n * @overload Multiple attributes: `atomAttr({ href: urlAtom, title: titleAtom })`\n */\n$.fn.atomAttr = function (\n nameOrMap: string | Record<string, ReactiveValue<PrimitiveValue>>,\n source?: ReactiveValue<PrimitiveValue>\n): JQuery {\n // Validate arguments once before iterating — avoids repeated warnings per element.\n if (typeof nameOrMap === 'string' && source === undefined) {\n console.warn(`${LOG_PREFIXES.BINDING} ${ERROR_MESSAGES.BINDING.MISSING_SOURCE('atomAttr')}`);\n return this;\n }\n // Hoist: build the map once, not once-per-element inside each().\n const attrMap: Record<string, ReactiveValue<PrimitiveValue>> = typeof nameOrMap === 'string'\n ? { [nameOrMap]: source! }\n : nameOrMap;\n for (let i = 0, len = this.length; i < len; i++) {\n const el = this[i]!;\n if (el.nodeType === 1) bindAttr(createContext(el as HTMLElement), attrMap);\n else warnNonElement(el.nodeType);\n }\n return this;\n};\n\n/**\n * Binds one or more DOM properties to reactive values.\n * Dangerous properties (`innerHTML`, `outerHTML`, etc.) are blocked.\n *\n * @overload Single property: `atomProp(name, source)`\n * @overload Multiple properties: `atomProp({ disabled: isDisabled, value: valAtom })`\n */\n$.fn.atomProp = function <T>(\n nameOrMap: string | Record<string, ReactiveValue<T>>,\n source?: ReactiveValue<T>\n): JQuery {\n // Validate arguments once before iterating — avoids repeated warnings per element.\n if (typeof nameOrMap === 'string' && source === undefined) {\n console.warn(`${LOG_PREFIXES.BINDING} ${ERROR_MESSAGES.BINDING.MISSING_SOURCE('atomProp')}`);\n return this;\n }\n // Hoist: build the map once, not once-per-element inside each().\n const propMap: Record<string, ReactiveValue<unknown>> = typeof nameOrMap === 'string'\n ? { [nameOrMap]: source as ReactiveValue<unknown> }\n : (nameOrMap as Record<string, ReactiveValue<unknown>>);\n for (let i = 0, len = this.length; i < len; i++) {\n const el = this[i]!;\n if (el.nodeType === 1) bindProp(createContext(el as HTMLElement), propMap);\n else warnNonElement(el.nodeType);\n }\n return this;\n};\n\n/**\n * Shows the element when `condition` is truthy (`display: ''`).\n */\n$.fn.atomShow = function (condition: ReactiveValue<boolean>): JQuery {\n for (let i = 0, len = this.length; i < len; i++) {\n const el = this[i]!;\n if (el.nodeType === 1) bindVisibility(createContext(el as HTMLElement), condition, false);\n else warnNonElement(el.nodeType);\n }\n return this;\n};\n\n/**\n * Hides the element when `condition` is truthy (`display: 'none'`).\n * Inverse of `atomShow`.\n */\n$.fn.atomHide = function (condition: ReactiveValue<boolean>): JQuery {\n for (let i = 0, len = this.length; i < len; i++) {\n const el = this[i]!;\n if (el.nodeType === 1) bindVisibility(createContext(el as HTMLElement), condition, true);\n else warnNonElement(el.nodeType);\n }\n return this;\n};\n\n/**\n * Two-way binding for `<input>`, `<select>`, and `<textarea>` values.\n * Supports debouncing, IME composition, parse/format, and focus-aware updates.\n *\n * @param atom - Writable atom to sync with the input.\n * @param options - Optional configuration (debounce, event, parse, format, equal).\n * An empty object and an omitted options argument are equivalent — both use defaults.\n */\n$.fn.atomVal = function <T>(atom: WritableAtom<T>, options: ValOptions<T> = {}): JQuery {\n for (let i = 0, len = this.length; i < len; i++) {\n const el = this[i]!;\n if (el.nodeType === 1)\n bindVal(\n createContext(el as HTMLElement),\n atom as WritableAtom<unknown>,\n options as ValOptions<unknown>\n );\n else warnNonElement(el.nodeType);\n }\n return this;\n};\n\n/**\n * Two-way binding for checkbox and radio button `checked` state.\n * Uses the jQuery event system (not native `addEventListener`) for `.trigger()` compatibility.\n */\n$.fn.atomChecked = function (atom: WritableAtom<boolean>): JQuery {\n for (let i = 0, len = this.length; i < len; i++) {\n const el = this[i]!;\n if (el.nodeType === 1) bindChecked(createContext(el as HTMLElement), atom);\n else warnNonElement(el.nodeType);\n }\n return this;\n};\n\n/**\n * Attaches a lifecycle-aware event handler using the jQuery event system.\n * The handler is automatically removed when the element is unbound via `atomUnbind`.\n *\n * @param event - jQuery event name (e.g. `'click'`, `'input'`, `'change.myns'`).\n * @param handler - Callback receiving the jQuery event object.\n */\n$.fn.atomOn = function (event: string, handler: (e: JQuery.Event) => void): JQuery {\n for (let i = 0, len = this.length; i < len; i++) {\n const el = this[i]!;\n if (el.nodeType === 1) bindOn(createContext(el as HTMLElement), event, handler);\n else warnNonElement(el.nodeType);\n }\n return this;\n};\n\n/**\n * Integrated multi-behavior reactive binding.\n * Delegates to the focused bind helpers — each option maps 1:1 to a handler.\n *\n * All conditional checks use `!== undefined` consistently so that meaningful\n * falsy values (`show: false`, `hide: false`, `class: {}`) are handled correctly.\n */\n$.fn.atomBind = function <T = unknown>(options: BindingOptions<T>): JQuery {\n const { text, html, class: cls, css, attr, prop, show, hide, val, checked, on } = options;\n\n // Parse val once before the element loop. Result is kept as a typed pair so\n // the call site (bindVal) can receive atom and opts without a non-null assertion.\n const valParsed: { atom: WritableAtom<unknown>; opts: ValOptions<unknown> | undefined } | null =\n val === undefined\n ? null\n : Array.isArray(val)\n ? {\n atom: val[0] as WritableAtom<unknown>,\n opts: val[1] as unknown as ValOptions<unknown>,\n }\n : { atom: val as WritableAtom<unknown>, opts: undefined };\n\n for (let i = 0, len = this.length; i < len; i++) {\n const el = this[i]!;\n if (el.nodeType !== 1) {\n warnNonElement(el.nodeType);\n continue;\n }\n const ctx = createContext(el as HTMLElement);\n\n if (text !== undefined) bindText(ctx, text);\n if (html !== undefined) bindHtml(ctx, html);\n if (cls !== undefined) bindClass(ctx, cls);\n if (css !== undefined) bindCss(ctx, css);\n if (attr !== undefined) bindAttr(ctx, attr);\n if (prop !== undefined) bindProp(ctx, prop);\n if (show !== undefined) bindVisibility(ctx, show, false);\n if (hide !== undefined) bindVisibility(ctx, hide, true);\n if (valParsed !== null) bindVal(ctx, valParsed.atom, valParsed.opts);\n if (checked !== undefined) bindChecked(ctx, checked);\n if (on !== undefined) bindEvents(ctx, on);\n }\n return this;\n};\n\n/**\n * Destroys all reactive bindings on the selected elements **and their descendants**.\n * This calls `registry.cleanupTree` on each element, which disposes effects,\n * cleanup callbacks, and component lifecycle functions recursively.\n *\n * Difference from `atomUnmount`: `atomUnmount` is scoped to components mounted via\n * `atomMount`. `atomUnbind` removes all bindings regardless of how they were created.\n */\n$.fn.atomUnbind = function (): JQuery {\n for (let i = 0, len = this.length; i < len; i++) {\n const el = this[i]!;\n if (el.nodeType === 1) bindUnbind(el as HTMLElement);\n else warnNonElement(el.nodeType);\n }\n return this;\n};\n","import { effect, untracked } from '@but212/atom-effect';\nimport $ from 'jquery';\nimport { ERROR_MESSAGES, LOG_PREFIXES } from './constants';\nimport { debug } from './debug';\nimport { registry } from './registry';\nimport { sanitizeHtml } from './sanitize';\nimport type {\n EffectObject,\n ListItemEntry,\n ListItemState,\n ListKey,\n ListKeyFn,\n ListOptions,\n ReadonlyAtom,\n} from './types';\nimport { getLIS, getSelector, hasOwn, shallowEqual } from './utils';\n\n// ============================================================================\n// Helpers\n// ============================================================================\n\nconst listInstances = new WeakMap<Element, { fx: EffectObject; ctx: ListContext<unknown> }>();\nlet listBatchIdCounter = 0;\n\n/**\n * Inserts `$el` before `nextNode` when `nextNode` is non-null and connected,\n * otherwise appends it to `$container`.\n */\nfunction insertOrAppend($el: JQuery, nextNode: Node | null, $container: JQuery): void {\n if (nextNode?.isConnected) $el.insertBefore(nextNode);\n else $el.appendTo($container);\n}\n\n/**\n * Applies bind or update callback to an existing entry's element.\n * - `state === undefined` → item existed before; call `update` if provided.\n * - `state !== undefined` → item was just rendered; call `bind` if provided.\n */\nfunction applyItemCallbacks<T>(\n state: ListItemState | undefined,\n entry: ListItemEntry<T>,\n item: T,\n index: number,\n bind: ListOptions<T>['bind'],\n update: ListOptions<T>['update']\n): void {\n if (!entry.$el[0]) return;\n if (state === undefined) {\n if (update) update(entry.$el, item, index);\n } else if (bind) {\n bind(entry.$el, item, index);\n }\n}\n\n// ============================================================================\n// ListContext\n// ============================================================================\n\n/**\n * Per-container mutable state + removal logic for a single atomList instance.\n * Replaces the flat closure variables from Phase 1.\n * @internal\n */\nclass ListContext<T> {\n readonly itemMap = new Map<ListKey, ListItemEntry<T>>();\n readonly removingKeys = new Set<ListKey>();\n oldKeys: ListKey[] = [];\n $emptyEl: JQuery | null = null;\n readonly elToKey = new WeakMap<Element, ListKey>();\n readonly keyToIndex = new Map<ListKey, number>();\n /** Assigned immediately after effect() returns. Used only inside commitRemoval callbacks. */\n fx?: EffectObject;\n\n constructor(\n public readonly $container: JQuery,\n /** @internal */\n public readonly containerSelector: string,\n private readonly onRemove: (($el: JQuery) => Promise<void> | void) | undefined\n ) {}\n\n scheduleRemoval(k: ListKey, entry: ListItemEntry<T>): void {\n const commitRemoval = () => {\n if (this.fx?.isDisposed) return;\n entry.$el.remove();\n this.removingKeys.delete(k);\n debug.log(LOG_PREFIXES.LIST, `${this.containerSelector} removed item:`, k);\n };\n if (!this.onRemove) {\n commitRemoval();\n return;\n }\n const result = this.onRemove(entry.$el);\n if (result instanceof Promise) {\n result.then(commitRemoval, commitRemoval);\n } else {\n commitRemoval();\n }\n }\n\n removeItem(k: ListKey, entry: ListItemEntry<T>): void {\n for (let j = 0; j < entry.$el.length; j++) {\n const el = entry.$el[j];\n if (el) this.elToKey.delete(el);\n }\n this.itemMap.delete(k);\n this.removingKeys.add(k);\n this.scheduleRemoval(k, entry);\n }\n\n dispose(): void {\n this.itemMap.clear();\n this.removingKeys.clear();\n this.oldKeys.length = 0;\n this.keyToIndex.clear();\n this.$emptyEl?.remove();\n this.$container.off('.atomList');\n }\n}\n\n// ============================================================================\n// Internal diff types\n// ============================================================================\n\n/** Return value of buildIndices() */\ninterface PreparedDiff<T> {\n newKeys: ListKey[];\n newKeySet: Set<ListKey>;\n newIndices: Int32Array;\n trKeys: ListKey[];\n trItems: T[];\n trIdxs: number[];\n}\n\n/** Callback subset of ListOptions passed to placeItems. */\ninterface PlaceCallbacks<T> {\n bind: ListOptions<T>['bind'];\n update: ListOptions<T>['update'];\n onAdd: ListOptions<T>['onAdd'];\n onRemove: ListOptions<T>['onRemove'];\n events: ListOptions<T>['events'];\n}\n\n// ============================================================================\n// Step functions\n// ============================================================================\n\n/**\n * Step 1: Handle empty list state.\n * Shows/hides the empty template and removes all current items.\n * Caller should `return` immediately after if `itemCount === 0`.\n */\nfunction handleEmpty<T>(\n ctx: ListContext<T>,\n itemCount: number,\n $container: JQuery,\n empty: ListOptions<T>['empty']\n): void {\n if (ctx.$emptyEl && itemCount > 0) {\n ctx.$emptyEl.remove();\n ctx.$emptyEl = null;\n }\n\n if (itemCount !== 0) return;\n\n if (empty && !ctx.$emptyEl) {\n const safeEmpty = typeof empty === 'string' ? sanitizeHtml(empty) : empty;\n ctx.$emptyEl = ($(safeEmpty as string) as JQuery).appendTo($container);\n }\n\n const { oldKeys, itemMap } = ctx;\n for (let i = 0, len = oldKeys.length; i < len; i++) {\n const k = oldKeys[i]!;\n const entry = itemMap.get(k);\n if (entry) ctx.removeItem(k, entry);\n }\n oldKeys.length = 0;\n}\n\n/**\n * Step 2: Build key/index structures for diff computation.\n */\nfunction buildIndices<T>(\n ctx: ListContext<T>,\n items: T[],\n itemCount: number,\n getKey: ListKeyFn<T>,\n update: ListOptions<T>['update']\n): PreparedDiff<T> {\n const { oldKeys, itemMap, removingKeys } = ctx;\n const oldIndexMap = new Map<ListKey, number>();\n for (let i = 0, len = oldKeys.length; i < len; i++) {\n oldIndexMap.set(oldKeys[i]!, i);\n }\n\n const newKeys: ListKey[] = new Array(itemCount);\n const newKeySet = new Set<ListKey>();\n const newIndices = new Int32Array(itemCount);\n // Parallel arrays replace an array-of-objects to reduce GC pressure and\n // improve cache locality when iterating targetsToRender (step 3).\n const trKeys: ListKey[] = [];\n const trItems: T[] = [];\n const trIdxs: number[] = [];\n\n for (let i = 0; i < itemCount; i++) {\n const item = items[i]!;\n const k = getKey(item, i);\n newKeys[i] = k;\n\n if (newKeySet.has(k)) {\n debug.warn(LOG_PREFIXES.LIST, ERROR_MESSAGES.LIST.DUPLICATE_KEY(k, i, ctx.containerSelector));\n newIndices[i] = -1;\n continue;\n }\n newKeySet.add(k);\n\n const entry = itemMap.get(k);\n if (!entry) {\n trKeys.push(k);\n trItems.push(item);\n trIdxs.push(i);\n newIndices[i] = -1;\n continue;\n }\n\n const oldItem = entry.item;\n if (!update && oldItem !== item && !shallowEqual(oldItem, item)) {\n trKeys.push(k);\n trItems.push(item);\n trIdxs.push(i);\n }\n newIndices[i] = removingKeys.has(k) ? -1 : (oldIndexMap.get(k) ?? -1);\n }\n\n return { newKeys, newKeySet, newIndices, trKeys, trItems, trIdxs };\n}\n\n/**\n * Step 3: Render new/updated items safely converting strings to DOM via batch sanitization.\n * Creates $el nodes and updates ctx.itemMap for each target.\n * Returns innerHTML fragments if the fast path can be used, otherwise null.\n */\nfunction renderItems<T>(\n ctx: ListContext<T>,\n diff: PreparedDiff<T>,\n options: ListOptions<T>,\n isInitial: boolean\n): string[] | null {\n const { trKeys, trItems, trIdxs } = diff;\n const renderCount = trKeys.length;\n const itemMap = ctx.itemMap;\n const render = options.render;\n\n const renderResults: Array<string | Element | DocumentFragment | JQuery> = new Array(renderCount);\n const htmlParts: string[] = [];\n let stringRenderCount = 0;\n\n for (let t = 0; t < renderCount; t++) {\n const raw = render(trItems[t]!, trIdxs[t]!);\n renderResults[t] = raw;\n if (typeof raw === 'string') {\n htmlParts.push(raw);\n stringRenderCount++;\n }\n }\n\n let sanitizedFragments: string[] | null = null;\n const htmlPartCount = htmlParts.length;\n if (htmlPartCount === 1) {\n sanitizedFragments = [sanitizeHtml(htmlParts[0]!)];\n } else if (htmlPartCount > 1) {\n const batchId = (listBatchIdCounter++).toString(36);\n const batchSeparator = `<template data-atom-sep=\"${batchId}\"></template>`;\n sanitizedFragments = sanitizeHtml(htmlParts.join(batchSeparator)).split(batchSeparator);\n }\n\n const useInnerHtml =\n isInitial &&\n sanitizedFragments !== null &&\n stringRenderCount === renderCount &&\n !options.bind &&\n !options.onAdd &&\n !options.onRemove &&\n !options.events;\n\n if (useInnerHtml) {\n return sanitizedFragments;\n }\n\n let fragIdx = 0;\n for (let t = 0; t < renderCount; t++) {\n const raw = renderResults[t]!;\n const $el =\n typeof raw === 'string' ? $(sanitizedFragments![fragIdx++]!) : ($(raw as never) as JQuery);\n\n const k = trKeys[t]!;\n const entry = itemMap.get(k);\n\n if (!entry) {\n itemMap.set(k, { $el, item: null as unknown as T, state: 'new' });\n continue;\n }\n\n const oldEl = entry.$el[0];\n if (oldEl) registry.cleanupTree(oldEl);\n entry.$el.replaceWith($el);\n entry.$el = $el;\n entry.state = 'replaced';\n }\n\n return null;\n}\n\n/**\n * Step 4: Remove keys no longer present in the new list.\n */\nfunction cleanupRemoved<T>(ctx: ListContext<T>, newKeySet: Set<ListKey>): void {\n // Array iteration is faster than itemMap entries iteration,\n // and safely skips keys already in removingKeys since oldKeys\n // never overlaps with them.\n const { oldKeys, itemMap } = ctx;\n for (let i = 0, len = oldKeys.length; i < len; i++) {\n const k = oldKeys[i]!;\n if (newKeySet.has(k)) continue;\n\n const entry = itemMap.get(k);\n if (entry) ctx.removeItem(k, entry);\n }\n}\n\n/**\n * Step 5: Place and reorder DOM elements via LIS-based reconciliation.\n * `isInitial` is derived from `ctx.oldKeys.length === 0` inside the function.\n */\nfunction placeItems<T>(\n ctx: ListContext<T>,\n items: T[],\n diff: PreparedDiff<T>,\n rawContainer: Element,\n $container: JQuery,\n callbacks: PlaceCallbacks<T>,\n innerHtmlFragments: string[] | null\n): void {\n const { bind, update, onAdd } = callbacks;\n const { newKeys, newIndices } = diff;\n const itemCount = items.length;\n const isInitial = ctx.oldKeys.length === 0;\n\n const lisArr = getLIS(newIndices);\n let lisIdx = lisArr.length - 1;\n\n const { itemMap, removingKeys } = ctx;\n\n if (innerHtmlFragments !== null) {\n // ── Initial render: innerHTML fast path ──────────────\n rawContainer.innerHTML = innerHtmlFragments.join('');\n\n let childIdx = 0;\n for (let i = 0; i < itemCount; i++) {\n const k = newKeys[i]!;\n const item = items[i]!;\n\n // Note: If an item renders multiple sibling roots, childIdx++ only captures the first one.\n // This is a known limitation of the innerHTML fast-path from previous versions.\n const el = rawContainer.children[childIdx++] as HTMLElement | undefined;\n if (el) {\n const $el = $(el);\n itemMap.set(k, { $el, item, state: undefined });\n removingKeys.delete(k);\n if (debug.enabled) debug.domUpdated(LOG_PREFIXES.LIST, $el, 'list.add', item);\n }\n }\n return;\n }\n\n if (isInitial) {\n // ── Initial render: accumulate into DocumentFragment ──────────────\n const fragment = document.createDocumentFragment();\n for (let i = itemCount - 1; i >= 0; i--) {\n const k = newKeys[i]!;\n const entry = itemMap.get(k);\n if (!entry) continue;\n\n const $el = entry.$el;\n for (let j = $el.length - 1; j >= 0; j--) {\n fragment.insertBefore($el[j]!, fragment.firstChild);\n }\n }\n rawContainer.appendChild(fragment);\n } else {\n // ── Incremental update: LIS-based reconciliation ──────────────────\n let nextNode: Node | null = null;\n for (let i = itemCount - 1; i >= 0; i--) {\n const k = newKeys[i]!;\n const entry = itemMap.get(k);\n if (!entry) continue;\n\n if (lisIdx >= 0 && lisArr[lisIdx] === i) {\n lisIdx--;\n } else {\n insertOrAppend(entry.$el, nextNode, $container);\n }\n\n nextNode = entry.$el[0] ?? null;\n }\n }\n\n // ── Post-DOM insertion: apply callbacks ───────────────────────────\n for (let i = 0; i < itemCount; i++) {\n const k = newKeys[i]!;\n const item = items[i]!;\n const entry = itemMap.get(k);\n if (!entry) continue;\n\n const state = entry.state;\n entry.item = item;\n entry.state = undefined;\n\n applyItemCallbacks(state, entry, item, i, bind, update);\n\n if (state === 'new') {\n if (onAdd) onAdd(entry.$el);\n removingKeys.delete(k);\n if (debug.enabled) debug.domUpdated(LOG_PREFIXES.LIST, entry.$el, 'list.add', item);\n }\n }\n}\n\n/**\n * Step 5 (tail): Sync reverse/forward indexes for delegated event lookup.\n * Caller must check `if (events)` before calling.\n */\nfunction syncEventIndices<T>(ctx: ListContext<T>, diff: PreparedDiff<T>): void {\n const { newKeys, newKeySet } = diff;\n const itemCount = newKeys.length;\n const { oldKeys, itemMap, elToKey, keyToIndex } = ctx;\n\n // Remove stale entries for keys no longer in the list.\n for (let i = 0, len = oldKeys.length; i < len; i++) {\n const k = oldKeys[i]!;\n if (!newKeySet.has(k)) {\n keyToIndex.delete(k);\n }\n }\n // Register/update entries for keys in the new list.\n for (let i = 0; i < itemCount; i++) {\n const k = newKeys[i]!;\n const entry = itemMap.get(k);\n if (entry) {\n for (let j = 0; j < entry.$el.length; j++) {\n const rootEl = entry.$el[j];\n if (rootEl) elToKey.set(rootEl, k);\n }\n keyToIndex.set(k, i);\n }\n }\n}\n\n// ============================================================================\n// atomList\n// ============================================================================\n\n/**\n * Reactive list rendering with LIS-based DOM reconciliation.\n *\n * Note: when `key` is a property name string, the resolved property value is\n * used as the Map key. The property must produce a `string | number` at\n * runtime — boolean or object values will be coerced by the Map and may cause\n * unexpected key collisions.\n */\n$.fn.atomList = function <T>(source: ReadonlyAtom<T[]>, options: ListOptions<T>): JQuery {\n const { key, bind, update, onAdd, onRemove, empty, events } = options;\n\n const getKey: ListKeyFn<T> =\n typeof key === 'function'\n ? key\n : (item: T, _index: number) => item[key as keyof T] as unknown as ListKey;\n\n const callbacks: PlaceCallbacks<T> = { bind, update, onAdd, onRemove, events };\n\n for (\n let containerIdx = 0, containerLen = this.length;\n containerIdx < containerLen;\n containerIdx++\n ) {\n const rawContainer = this[containerIdx]!;\n const $container = $(rawContainer);\n\n // Unbind previous list delegation to prevent memory leaks when re-initializing\n $container.off('.atomList');\n // Clean up any previous atomList instance on this container\n const oldInstance = listInstances.get(rawContainer);\n if (oldInstance) {\n oldInstance.fx.dispose();\n oldInstance.ctx.dispose();\n }\n\n const containerSelector = getSelector(rawContainer);\n\n const ctx = new ListContext<T>($container, containerSelector, onRemove);\n\n const fx = effect(() => {\n // Only source.value is tracked. All side effects (DOM reads/writes,\n // render calls, bind calls) ran inside untracked() so they cannot\n // accidentally subscribe the list effect to atom reads within user callbacks.\n const items = source.value;\n const itemCount = items.length;\n\n untracked(() => {\n handleEmpty(ctx, itemCount, $container, empty);\n if (itemCount === 0) return;\n\n debug.log(LOG_PREFIXES.LIST, `${containerSelector} updating with ${itemCount} items`);\n\n const diff = buildIndices(ctx, items, itemCount, getKey, update);\n const isInitial = ctx.oldKeys.length === 0;\n\n const innerHtmlFragments = renderItems(ctx, diff, options, isInitial);\n cleanupRemoved(ctx, diff.newKeySet);\n placeItems(ctx, items, diff, rawContainer, $container, callbacks, innerHtmlFragments);\n\n if (events) syncEventIndices(ctx, diff);\n\n ctx.oldKeys = diff.newKeys;\n });\n });\n\n ctx.fx = fx;\n\n // ── Delegated event listeners ─────────────────────────────────────────\n // We leverage jQuery's native event delegation to properly handle bubbling\n // and correct semantics for mouseenter/mouseleave.\n if (events) {\n for (const eventKey in events) {\n if (!hasOwn.call(events, eventKey)) continue;\n const handler = events[eventKey]!;\n\n // Split \"click .selector\" → eventType=\"click\", childSelector=\".selector\"\n const spaceIdx = eventKey.indexOf(' ');\n const eventType = spaceIdx === -1 ? eventKey : eventKey.slice(0, spaceIdx);\n const childSelector = spaceIdx === -1 ? null : eventKey.slice(spaceIdx + 1).trim();\n\n // If no child selector is provided, default to immediate children of container.\n // This ensures non-bubbling events like mouseenter work properly on item boundaries.\n const actualSelector = childSelector ? childSelector : '> *';\n\n const delegateHandler = function (this: Element, e: JQuery.TriggeredEvent) {\n // `this` is the matched delegated element.\n // Walk up to find the element that is actually an item root.\n let node: HTMLElement | null = this as HTMLElement | null;\n while (node && node !== rawContainer) {\n const k = ctx.elToKey.get(node);\n if (k !== undefined) {\n const entry = ctx.itemMap.get(k);\n if (entry) {\n handler.call(this as HTMLElement, entry.item, ctx.keyToIndex.get(k) ?? -1, e);\n }\n return;\n }\n node = node.parentElement;\n }\n };\n\n // Attach with namespace so cleanup can easily unbind all atomList events.\n $container.on(`${eventType}.atomList`, actualSelector, delegateHandler);\n }\n }\n\n registry.trackEffect(rawContainer, fx);\n listInstances.set(rawContainer, { fx, ctx });\n registry.trackCleanup(rawContainer, () => {\n ctx.dispose();\n listInstances.delete(rawContainer);\n });\n }\n\n return this;\n};\n","import { untracked } from '@but212/atom-effect';\nimport $ from 'jquery';\nimport { ERROR_MESSAGES, LOG_PREFIXES } from './constants';\nimport { debug } from './debug';\nimport { registry } from './registry';\nimport type { ComponentFn } from './types';\nimport { bindUnbind } from './unified';\n\n// ============================================================================\n// Internal helpers\n// ============================================================================\n\nconst EMPTY_PROPS = Object.freeze({});\n\n// ============================================================================\n// jQuery plugin methods\n// ============================================================================\n\n/**\n * Mounts a functional component on each selected element.\n *\n * @param component - Function receiving `($el, props)` and returning an\n * optional cleanup callback. See {@link ComponentFn}.\n * @param props - Props passed to the component. When omitted, `P` must be\n * compatible with an empty object (i.e. all fields optional or\n * `P = object`). Passing no props to a component with required fields is\n * a type error that TypeScript will catch at the call site, but only when\n * `props` is explicitly typed — the `{} as P` fallback is not type-safe\n * for components with required fields, which is why the cast is explicit\n * rather than implicit.\n */\n$.fn.atomMount = function <P>(component: ComponentFn<P>, props?: P): JQuery {\n // `props ?? EMPTY_PROPS` is cast to P: when props is omitted, P is\n // constrained by the caller to be compatible with `{}` (all fields optional).\n // The cast is necessary because TypeScript cannot infer the exact type of P\n // from the `props` argument alone, especially for components with required fields.\n const p = (props ?? EMPTY_PROPS) as P;\n\n for (let i = 0, len = this.length; i < len; i++) {\n const rootEl = this[i];\n if (!rootEl) continue;\n\n // Dispose any existing component and its reactive bindings on this element\n // *before* mounting the new one. This ensures a clean slate and uses the\n // same `cleanupTree` path as `atomUnmount` for consistency.\n registry.cleanupTree(rootEl);\n\n const $el = $(rootEl);\n let teardown: ReturnType<typeof component>;\n try {\n // untracked: component setup code must not register dependencies on any\n // outer reactive context (e.g. if atomMount is called inside an effect).\n teardown = untracked(() => component($el, p));\n } catch (err) {\n debug.error(LOG_PREFIXES.MOUNT, ERROR_MESSAGES.MOUNT.ERROR(component.name), err);\n continue;\n }\n\n if (typeof teardown === 'function') {\n registry.setComponentCleanup(rootEl, teardown);\n }\n }\n\n return this;\n};\n\n/**\n * Unmounts the component and disposes all reactive bindings on each selected\n * element and its descendants.\n *\n * Delegates to `bindUnbind`, which calls `registry.cleanupTree` — performing\n * a recursive cleanup of all reactive bindings on the element and its descendants.\n * This is the same full-subtree cleanup path used by `atomMount` when replacing\n * an existing component.\n */\n$.fn.atomUnmount = function (): JQuery {\n for (let i = 0, len = this.length; i < len; i++) {\n const el = this[i];\n if (el) bindUnbind(el);\n }\n return this;\n};\n","import type { ReadonlyAtom } from '@but212/atom-effect';\nimport { computed, atom as createAtom, effect, untracked } from '@but212/atom-effect';\nimport $ from 'jquery';\nimport { ERROR_MESSAGES, LOG_PREFIXES, ROUTE_DEFAULTS } from './constants';\nimport { debug } from './debug';\nimport { registry } from './registry';\nimport type { RouteConfig, RouteDefinition, Router, WritableAtom } from './types';\n\n// --- Helper: Safe History API Wrappers ---\nfunction safePushState(data: unknown, url: string | URL | null): boolean {\n try {\n // Second argument (title) is deprecated in the spec and ignored by all\n // browsers — pass an empty string as required by the signature.\n history.pushState(data, '', url);\n return true;\n } catch (e) {\n debug.warn(\n LOG_PREFIXES.ROUTE,\n 'PushState failed (likely file:// protocol or security restriction). UI will update, but URL will not.',\n e\n );\n return false;\n }\n}\n\nclass RouterImpl implements Router {\n /**\n * Reactive atom containing the current route name.\n * Exposed as ReadonlyAtom so external code cannot mutate route state\n * without going through navigate(), which keeps URL and atom in sync.\n */\n public currentRoute: ReadonlyAtom<string>;\n public queryParams: ReadonlyAtom<Record<string, string>>;\n\n private config: RouteConfig;\n private isDestroyed = false;\n /**\n * Tracks the route name of the last completed transition.\n * Initialized to empty string so beforeTransition/afterTransition always\n * receive a consistent `from` value — never `from === to` on the first render.\n */\n private previousRoute = '';\n /**\n * Mirrors the browser URL after every committed navigation.\n * Used by handleUrlChange to detect real URL changes (vs. our own\n * programmatic updates) and by restoreUrl to roll back blocked transitions.\n */\n private previousUrl: string;\n private cleanups: Array<() => void> = [];\n\n private $target: JQuery;\n private isHistoryMode: boolean;\n private currentRouteAtom: WritableAtom<string>;\n private queryParamsAtom: WritableAtom<Record<string, string>>;\n /** Caches resolved HTMLTemplateElement references to avoid repeated querySelector calls. */\n private templateCache = new Map<string, HTMLTemplateElement>();\n /** Pre-calculated base path with trailing slash stripped for consistent URL building. */\n private normalizedBasePath: string;\n /**\n * Resolved CSS class for active links. Never `undefined` at runtime as it's\n * always filled from `ROUTE_DEFAULTS.activeClass` in the constructor.\n */\n private activeClass: string;\n\n constructor(config: RouteConfig) {\n // Destructure configuration with defaults for internal use\n this.config = {\n ...config,\n mode: config.mode ?? ROUTE_DEFAULTS.mode,\n basePath: config.basePath ?? ROUTE_DEFAULTS.basePath,\n autoBindLinks: config.autoBindLinks ?? ROUTE_DEFAULTS.autoBindLinks,\n activeClass: config.activeClass ?? ROUTE_DEFAULTS.activeClass,\n };\n\n this.isHistoryMode = this.config.mode === 'history';\n this.$target = $(this.config.target);\n // Strip trailing slash so URL construction is always `${base}/${route}`.\n this.normalizedBasePath = this.config.basePath?.replace(/\\/$/, '') || '';\n this.activeClass = this.config.activeClass ?? ROUTE_DEFAULTS.activeClass;\n\n // Initialize previousUrl based on current state before setting up atoms.\n // getCurrentUrl() cannot be called yet (method depends on isHistoryMode which is set above).\n this.previousUrl = this.isHistoryMode\n ? window.location.pathname + window.location.search\n : window.location.hash;\n\n // Initialize state atoms; expose via ReadonlyAtom to prevent external mutation.\n this.currentRouteAtom = createAtom(this.getRouteName());\n this.currentRoute = this.currentRouteAtom;\n this.queryParamsAtom = createAtom(this.getQueryParams());\n // Use computed() to ensure queryParams is truly read-only at runtime,\n // as verified by the 'should be read-only (computed)' test.\n this.queryParams = computed(() => this.queryParamsAtom.value);\n\n // Bind methods that are used as callbacks\n this.handleUrlChange = this.handleUrlChange.bind(this);\n this.destroy = this.destroy.bind(this);\n\n // Initialize\n this.init();\n }\n\n private init() {\n // Set up URL change listener\n const eventName = this.isHistoryMode ? 'popstate' : 'hashchange';\n window.addEventListener(eventName, this.handleUrlChange);\n this.cleanups.push(() => window.removeEventListener(eventName, this.handleUrlChange));\n\n // Set up reactive rendering effect.\n // Only currentRouteAtom.value is the intended reactive dependency.\n // renderRoute calls user lifecycle hooks (beforeTransition, onEnter, render,\n // onMount, afterTransition) that may read atoms — those reads must not\n // subscribe this effect to extra dependencies.\n const renderEffect = effect(() => {\n const routeName = this.currentRouteAtom.value; // sole tracked dependency\n untracked(() => this.renderRoute(routeName)); // user hooks run untracked\n });\n this.cleanups.push(() => renderEffect.dispose());\n\n // Auto-bind navigation links\n this.setupAutoBindLinks();\n\n // Auto-cleanup router if target element is removed\n if (this.$target[0]) {\n registry.trackCleanup(this.$target[0], this.destroy);\n }\n }\n\n // --- Mode-abstracted internal methods ---\n\n /**\n * Extracts route name from current URL.\n * Uses `normalizedBasePath` for consistent stripping in history mode.\n */\n private getRouteName(): string {\n const { default: defaultRoute } = this.config;\n\n if (this.isHistoryMode) {\n let pathname = window.location.pathname;\n // Strip the pre-normalized base path prefix.\n if (this.normalizedBasePath && pathname.startsWith(this.normalizedBasePath)) {\n pathname = pathname.substring(this.normalizedBasePath.length);\n }\n // Remove leading slash (optimized: charCodeAt avoids substring allocation)\n if (pathname.charCodeAt(0) === 47) {\n pathname = pathname.slice(1);\n }\n return pathname || defaultRoute;\n }\n // Hash mode\n const hash = window.location.hash;\n const qIndex = hash.indexOf('?');\n const routeName = qIndex === -1 ? hash.substring(1) : hash.substring(1, qIndex);\n return routeName || defaultRoute;\n }\n\n /**\n * Parses query parameters from the current URL.\n *\n * Note: duplicate keys (e.g. `?a=1&a=2`) are collapsed to the last value\n * only (`{ a: '2' }`). This matches `URLSearchParams` → `Object.fromEntries`\n * behaviour. If multi-value keys are needed, access `queryParams` via\n * `new URLSearchParams(window.location.search).getAll('key')` directly.\n *\n * Malformed percent-encoding (e.g. `%FF%FE`) is handled silently by\n * `URLSearchParams` — it replaces undecodable sequences with the replacement\n * character (U+FFFD) and continues parsing. If malformed encoding is detected,\n * a warning is emitted via `debug.warn`, but the best-effort parsed result\n * is still returned.\n */\n private getQueryParams(): Record<string, string> {\n let raw: string;\n\n if (this.isHistoryMode) {\n raw = window.location.search.substring(1); // Remove leading '?'\n if (!raw) return {};\n } else {\n const hash = window.location.hash;\n const qIndex = hash.indexOf('?');\n if (qIndex === -1) return {};\n raw = hash.substring(qIndex + 1);\n }\n\n const sp = new URLSearchParams(raw);\n const params: Record<string, string> = Object.fromEntries(sp);\n\n // Warn about malformed percent-encoded sequences\n if (raw.includes('%')) {\n try {\n decodeURIComponent(raw);\n } catch (_e) {\n debug.warn(LOG_PREFIXES.ROUTE, ERROR_MESSAGES.ROUTE.MALFORMED_URI(raw));\n }\n }\n\n return params;\n }\n\n /**\n * Updates the browser URL to reflect a new route and keeps `previousUrl`\n * in sync so `handleUrlChange` does not re-process our own navigation.\n */\n private setUrl(routeName: string): void {\n if (this.isHistoryMode) {\n const url = `${this.normalizedBasePath}/${routeName}`;\n safePushState(null, url);\n this.previousUrl = url;\n } else {\n const hash = `#${routeName}`;\n window.location.hash = hash;\n this.previousUrl = hash;\n }\n }\n\n /**\n * Restores the URL when a navigation guard blocks the transition.\n * Uses pushState to safely add a new history entry, avoiding \"back button traps\"\n * that occur with replaceState during popstate events.\n */\n private restoreUrl(): void {\n if (this.isHistoryMode) {\n safePushState(null, this.previousUrl);\n } else {\n window.location.hash = this.previousUrl;\n }\n }\n\n /**\n * Returns the current full URL string for comparison purposes.\n */\n private getCurrentUrl(): string {\n if (this.isHistoryMode) {\n return window.location.pathname + window.location.search;\n }\n return window.location.hash;\n }\n\n // --- End mode-abstracted methods ---\n\n /**\n * Resolves route configuration, falling back to notFound route if needed.\n */\n private getRouteConfig(routeName: string): RouteDefinition | null {\n const { routes, notFound } = this.config;\n let routeConfig = routes[routeName];\n\n // Fallback to notFound route if route doesn't exist\n if (!routeConfig && notFound) {\n routeConfig = routes[notFound];\n }\n\n if (!routeConfig) {\n debug.warn(LOG_PREFIXES.ROUTE, ERROR_MESSAGES.ROUTE.NOT_FOUND(routeName));\n return null;\n }\n\n return routeConfig;\n }\n\n /**\n * Appends cloned template content into the target container.\n * Always appends — callers are responsible for calling `$target.empty()`\n * before invoking this method if a clean slate is needed.\n */\n private renderTemplate(templateSelector: string): boolean {\n let template = this.templateCache.get(templateSelector);\n\n if (!template) {\n const el = document.querySelector(templateSelector);\n if (!el || !(el instanceof HTMLTemplateElement)) {\n debug.warn(LOG_PREFIXES.ROUTE, ERROR_MESSAGES.ROUTE.TEMPLATE_NOT_FOUND(templateSelector));\n return false;\n }\n template = el;\n this.templateCache.set(templateSelector, template);\n }\n\n const clonedContent = template.content.cloneNode(true) as DocumentFragment;\n this.$target.append(clonedContent);\n\n return true;\n }\n\n /**\n * Renders the specified route, including lifecycle hooks and content.\n *\n * Called from within a reactive effect, so DOM mutations here run\n * synchronously inside the effect body. `registry.cleanupDescendants` is\n * called before `$target.empty()` to ensure any reactive bindings on\n * outgoing content are disposed before the nodes are removed — preventing\n * the MutationObserver auto-cleanup path from firing a redundant cleanup.\n *\n * EXCEPTION BEHAVIOUR:\n * - `beforeTransition` throws → render aborted, outgoing DOM intact,\n * `previousRoute` unchanged. Intentional: a throwing hook signals that\n * the transition should not proceed.\n * - `onEnter` throws → container is already empty (`$target.empty()` ran),\n * rendering is skipped, and `previousRoute` is NOT updated. The router\n * is left in an empty-container / stale-previousRoute state. This behavior\n * is by design to prevent unintended state changes if the `onEnter` hook fails.\n * If recovery is needed, the hook should catch its own errors internally.\n */\n private renderRoute(routeName: string): void {\n if (this.isDestroyed) return;\n\n // Validate target element exists\n const container = this.$target[0];\n if (!container) {\n debug.warn(LOG_PREFIXES.ROUTE, ERROR_MESSAGES.ROUTE.TARGET_NOT_FOUND(this.config.target));\n return;\n }\n\n // Resolve route configuration\n const routeConfig = this.getRouteConfig(routeName);\n if (!routeConfig) return;\n\n // Parse query parameters\n const params = this.getQueryParams();\n\n // `previousRoute` is '' on first render, so from !== to in all cases.\n const fromRoute = this.previousRoute;\n\n // Call beforeTransition hook.\n // If it throws, the render is aborted — outgoing content stays in the DOM.\n if (this.config.beforeTransition) {\n this.config.beforeTransition(fromRoute, routeName);\n }\n\n // Dispose reactive bindings on outgoing content before clearing the DOM.\n // $.fn.empty() (patched via jquery-patch) handles cleanupDescendants automatically.\n this.$target.empty();\n\n // Call onEnter hook and merge params\n let routeParams = params;\n if (routeConfig.onEnter) {\n const result = routeConfig.onEnter(params);\n if (result !== undefined) {\n routeParams = { ...params, ...result };\n }\n }\n\n // Render content (custom render or template)\n if (routeConfig.render) {\n routeConfig.render(container, routeName, routeParams);\n } else if (routeConfig.template) {\n if (this.renderTemplate(routeConfig.template)) {\n if (routeConfig.onMount) {\n routeConfig.onMount(this.$target.children());\n }\n }\n }\n\n // Call afterTransition hook\n if (this.config.afterTransition) {\n this.config.afterTransition(fromRoute, routeName);\n }\n\n // Update previous route for next transition\n this.previousRoute = routeName;\n }\n\n /**\n * Handles browser URL change events (hashchange or popstate).\n */\n private handleUrlChange(): void {\n if (this.isDestroyed) return;\n\n const currentUrl = this.getCurrentUrl();\n // Early-exit if URL didn't actually change (e.g., called by our own navigate()).\n if (currentUrl === this.previousUrl) return;\n\n const newRoute = this.getRouteName();\n // peek(): event handler path — reading for comparison only, not to subscribe.\n const oldRouteName = this.currentRouteAtom.peek();\n const params = this.getQueryParams();\n\n if (oldRouteName !== newRoute) {\n // Check onLeave guard for user-driven navigation\n const oldRouteConfig = this.config.routes[oldRouteName];\n if (oldRouteConfig?.onLeave) {\n if (oldRouteConfig.onLeave() === false) {\n // Navigation blocked — restore the URL without updating previousUrl,\n // so the next real navigation is still detected correctly.\n this.restoreUrl();\n return;\n }\n }\n // Two separate writes — the scheduler's automatic microtask batching\n // guarantees they are flushed together in the next microtask tick,\n // so subscribers always see a consistent snapshot of the (route, params) pair.\n // renderRoute reads getQueryParams() directly from the URL, so there\n // is no double-write risk from the queryParamsAtom update.\n this.currentRouteAtom.value = newRoute;\n this.queryParamsAtom.value = params;\n } else {\n // Same route but URL changed (e.g., query params only)\n this.queryParamsAtom.value = params;\n const routeConfig = this.config.routes[oldRouteName];\n if (routeConfig?.onParamsChange) {\n routeConfig.onParamsChange(params);\n } else {\n this.renderRoute(newRoute);\n }\n }\n\n // Commit the new URL only after a successful (unblocked) transition.\n this.previousUrl = currentUrl;\n }\n\n /**\n * Sets up automatic binding for navigation links with data-route attribute.\n *\n * Event delegation is attached to `document` (not `$target`) so that\n * `[data-route]` links anywhere in the page — including outside the router's\n * target container — can trigger navigation. This is intentional: nav links\n * typically live in headers or sidebars, not inside the routed content area.\n *\n * Active-link management uses a reactive effect that re-runs only when\n * `currentRoute` changes — more efficient than a persistent MutationObserver.\n */\n private setupAutoBindLinks(): void {\n if (!this.config.autoBindLinks) return;\n\n // 1. Event delegation on document so nav links outside $target are handled.\n const delegateHandler = (e: JQuery.TriggeredEvent) => {\n e.preventDefault();\n const routeAttr = (e.currentTarget as HTMLElement).dataset.route;\n if (routeAttr != null) this.navigate(routeAttr);\n };\n\n $(document).on('click', '[data-route]', delegateHandler);\n this.cleanups.push(() => {\n $(document).off('click', '[data-route]', delegateHandler);\n });\n\n // 2. Active state management — re-runs only when currentRoute changes.\n const activeClass = this.activeClass;\n\n const activeLinksEffect = effect(() => {\n const current = this.currentRouteAtom.value; // sole tracked dependency\n // DOM queries and class manipulations run untracked: they must not\n // subscribe the effect to anything beyond currentRouteAtom.\n untracked(() => {\n const links = document.querySelectorAll<HTMLElement>('[data-route]');\n\n for (let i = 0, len = links.length; i < len; i++) {\n const el = links[i]!;\n const routeAttr = el.dataset.route!;\n const isActive = current === routeAttr;\n\n el.classList.toggle(activeClass, isActive);\n if (isActive) {\n el.setAttribute('aria-current', 'page');\n } else {\n el.removeAttribute('aria-current');\n }\n }\n });\n });\n\n this.cleanups.push(() => activeLinksEffect.dispose());\n }\n\n /**\n * Navigates to the specified route programmatically.\n *\n * If `routeName` resolves to an empty string after falling back to\n * `config.default`, `setUrl` will be called with an empty string, producing\n * a URL of `${basePath}/` in history mode. Callers should ensure\n * `config.default` is always a non-empty route name.\n */\n public navigate(routeName: string): void {\n if (this.isDestroyed) return;\n\n // peek(): navigate() is called imperatively (not inside an effect), so\n // reading the current route must not register a reactive dependency.\n const currentRouteName = this.currentRouteAtom.peek();\n const currentRouteConfig = this.config.routes[currentRouteName];\n\n if (currentRouteConfig?.onLeave) {\n const canLeave = currentRouteConfig.onLeave();\n if (canLeave === false) return; // Navigation blocked\n }\n\n // Resolve empty route name to default route, matching getRouteName behavior\n const resolved = routeName || this.config.default;\n if (!resolved) {\n debug.warn(\n LOG_PREFIXES.ROUTE,\n 'navigate() called with empty routeName and no default configured.'\n );\n return;\n }\n\n // setUrl() updates the browser URL AND sets this.previousUrl so that\n // the resulting hashchange/popstate event (which fires synchronously on\n // some browsers for hash-mode) is ignored by handleUrlChange.\n // This is intentionally different from handleUrlChange, where previousUrl\n // is committed at the END after a successful unblocked transition.\n this.setUrl(resolved);\n // Two separate writes — the scheduler's automatic microtask batching\n // guarantees they are flushed together in the next microtask tick,\n // so subscribers always see a consistent snapshot of the (route, params) pair.\n this.queryParamsAtom.value = {};\n this.currentRouteAtom.value = resolved;\n }\n\n /**\n * Cleans up all event listeners and effects, and releases the template cache.\n * Each cleanup function is called in a try/catch so that a single failing\n * cleanup does not prevent the remaining ones from running.\n */\n public destroy(): void {\n if (this.isDestroyed) return;\n this.isDestroyed = true;\n\n // Swap before iterating: if a cleanup function somehow pushes to\n // this.cleanups (e.g. a misbehaving plugin), those additions are not\n // iterated and do not cause an infinite loop or missed teardown.\n const cleanups = this.cleanups;\n this.cleanups = [];\n\n for (let i = 0, len = cleanups.length; i < len; i++) {\n try {\n cleanups[i]!();\n } catch (e) {\n debug.warn(LOG_PREFIXES.ROUTE, 'Cleanup error during destroy:', e);\n }\n }\n\n // Release cached template references to allow GC.\n this.templateCache.clear();\n }\n}\n\n/**\n * Creates an SPA router with reactive state management.\n * Supports both hash-based and pushState-based (history) routing.\n *\n * This removes boilerplate from manual route handling by:\n * - Automatically tracking URL changes and updating the UI\n * - Managing template rendering with lifecycle hooks\n * - Handling active link states reactively\n * - Providing navigation guard support (onLeave)\n *\n * @param config - Router configuration\n * @returns Router instance with navigate, destroy methods and currentRoute atom\n *\n * @example\n * ```ts\n * const router = $.route({\n * target: '#app',\n * default: 'home',\n * routes: {\n * home: { template: '#tmpl-home' },\n * about: { template: '#tmpl-about' }\n * }\n * });\n * ```\n */\nexport function route(config: RouteConfig): Router {\n return new RouterImpl(config);\n}\n\n/**\n * Register as jQuery static method.\n * `$.extend(obj)` merges into JQueryStatic; use `$.fn.extend(obj)` for instance methods.\n */\n$.extend({\n route,\n});\n","import { computed } from '@but212/atom-effect';\nimport $ from 'jquery';\nimport type { ComputedAtom, FetchError, FetchOptions } from './types';\n\n// ============================================================================\n// atomFetch\n// ============================================================================\n\nclass FetchContext<T> {\n private abortController: AbortController | null = null;\n private readonly ajaxOptionsFn?: () => JQuery.AjaxSettings;\n private readonly staticOptions: JQuery.AjaxSettings;\n private readonly isStaticUrl: boolean;\n private readonly staticUrl?: string;\n private readonly getUrl?: () => string;\n private readonly transformFn: ((val: unknown) => T) | undefined;\n private readonly onErrorFn: ((err: unknown) => void) | undefined;\n\n constructor(urlOrFn: string | (() => string), options: FetchOptions<T>) {\n this.isStaticUrl = typeof urlOrFn === 'string';\n if (this.isStaticUrl) {\n this.staticUrl = urlOrFn as string;\n } else {\n this.getUrl = urlOrFn as () => string;\n }\n\n if (typeof options.ajaxOptions === 'function') {\n this.ajaxOptionsFn = options.ajaxOptions;\n this.staticOptions = {};\n } else {\n this.staticOptions = { ...options.ajaxOptions };\n }\n if (options.method !== undefined) this.staticOptions.method = options.method;\n if (options.headers !== undefined)\n this.staticOptions.headers = { ...this.staticOptions.headers, ...options.headers };\n\n this.transformFn = options.transform;\n this.onErrorFn = options.onError;\n\n this.execute = this.execute.bind(this);\n }\n\n public abort(): void {\n this.abortController?.abort();\n }\n\n public async execute(): Promise<T> {\n this.abortController?.abort();\n this.abortController = new AbortController();\n const signal = this.abortController.signal;\n\n // Evaluate ajaxOptionsFn each time to track reactive atoms inside it.\n // Merge order: staticOptions (method, headers, …) as base, then ajaxOptionsFn()\n // on top so dynamic values can override statics but statics are never lost.\n const dynamicOpts = this.ajaxOptionsFn ? this.ajaxOptionsFn() : {};\n // Deep clone to prevent jQuery from mutating shared objects\n const reqOptions: JQuery.AjaxSettings = $.extend(true, {}, this.staticOptions, dynamicOpts);\n\n // Block jQuery legacy callbacks to prevent fake errors on internal Abort\n reqOptions.success = undefined;\n reqOptions.error = undefined;\n reqOptions.complete = undefined;\n\n reqOptions.url = this.isStaticUrl ? this.staticUrl : this.getUrl!();\n\n const xhr = $.ajax(reqOptions);\n\n signal.onabort = () => xhr.abort();\n if (signal.aborted) xhr.abort();\n\n let raw: unknown;\n try {\n raw = await xhr;\n } catch (err) {\n if (signal.aborted) {\n // Delegate abort handling gracefully to the core computed tracking system.\n // - Superseded aborts: core ignores them (since _promiseId bumps up).\n // - Manual aborts: core catches them, updating state (hasError/isPending).\n const abortErr = new Error('AbortError');\n abortErr.name = 'AbortError';\n throw abortErr;\n }\n\n let finalErr: Error;\n // Normalize jqXHR and other potential rejection values into standard Error instances.\n if (err && typeof (err as JQuery.jqXHR).readyState !== 'undefined') {\n const jXhr = err as JQuery.jqXHR;\n finalErr = new Error(`Network Error: ${jXhr.statusText || 'Unknown'} (${jXhr.status})`);\n (finalErr as FetchError).jqXHR = jXhr;\n } else {\n finalErr = err instanceof Error ? err : new Error(String(err ?? 'Unknown network error'));\n }\n\n const onError = this.onErrorFn;\n if (onError) {\n try {\n // Call without `this` binding to preserve purity of user callback\n onError(finalErr);\n } catch {\n // Ignore errors thrown by onError itself.\n }\n }\n throw finalErr;\n } finally {\n signal.onabort = null;\n if (this.abortController?.signal === signal) this.abortController = null;\n }\n\n // Transform runs synchronously after await, so atoms read here won't be tracked.\n // This is an inherent limitation of async computed.\n // Users who need reactive transform should use a separate synchronous computed.\n const transform = this.transformFn;\n if (transform) {\n try {\n return transform(raw);\n } catch (err) {\n // Surface transform errors via onError callback\n const onError = this.onErrorFn;\n if (onError) {\n try {\n onError(err);\n } catch {\n // Ignore errors thrown by onError itself.\n }\n }\n throw err;\n }\n }\n return raw as T;\n }\n}\n\n$.extend({\n atomFetch<T>(urlOrFn: string | (() => string), options: FetchOptions<T>): ComputedAtom<T> {\n const context = new FetchContext<T>(urlOrFn, options);\n const isLazy = !(options.eager ?? true);\n\n const atomVal = computed(context.execute, {\n defaultValue: options.defaultValue,\n lazy: isLazy,\n });\n\n return Object.assign(atomVal, {\n abort: () => context.abort(),\n }) as ComputedAtom<T> & { abort: () => void };\n },\n});\n","/**\n * atom-effect-jquery\n *\n * Brings reactivity to jQuery.\n *\n * Features:\n * - Full CJK IME Support (Input Method Editor).\n * - Auto-cleanup via MutationObserver (No memory leaks).\n * - Debug Mode: Console logging + Visual Highlighting.\n *\n * Type augmentation note:\n * This package extends both `JQuery` and `JQueryStatic` via global interface\n * merging in `types.ts`. Consumers using the `export default $` path will\n * receive the augmented type automatically because the module's side-effect\n * imports apply the augmentation at import time.\n */\n\nimport $ from 'jquery';\n\n// ============================================================================\n// Plugin registrations (order matters — namespace must come first)\n// ============================================================================\n\n// Registers $.atom, $.computed, $.effect, $.batch, $.untracked,\n// $.isAtom, $.isComputed, $.isReactive, $.nextTick\nimport './namespace';\n\n// Registers $.fn.atomText/Html/Class/Css/Attr/Prop/Show/Hide/Val/Checked/On/Bind/Unbind.\nimport './chainable';\n\n// Registers $.fn.atomList\nimport './list';\n\n// Registers $.fn.atomMount / $.fn.atomUnmount\nimport './mount';\n\n// Registers $.route\nimport './route';\n\n// Registers $.atomFetch\nimport './fetch';\n\n// ============================================================================\n// Runtime initialisation (browser only)\n// ============================================================================\n\nimport { enablejQueryOverrides } from './jquery-patch';\nimport { disableAutoCleanup, enableAutoCleanup, registry } from './registry';\n\n// $() runs after DOMContentLoaded, so document.body is guaranteed non-null here.\n// In JSDOM/test environments jQuery calls the callback synchronously.\n$(() => {\n // Wraps jQuery event dispatch in batch() so that rapid user interactions\n // (e.g. typing in an input) batch atom writes into a single reactive flush.\n enablejQueryOverrides();\n\n // Watches document.body for removed elements and disposes their reactive\n // bindings automatically, preventing memory leaks without manual cleanup.\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n enableAutoCleanup(document.body!);\n});\n\n// ============================================================================\n// ESM exports — values\n// ============================================================================\n\n// Core primitives — re-exported so consumers do not need to depend on\n// @but212/atom-effect directly.\nexport {\n atom,\n batch,\n computed,\n effect,\n isAtom,\n isComputed,\n untracked,\n} from '@but212/atom-effect';\n\n// jQuery override controls — called automatically on DOM ready, but exposed\n// here for consumers who manage initialisation themselves (e.g. custom roots,\n// shadow DOMs, or environments where the automatic call is not appropriate).\nexport { disablejQueryOverrides, enablejQueryOverrides } from './jquery-patch';\n\n// nextTick is registered on $ via namespace.ts and exported here so ESM\n// consumers can import it without touching $.\n// isReactive is defined in utils.ts and also registered on $ via namespace.ts.\nexport { nextTick } from './namespace';\nexport { isReactive } from './utils';\n\n// Registry API — for advanced lifecycle control (custom roots, manual cleanup).\n// Note: enableAutoCleanup is called automatically on DOM ready with document.body.\n// Call it again only if you need a different root or want to re-initialise.\nexport { registry, enableAutoCleanup, disableAutoCleanup };\n\n// ============================================================================\n// ESM exports — types\n// ============================================================================\n\n// Public-facing types — includes everything needed to fully type-check calls\n// to every exported function and jQuery plugin method.\nexport type {\n // Binding authoring\n BindingOptions,\n ComponentFn,\n // Reactive primitives (core)\n ComputedAtom,\n CssBindings,\n CssValue,\n EffectCleanup,\n EffectResult,\n EqualFn,\n // Fetch\n FetchOptions,\n // List\n ListOptions,\n PrimitiveValue,\n ReactiveValue,\n ReadonlyAtom,\n // Routing\n RenderRoute,\n RouteConfig,\n RouteDefinition,\n RouteLifecycle,\n Router,\n TemplateRoute,\n ValOptions,\n WritableAtom,\n} from './types';\n\n// The augmented jQuery object. Consumers importing this receive a $ with all\n// atom-effect plugin methods already typed via global interface merging.\nexport default $;\n"],"names":["N","_","W","a","d","ht","V","g","F","Z","ot","X","s","e","r","h","o","y","ct","k","I","C","m","c","ut","_t","x","B","lt","at","S","J","tt","U","v","w","M","z","R","st","et","G","Q","ft","Et","T","H","it","nt","dt","l","Dt","Y","q","It","bt","pt","u","f","Tt","Nt","rt","j","$","L","p","O","E","b","A","D","P","Ct","gt","St","i","At","K","kt","Ot","yt","LOG_PREFIXES","ROUTE_DEFAULTS","INPUT_DEFAULTS","DEBUG_DEFAULTS","VALID_INPUT_TAGS","URL_PROPS","DANGEROUS_PROPS","ERROR_MESSAGES","name","selector","raw","prop","tagName","method","debugType","isStatic","info","details","key","index","container","isReactive","value","isAtom","getSelector","el","list","len","hasOwn","shallowEqual","keysA","keysB","objA","objB","getLIS","arr","predecessors","result","resultLen","val","lastIdx","left","right","mid","midIdx","leftIdx","lis","curr","HIGHLIGHT_TRANSITION","getInitialDebugState","flag","__vite_import_meta_env__","debugEnabled","debug","globalFlag","prefix","args","oldVal","newVal","target","type","highlightElement","message","rest","cause","HIGHLIGHT_CLASS","HIGHLIGHT_STYLE_ATTR","highlightStyleRef","injectHighlightStyle","style","highlightTimers","highlightRafs","existingRaf","existingTimer","rafId","atom","initialValue","options","createAtom","nextTick","resolve","staticExtensions","computed","effect","batch","untracked","isComputed","AES_BOUND","BindingRegistry","node","res","fx","record","fn","effects","cleanups","descendants","child","registry","observers","enableAutoCleanup","root","observer","mutations","mLen","removedNodes","rLen","disableAutoCleanup","obs","registerReactiveEffect","source","updater","reactiveSource","INTERNAL_HANDLER","handlerMap","originals","getWrappedHandler","wrapped","wrapEventMap","map","newMap","entries","entry","handler","resolveOffEventMap","enablejQueryOverrides","orig","targets","types","lastIndex","disablejQueryOverrides","BindingFlags","instanceCounter","markInternal","InputBinding","$el","wasComposing","formatted","currentVal","isFocused","parsedCurrent","start","end","debounce","eventName","baseEqual","formattedArr","rawValue","parsed","ns","namespacedEvents","applyInputBinding","binding","URL_ATTRS","DANGEROUS_PROTOCOL_RE","DANGEROUS_CSS_RE","DANGEROUS_CSS_URL_RE","STRIP_CTRL_RE","DECODE_NUMERIC_ENTITY_RE","NAMED_ENTITY_MAP","DECODE_NAMED_ENTITY_RE","STRIP_XML_RE","DANGEROUS_TAG_RE","DANGEROUS_PROTOCOL_GLOBAL_RE","DANGEROUS_DATA_URI_RE","UNSAFE_ATTR_RE","DANGEROUS_CSS_GLOBAL_RE","sanitizeHtml","html","safe","hex","dec","prev","isDangerousUrl","attrName","isDangerousCssValue","camelCache","getCamelCase","cached","htmlSanitizeCache","getSanitizedHtml","createContext","bindText","ctx","formatter","bindHtml","sanitized","bindClass","classMap","className","tokens","bindCss","cssMap","camel","unit","strVal","bindAttr","attrMap","lowerName","isAria","bindProp","propMap","isUrlProp","bindVisibility","condition","invert","label","originalDisplay","showDisplay","bindVal","cleanup","bindChecked","isRadio","current","escapedName","bindEvents","eventMap","bindOn","event","bindUnbind","warnNonElement","nodeType","classNameOrMap","propOrMap","nameOrMap","text","cls","css","attr","show","hide","checked","on","valParsed","listInstances","listBatchIdCounter","insertOrAppend","nextNode","$container","applyItemCallbacks","state","item","bind","update","ListContext","containerSelector","onRemove","commitRemoval","handleEmpty","itemCount","empty","safeEmpty","oldKeys","itemMap","buildIndices","items","getKey","removingKeys","oldIndexMap","newKeys","newKeySet","newIndices","trKeys","trItems","trIdxs","oldItem","renderItems","diff","isInitial","renderCount","render","renderResults","htmlParts","stringRenderCount","t","sanitizedFragments","htmlPartCount","batchSeparator","fragIdx","oldEl","cleanupRemoved","placeItems","rawContainer","callbacks","innerHtmlFragments","onAdd","lisArr","lisIdx","childIdx","fragment","syncEventIndices","elToKey","keyToIndex","rootEl","events","_index","containerIdx","containerLen","oldInstance","eventKey","spaceIdx","eventType","childSelector","actualSelector","delegateHandler","EMPTY_PROPS","component","props","teardown","err","safePushState","data","url","RouterImpl","config","renderEffect","routeName","defaultRoute","pathname","hash","qIndex","sp","params","routes","notFound","routeConfig","templateSelector","template","clonedContent","fromRoute","routeParams","currentUrl","newRoute","oldRouteName","oldRouteConfig","routeAttr","activeClass","activeLinksEffect","links","isActive","currentRouteName","currentRouteConfig","resolved","route","FetchContext","urlOrFn","signal","dynamicOpts","reqOptions","xhr","abortErr","finalErr","jXhr","onError","transform","context","isLazy","atomVal"],"mappings":";;AAAA,MAAMA,KAAI;AAAA,EACR,MAAM;AAAA,EACN,SAAS;AAAA,EACT,UAAU;AAAA,EACV,UAAU;AACZ,GAAGC,IAAI;AAAA,EACL,UAAU;AAAA,EACV,WAAW;AACb,GAAGC,KAAI;AAAA,EACL,UAAU;AAAA;AAAA,EAEV,aAAa;AAAA,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