@but212/atom-effect-jquery 0.22.0 → 0.22.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/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.mjs +972 -935
- package/dist/index.mjs.map +1 -1
- package/package.json +2 -2
package/dist/index.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.cjs","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}, nt = {\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}, R = 1073741823, W = typeof process < \"u\" && process.env && !1 || !1, rt = 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 ot = /* @__PURE__ */ Symbol(\"AtomEffect.DebugName\"), ht = /* @__PURE__ */ Symbol(\"AtomEffect.Type\"), x = /* @__PURE__ */ Symbol(\"AtomEffect.NoDefaultValue\"), F = {\n // Dev mode flag\n enabled: W,\n warnInfiniteLoop: nt.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?.[ot],\n getDebugType: (i) => i?.[ht]\n};\nlet ct = 1;\nconst ut = () => ct++;\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 = ut() & R;\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 & R || 1, k), M = (i) => i + 1 & R;\nlet B = 0, L = !1, tt = 0;\nconst _t = () => tt;\nfunction X() {\n return L ? !1 : (L = !0, tt = w(), B = 0, !0);\n}\nconst G = () => {\n L = !1;\n}, at = () => L ? ++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\"), et = /* @__PURE__ */ Symbol.for(\"atom-effect/computed\"), st = /* @__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\" && et in i;\n}\nfunction bt(i) {\n return i !== null && typeof i == \"object\" && st in i;\n}\nfunction it(i) {\n return i !== null && typeof i == \"object\" && typeof i.then == \"function\";\n}\nvar Y, q;\nconst { IDLE: A, DIRTY: p, PENDING: y, RESOLVED: E, REJECTED: g, HAS_ERROR: N, RECOMPUTING: C, DISPOSED: U, IS_COMPUTED: dt } = $;\nfunction pt(i) {\n return i & E ? b.RESOLVED : i & y ? 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._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) & R, 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 & y) {\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 | N) ? !0 : this._links.some((t) => t?.node?.flags & N);\n }\n get isValid() {\n return !this.hasError;\n }\n get errors() {\n if (this._track(), !this.hasError) return rt;\n const t = [];\n return this._error && t.push(this._error), this._links.forEach((s) => {\n const n = s.node;\n n.flags & N && 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 & y) !== 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 = et, 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, it(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 | y) & -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 return 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 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 | N, 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 = st, 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, it(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 = _t();\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 Nt(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 yt(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 et as COMPUTED_BRAND,\n f as ComputedError,\n nt as DEBUG_CONFIG,\n F as DEBUG_RUNTIME,\n st 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 yt as batch,\n At as computed,\n Nt 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 // Chromium fires an input event after compositionend.\n // Safari/Firefox may not, so we trigger sync manually.\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 // Re-format the displayed value to match the atom's canonical format.\n // peek() instead of .value: this is an event handler path — we want the\n // current value but must not register a reactive dependency here.\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 // Mirror the target URL so handleUrlChange knows this change was programmatic.\n this.previousUrl = url;\n } else {\n const hash = `#${routeName}`;\n // Set hash before updating previousUrl so getCurrentUrl() returns the\n // new value when we store it.\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 // Optimization: Use pre-merged options.\n // If staticUrl is present, it's used; otherwise getUrl() is called.\n // jQuery's ajax settings object is mutable but $.ajax copies it.\n // We create a fresh object here to be safe and reactive-friendly.\n const reqOptions = staticUrl\n ? { ...baseOptions, url: staticUrl }\n : { ...baseOptions, url: getUrl!() };\n\n const xhr = $.ajax(reqOptions);\n\n // Optimization: Use onabort property directly instead of addEventListener\n // to avoid the overhead of the EventTarget registry.\n // This signal is fresh per request and private to this scope.\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; // Cleanup\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","nt","H","R","W","rt","D","e","s","f","I","m","ot","ht","x","F","i","ct","ut","K","n","P","V","v","h","S","O","J","Z","r","k","w","M","B","L","tt","_t","X","G","at","lt","T","z","et","st","_","Ct","Q","ft","Et","c","l","Tt","Ot","it","Y","q","A","p","y","E","g","N","C","U","dt","pt","It","o","At","j","St","Nt","yt","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":"sIAAMA,GAAI,CACR,KAAM,OACN,QAAS,UACT,SAAU,WACV,SAAU,UACZ,EAAGC,EAAI,CACL,SAAU,EACV,UAAW,CACb,EAAGC,GAAI,CACL,SAAU,EAEV,YAAa,EACb,MAAO,EACP,KAAM,GACN,QAAS,GACT,SAAU,GACV,SAAU,IACV,YAAa,IACb,UAAW,GACb,EAAGC,EAAI,CACL,SAAU,EACV,KAAM,EACN,uBAAwB,EAC1B,EAIGC,EAAI,CAEL,0BAA2B,IAC3B,0BAA2B,IAE3B,yBAA0B,IAC1B,qBAAsB,IACtB,qBAAsB,GAEtB,6BAA8B,GAChC,EAAGC,GAAK,CACN,mBAAoB,EAEtB,EAAGC,GAAI,CACL,kBAAmB,EACnB,eAAgB,OAAO,iBAAmB,CAC5C,EAAGC,GAAI,WAAYC,GAAI,OAAO,QAAU,KAAO,QAAQ,KAAO,IAAM,GAAIC,GAAK,OAAO,OAAO,CAAA,CAAE,EAC7F,MAAMC,WAAU,KAAM,CACpB,YAAY,EAAGC,EAAI,KAAMC,EAAI,GAAI,CAC/B,MAAM,CAAC,EAAG,KAAK,MAAQD,EAAG,KAAK,YAAcC,EAAG,KAAK,KAAO,WAC9D,CACF,CACA,MAAMC,UAAUH,EAAE,CAChB,YAAY,EAAGC,EAAI,KAAM,CACvB,MAAM,EAAGA,EAAG,EAAE,EAAG,KAAK,KAAO,eAC/B,CACF,CACA,MAAMG,UAAUJ,EAAE,CAChB,YAAY,EAAGC,EAAI,KAAM,CACvB,MAAM,EAAGA,EAAG,EAAE,EAAG,KAAK,KAAO,aAC/B,CACF,CACA,MAAMI,WAAUL,EAAE,CAChB,YAAY,EAAGC,EAAI,KAAM,CACvB,MAAM,EAAGA,EAAG,EAAE,EAAG,KAAK,KAA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M,CAGN8M,GAAA,EAKAnB,GAAkB,SAAS,IAAK,CAClC,CAAC"}
|
|
1
|
+
{"version":3,"file":"index.cjs","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 */\nexport const 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*:|-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/** 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;\n// Numeric HTML entity decoder: &#NNN; and &#xHH; forms.\n// Must run before protocol/tag checks so entity-encoded bypasses like\n// \"javascript:\" (j=106) are normalised to their literal characters\n// before the dangerous-protocol regex sees them.\n// Named entities (: 	 
) that are relevant to protocol\n// smuggling are also decoded here to close the named-entity bypass path.\nconst DECODE_NUMERIC_ENTITY_RE = /&#x([0-9a-f]+);?|&#([0-9]+);?/gi;\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;\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 // 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. Safe structural entities (& < >\n // ") are intentionally left encoded — they do not produce dangerous\n // characters and must remain escaped for correct HTML rendering.\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 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 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 debug.error(LOG_PREFIXES.BINDING, ERROR_MESSAGES.EFFECT_DISPOSE_ERROR(), 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 debug.error(LOG_PREFIXES.BINDING, ERROR_MESSAGES.BINDING_CLEANUP_ERROR(), e);\n }\n }\n }\n }\n\n cleanupDescendants(el: Element): void {\n // getElementsByClassName is significantly faster than querySelectorAll as it\n // avoids the CSS selector parsing engine and returns a live HTMLCollection.\n // Iterating backwards handles live collection mutations gracefully, though\n // cleanup() doesn't immediately remove elements from the tree.\n const descendants = el.getElementsByClassName(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): 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: 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}\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\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 // 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 this.ns = `.atomBind-${++instanceCounter}`;\n\n const debounce = options.debounce ?? 0;\n const eventName = options.event ?? INPUT_DEFAULTS.EVENT;\n this.parse = options.parse ?? ((v: string) => v as unknown as T);\n this.format = options.format ?? ((v: T) => String(v ?? ''));\n this.equal = options.equal ?? Object.is;\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(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 // 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.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.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.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.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.equal(this.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 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 } 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(eventName: string): void {\n // Hoist 1: Pre-compute event strings to avoid N allocations per input.\n const ns = this.ns;\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(`${eventName}${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 { hasOwn, 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 for (const className in classMap) {\n if (hasOwn.call(classMap, className)) {\n const source = classMap[className]!;\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/**\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 ? `${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 // 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')) continue;\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/**\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 for (const name in propMap) {\n if (hasOwn.call(propMap, name)) {\n // Block dangerous DOM properties that can inject raw HTML (e.g., innerHTML)\n if (DANGEROUS_PROPS.has(name)) continue;\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/**\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 for (let i = 0, len = this.length; i < len; i++) {\n bindText(createContext(this[i]!), source, formatter);\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 bindHtml(createContext(this[i]!), source);\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(`${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 for (let i = 0, len = this.length; i < len; i++) {\n bindClass(createContext(this[i]!), classMap);\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.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 bindCss(createContext(this[i]!), cssMap);\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.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 bindAttr(createContext(this[i]!), attrMap);\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.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 bindProp(createContext(this[i]!), propMap);\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 bindVisibility(createContext(this[i]!), condition, false);\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 bindVisibility(createContext(this[i]!), condition, true);\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 bindVal(createContext(this[i]!), atom as WritableAtom<unknown>, options as ValOptions<unknown>);\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 bindChecked(createContext(this[i]!), atom);\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 bindOn(createContext(this[i]!), event, handler);\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 (options: BindingOptions): JQuery {\n const { text, html, class: cls, css, attr, prop, show, hide, val, checked, on } = options;\n let valAtom: WritableAtom<unknown> | undefined;\n let valOpts: ValOptions<unknown> | undefined;\n\n if (val !== undefined) {\n if (Array.isArray(val)) {\n valAtom = val[0] as WritableAtom<unknown>;\n valOpts = val[1] as ValOptions<unknown>;\n } else {\n valAtom = val as WritableAtom<unknown>;\n }\n }\n\n for (let i = 0, len = this.length; i < len; i++) {\n const ctx = createContext(this[i]!);\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 (val !== undefined) bindVal(ctx, valAtom!, valOpts);\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 bindUnbind(this[i]!);\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 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 for (\n let containerIdx = 0, containerLen = this.length;\n containerIdx < containerLen;\n containerIdx++\n ) {\n const rawContainer = this[containerIdx]!;\n const $container = $(rawContainer);\n const containerSelector = getSelector(rawContainer);\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 commitRemoval();\n return;\n }\n\n const result = onRemove(entry.$el);\n if (result instanceof Promise) {\n result.then(commitRemoval, commitRemoval);\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 for (let i = 0; i < oldKeys.length; i++) {\n const k = oldKeys[i]!;\n const entry = itemMap.get(k);\n if (entry) removeItem(k, entry);\n }\n oldKeys.length = 0;\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 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 // Generate an ephemeral separator per batch to ensure zero collision with user content\n const batchSeparator = `<!--sep-${Math.random().toString(36).substring(2)}-${Date.now().toString(36)}-->`;\n sanitizedFragments = sanitizeHtml(htmlParts.join(batchSeparator)).split(batchSeparator);\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 // Array iteration is faster than itemMap entries iteration,\n // and safely skips keys already in removingKeys since oldKeys\n // never overlaps with them.\n for (let i = 0; i < oldKeys.length; i++) {\n const k = oldKeys[i]!;\n if (!newKeySet.has(k)) {\n const entry = itemMap.get(k);\n if (entry) 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 rawContainer.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 = rawContainer.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 entry.item = item;\n entry.state = undefined;\n\n if (entry.$el[0]) {\n if (state === undefined) {\n if (update) update(entry.$el, item, i);\n } else if (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\n if (state === 'new') {\n if (onAdd) onAdd(entry.$el);\n removingKeys.delete(k);\n debug.domUpdated(entry.$el, 'list.add', item);\n }\n }\n rawContainer.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 entry.item = item;\n entry.state = undefined;\n\n if (entry.$el[0]) {\n if (state === undefined) {\n if (update) update(entry.$el, item, i);\n } else if (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\n nextNode = entry.$el[0] ?? null;\n\n if (state === 'new') {\n if (onAdd) onAdd(entry.$el);\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(rawContainer, fx);\n registry.trackCleanup(rawContainer, () => {\n itemMap.clear();\n removingKeys.clear();\n oldKeys.length = 0;\n $emptyEl?.remove();\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.\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 for (let i = 0, len = this.length; i < len; i++) {\n const rootEl = this[i];\n if (!rootEl) continue;\n\n // Unmount any existing component before mounting the new one.\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(), 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$.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 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 (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 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 const cleanups = this.cleanups;\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 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 isStaticUrl = typeof urlOrFn === 'string';\n const staticUrl = isStaticUrl ? urlOrFn : undefined;\n const getUrl = isStaticUrl ? null : urlOrFn;\n\n // Hoist 2: Pre-merge static options to avoid repeated object spreads per request.\n const reqOptions: JQuery.AjaxSettings = Object.assign({}, ajaxOptions);\n if (method !== undefined) reqOptions.method = method;\n if (headers !== undefined) reqOptions.headers = headers;\n\n if (isStaticUrl) {\n reqOptions.url = staticUrl;\n }\n\n let abortController: AbortController | null = null;\n const isLazy = !(eager ?? true);\n\n return computed(\n async () => {\n abortController?.abort();\n abortController = new AbortController();\n const signal = abortController.signal;\n\n if (!isStaticUrl) {\n reqOptions.url = getUrl!();\n }\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: isLazy }\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","s","f","I","m","ht","ct","x","F","i","ut","_t","K","n","r","P","V","o","v","h","S","O","J","Z","k","w","M","B","R","tt","et","X","G","at","lt","T","z","st","it","_","Ct","Q","ft","gt","Et","c","l","Ot","nt","Y","q","A","p","N","E","g","y","C","U","dt","pt","It","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","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","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","e","effects","cleanups","descendants","child","registry","observer","observedRoot","enableAutoCleanup","root","mutations","mLen","removedNodes","rLen","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","eventName","parsed","ns","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","text","cls","css","attr","show","hide","checked","on","valAtom","valOpts","insertOrAppend","nextNode","$container","render","bind","update","onAdd","onRemove","empty","getKey","item","_index","containerIdx","containerLen","rawContainer","containerSelector","itemMap","removingKeys","oldKeys","$emptyEl","scheduleRemoval","entry","commitRemoval","removeItem","items","itemCount","safeEmpty","oldIndexMap","newKeys","newKeySet","newIndices","trKeys","trItems","trIdxs","oldItem","renderCount","renderResults","htmlParts","t","sanitizedFragments","batchSeparator","fragIdx","oldEl","lisArr","lisIdx","isInitial","childIdx","fragment","state","EMPTY_PROPS","component","props","rootEl","teardown","err","safePushState","data","url","RouterImpl","config","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","isStaticUrl","staticUrl","getUrl","reqOptions","abortController","signal","xhr"],"mappings":"sIAAMA,GAAI,CACR,KAAM,OACN,QAAS,UACT,SAAU,WACV,SAAU,UACZ,EAAGC,EAAI,CACL,SAAU,EACV,UAAW,CACb,EAAGC,GAAI,CACL,SAAU,EAEV,YAAa,EACb,MAAO,EACP,KAAM,GACN,QAAS,GACT,SAAU,GACV,SAAU,IACV,YAAa,IACb,UAAW,GACb,EAAGC,EAAI,CACL,SAAU,EACV,KAAM,EACN,uBAAwB,EAC1B,EAIGC,EAAI,CAEL,0BAA2B,IAC3B,0BAA2B,IAE3B,yBAA0B,IAC1B,qBAAsB,IACtB,qBAAsB,GAEtB,6BAA8B,GAChC,EAAGC,GAAK,CACN,mBAAoB,EAEtB,EAAGC,GAAI,CACL,kBAAmB,EACnB,eAAgB,OAAO,iBAAmB,CAC5C,EAAGC,GAAI,WAAYC,GAAI,OAAO,QAAU,KAAO,QAAQ,KAAO,IAAM,GAAIC,GAAK,OAAO,OAAO,CAAA,CAAE,EAC7F,MAAMC,WAAU,KAAM,CACpB,YAAY,EAAG,EAAI,KAAMC,EAAI,GAAI,CAC/B,MAAM,CAAC,EAAG,KAAK,MAAQ,EAAG,KAAK,YAAcA,EAAG,KAAK,KAAO,WAC9D,CACF,CACA,MAAMC,UAAUF,EAAE,CAChB,YAAY,EAAG,EAAI,KAAM,CACvB,MAAM,EAAG,EAAG,EAAE,EAAG,KAAK,KAAO,eAC/B,CACF,CACA,MAAMG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