march-hare 0.13.8 → 0.13.11

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.
@@ -1 +1 @@
1
- {"version":3,"file":"march-hare.js","sources":["../node_modules/eventemitter3/index.js","../src/library/boundary/components/broadcast/utils.ts","../src/library/boundary/components/broadcast/index.tsx","../src/library/boundary/components/tasks/utils.ts","../src/library/boundary/components/tasks/index.tsx","../src/library/boundary/components/env/utils.ts","../src/library/utils.ts","../src/library/types/index.ts","../src/library/boundary/components/env/index.tsx","../src/library/boundary/components/sharing/index.tsx","../src/library/boundary/components/tap/utils.ts","../src/library/boundary/components/tap/index.tsx","../src/library/boundary/components/consumer/utils.ts","../src/library/boundary/index.tsx","../src/library/action/utils.ts","../src/library/action/index.ts","../src/library/actions/utils.ts","../src/library/utils/utils.ts","../src/library/error/types.ts","../src/library/error/index.ts","../src/library/boundary/components/scope/utils.ts","../src/library/cache/index.ts","../src/library/resource/utils.ts","../src/library/resource/index.ts","../src/library/coalesce/index.ts","../node_modules/immertation/dist/immertation.mjs","../src/library/boundary/components/consumer/components/partition/index.tsx","../src/library/with/utils.ts","../src/library/context/index.ts","../src/library/actions/index.ts","../src/library/error/utils.ts","../src/library/scope/utils.tsx","../src/library/app/index.tsx","../src/library/with/index.ts","../src/library/annotate/index.ts","../src/library/utils/index.ts","../src/library/shared/index.ts","../src/library/scope/index.tsx"],"sourcesContent":["'use strict';\n\nvar has = Object.prototype.hasOwnProperty\n , prefix = '~';\n\n/**\n * Constructor to create a storage for our `EE` objects.\n * An `Events` instance is a plain object whose properties are event names.\n *\n * @constructor\n * @private\n */\nfunction Events() {}\n\n//\n// We try to not inherit from `Object.prototype`. In some engines creating an\n// instance in this way is faster than calling `Object.create(null)` directly.\n// If `Object.create(null)` is not supported we prefix the event names with a\n// character to make sure that the built-in object properties are not\n// overridden or used as an attack vector.\n//\nif (Object.create) {\n Events.prototype = Object.create(null);\n\n //\n // This hack is needed because the `__proto__` property is still inherited in\n // some old browsers like Android 4, iPhone 5.1, Opera 11 and Safari 5.\n //\n if (!new Events().__proto__) prefix = false;\n}\n\n/**\n * Representation of a single event listener.\n *\n * @param {Function} fn The listener function.\n * @param {*} context The context to invoke the listener with.\n * @param {Boolean} [once=false] Specify if the listener is a one-time listener.\n * @constructor\n * @private\n */\nfunction EE(fn, context, once) {\n this.fn = fn;\n this.context = context;\n this.once = once || false;\n}\n\n/**\n * Add a listener for a given event.\n *\n * @param {EventEmitter} emitter Reference to the `EventEmitter` instance.\n * @param {(String|Symbol)} event The event name.\n * @param {Function} fn The listener function.\n * @param {*} context The context to invoke the listener with.\n * @param {Boolean} once Specify if the listener is a one-time listener.\n * @returns {EventEmitter}\n * @private\n */\nfunction addListener(emitter, event, fn, context, once) {\n if (typeof fn !== 'function') {\n throw new TypeError('The listener must be a function');\n }\n\n var listener = new EE(fn, context || emitter, once)\n , evt = prefix ? prefix + event : event;\n\n if (!emitter._events[evt]) emitter._events[evt] = listener, emitter._eventsCount++;\n else if (!emitter._events[evt].fn) emitter._events[evt].push(listener);\n else emitter._events[evt] = [emitter._events[evt], listener];\n\n return emitter;\n}\n\n/**\n * Clear event by name.\n *\n * @param {EventEmitter} emitter Reference to the `EventEmitter` instance.\n * @param {(String|Symbol)} evt The Event name.\n * @private\n */\nfunction clearEvent(emitter, evt) {\n if (--emitter._eventsCount === 0) emitter._events = new Events();\n else delete emitter._events[evt];\n}\n\n/**\n * Minimal `EventEmitter` interface that is molded against the Node.js\n * `EventEmitter` interface.\n *\n * @constructor\n * @public\n */\nfunction EventEmitter() {\n this._events = new Events();\n this._eventsCount = 0;\n}\n\n/**\n * Return an array listing the events for which the emitter has registered\n * listeners.\n *\n * @returns {Array}\n * @public\n */\nEventEmitter.prototype.eventNames = function eventNames() {\n var names = []\n , events\n , name;\n\n if (this._eventsCount === 0) return names;\n\n for (name in (events = this._events)) {\n if (has.call(events, name)) names.push(prefix ? name.slice(1) : name);\n }\n\n if (Object.getOwnPropertySymbols) {\n return names.concat(Object.getOwnPropertySymbols(events));\n }\n\n return names;\n};\n\n/**\n * Return the listeners registered for a given event.\n *\n * @param {(String|Symbol)} event The event name.\n * @returns {Array} The registered listeners.\n * @public\n */\nEventEmitter.prototype.listeners = function listeners(event) {\n var evt = prefix ? prefix + event : event\n , handlers = this._events[evt];\n\n if (!handlers) return [];\n if (handlers.fn) return [handlers.fn];\n\n for (var i = 0, l = handlers.length, ee = new Array(l); i < l; i++) {\n ee[i] = handlers[i].fn;\n }\n\n return ee;\n};\n\n/**\n * Return the number of listeners listening to a given event.\n *\n * @param {(String|Symbol)} event The event name.\n * @returns {Number} The number of listeners.\n * @public\n */\nEventEmitter.prototype.listenerCount = function listenerCount(event) {\n var evt = prefix ? prefix + event : event\n , listeners = this._events[evt];\n\n if (!listeners) return 0;\n if (listeners.fn) return 1;\n return listeners.length;\n};\n\n/**\n * Calls each of the listeners registered for a given event.\n *\n * @param {(String|Symbol)} event The event name.\n * @returns {Boolean} `true` if the event had listeners, else `false`.\n * @public\n */\nEventEmitter.prototype.emit = function emit(event, a1, a2, a3, a4, a5) {\n var evt = prefix ? prefix + event : event;\n\n if (!this._events[evt]) return false;\n\n var listeners = this._events[evt]\n , len = arguments.length\n , args\n , i;\n\n if (listeners.fn) {\n if (listeners.once) this.removeListener(event, listeners.fn, undefined, true);\n\n switch (len) {\n case 1: return listeners.fn.call(listeners.context), true;\n case 2: return listeners.fn.call(listeners.context, a1), true;\n case 3: return listeners.fn.call(listeners.context, a1, a2), true;\n case 4: return listeners.fn.call(listeners.context, a1, a2, a3), true;\n case 5: return listeners.fn.call(listeners.context, a1, a2, a3, a4), true;\n case 6: return listeners.fn.call(listeners.context, a1, a2, a3, a4, a5), true;\n }\n\n for (i = 1, args = new Array(len -1); i < len; i++) {\n args[i - 1] = arguments[i];\n }\n\n listeners.fn.apply(listeners.context, args);\n } else {\n var length = listeners.length\n , j;\n\n for (i = 0; i < length; i++) {\n if (listeners[i].once) this.removeListener(event, listeners[i].fn, undefined, true);\n\n switch (len) {\n case 1: listeners[i].fn.call(listeners[i].context); break;\n case 2: listeners[i].fn.call(listeners[i].context, a1); break;\n case 3: listeners[i].fn.call(listeners[i].context, a1, a2); break;\n case 4: listeners[i].fn.call(listeners[i].context, a1, a2, a3); break;\n default:\n if (!args) for (j = 1, args = new Array(len -1); j < len; j++) {\n args[j - 1] = arguments[j];\n }\n\n listeners[i].fn.apply(listeners[i].context, args);\n }\n }\n }\n\n return true;\n};\n\n/**\n * Add a listener for a given event.\n *\n * @param {(String|Symbol)} event The event name.\n * @param {Function} fn The listener function.\n * @param {*} [context=this] The context to invoke the listener with.\n * @returns {EventEmitter} `this`.\n * @public\n */\nEventEmitter.prototype.on = function on(event, fn, context) {\n return addListener(this, event, fn, context, false);\n};\n\n/**\n * Add a one-time listener for a given event.\n *\n * @param {(String|Symbol)} event The event name.\n * @param {Function} fn The listener function.\n * @param {*} [context=this] The context to invoke the listener with.\n * @returns {EventEmitter} `this`.\n * @public\n */\nEventEmitter.prototype.once = function once(event, fn, context) {\n return addListener(this, event, fn, context, true);\n};\n\n/**\n * Remove the listeners of a given event.\n *\n * @param {(String|Symbol)} event The event name.\n * @param {Function} fn Only remove the listeners that match this function.\n * @param {*} context Only remove the listeners that have this context.\n * @param {Boolean} once Only remove one-time listeners.\n * @returns {EventEmitter} `this`.\n * @public\n */\nEventEmitter.prototype.removeListener = function removeListener(event, fn, context, once) {\n var evt = prefix ? prefix + event : event;\n\n if (!this._events[evt]) return this;\n if (!fn) {\n clearEvent(this, evt);\n return this;\n }\n\n var listeners = this._events[evt];\n\n if (listeners.fn) {\n if (\n listeners.fn === fn &&\n (!once || listeners.once) &&\n (!context || listeners.context === context)\n ) {\n clearEvent(this, evt);\n }\n } else {\n for (var i = 0, events = [], length = listeners.length; i < length; i++) {\n if (\n listeners[i].fn !== fn ||\n (once && !listeners[i].once) ||\n (context && listeners[i].context !== context)\n ) {\n events.push(listeners[i]);\n }\n }\n\n //\n // Reset the array, or remove it completely if we have no more listeners.\n //\n if (events.length) this._events[evt] = events.length === 1 ? events[0] : events;\n else clearEvent(this, evt);\n }\n\n return this;\n};\n\n/**\n * Remove all listeners, or those of the specified event.\n *\n * @param {(String|Symbol)} [event] The event name.\n * @returns {EventEmitter} `this`.\n * @public\n */\nEventEmitter.prototype.removeAllListeners = function removeAllListeners(event) {\n var evt;\n\n if (event) {\n evt = prefix ? prefix + event : event;\n if (this._events[evt]) clearEvent(this, evt);\n } else {\n this._events = new Events();\n this._eventsCount = 0;\n }\n\n return this;\n};\n\n//\n// Alias methods names because people roll like that.\n//\nEventEmitter.prototype.off = EventEmitter.prototype.removeListener;\nEventEmitter.prototype.addListener = EventEmitter.prototype.on;\n\n//\n// Expose the prefix.\n//\nEventEmitter.prefixed = prefix;\n\n//\n// Allow `EventEmitter` to be imported as module namespace.\n//\nEventEmitter.EventEmitter = EventEmitter;\n\n//\n// Expose the module.\n//\nif ('undefined' !== typeof module) {\n module.exports = EventEmitter;\n}\n","import EventEmitter from \"eventemitter3\";\nimport * as React from \"react\";\n\n/**\n * EventEmitter subclass that caches the latest payload per event.\n *\n * When a broadcast or multicast action is dispatched, the payload is\n * stored so that late-mounting components can replay it via\n * {@link useLifecycles} and handlers can read it via\n * `context.actions.final()`.\n */\nexport class BroadcastEmitter extends EventEmitter {\n private cache = new Map<string | symbol, unknown>();\n\n override emit(event: string | symbol, ...args: unknown[]): boolean {\n this.cache.set(event, args[0]);\n return super.emit(event, ...args);\n }\n\n /**\n * Cache a value for a given event without emitting to listeners.\n * Used by {@link emitAsync} to preserve caching when bypassing `emit()`.\n */\n setCache(event: string | symbol, value: unknown): void {\n this.cache.set(event, value);\n }\n\n /**\n * Retrieve the last emitted payload for a given event.\n */\n getCached(event: string | symbol): unknown {\n return this.cache.get(event);\n }\n\n /**\n * Emit without caching the payload. Used by the framework to publish\n * fire-and-forget events (such as `Lifecycle.Fault`) where late-mounting\n * subscribers must not replay a stale value.\n */\n fire(event: string | symbol, ...args: unknown[]): boolean {\n return super.emit(event, ...args);\n }\n}\n\n/**\n * React context for broadcasting distributed actions across components.\n */\nexport const Context = React.createContext<BroadcastEmitter>(\n new BroadcastEmitter(),\n);\n\n/**\n * Hook to access the broadcast EventEmitter for emitting and listening to distributed actions.\n *\n * @returns The BroadcastEmitter instance for distributed actions.\n */\nexport function useBroadcast(): BroadcastEmitter {\n return React.useContext(Context);\n}\n","import { Props } from \"./types.ts\";\nimport { Context, BroadcastEmitter } from \"./utils.ts\";\nimport * as React from \"react\";\n\nexport { useBroadcast, BroadcastEmitter } from \"./utils.ts\";\n\n/**\n * Creates a new broadcast context for distributed actions. Only needed if you\n * want to isolate a broadcast context, useful for libraries that want to provide\n * their own broadcast context without interfering with the app's broadcast context.\n *\n * @param props.children - The children to render within the broadcast context.\n * @returns The children wrapped in a broadcast context provider.\n */\nexport function Broadcaster({ children }: Props): React.ReactNode {\n const context = React.useMemo(() => new BroadcastEmitter(), []);\n\n return <Context.Provider value={context}>{children}</Context.Provider>;\n}\n","import { Tasks } from \"./types.ts\";\nimport * as React from \"react\";\n\n/**\n * React context for the shared tasks Set.\n * Tasks are ordered by creation time (oldest first) since Sets maintain insertion order.\n */\nexport const Context = React.createContext<Tasks>(new Set());\n\n/**\n * Hook to access the shared tasks Set from context.\n * Returns the Set of all currently running tasks across all components in the context.\n *\n * @returns The Set of Task instances in the current context.\n *\n * @example\n * ```ts\n * const tasks = useTasks();\n *\n * // Abort all tasks for a specific action\n * for (const task of tasks) {\n * if (task.action === Actions.Fetch) {\n * task.controller.abort();\n * }\n * }\n * ```\n */\nexport function useTasks(): Tasks {\n return React.useContext(Context);\n}\n","import { Context } from \"./utils.ts\";\nimport type { Props, Tasks } from \"./types.ts\";\nimport * as React from \"react\";\n\nexport type { Task } from \"./types.ts\";\n\n/**\n * Creates a new tasks context for action control. Only needed if you\n * want to isolate a tasks context, useful for libraries that want to provide\n * their own tasks context without interfering with the app's tasks context.\n *\n * Tasks added within this context are isolated from tasks in other contexts.\n *\n * @param props.children - The children to render within the tasks context.\n * @returns The children wrapped in a tasks context provider.\n */\nexport function Tasks({ children }: Props): React.ReactNode {\n const tasks = React.useMemo<Tasks>(() => new Set(), []);\n\n return <Context.Provider value={tasks}>{children}</Context.Provider>;\n}\n","import * as React from \"react\";\nimport type { RefObject } from \"react\";\nimport { G } from \"@mobily/ts-belt\";\nimport type { Env } from \"./types.ts\";\n\n/**\n * Internal singleton fallback used when `useEnv` is read outside any\n * `<Boundary>` (or `<Env>` provider). Reads see `{}`; writes through\n * `context.actions.produce(({ env }) => ...)` mutate this slot but\n * are not observed by any handler.\n *\n * @internal\n */\nconst fallback: RefObject<Env> = { current: <Env>{} };\n\n/**\n * React context exposing the per-Boundary Env ref. The ref itself is\n * stable across renders &mdash; readers grab `.current` at call time.\n *\n * @internal\n */\nexport const Context = React.createContext<RefObject<Env>>(fallback);\n\n/**\n * Hook that returns a read-only handle to the per-Boundary {@link Env}.\n * Reads use plain dot notation (`env.session`) and always reflect the\n * latest value, even after `await` boundaries &mdash; the handle is a\n * `Proxy` that delegates property access to the live ref.\n *\n * Writes are not exposed here. Mutate the Env inside an action handler\n * via `context.actions.produce(({ model, env }) => { env.x = ... })`\n * &mdash; the same Immer-style recipe used for the model. Mutations do\n * **not** trigger a re-render; drive view state through the model.\n *\n * Prefer `app.useEnv()` from an {@link App} instance &mdash; the App\n * factory infers the Env's shape from `app.env` and types every\n * read/write against it. The bare `useEnv()` exists for non-App\n * call sites and returns the loose {@link Env} record type.\n */\nexport function useEnv(): Env {\n const ref = React.useContext(Context);\n return React.useMemo<Env>(\n () =>\n new Proxy(<Env>{}, {\n get(_target, key) {\n return Reflect.get(ref.current, key);\n },\n has(_target, key) {\n return key in ref.current;\n },\n ownKeys() {\n return Reflect.ownKeys(ref.current);\n },\n getOwnPropertyDescriptor(_target, key) {\n const descriptor = Object.getOwnPropertyDescriptor(ref.current, key);\n if (G.isUndefined(descriptor)) return undefined;\n return { ...descriptor, configurable: true };\n },\n set() {\n throw new TypeError(\n \"Env is read-only outside `context.actions.produce`. \" +\n \"Mutate via produce(({ env }) => { env.x = ... }) instead.\",\n );\n },\n }),\n [ref],\n );\n}\n\n/**\n * Internal accessor for the per-Boundary Env ref &mdash; used by the\n * Resource layer to pass a fresh snapshot to each fetcher invocation\n * and by the action layer to write through `context.actions.produce`.\n * Not exported from the library.\n *\n * @internal\n */\nexport function useEnvRef(): RefObject<Env> {\n return React.useContext(Context);\n}\n","/**\n * Internal symbol description factories. Each function returns a namespaced\n * string suitable for `Symbol()` descriptions or `startsWith` checks.\n *\n * @internal\n */\nexport const describe = {\n /** Unicast action description. `describe.action(\"Fetch\")` &rarr; `\"march-hare.action/Fetch\"` */\n action: (name = \"\") => `march-hare.action/${name}`,\n /** Broadcast action description. `describe.broadcast(\"User\")` &rarr; `\"march-hare.action/broadcast/User\"` */\n broadcast: (name = \"\") => `march-hare.action/broadcast/${name}`,\n /** Multicast action description. `describe.multicast(\"Update\")` &rarr; `\"march-hare.action/multicast/Update\"` */\n multicast: (name = \"\") => `march-hare.action/multicast/${name}`,\n /** Channeled action description. `describe.channel(\"user\")` &rarr; `\"march-hare.channel/user\"` */\n channel: (name = \"\") => `march-hare.channel/${name}`,\n /** Cache entry description. `describe.cache(\"users\")` &rarr; `\"march-hare.cache/users\"` */\n cache: (name = \"\") => `march-hare.cache/${name}`,\n /** Lifecycle action description. `describe.lifecycle(\"Mount\")` &rarr; `\"march-hare.action.lifecycle/Mount\"` */\n lifecycle: (name = \"\") => `march-hare.action.lifecycle/${name}`,\n /** Mount replay sentinel description. Used to create the {@link replay} symbol. */\n replay: (name = \"\") => `march-hare/replay${name}`,\n};\n\n/**\n * Flat record used for shallow property comparison in {@link changes}.\n * @internal\n */\ntype Changes = Record<string, unknown>;\n\n/**\n * Get high-level changed paths between two objects.\n * Returns an object containing only the properties that were added or updated.\n *\n * @param previous - The previous state object\n * @param next - The next state object\n * @returns Object with changed property keys and their new values\n */\nexport function changes(previous: Changes, next: Changes): Changes {\n return <Changes>(\n Object.keys(next).reduce(\n (result, key) =>\n previous[key] !== next[key] ? { ...result, [key]: next[key] } : result,\n {},\n )\n );\n}\n","import * as React from \"react\";\nimport { Operation } from \"immertation\";\nimport { Process, Inspect as ImmInspect, Box } from \"immertation\";\nimport type {\n ActionId,\n Task,\n Tasks,\n} from \"../boundary/components/tasks/types.ts\";\nimport type { Fault } from \"../error/types.ts\";\nimport type { Env } from \"../boundary/components/env/types.ts\";\nimport type { Coalesce, Invocation } from \"../resource/types.ts\";\nimport type { WithHandle } from \"../with/types.ts\";\n\n/**\n * Bounded recursion depths for {@link Inspect}. Matches Immertation's\n * `DepthLimiter` shape so the two stay in lock-step.\n */\ntype DepthLimiter = [never, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12];\n\n/** Union of all keys across each arm of `T`. */\ntype UnionKeys<T> = T extends T ? keyof T : never;\n\n/** The value at `K` for each arm of `T`, falling back to `undefined` if `K` is absent on that arm. */\ntype ValueAt<T, K extends PropertyKey> = T extends T\n ? K extends keyof T\n ? T[K]\n : undefined\n : never;\n\n/**\n * March-hare's `Inspect<T>` wraps Immertation's so that property\n * navigation works when `T` is a discriminated union (e.g. the App's\n * Env union). For each key that appears on **any** union arm, the\n * resulting Inspect is `Inspect<ValueAt<T, K>>` &mdash; arms missing\n * the key contribute `undefined`, so optional chaining stays sound.\n *\n * For a single concrete `T`, the wrapper is transparent.\n */\nexport type Inspect<T, D extends number = 12> = ImmInspect<T> &\n ([D] extends [0]\n ? object\n : {\n [K in UnionKeys<T> as ValueAt<T, K> extends (\n ...args: unknown[]\n ) => unknown\n ? never\n : K]: Inspect<ValueAt<T, K>, DepthLimiter[D]>;\n });\n\n/**\n * Chainable handle returned from `context.actions.resource(invocation)`.\n *\n * - `.exceeds(duration)` short-circuits the fetch when the per-params\n * cache age is within the supplied freshness window.\n * - `.coalesce(token)` opts the call into in-flight sharing: any other\n * caller with the same Resource, same structural params, and equal\n * `token` joins the same promise.\n *\n * Awaiting the handle (`await context.actions.resource(...)`) triggers\n * the fetch with whichever options have been set on the chain.\n */\n/**\n * Fetch-configured chain returned from `.exceeds(...)` and\n * `.coalesce(...)`. Awaiting the chain runs the fetch with whichever\n * options are set; `.evict()` is intentionally absent because the\n * \"configured a fetch then evicted instead\" sequence has no coherent\n * meaning &mdash; eviction is always available off the bare\n * `context.actions.resource(...)` call.\n */\nexport type ResourceFetch<T> = PromiseLike<T> & {\n /**\n * Skip the fetch when the cached payload is within `duration`.\n * Accepts a `Temporal.Duration`, a `DurationLike` object\n * (`{ minutes: 5 }`), or an ISO 8601 string (`\"PT5M\"`).\n */\n readonly exceeds: (duration: Temporal.DurationLike) => ResourceFetch<T>;\n /**\n * Join an in-flight fetch for the same `(resource, params, token)`\n * tuple. The shared fetch runs against a detached `AbortController`\n * so a single caller's abort never cancels work other callers are\n * waiting on; each caller still sees its own `context.task.controller`\n * abort as a rejection of its personal await.\n *\n * `token` is optional &mdash; omit it to share with every other\n * untokened caller for the same `(resource, params)` slot.\n */\n readonly coalesce: (token?: Coalesce) => ResourceFetch<T>;\n};\n\n/**\n * Chainable handle returned from `context.actions.resource(invocation)`.\n * Either resolve to the fetched value (`.exceeds`/`.coalesce` + await)\n * or drop the cache slot (`.evict`) &mdash; the two paths are mutually\n * exclusive, so once `.exceeds` or `.coalesce` runs the chain narrows\n * to {@link ResourceFetch} and `.evict` is no longer available.\n */\nexport type ResourceCall<T> = ResourceFetch<T> & {\n /**\n * Drop cache entries for the primed resource without fetching. With\n * no argument, uses the params from the originating call as the\n * pattern. With an argument, evicts every stored entry whose params\n * satisfy the pattern's keys (partial match &mdash; extra keys in\n * the stored params are ignored).\n *\n * Strictly synchronous &mdash; the Adapter contract is sync, so the\n * warm-start `Map` and the user adapter both settle in the current\n * tick. Async backends fire-and-forget their underlying delete from\n * inside the adapter body; the call site doesn't `await` anything.\n *\n * The `where` pattern is typed as `Record<string, unknown>` rather\n * than `Partial<P>` because the resource's params type `P` isn't\n * threaded through the chain. Pass the literal you'd pass to the\n * underlying fetcher &mdash; TypeScript won't catch typos in pattern\n * keys, so prefer the no-argument form when possible.\n *\n * ```ts\n * // Drop the {id: 5} slot.\n * context.actions.resource(resource.user({ id: 5 })).evict();\n *\n * // Drop every user slot whose stored params include name \"Adam\".\n * context.actions.resource(resource.user()).evict({ name: \"Adam\" });\n * ```\n */\n readonly evict: (where?: Record<string, unknown>) => void;\n};\nimport { describe } from \"../utils.ts\";\n\nexport type { ActionId, Box, Task, Tasks };\n/**\n * Type for objects with a Brand.Action symbol property.\n * Used for type-safe access to the action symbol.\n */\nexport type BrandedAction = { readonly [K in typeof Brand.Action]: symbol };\n\n/**\n * Type for objects with a Brand.Broadcast symbol property.\n * Used for type-safe access to the broadcast flag.\n */\nexport type BrandedBroadcast = {\n readonly [K in typeof Brand.Broadcast]: boolean;\n};\n\n/**\n * Type for objects with a Brand.Multicast symbol property.\n * Used for type-safe access to the multicast flag.\n */\nexport type BrandedMulticast = {\n readonly [K in typeof Brand.Multicast]: boolean;\n};\n\n/**\n * Base type for any object that may contain branded symbol properties.\n * Used as a permissive input type for action utilities.\n */\nexport type BrandedObject = { readonly [x: symbol]: unknown };\n\n/**\n * Recursive readonly. Locks every nested property so that read-only\n * projections on `context` (model, data, env) reject direct assignment\n * &mdash; mutation must go through `context.actions.produce(...)`.\n *\n * Function types pass through untouched so method calls (e.g.\n * `AbortController#abort`) remain callable. Built-in mutable containers\n * are mapped to their readonly counterparts.\n *\n * @internal\n */\nexport type DeepReadonly<T> = T extends (...args: never) => unknown\n ? T\n : T extends ReadonlyArray<infer U>\n ? ReadonlyArray<DeepReadonly<U>>\n : T extends ReadonlyMap<infer K, infer V>\n ? ReadonlyMap<DeepReadonly<K>, DeepReadonly<V>>\n : T extends ReadonlySet<infer U>\n ? ReadonlySet<DeepReadonly<U>>\n : T extends object\n ? { readonly [K in keyof T]: DeepReadonly<T[K]> }\n : T;\n\n/**\n * Union type representing any valid action that can be passed to action utilities.\n * This includes raw ActionIds (symbol/string), and any branded object.\n */\nexport type AnyAction = ActionId | BrandedObject;\n\n/**\n * Internal symbols used as brand keys to distinguish typed objects at runtime.\n * These enable TypeScript to differentiate between HandlerPayload, BroadcastPayload,\n * and channeled actions through branded types.\n * @internal\n */\nexport class Brand {\n /** Brand key for HandlerPayload type */\n static readonly Payload = Symbol(\"march-hare.brand/Payload\");\n /** Brand key for BroadcastPayload type */\n static readonly Broadcast = Symbol(\"march-hare.brand/Broadcast\");\n /** Brand key for MulticastPayload type */\n static readonly Multicast = Symbol(\"march-hare.brand/Multicast\");\n /** Access the underlying symbol from an action */\n static readonly Action = Symbol(\"march-hare.brand/Action\");\n /** Identifies channeled actions (result of calling Action(channel)) */\n static readonly Channel = Symbol(\"march-hare.brand/Channel\");\n /**\n * Phantom brand carrying the action's literal name. Used purely at the\n * type level to make `Action(\"X\")` and `Action(\"Y\")` produce\n * structurally-distinct types so `dispatch`/`useAction` can reject\n * symbols imported from a class outside `AC`.\n */\n static readonly Name = Symbol(\"march-hare.brand/Name\");\n /**\n * Phantom brand identifying lifecycle actions returned by\n * `Lifecycle.Mount()`, `Lifecycle.Unmount()`, `Lifecycle.Error()`, and\n * `Lifecycle.Update()`. Carries the lifecycle's literal kind so that\n * `useAction` can pick distinct overloads &mdash; in particular,\n * `Lifecycle.Update` resolves its payload to `Partial<DeepReadonly<D>>`\n * against the surrounding `useActions` data generic instead of the\n * factory-level `Record<string, unknown>` placeholder. Without this\n * brand a user-defined `Action<P>(\"Update\")` would collide with the\n * lifecycle overload.\n */\n static readonly Lifecycle = Symbol(\"march-hare.brand/Lifecycle\");\n}\n\n/**\n * Creates a lifecycle action with the given name.\n * Produces a branded `HandlerPayload` backed by a fresh\n * `Symbol(\"march-hare.action.lifecycle/${name}\")` on each call.\n *\n * @internal\n */\nfunction createLifecycleAction<\n P = never,\n C extends Filter = never,\n K extends string = string,\n>(name: K): LifecyclePayload<P, C, K> {\n const symbol = Symbol(`march-hare.action.lifecycle/${name}`);\n const action = function (channel: C): ChanneledAction<P, C, K> {\n return {\n [Brand.Action]: symbol,\n [Brand.Payload]: <P>undefined,\n [Brand.Channel]: channel,\n [Brand.Name]: name,\n channel,\n };\n };\n // eslint-disable-next-line fp/no-mutating-methods\n Object.defineProperty(action, Brand.Action, {\n value: symbol,\n enumerable: false,\n });\n // eslint-disable-next-line fp/no-mutating-methods\n Object.defineProperty(action, Brand.Payload, {\n value: undefined,\n enumerable: false,\n });\n // eslint-disable-next-line fp/no-mutating-methods\n Object.defineProperty(action, Brand.Name, { value: name, enumerable: false });\n // eslint-disable-next-line fp/no-mutating-methods\n Object.defineProperty(action, Brand.Lifecycle, {\n value: name,\n enumerable: false,\n });\n return <LifecyclePayload<P, C, K>>action;\n}\n\n/**\n * Internal symbol for the global `Lifecycle.Fault` broadcast. Exposed so the\n * dispatch pipeline can fire faults without depending on the `Lifecycle`\n * class at runtime.\n *\n * @internal\n */\nexport const FaultSymbol: unique symbol = <typeof FaultSymbol>(\n Symbol(describe.broadcast(\"Fault\"))\n);\n\n/**\n * Internal symbol for the global `Lifecycle.Env` broadcast. The env\n * mutation path in `useActions` fires this symbol whenever a\n * `produce({ env })` call changes the slot reference.\n *\n * @internal\n */\nexport const EnvSymbol: unique symbol = <typeof EnvSymbol>(\n Symbol(describe.broadcast(\"Env\"))\n);\n\n/**\n * Factory functions for lifecycle actions.\n *\n * Each call returns a **unique** action symbol so that each component can\n * subscribe independently. Assign the result as a static property in your\n * Actions class:\n *\n * @example\n * ```ts\n * export class Actions {\n * static Mount = Lifecycle.Mount();\n * static Unmount = Lifecycle.Unmount();\n * static Error = Lifecycle.Error();\n * static Update = Lifecycle.Update();\n *\n * static Increment = Action(\"Increment\");\n * }\n * ```\n *\n * `Lifecycle.Fault` and `Lifecycle.Env` are singleton broadcasts (not\n * factories). All components subscribe to the same shared symbol &mdash;\n * `Fault` delivers global fault notifications, `Env` delivers per-`Boundary`\n * env-change notifications.\n */\nexport class Lifecycle {\n /** Creates a Mount lifecycle action. Triggered once on component mount (`useLayoutEffect`). */\n static Mount(): LifecyclePayload<never, never, \"Mount\"> {\n return createLifecycleAction<never, never, \"Mount\">(\"Mount\");\n }\n\n /** Creates an Unmount lifecycle action. Triggered when the component unmounts. */\n static Unmount(): LifecyclePayload<never, never, \"Unmount\"> {\n return createLifecycleAction<never, never, \"Unmount\">(\"Unmount\");\n }\n\n /** Creates an Error lifecycle action. Triggered when an action throws. Receives `Fault` as payload. */\n static Error(): LifecyclePayload<Fault, never, \"Error\"> {\n return createLifecycleAction<Fault, never, \"Error\">(\"Error\");\n }\n\n /**\n * Creates an Update lifecycle action. Triggered when `context.data` changes\n * (not on initial mount). The handler payload is typed as\n * `Partial<DeepReadonly<D>>` at the subscription site &mdash; only the keys\n * whose values changed between the previous and current render are present.\n */\n static Update(): LifecyclePayload<Record<string, unknown>, never, \"Update\"> {\n return createLifecycleAction<Record<string, unknown>, never, \"Update\">(\n \"Update\",\n );\n }\n\n /**\n * Global fault broadcast. Receives a `Fault` whenever any action in the\n * `<Boundary>` errors, times out, or is supplanted. Subscribe via\n * `actions.useAction(Lifecycle.Fault, handler)`.\n *\n * Unlike the per-component `Lifecycle.Error()` factory, `Fault` is a single\n * shared broadcast — every subscriber points at the same symbol.\n *\n * @example\n * ```tsx\n * const actions = useActions<void, typeof Actions>();\n *\n * actions.useAction(Lifecycle.Fault, (context, fault) => {\n * if (fault.reason === Reason.Errored) {\n * console.error(`Action \"${fault.action}\" failed`, fault.error);\n * }\n * });\n * ```\n */\n static Fault: BroadcastPayload<Fault, never, \"Fault\"> = (() => {\n const action: Record<symbol, unknown> = {};\n // eslint-disable-next-line fp/no-mutating-methods\n Object.defineProperty(action, Brand.Action, {\n value: FaultSymbol,\n enumerable: false,\n });\n // eslint-disable-next-line fp/no-mutating-methods\n Object.defineProperty(action, Brand.Payload, {\n value: undefined,\n enumerable: false,\n });\n // eslint-disable-next-line fp/no-mutating-methods\n Object.defineProperty(action, Brand.Broadcast, {\n value: true,\n enumerable: false,\n });\n // eslint-disable-next-line fp/no-mutating-methods\n Object.defineProperty(action, Brand.Name, {\n value: \"Fault\",\n enumerable: false,\n });\n return <BroadcastPayload<Fault, never, \"Fault\">>(<unknown>action);\n })();\n\n /**\n * Global env-change broadcast. Receives the latest {@link Env}\n * snapshot whenever a `context.actions.produce(({ env }) => ...)` call\n * mutates the slot. Subscribe via\n * `actions.useAction(Lifecycle.Env, handler)` &mdash; or render against\n * it directly with `actions.stream(Lifecycle.Env, (env) => ...)`.\n *\n * Like `Lifecycle.Fault`, this is a singleton broadcast (not a factory):\n * every subscriber points at the same shared symbol. The latest value is\n * cached on the broadcast emitter so that late-mounting handlers and\n * streams receive the current env on mount.\n *\n * @example\n * ```tsx\n * actions.useAction(Lifecycle.Env, (context, env) => {\n * console.log(\"env changed\", env);\n * });\n *\n * // In JSX:\n * {actions.stream(Lifecycle.Env, (env) => (\n * <span>{env.locale}</span>\n * ))}\n * ```\n */\n static Env: BroadcastPayload<Env, never, \"Env\"> = (() => {\n const action: Record<symbol, unknown> = {};\n // eslint-disable-next-line fp/no-mutating-methods\n Object.defineProperty(action, Brand.Action, {\n value: EnvSymbol,\n enumerable: false,\n });\n // eslint-disable-next-line fp/no-mutating-methods\n Object.defineProperty(action, Brand.Payload, {\n value: undefined,\n enumerable: false,\n });\n // eslint-disable-next-line fp/no-mutating-methods\n Object.defineProperty(action, Brand.Broadcast, {\n value: true,\n enumerable: false,\n });\n // eslint-disable-next-line fp/no-mutating-methods\n Object.defineProperty(action, Brand.Name, {\n value: \"Env\",\n enumerable: false,\n });\n return <BroadcastPayload<Env, never, \"Env\">>(<unknown>action);\n })();\n}\n\n/**\n * Distribution modes for actions.\n *\n * - **Unicast** &ndash; Action is scoped to the component that defines it and cannot be\n * consumed by other components. This is the default behaviour.\n * - **Broadcast** &ndash; Action is distributed to all mounted components that have\n * defined a handler for it. Values are cached for late-mounting components.\n * - **Multicast** &ndash; Action defines its own scope. Components reach it by\n * rendering inside a `<scope.Boundary>` produced by `app.Scope<MulticastActions>()`.\n *\n * @example\n * ```ts\n * export class MulticastActions {\n * static Mood = Action<Mood>(\"Mood\", Distribution.Multicast);\n * }\n *\n * export const scope = app.Scope<typeof MulticastActions>();\n *\n * // Wrap the subtree where the scope applies.\n * export default function Mood() {\n * return (\n * <scope.Boundary>\n * <Happy />\n * <Sad />\n * </scope.Boundary>\n * );\n * }\n *\n * // Dispatch / subscribe — no extra options.\n * actions.dispatch(MulticastActions.Mood, mood);\n * actions.useAction(MulticastActions.Mood, (context, mood) => { ... });\n * ```\n */\nexport enum Distribution {\n /** Action is scoped to the component that defines it. This is the default. */\n Unicast = \"unicast\",\n /** Action is broadcast to all mounted components and can be consumed. */\n Broadcast = \"broadcast\",\n /** Action is multicast to every component inside its `<scope.Boundary>`. */\n Multicast = \"multicast\",\n}\n\n/**\n * Lifecycle phase of a component using useActions.\n * Tracks whether the component is in the process of mounting, fully mounted,\n * unmounting, or completely unmounted.\n *\n * @example\n * ```ts\n * actions.useAction(Actions.Counter, (context, payload) => {\n * if (context.phase === Phase.Mounting) {\n * // Handler called during mount (e.g., cached distributed action value)\n * } else if (context.phase === Phase.Mounted) {\n * // Handler called after component is fully mounted\n * }\n * });\n * ```\n */\nexport enum Phase {\n /** Component is in the process of mounting (before useLayoutEffect completes). */\n Mounting = \"mounting\",\n /** Component has fully mounted (after useLayoutEffect). */\n Mounted = \"mounted\",\n /** Component is in the process of unmounting. */\n Unmounting = \"unmounting\",\n /** Component has fully unmounted. */\n Unmounted = \"unmounted\",\n}\n\n/**\n * Primary key type for identifying entities in collections.\n * Can be undefined (not yet assigned), a symbol (temporary/local), or a concrete value T.\n *\n * @template T - The concrete primary key type (e.g., string, number)\n */\nexport type Pk<T> = undefined | symbol | T;\n\n/**\n * Maybe-present field type &mdash; a value that may be a concrete `T`,\n * or `null` / `undefined` while loading, awaiting a fetch, or before\n * upstream data has arrived. Use this for model fields whose presence\n * is determined by async or external state.\n *\n * @template T - The concrete value type\n */\nexport type Maybe<T> = T | null | undefined;\n\n/**\n * Base constraint type for model state objects.\n * Models must be plain objects with string keys.\n *\n * @template M - The specific model shape\n */\nexport type Model<M = Record<string, unknown>> = M;\n\n/**\n * Branded type for action objects created with `Action()`.\n * The phantom type parameters carry the payload and channel types at the type level.\n *\n * Actions wrap an internal symbol (used as event emitter keys) in a callable object.\n * When a channel type is specified, the action can be called to create a channeled dispatch.\n *\n * @template P - The payload type for the action\n * @template C - The channel type for channeled dispatches (defaults to never = no channel)\n *\n * @example\n * ```ts\n * // Action without channel support\n * const Increment = Action<number>(\"Increment\");\n * dispatch(Increment, 5);\n *\n * // Action with channel support\n * const UserUpdated = Action<User, { UserId: number }>(\"UserUpdated\");\n * dispatch(UserUpdated, user); // broadcast to all handlers\n * dispatch(UserUpdated({ UserId: 5 }), user); // channeled dispatch\n * ```\n */\nexport type HandlerPayload<\n P = unknown,\n C extends Filter = never,\n Name extends string = string,\n> = {\n readonly [Brand.Action]: symbol;\n readonly [Brand.Payload]: P;\n readonly [Brand.Name]: Name;\n readonly [Brand.Broadcast]?: boolean;\n} & ([C] extends [never]\n ? unknown\n : {\n (channel: C): ChanneledAction<P, C, Name>;\n });\n\n/**\n * Branded type returned by `Lifecycle.Mount`, `Lifecycle.Unmount`,\n * `Lifecycle.Error`, and `Lifecycle.Update`. Structurally identical to a\n * `HandlerPayload` but carries a phantom `Brand.Lifecycle` brand whose value\n * is the lifecycle's literal kind. The brand is what lets `useAction` and\n * `Handlers` resolve `Lifecycle.Update`'s payload to `Partial<DeepReadonly<D>>`\n * (against the surrounding `useActions` data generic) instead of the\n * factory-level `Record<string, unknown>` placeholder &mdash; a user-defined\n * `Action<P>(\"Update\")` would have `Name = \"Update\"` but no `Brand.Lifecycle`,\n * so it falls into the generic payload overload as expected.\n *\n * @template P Payload type for the lifecycle.\n * @template C Channel filter (always `never` for lifecycles &mdash; they are\n * not channeled).\n * @template Name Literal name (`\"Mount\"`, `\"Unmount\"`, `\"Error\"`, `\"Update\"`).\n */\nexport type LifecyclePayload<\n P = unknown,\n C extends Filter = never,\n Name extends string = string,\n> = HandlerPayload<P, C, Name> & {\n readonly [Brand.Lifecycle]: Name;\n};\n\n/**\n * Result of calling an action with a channel argument.\n * Contains the action reference and the channel data for filtered dispatch.\n *\n * @template P - The payload type for the action\n * @template C - The channel type\n *\n * @example\n * ```ts\n * const UserUpdated = Action<User, { UserId: number }>(\"UserUpdated\");\n *\n * // UserUpdated({ UserId: 5 }) returns ChanneledAction<User, { UserId: number }>\n * dispatch(UserUpdated({ UserId: 5 }), user);\n * ```\n */\nexport type ChanneledAction<\n P = unknown,\n C = unknown,\n Name extends string = string,\n> = {\n readonly [Brand.Action]: symbol;\n readonly [Brand.Payload]: P;\n readonly [Brand.Channel]: C;\n readonly [Brand.Name]: Name;\n readonly channel: C;\n};\n\n/**\n * Branded type for broadcast action objects created with `Action()` and `Distribution.Broadcast`.\n * Broadcast actions are sent to all mounted components. Values are cached so that\n * late-mounting components receive the most recent payload.\n *\n * Late-mounting components receive the most recent cached payload via their\n * `useAction` handler during mount. Use `peek()` in a `Lifecycle.Mount` handler\n * to check whether a cached value exists before performing default fetches.\n *\n * This type extends `HandlerPayload<P, C>` with an additional brand to enforce at compile-time\n * that only broadcast actions can be passed to `context.actions.final()`.\n *\n * @template P - The payload type for the action\n * @template C - The channel type for channeled dispatches (defaults to never)\n *\n * @example\n * ```ts\n * const SignedOut = Action<User>(\"SignedOut\", Distribution.Broadcast);\n *\n * // Resolve the latest value inside a handler\n * const user = await context.actions.final(SignedOut);\n * ```\n */\nexport type BroadcastPayload<\n P = unknown,\n C extends Filter = never,\n Name extends string = string,\n> = HandlerPayload<P, C, Name> & {\n readonly [Brand.Broadcast]: true;\n};\n\n/**\n * Branded type for multicast action objects created with `Action()` and `Distribution.Multicast`.\n * Multicast actions are dispatched to all components within a named scope boundary.\n *\n * When dispatching a multicast action, you MUST provide the scope name as the third argument:\n * ```ts\n * actions.dispatch(Actions.Multicast.Update, payload, { scope: Actions.Multicast.Scope });\n * ```\n *\n * Components receive multicast events only if they are descendants of a `<Scope of={...}>`.\n *\n * @template P - The payload type for the action\n * @template C - The channel type for channeled dispatches (defaults to never)\n *\n * @example\n * ```tsx\n * export enum Scope {\n * Counter = \"counter\",\n * }\n *\n * class MulticastActions {\n * static Update = Action<number>(\"Update\", Distribution.Multicast(Scope.Counter));\n * }\n *\n * // Reference from component-level Actions\n * class Actions {\n * static Multicast = MulticastActions;\n * }\n *\n * // Wrap the subtree where the scope applies via the withScope HOC.\n * export default withScope(Scope.Counter, function Counters() {\n * return (\n * <>\n * <CounterA />\n * <CounterB />\n * </>\n * );\n * });\n *\n * // Dispatch — the scope is read from the action itself.\n * actions.dispatch(Actions.Multicast.Update, 42);\n * ```\n */\nexport type MulticastPayload<\n P = unknown,\n C extends Filter = never,\n Name extends string = string,\n> = HandlerPayload<P, C, Name> & {\n readonly [Brand.Multicast]: true;\n};\n\n/**\n * Extracts the payload type `P` from a `HandlerPayload<P>` or `ChanneledAction<P, C>`.\n * Use this in handler signatures to get the action's payload type.\n *\n * Works with both plain actions and channeled actions:\n * - `Payload<Action<User>>` → `User`\n * - `Payload<ChanneledAction<User, { UserId: number }>>` → `User`\n *\n * @template A - The action type (HandlerPayload or ChanneledAction)\n */\n\nexport type Payload<A> = A extends { readonly [Brand.Payload]: infer P }\n ? P\n : never;\n\n/**\n * Filter object for channeled actions.\n * Must be an object where each value is a non-nullable primitive.\n *\n * By convention, use uppercase keys (e.g., `{UserId: 4}` not `{userId: 4}`)\n * to distinguish filter keys from payload properties.\n *\n * When dispatching, handlers are invoked if ALL properties in the dispatch filter\n * match the corresponding properties in the registered filter.\n *\n * @example\n * ```ts\n * // Register a handler for a specific user\n * actions.useAction([Actions.User, { UserId: 1 }], handler);\n *\n * // Dispatch matches if all dispatch properties match registered properties\n * dispatch([Actions.User, { UserId: 1 }], payload); // Matches\n * dispatch([Actions.User, { UserId: 2 }], payload); // No match\n * dispatch([Actions.User, { UserId: 1, Role: \"admin\" }], payload); // Matches\n * dispatch([Actions.User, {}], payload); // Matches all\n * dispatch(Actions.User, payload); // Matches ALL handlers\n * ```\n */\nexport type Filter = Record<\n string,\n string | number | bigint | boolean | symbol\n>;\n\n/**\n * Union type representing either a plain action or a channeled action.\n * Used in `useAction` and `dispatch` signatures to accept both forms.\n *\n * @template A - The action type\n *\n * @example\n * ```ts\n * class Actions {\n * static UserUpdated = Action<User, { UserId: number }>(\"UserUpdated\", Distribution.Broadcast);\n * }\n *\n * // Subscribe to updates for a specific user (channeled)\n * actions.useAction(Actions.UserUpdated({ UserId: props.userId }), (context, user) => {\n * context.actions.produce((draft) => {\n * draft.model.user = user;\n * });\n * });\n *\n * // Dispatch to specific user (channeled)\n * actions.dispatch(Actions.UserUpdated({ UserId: user.id }), user);\n *\n * // Dispatch to ALL handlers (plain)\n * actions.dispatch(Actions.UserUpdated, user);\n * ```\n */\nexport type ActionOrChanneled<A extends HandlerPayload = HandlerPayload> =\n | A\n | ChanneledAction;\n\n/**\n * Type guard that produces a compile-time error if an async function is\n * passed. Used to enforce synchronous callbacks in `produce()`.\n *\n * The `[F]` tuple wrapping prevents distribution over function unions, and\n * checking the actual signature (`(...args: never[]) => Promise<unknown>`)\n * sidesteps TypeScript's lenient `Promise<void>`→`void` assignability that\n * would otherwise let an async recipe satisfy a `(draft) => void`\n * constraint. Async F collapses the argument type to `never`, which no\n * function value can satisfy.\n *\n * @internal\n */\ntype AssertSync<F> = [F] extends [(...args: never[]) => Promise<unknown>]\n ? never\n : F;\n\n/**\n * Base type for data props passed to useActions.\n * Represents any object that can be captured as reactive data.\n */\nexport type Props = Record<string, unknown>;\n\n/**\n * Constraint type for action containers.\n * Actions are symbols grouped in an object (typically a class with static properties).\n */\nexport type Actions = object;\n\n/**\n * Internal result container for tracking Immertation processes during action execution.\n * @internal\n */\nexport type Result = {\n processes: Set<Process>;\n};\n\nexport type HandlerContext<\n M extends Model | void,\n AC extends Actions | void,\n D extends Props = Props,\n E extends Env = Env,\n> = {\n readonly model: DeepReadonly<M>;\n readonly phase: Phase;\n readonly task: Task;\n readonly data: DeepReadonly<D>;\n readonly tasks: ReadonlySet<Task>;\n readonly env: Readonly<E>;\n readonly actions: {\n produce<\n F extends (draft: {\n model: M;\n env: E;\n readonly inspect: Readonly<Inspect<M>>;\n }) => void,\n >(\n ƒ: F & AssertSync<F>,\n ): void;\n dispatch(action: NoPayloadActions<Dispatchable<AC>>): Promise<void>;\n dispatch<A extends WithPayloadActions<Dispatchable<AC>>>(\n action: A,\n payload: Payload<A>,\n ): Promise<void>;\n annotate<T>(value: T, operation?: Operation): T;\n readonly inspect: Readonly<Inspect<M>>;\n resource: (<T, P extends object>(\n invocation: Invocation<T, P>,\n ) => ResourceCall<T>) & {\n nuke(where?: Record<string, unknown>): void;\n };\n final<T>(\n action: BroadcastPayload<T> | MulticastPayload<T>,\n ): Promise<T | null>;\n peek<T>(action: BroadcastPayload<T> | MulticastPayload<T>): T | null;\n };\n};\n\n/**\n * Return type for the useActions hook.\n *\n * A tuple containing:\n * 1. The current model state of type M\n * 2. An actions object with dispatch and inspect capabilities\n * 3. The current data snapshot of type D &mdash; the same React-owned values\n * that handlers read via `context.data`, exposed here for JSX consumption\n * so the view and the handler share a single named source of truth.\n *\n * @template M - The model type representing the component's state\n * @template AC - The actions class containing action definitions\n * @template D - The data type for reactive external values\n *\n * @example\n * ```tsx\n * const [model, actions, data] = useActions<Model, typeof Actions, Data>(\n * model,\n * () => ({ user, theme }),\n * );\n *\n * // Access state\n * model.count;\n *\n * // Dispatch actions\n * actions.dispatch(Actions.Increment, 5);\n *\n * // Read React-owned dependencies in JSX (same values as context.data)\n * data.user.name;\n *\n * // Check pending state\n * actions.inspect.count.pending();\n * ```\n */\n/**\n * Utility type for defining a single action handler function.\n * Use this when you need to type a specific handler directly.\n *\n * @template M - The model type\n * @template AC - The actions class type\n * @template K - The action key (keyof AC) — determines payload type via lookup\n * @template D - Optional data/props type (defaults to Props)\n *\n * @see {@link Handlers} for the recommended HKT pattern\n */\nexport type Handler<\n M extends Model | void,\n AC extends Actions | void,\n K extends keyof AC & string,\n D extends Props = Props,\n E extends Env = Env,\n> = (\n context: HandlerContext<M, AC, D, E>,\n ...args: [Payload<AC[K] & HandlerPayload<unknown>>] extends [never]\n ? []\n : [payload: Payload<AC[K] & HandlerPayload<unknown>>]\n) => void | Promise<void> | AsyncGenerator | Generator;\n\n/**\n * String keys of `AC` excluding inherited `prototype` from class constructors.\n * When action containers are classes (`typeof MyActions`), TypeScript includes\n * `\"prototype\"` in `keyof`. Excluding it prevents `prototype` from appearing\n * as a handler key and avoids recursion into Function internals.\n */\ntype OwnKeys<AC> = Exclude<keyof AC & string, \"prototype\">;\n\n/**\n * Recursively flattens an actions class into the union of its leaf action\n * types. A \"leaf\" is any property whose own string keys are empty &mdash; the\n * branded `HandlerPayload` / `BroadcastPayload` / `MulticastPayload` values\n * produced by `Action(...)` and `Lifecycle.*()`. Nested namespace classes\n * (e.g. `static Broadcast = BroadcastActions`) are descended into.\n *\n * Used to constrain `dispatch` and `useAction` so that only actions owned by\n * the component's `AC` (plus the global `Lifecycle.Fault` /\n * `Lifecycle.Env`) can be referenced.\n */\nexport type LeafActions<AC> = AC extends void\n ? never\n : {\n [K in OwnKeys<AC>]: OwnKeys<AC[K]> extends never\n ? AC[K]\n : LeafActions<AC[K]>;\n }[OwnKeys<AC>];\n\n/**\n * Maps each action in a union to its channeled-call variant, when one exists.\n * Distributes over unions so a mixed bag of leaf actions produces the union\n * of their `ChanneledAction<P, C>` results.\n */\nexport type ChanneledOf<A> =\n A extends HandlerPayload<infer P, infer C>\n ? [C] extends [never]\n ? never\n : ChanneledAction<P, C>\n : never;\n\n/**\n * Everything `dispatch` accepts for a given `AC`: leaf actions on the class\n * and their channeled-call variants. The shared `Lifecycle.Fault` broadcast\n * is excluded — it's library-internal and not user-dispatchable.\n */\nexport type Dispatchable<AC> = LeafActions<AC> | ChanneledOf<LeafActions<AC>>;\n\n/**\n * Everything `useAction` will subscribe to for a given `AC`: same as\n * `Dispatchable<AC>` plus the shared `Lifecycle.Fault` and `Lifecycle.Env`\n * broadcasts which live outside `AC` but are subscribable by any component.\n */\nexport type Subscribable<AC> =\n | Dispatchable<AC>\n | typeof Lifecycle.Fault\n | typeof Lifecycle.Env;\n\n/**\n * Subset of a union of actions whose payload type is `never`. Used to split\n * `dispatch`/`useAction` into a no-payload and a with-payload overload so\n * TypeScript reports a clear \"no overload matches\" error instead of widening\n * the inferred action type when constraints don't match.\n */\nexport type NoPayloadActions<U> = Extract<\n U,\n { readonly [Brand.Payload]: never }\n>;\n\n/** Subset of a union of actions whose payload type is non-`never`. */\nexport type WithPayloadActions<U> = Exclude<\n U,\n { readonly [Brand.Payload]: never }\n>;\n\n/**\n * Recursive mapped type for action handlers that mirrors the action class hierarchy.\n *\n * For leaf actions (values with no own string keys, i.e. `HandlerPayload`), produces\n * a handler function signature. For namespace objects (containing nested actions),\n * produces a nested `Handlers` object.\n *\n * Access handlers using bracket notation matching the action structure:\n *\n * @template M - The model type\n * @template AC - The actions class type\n * @template D - Optional data/props type (defaults to Props)\n *\n * @example\n * ```ts\n * import { Action, Distribution, type Handlers } from \"march-hare\";\n *\n * class BroadcastActions {\n * static PaymentSent = Action(\"PaymentSent\", Distribution.Broadcast);\n * static PaymentLink = Action<PaymentLinkData>(\n * \"PaymentLink\",\n * Distribution.Broadcast,\n * );\n * }\n *\n * class Actions {\n * static SetName = Action<string>(\"SetName\");\n * static Broadcast = BroadcastActions;\n * }\n *\n * type H = Handlers<Model, typeof Actions>;\n *\n * // Flat actions\n * export const handleSetName: H[\"SetName\"] = (context, name) => { ... };\n *\n * // Nested actions use chained bracket notation\n * export const handlePaymentSent: H[\"Broadcast\"][\"PaymentSent\"] = (context) => { ... };\n * ```\n */\nexport type Handlers<\n M extends Model | void,\n AC extends Actions | void,\n D extends Props = Props,\n RootAC extends Actions | void = AC,\n E extends Env = Env,\n> = {\n [K in OwnKeys<AC>]: OwnKeys<AC[K]> extends never\n ? AC[K] extends { readonly [Brand.Lifecycle]: \"Update\" }\n ? (\n context: HandlerContext<M, RootAC, D, E>,\n changes: Partial<DeepReadonly<D>>,\n ) => void | Promise<void> | AsyncGenerator | Generator\n : (\n context: HandlerContext<M, RootAC, D, E>,\n ...args: [Payload<AC[K] & HandlerPayload<unknown>>] extends [never]\n ? []\n : [payload: Payload<AC[K] & HandlerPayload<unknown>>]\n ) => void | Promise<void> | AsyncGenerator | Generator\n : Handlers<M, AC[K] & Actions, D, RootAC, E>;\n};\n\nexport type UseActions<\n M extends Model | void,\n AC extends Actions | void,\n D extends Props = Props,\n E extends Env = Env,\n> = [\n Readonly<M>,\n {\n /**\n * Dispatches an action with an optional payload. Multicast actions read\n * their scope from the action declaration, so no extra options are\n * required at the call site.\n */\n dispatch(action: NoPayloadActions<Dispatchable<AC>>): Promise<void>;\n dispatch<A extends WithPayloadActions<Dispatchable<AC>>>(\n action: A,\n payload: Payload<A>,\n ): Promise<void>;\n inspect: Inspect<M>;\n /**\n * Streams broadcast values declaratively in JSX using a render-prop pattern.\n *\n * Subscribes to the given broadcast action and re-renders when a new value\n * is dispatched. Returns `null` until the first dispatch. The renderer\n * receives the value and an inspect proxy for annotation tracking.\n *\n * @param action - The broadcast action to subscribe to.\n * @param renderer - Callback that receives value and inspect, returns React nodes.\n * @returns React nodes from the renderer, or null if no value has been dispatched.\n *\n * @example\n * ```tsx\n * return (\n * <div>\n * {actions.stream(Actions.Broadcast.User, (user, inspect) => (\n * <span>{user.name}</span>\n * ))}\n * </div>\n * );\n * ```\n */\n stream(\n action: typeof Lifecycle.Env,\n renderer: (value: Readonly<E>, inspect: Inspect<E>) => React.ReactNode,\n ): React.ReactNode;\n stream<T extends object>(\n action: BroadcastPayload<T>,\n renderer: (value: T, inspect: Inspect<T>) => React.ReactNode,\n ): React.ReactNode;\n },\n DeepReadonly<D>,\n] & {\n /**\n * Dispatches an action with an optional payload &mdash; same as\n * `result[1].dispatch`, exposed on the tuple itself so call sites that\n * already have `actions` in scope can write `actions.dispatch(...)`\n * without indexing into `actions[1]`.\n */\n dispatch(action: NoPayloadActions<Dispatchable<AC>>): Promise<void>;\n dispatch<A extends WithPayloadActions<Dispatchable<AC>>>(\n action: A,\n payload: Payload<A>,\n ): Promise<void>;\n\n /**\n * Registers an action handler with the current scope.\n * Types are pre-baked from the `channel.use(...)` call, so no type\n * parameter is needed.\n *\n * Supports two subscription patterns:\n * 1. **Plain action** - Receives ALL dispatches for that action (including channeled ones)\n * 2. **Channeled action** `Action(channel)` - Receives only dispatches matching the channel\n *\n * @param action - The action or channeled action (e.g., `Action({ UserId: 1 })`)\n * @param handler - The handler function receiving context and payload\n *\n * @example\n * ```ts\n * const context = useContext<Model, typeof Actions>();\n * const actions = context.useActions(model);\n *\n * // Subscribe to ALL UserUpdated events\n * actions.useAction(Actions.UserUpdated, (context, user) => {\n * // Fires for any UserUpdated dispatch\n * });\n *\n * // Subscribe to UserUpdated for a specific user only (channeled)\n * actions.useAction(Actions.UserUpdated({ UserId: props.userId }), (context, user) => {\n * // Only fires when dispatched with matching channel\n * });\n * ```\n */\n useAction(\n action: NoPayloadActions<Subscribable<AC>>,\n handler: (\n context: HandlerContext<M, AC, D, E>,\n ) => void | Promise<void> | AsyncGenerator | Generator,\n ): void;\n useAction(\n action: typeof Lifecycle.Env,\n handler: (\n context: HandlerContext<M, AC, D, E>,\n env: Readonly<E>,\n ) => void | Promise<void> | AsyncGenerator | Generator,\n ): void;\n useAction<\n A extends Extract<\n Subscribable<AC>,\n { readonly [Brand.Lifecycle]: \"Update\" }\n >,\n >(\n action: A,\n handler: (\n context: HandlerContext<M, AC, D, E>,\n changes: Partial<DeepReadonly<D>>,\n ) => void | Promise<void> | AsyncGenerator | Generator,\n ): void;\n useAction<A extends WithPayloadActions<Subscribable<AC>>>(\n action: A,\n handler: (\n context: HandlerContext<M, AC, D, E>,\n payload: Payload<A>,\n ) => void | Promise<void> | AsyncGenerator | Generator,\n ): void;\n};\n\n/**\n * Stable, typed dispatch function for the actions class `AC`. Same call\n * signatures as `actions.dispatch` returned by `useActions`, available\n * before the paired `useActions` has run via {@link Context}.\n */\nexport type Dispatch<AC extends Actions | void> = {\n (action: NoPayloadActions<Dispatchable<AC>>): Promise<void>;\n <A extends WithPayloadActions<Dispatchable<AC>>>(\n action: A,\n payload: Payload<A>,\n ): Promise<void>;\n};\n\n/**\n * Handle returned by `useContext<M, AC, D>()`. Exposes\n * `dispatch(action, payload?)` and a `useActions` method that materialises\n * the component-local model and reactive data against the same dispatch\n * target. Generics are declared on `useContext`; `useActions` inherits\n * them &mdash; the call site does not re-state `Model` / `Actions` /\n * `Data`.\n *\n * Note: this `Context` type is distinct from React's `useContext` /\n * `React.Context` &mdash; it's the March Hare action surface returned by\n * the `useContext` hook of this library.\n */\nexport type Context<\n M extends Model | void,\n AC extends Actions | void,\n D extends Props = Props,\n E extends Env = Env,\n> = {\n readonly actions: { dispatch: Dispatch<AC> };\n /**\n * Typed bag of handler factories bound to `M`. Methods accept lodash-style\n * dotted paths with array indices (e.g. `\"a.b.c\"`, `\"items.0.id\"`) and\n * autocomplete from the model. See {@link WithHandle}.\n */\n readonly with: WithHandle<M>;\n useActions(getData?: () => D): UseActions<M, AC, D, E>;\n useActions(\n model: M extends void ? never : M,\n getData?: () => D,\n ): UseActions<M, AC, D, E>;\n};\n","import * as React from \"react\";\nimport { G } from \"@mobily/ts-belt\";\nimport type { Env as EnvType, Props } from \"./types.ts\";\nimport { Context } from \"./utils.ts\";\nimport { useBroadcast } from \"../broadcast/index.tsx\";\nimport { EnvSymbol } from \"../../../types/index.ts\";\n\nexport { useEnv } from \"./utils.ts\";\n\n/**\n * Provides a per-Boundary {@link EnvType} value to every component inside\n * the boundary. Usually wired in via the `<Boundary env={initial}>`\n * prop rather than used directly.\n *\n * The Env is **not** reactive. Mutating it does not trigger a\n * re-render. Drive view state through the model; use the Env for\n * cross-handler coordination.\n */\n\nexport function Env({ initial, children }: Props): React.ReactNode {\n const ref = React.useRef<EnvType>(initial);\n const broadcast = useBroadcast();\n\n if (G.isUndefined(broadcast.getCached(EnvSymbol))) {\n broadcast.setCache(EnvSymbol, ref.current);\n }\n\n return <Context.Provider value={ref}>{children}</Context.Provider>;\n}\n","import * as React from \"react\";\nimport type { Invocation } from \"../../../resource/index.ts\";\n\n/**\n * Per-`<Boundary>` registry for `.coalesce(token)` sharing. Outer map\n * keys on the `Invocation.run` function identity (stable per Resource\n * via the `build()` closure); inner map keys on\n * `${paramsKey}|${coalesceKey(token)}`. While an entry exists every\n * caller awaiting `.coalesce(token)` for the same Resource + params +\n * token receives the same promise.\n *\n * Lifted into React context so each `<app.Boundary>` owns its own\n * registry &mdash; two `App` instances in the same tree cannot collide\n * on a shared token like `.coalesce(\"k\")`.\n *\n * @internal\n */\nexport type Sharing = WeakMap<\n Invocation<unknown, object>[\"run\"],\n Map<string, Promise<unknown>>\n>;\n\nconst fallback: Sharing = new WeakMap();\n\n/**\n * React context exposing the per-Boundary sharing registry. The\n * fallback is a fresh `WeakMap` used when `useSharing()` is read\n * outside any `<Boundary>` &mdash; calls work but never share with any\n * other component.\n *\n * @internal\n */\nexport const Context = React.createContext<Sharing>(fallback);\n\n/**\n * Wraps children with a Boundary-scoped sharing registry for\n * `.coalesce(token)`. Rendered as part of {@link Boundary}; not\n * exposed standalone.\n *\n * @internal\n */\nexport function SharingProvider({\n children,\n}: {\n children: React.ReactNode;\n}): React.ReactElement {\n const registry = React.useMemo<Sharing>(() => new WeakMap(), []);\n return <Context.Provider value={registry}>{children}</Context.Provider>;\n}\n\n/**\n * Hook returning the per-Boundary sharing registry. Used by the\n * `.coalesce(token)` chainable inside `useActions`.\n *\n * @internal\n */\nexport function useSharing(): Sharing {\n return React.useContext(Context);\n}\n","import * as React from \"react\";\nimport type { Tap } from \"./types.ts\";\n\nconst noop: Tap = () => {};\n\n/**\n * React context carrying the active {@link Tap} observer for the\n * surrounding `<Boundary>`. Defaults to a no-op so `useTap()` callers\n * never need to null-check.\n */\nexport const Context = React.createContext<Tap>(noop);\n\n/**\n * Hook returning the active tap observer. Always returns a callable\n * &mdash; if no `<Boundary tap={...}>` is mounted above, calls are\n * silent no-ops with no allocation cost beyond the function call itself.\n */\nexport function useTap(): Tap {\n return React.useContext(Context);\n}\n","import * as React from \"react\";\nimport { Context } from \"./utils.ts\";\nimport type { Props, Tap } from \"./types.ts\";\n\nexport { useTap } from \"./utils.ts\";\nexport type {\n Tap,\n Taps,\n Invocation,\n Failure,\n Mutations,\n Snapshot,\n} from \"./types.ts\";\n\n/**\n * Internal provider that wires a {@link Tap} observer into the React\n * context consumed by `useActions` during dispatch. Rendered by the\n * top-level `<Boundary>` (and indirectly by `<app.Boundary>`); not\n * exposed on the public surface &mdash; consumers should pass the\n * callback via the `tap` prop of either boundary instead of mounting\n * this provider directly.\n *\n * The supplied `tap` callback is held in a `useRef` and indirected\n * through a stable `useMemo` wrapper. The ref is synchronised inside a\n * `useLayoutEffect` &mdash; React's sanctioned write-after-commit\n * window &mdash; so the provider stays compatible with Concurrent\n * rendering, where the render function may be invoked more than once\n * per commit and direct mutation during render would race the\n * scheduler.\n *\n * Keeping the context value referentially constant for the lifetime of\n * the boundary means callers may pass inline arrow functions without\n * invalidating the dispatch pipeline on every render &mdash; the\n * latest callback is read at fire time, not at provider-render time.\n * When `tap` is `undefined`, the wrapper short-circuits via optional\n * chaining: no allocation per event beyond the wrapper call itself.\n *\n * @param props.tap Observer to receive lifecycle events for every action\n * handler dispatched inside the boundary. See {@link Tap}.\n * @param props.children Subtree that should observe the supplied tap.\n * @returns Children rendered inside the tap context provider.\n *\n * @see {@link Tap} &mdash; the observer signature.\n * @see {@link Taps} &mdash; the discriminated union of event shapes.\n */\nexport function Tappable({ tap, children }: Props): React.ReactNode {\n const ref = React.useRef<Tap | undefined>(tap);\n React.useLayoutEffect(() => void (ref.current = tap), [tap]);\n\n const value = React.useMemo<Tap>(() => (event) => ref.current?.(event), []);\n\n return <Context.Provider value={value}>{children}</Context.Provider>;\n}\n","import type { ConsumerContext } from \"./types.ts\";\nimport * as React from \"react\";\n\n/**\n * React context for the consumer store.\n * Stores the latest value for each distributed action with full annotation support.\n */\nexport const Context = React.createContext<ConsumerContext>(new Map());\n\n/**\n * Hook to access the consumer store from context.\n *\n * @returns The Map of action symbols to their State entries.\n */\nexport function useConsumer(): ConsumerContext {\n return React.useContext(Context);\n}\n","import * as React from \"react\";\nimport { Broadcaster } from \"./components/broadcast/index.tsx\";\nimport { Tasks } from \"./components/tasks/index.tsx\";\nimport { Env } from \"./components/env/index.tsx\";\nimport type { Env as EnvType } from \"./components/env/types.ts\";\nimport { SharingProvider } from \"./components/sharing/index.tsx\";\nimport { Tappable } from \"./components/tap/index.tsx\";\nimport { Context as ConsumerContext } from \"./components/consumer/utils.ts\";\nimport type { ConsumerContext as ConsumerStore } from \"./components/consumer/types.ts\";\nimport type { Props } from \"./types.ts\";\n\n/**\n * Low-level boundary primitive. Wraps children with the Broadcaster,\n * Env, and Tasks providers required by every March Hare hook.\n *\n * Most applications should reach for {@link App} instead &mdash;\n * `App<E>({ env })` returns a typed `app.Boundary` along with\n * matching `useContext` / `useEnv` / `Resource` factories that all\n * close over the App's inferred env shape `E`. The bare `Boundary`\n * is exposed for advanced or library-internal use where the loose\n * Env record type is sufficient.\n *\n * @example\n * ```tsx\n * <Boundary env={{ session: null, locale: \"en-GB\" }}>\n * <App />\n * </Boundary>\n * ```\n */\nexport function Boundary({ env, tap, children }: Props): React.ReactNode {\n const consumer = React.useMemo<ConsumerStore>(() => new Map(), []);\n return (\n <Broadcaster>\n <ConsumerContext.Provider value={consumer}>\n <Env initial={env ?? ({} as EnvType)}>\n <Tasks>\n <Tappable tap={tap}>\n <SharingProvider>{children}</SharingProvider>\n </Tappable>\n </Tasks>\n </Env>\n </ConsumerContext.Provider>\n </Broadcaster>\n );\n}\n","import {\n ChanneledAction,\n Brand,\n BrandedAction,\n BrandedBroadcast,\n BrandedMulticast,\n AnyAction,\n} from \"../types/index.ts\";\nimport type { ActionId } from \"../boundary/components/tasks/types.ts\";\nimport { describe } from \"../utils.ts\";\nimport { G } from \"@mobily/ts-belt\";\n\nconst isSymbol = (value: unknown): value is symbol => typeof value === \"symbol\";\n\n/**\n * Extracts the underlying symbol from an action or channeled action.\n * This symbol is used as the event emitter key for dispatching.\n *\n * @param action The action or channeled action to extract the symbol from.\n * @returns The underlying symbol, or the action itself if it's already a symbol/string.\n *\n * @example\n * ```typescript\n * const Increment = Action<number>(\"Increment\");\n * getActionSymbol(Increment); // Symbol(march-hare.action/Increment)\n * getActionSymbol(Increment({ UserId: 5 })); // Symbol(march-hare.action/Increment)\n * ```\n */\nexport function getActionSymbol(action: AnyAction): ActionId {\n if (G.isString(action)) return action;\n if (isSymbol(action)) return action;\n if ((G.isObject(action) || G.isFunction(action)) && Brand.Action in action) {\n return (<BrandedAction>action)[Brand.Action];\n }\n return <ActionId>(<unknown>action);\n}\n\n/**\n * Checks whether an action is a broadcast action.\n * Broadcast actions are sent to all mounted components that have defined a handler for them.\n *\n * @param action The action to check.\n * @returns True if the action is a broadcast action, false otherwise.\n */\nexport function isBroadcastAction(action: AnyAction): boolean {\n if (G.isString(action)) return action.startsWith(describe.broadcast());\n\n if (isSymbol(action))\n return action.description?.startsWith(describe.broadcast()) ?? false;\n\n if (G.isObject(action) || G.isFunction(action)) {\n if (\n Brand.Broadcast in action &&\n (<BrandedBroadcast>action)[Brand.Broadcast]\n ) {\n return true;\n }\n\n if (Brand.Action in action) {\n const actionSymbol = (<BrandedAction>action)[Brand.Action];\n return (\n actionSymbol.description?.startsWith(describe.broadcast()) ?? false\n );\n }\n }\n\n return false;\n}\n\n/**\n * Extracts the action name from an action.\n *\n * Parses both regular actions (`march-hare.action/Name`) and\n * distributed actions (`march-hare.action/distributed/Name`)\n * to extract just the name portion.\n *\n * @param action The action to extract the name from.\n * @returns The extracted action name, or \"unknown\" if parsing fails.\n *\n * @example\n * ```typescript\n * const Increment = Action(\"Increment\");\n * getName(Increment); // \"Increment\"\n *\n * const SignedOut = Action(\"SignedOut\", Distribution.Broadcast);\n * getName(SignedOut); // \"SignedOut\"\n * ```\n */\nexport function getName(action: AnyAction): string {\n const symbol = getActionSymbol(action);\n const description = G.isString(symbol) ? symbol : (symbol.description ?? \"\");\n if (!description.startsWith(describe.action())) return \"unknown\";\n const name = description.slice(description.lastIndexOf(\"/\") + 1);\n return name || \"unknown\";\n}\n\n/**\n * Checks if the given action is a channeled action (result of calling `Action(channel)`).\n *\n * @param action - The action to check\n * @returns `true` if the action is a channeled action with a channel property, `false` otherwise\n *\n * @example\n * ```ts\n * const UserUpdated = Action<User, { UserId: number }>(\"UserUpdated\");\n *\n * isChanneledAction(UserUpdated); // false\n * isChanneledAction(UserUpdated({ UserId: 1 })); // true\n * ```\n */\nexport function isChanneledAction(\n action: AnyAction,\n): action is ChanneledAction {\n return G.isObject(action) && Brand.Channel in action && \"channel\" in action;\n}\n\n/**\n * Extracts the lifecycle type from an action's symbol description.\n *\n * Returns the lifecycle name (`\"Mount\"`, `\"Unmount\"`, `\"Error\"`, `\"Update\"`)\n * when the action symbol's description starts with the lifecycle prefix, or\n * `null` for non-lifecycle actions.\n *\n * @param action The action to inspect.\n * @returns The lifecycle name, or `null` if not a lifecycle action.\n *\n * @example\n * ```typescript\n * class Actions {\n * static Mount = Lifecycle.Mount();\n * }\n *\n * getLifecycleType(Actions.Mount); // \"Mount\"\n * getLifecycleType(Action(\"Increment\")); // null\n * ```\n */\nexport function getLifecycleType(action: AnyAction): string | null {\n const symbol = getActionSymbol(action);\n const description = isSymbol(symbol) ? (symbol.description ?? \"\") : symbol;\n if (!description.startsWith(describe.lifecycle())) return null;\n return description.slice(describe.lifecycle().length) || null;\n}\n\n/**\n * Checks whether an action is a multicast action.\n * Multicast actions are dispatched to all components within a named scope boundary.\n *\n * @param action The action to check.\n * @returns True if the action is a multicast action, false otherwise.\n */\nexport function isMulticastAction(action: AnyAction): boolean {\n if (G.isString(action)) return action.startsWith(describe.multicast());\n\n if (isSymbol(action))\n return action.description?.startsWith(describe.multicast()) ?? false;\n\n if (G.isObject(action) || G.isFunction(action)) {\n if (\n Brand.Multicast in action &&\n (<BrandedMulticast>action)[Brand.Multicast]\n ) {\n return true;\n }\n\n if (Brand.Action in action) {\n const actionSymbol = (<BrandedAction>action)[Brand.Action];\n return (\n actionSymbol.description?.startsWith(describe.multicast()) ?? false\n );\n }\n }\n\n return false;\n}\n","import {\n HandlerPayload,\n BroadcastPayload,\n MulticastPayload,\n Distribution,\n ChanneledAction,\n Brand,\n Filter,\n} from \"../types/index.ts\";\nimport { describe } from \"../utils.ts\";\n\nexport {\n getActionSymbol,\n getLifecycleType,\n isBroadcastAction,\n isMulticastAction,\n getName,\n isChanneledAction,\n} from \"./utils.ts\";\n\n/**\n * Interface for the Action factory function.\n */\ntype ActionFactory = {\n /**\n * Creates a new unicast action with an optional name.\n *\n * `K` is the literal type of the action name and is captured as a phantom\n * brand so `Action(\"A\")` and `Action(\"B\")` produce structurally-distinct\n * types. **Note:** when the caller supplies any explicit generic\n * (`Action<P>(\"Name\")`), TypeScript fills `K` from its default and the\n * literal is lost. The Name brand still helps for `Action(\"Name\")` calls\n * (e.g. lifecycle / no-payload actions) which is the most common source of\n * foreign-class collisions.\n *\n * Omitting the name produces an action whose symbol description has no\n * suffix. Symbol identity (and therefore dispatch routing) is unaffected\n * — names are only used for fault reporting and debugger readability.\n *\n * @template P The payload type for the action.\n * @template C The channel type for channeled dispatches.\n * @template K The literal type of the action name (inferred when no other\n * generics are supplied; defaults to `string` otherwise).\n */\n <P = never, C extends Filter = never, K extends string = string>(\n name?: K,\n ): HandlerPayload<P, C, K>;\n\n /**\n * Creates a new action with the specified distribution mode.\n */\n <P = never, C extends Filter = never, K extends string = string>(\n name: K | undefined,\n distribution: Distribution.Broadcast,\n ): BroadcastPayload<P, C, K>;\n <P = never, C extends Filter = never, K extends string = string>(\n name: K | undefined,\n distribution: Distribution.Multicast,\n ): MulticastPayload<P, C, K>;\n <P = never, C extends Filter = never, K extends string = string>(\n name: K | undefined,\n distribution: Distribution.Unicast,\n ): HandlerPayload<P, C, K>;\n <P = never, C extends Filter = never, K extends string = string>(\n name: K | undefined,\n distribution: Distribution,\n ):\n | HandlerPayload<P, C, K>\n | BroadcastPayload<P, C, K>\n | MulticastPayload<P, C, K>;\n};\n\n/**\n * Creates a new action with a given payload type, optional channel type, and optional distribution mode.\n *\n * Actions are strongly typed identifiers used to dispatch and handle state changes.\n * By default, actions use `Distribution.Unicast` (local to the defining component).\n * Use `Distribution.Broadcast` for actions that need to be shared across components.\n *\n * When a channel type is specified, the action becomes callable to create channeled dispatches:\n * - `Action({ UserId: 5 })` creates a channeled action targeting that specific channel\n * - Plain `Action` (uncalled) broadcasts to all handlers\n *\n * @template P The type of the payload that the action will carry.\n * @template C The type of the channel for channeled dispatches (defaults to never).\n *\n * @example\n * ```ts\n * export class Actions {\n * // Unicast action with no payload\n * static Reset = Action(\"Reset\");\n *\n * // Unicast action with typed payload\n * static Increment = Action<number>(\"Increment\");\n *\n * // Action with channel support for targeted dispatches\n * static UserUpdated = Action<User, { UserId: number }>(\"UserUpdated\");\n *\n * // Broadcast action - can be read across components\n * static Counter = Action<number>(\"Counter\", Distribution.Broadcast);\n * }\n *\n * // Usage\n * actions.dispatch(Actions.Reset);\n * actions.dispatch(Actions.Increment, 5);\n * actions.dispatch(Actions.UserUpdated, user); // broadcast to all\n * actions.dispatch(Actions.UserUpdated({ UserId: 5 }), user); // channeled dispatch\n * actions.stream(Actions.Counter, (box) => box.value);\n * ```\n */\nexport const Action = <ActionFactory>(<unknown>(<\n P = never,\n C extends Filter = never,\n>(\n name: string = \"\",\n distribution: Distribution = Distribution.Unicast,\n): HandlerPayload<P, C> | BroadcastPayload<P, C> | MulticastPayload<P, C> => {\n const symbol =\n distribution === Distribution.Broadcast\n ? Symbol(describe.broadcast(name))\n : distribution === Distribution.Multicast\n ? Symbol(describe.multicast(name))\n : Symbol(describe.action(name));\n\n const action = function (channel: C): ChanneledAction<P, C> {\n return {\n [Brand.Action]: symbol,\n [Brand.Payload]: <P>undefined,\n [Brand.Channel]: channel,\n [Brand.Name]: name,\n channel,\n };\n };\n\n // eslint-disable-next-line fp/no-mutating-methods\n Object.defineProperty(action, Brand.Action, {\n value: symbol,\n enumerable: false,\n });\n // eslint-disable-next-line fp/no-mutating-methods\n Object.defineProperty(action, Brand.Payload, {\n value: undefined,\n enumerable: false,\n });\n // eslint-disable-next-line fp/no-mutating-methods\n Object.defineProperty(action, Brand.Name, { value: name, enumerable: false });\n if (distribution === Distribution.Broadcast) {\n // eslint-disable-next-line fp/no-mutating-methods\n Object.defineProperty(action, Brand.Broadcast, {\n value: true,\n enumerable: false,\n });\n }\n if (distribution === Distribution.Multicast) {\n // eslint-disable-next-line fp/no-mutating-methods\n Object.defineProperty(action, Brand.Multicast, {\n value: true,\n enumerable: false,\n });\n }\n\n return <\n HandlerPayload<P, C> | BroadcastPayload<P, C> | MulticastPayload<P, C>\n >action;\n}));\n","import * as React from \"react\";\nimport { RefObject } from \"react\";\nimport {\n Props,\n Phase,\n Model,\n Actions,\n Filter,\n ActionId,\n HandlerPayload,\n ChanneledAction,\n HandlerContext,\n} from \"../types/index.ts\";\nimport EventEmitter from \"eventemitter3\";\nimport { BroadcastEmitter } from \"../boundary/components/broadcast/index.tsx\";\nimport { describe } from \"../utils.ts\";\n\nimport type { Dispatchers, LifecycleConfig, Handler, Scope } from \"./types.ts\";\nimport { A, G } from \"@mobily/ts-belt\";\nimport { changes } from \"../utils.ts\";\nimport {\n isChanneledAction,\n getActionSymbol,\n getLifecycleType,\n} from \"../action/index.ts\";\n\n/**\n * Creates a new object with getters for each property of the input object.\n * The getters retrieve the current value from a ref, ensuring that the latest value is always accessed.\n */\nexport function withGetters<P extends Props>(a: P, b: RefObject<P>): P {\n return Object.keys(a).reduce(\n (proxy, key) => {\n Object.defineProperty(proxy, key, {\n get() {\n return b.current[key];\n },\n enumerable: true,\n });\n\n return proxy;\n },\n <P>{},\n );\n}\n\n/**\n * Checks if the given result is a generator or async generator object.\n * Uses `Object.prototype.toString` which reliably returns\n * `\"[object Generator]\"` or `\"[object AsyncGenerator]\"` regardless of\n * the generator function's name.\n */\nexport function isGenerator(\n result: unknown,\n): result is Generator | AsyncGenerator {\n if (!result || typeof result !== \"object\") return false;\n const tag = Object.prototype.toString.call(result);\n return tag === \"[object Generator]\" || tag === \"[object AsyncGenerator]\";\n}\n\n/**\n * Sentinel passed as the dispatch channel during mount replay. Channeled\n * handlers check for this to skip replay &mdash; they require specific\n * channel context and cannot meaningfully process a replay without it.\n *\n * @internal\n */\nexport const replay: unique symbol = Symbol(describe.replay());\n\n/**\n * Invokes all listeners for an event and returns a promise that resolves\n * when every handler has settled. For {@link BroadcastEmitter} instances the\n * payload is cached before listeners fire so late-mounting components still\n * see the latest value.\n *\n * @internal\n */\nexport function emitAsync(\n emitter: EventEmitter,\n event: string | symbol,\n ...args: unknown[]\n): Promise<void> {\n if (emitter instanceof BroadcastEmitter) emitter.setCache(event, args[0]);\n\n const listeners = emitter.listeners(event);\n if (listeners.length === 0) return Promise.resolve();\n\n return Promise.all(listeners.map((fn) => Promise.resolve(fn(...args)))).then(\n () => {},\n );\n}\n\n/**\n * Emits lifecycle events for component mount and DOM attachment.\n * Also invokes broadcast action handlers with cached values on mount.\n * Updates the phase ref to track the component's current lifecycle state.\n *\n * The Mount effect skips when `phase` is already `Mounted` — this catches\n * Strict Mode's dev-only double-invocation. It accepts both `Mounting` (first\n * mount) and `Unmounted` (re-mount after `<Activity>` show) as entry states\n * so that hidden-then-shown subtrees correctly re-emit Mount.\n *\n * Phase transitions:\n * - First mount: Mounting → Mounted\n * - Activity hide / show: Mounted → Unmounting → Unmounted → Mounting → Mounted\n */\nexport function useLifecycles({\n unicast,\n broadcast,\n dispatchers,\n scope,\n phase,\n data,\n handlers,\n}: LifecycleConfig): void {\n const previous = React.useRef<Props | null>(null);\n\n React.useLayoutEffect(() => {\n if (phase.current === Phase.Mounted) return;\n phase.current = Phase.Mounting;\n\n const mountAction = findLifecycleAction(handlers, \"Mount\");\n if (mountAction) unicast.emit(mountAction);\n\n dispatchers.broadcast.forEach((action) => {\n const cached = broadcast.getCached(action);\n if (!G.isNullable(cached)) unicast.emit(action, cached, replay);\n });\n\n if (scope) {\n dispatchers.multicast.forEach((action) => {\n const cached = scope.emitter.getCached(action);\n if (!G.isNullable(cached)) unicast.emit(action, cached, replay);\n });\n }\n\n phase.current = Phase.Mounted;\n }, []);\n\n React.useLayoutEffect(() => {\n if (G.isNotNullable(previous.current)) {\n const differences = changes(previous.current, data);\n if (A.isNotEmpty(Object.keys(differences))) {\n const updateAction = findLifecycleAction(handlers, \"Update\");\n if (updateAction) unicast.emit(updateAction, differences);\n }\n }\n\n previous.current = data;\n }, [data, unicast]);\n}\n\n/**\n * Creates a data proxy for a given object, returning a memoized version.\n * The proxy provides stable access to the object's properties,\n * even as the original object changes across renders.\n *\n * The ref is updated synchronously during render so the proxy is current\n * both during the render itself (for JSX reading the third tuple element\n * returned by {@link useActions}) and afterwards (for handler reads via\n * `context.data` across `await` boundaries).\n *\n * @template P The type of the object.\n * @param props The object to create a data proxy for.\n * @returns A memoized data proxy of the object.\n */\nexport function useData<P extends Props>(props: P): P {\n const ref = React.useRef<P>(props);\n ref.current = props;\n return React.useMemo(() => withGetters<P>(props, ref), [props]);\n}\n\n/**\n * Scans a handler registry for a lifecycle action of the given type.\n *\n * When lifecycle actions become per-class instances (via `Lifecycle.Mount()`),\n * each Actions class has its own unique symbol. Emission sites can no longer\n * emit to a shared singleton — they must discover the component's lifecycle\n * action by scanning the registry keys for matching lifecycle prefixes.\n *\n * Handler maps typically contain 5–15 entries, so the O(n) scan is trivial.\n *\n * @param handlers The handler map from a component's scope.\n * @param type The lifecycle type to find (e.g. `\"Mount\"`, `\"Unmount\"`, `\"Error\"`).\n * @returns The matching ActionId, or `null` if no lifecycle action of that type is registered.\n *\n * @internal\n */\nexport function findLifecycleAction(\n handlers: Map<ActionId, Set<unknown>>,\n type: string,\n): ActionId | null {\n for (const action of handlers.keys()) {\n if (getLifecycleType(action) === type) return action;\n }\n return null;\n}\n\n// Re-export isChanneledAction and getActionSymbol for convenience\nexport { isChanneledAction, getActionSymbol };\n\n/**\n * Manages sets of broadcast and multicast action IDs.\n *\n * This hook creates stable refs for tracking which actions have been registered\n * as broadcast or multicast within a component. These sets are used to:\n * - Replay cached broadcast values on mount\n * - Track multicast subscriptions for scope-based dispatch\n *\n * @returns Object with `broadcast` and `multicast` Sets for action tracking\n *\n * @example\n * ```ts\n * const actions = useDispatchers();\n *\n * // Register a broadcast action\n * actions.broadcast.add(getActionSymbol(MyBroadcastAction));\n *\n * // Check if an action is registered as multicast\n * if (actions.multicast.has(actionId)) {\n * // Handle multicast dispatch\n * }\n * ```\n *\n * @internal\n */\nexport function useDispatchers(): Dispatchers {\n const broadcast = React.useRef<Set<ActionId>>(new Set());\n const multicast = React.useRef<Set<ActionId>>(new Set());\n\n return React.useMemo(\n () => ({\n broadcast: broadcast.current,\n multicast: multicast.current,\n }),\n [],\n );\n}\n\n/**\n * Registers an action handler within a component's scope.\n *\n * This hook binds a handler function to an action, supporting both regular and channeled\n * actions. The handler is wrapped with `useEffectEvent` to ensure it always has access\n * to the latest closure values while maintaining a stable reference.\n *\n * For generator handlers (sync or async), the hook automatically iterates through\n * all yielded values to completion.\n *\n * @template M - The model type representing the component's state\n * @template AC - The actions class containing action definitions\n * @template D - The data type for reactive external values\n *\n * @param scope - Ref to the component's handler scope containing registered handlers\n * @param action - The action to register (ActionId, HandlerPayload, or ChanneledAction)\n * @param handler - The handler function to invoke when the action is dispatched\n *\n * @example\n * ```ts\n * useRegisterHandler(scope, Actions.Increment, async (context, payload) => {\n * context.actions.produce((draft) => {\n * draft.model.count += payload;\n * });\n * });\n *\n * // With channeled action\n * useRegisterHandler(scope, Actions.UserUpdated({ UserId: 5 }), (context, user) => {\n * // Only called when UserId matches 5\n * });\n * ```\n *\n * @internal\n */\nexport function useRegisterHandler<\n M extends Model | void,\n A extends Actions | void,\n D extends Props,\n>(\n scope: React.RefObject<Scope<M, A, D>>,\n action: ActionId | HandlerPayload | ChanneledAction,\n handler: (\n context: HandlerContext<M, A, D>,\n payload: unknown,\n ) => void | Promise<void> | AsyncGenerator | Generator,\n): void {\n // Store latest handler in ref to avoid stale closures (replaces useEffectEvent)\n const handlerRef = React.useRef(handler);\n React.useLayoutEffect(() => {\n handlerRef.current = handler;\n });\n\n // Store latest action for channel resolution\n const actionRef = React.useRef(action);\n React.useLayoutEffect(() => {\n actionRef.current = action;\n });\n\n // Stable handler wrapper that always calls the latest handler.\n // Generator detection and iteration is handled by createHandler in hooks/index.ts\n // so that generators can be excluded from the awaitable dispatch promise.\n const stableHandler = React.useCallback(\n (context: HandlerContext<M, A, D>, payload: unknown) =>\n handlerRef.current(context, payload),\n [],\n );\n\n // Stable channel getter\n const getChannel = React.useCallback(\n (): Filter | undefined =>\n isChanneledAction(actionRef.current)\n ? <Filter>actionRef.current.channel\n : undefined,\n [],\n );\n\n const base = getActionSymbol(action);\n const entries = scope.current.handlers.get(base) ?? new Set();\n if (entries.size === 0) scope.current.handlers.set(base, entries);\n entries.add({ getChannel, handler: <Handler<M, A, D>>stableHandler });\n}\n\n/**\n * Checks if a dispatch channel matches a registered handler channel.\n * All properties in the dispatch channel must match the corresponding properties in the registered channel.\n *\n * @param dispatchChannel - The channel from the dispatch call (from ChanneledAction)\n * @param registeredChannel - The channel registered with useAction\n * @returns `true` if all dispatch channel properties match the registered channel\n *\n * @example\n * ```ts\n * matchesChannel({ UserId: 1 }, { UserId: 1 }); // true\n * matchesChannel({ UserId: 1 }, { UserId: 2 }); // false\n * matchesChannel({ UserId: 1 }, { UserId: 1, Role: \"admin\" }); // true (subset match)\n * matchesChannel({ UserId: 1, Role: \"admin\" }, { UserId: 1 }); // false (missing Role)\n * ```\n */\nexport function matchesChannel(\n dispatchChannel: Filter,\n registeredChannel: Filter,\n): boolean {\n for (const key of Object.keys(dispatchChannel)) {\n if (registeredChannel[key] !== dispatchChannel[key]) return false;\n }\n return true;\n}\n","import * as React from \"react\";\nimport type { Stored } from \"./types.ts\";\n\n/**\n * Sentinel symbol marking \"no value present yet\". Shared by the Resource\n * cache and by storage handles so callers can distinguish \"nothing has been\n * recorded\" from \"a legitimately stored null\".\n */\nexport const unset: unique symbol = Symbol(\"march-hare.unset\");\n\n/**\n * Returns a function to force a component re-render. Useful when state is\n * managed externally (e.g., refs) but the UI needs updating.\n *\n * @returns A zero-arg callback that schedules a re-render of the host\n * component when invoked.\n */\nexport function useRerender(): () => void {\n const [, rerender] = React.useReducer((x: number) => x + 1, 0);\n return rerender;\n}\n\n/**\n * Constructs a {@link Stored} in the empty state. Internal helper shared\n * by the storage layer and the Resource snapshot accessor.\n *\n * @template T The payload type the resulting Stored would carry if populated.\n * @returns A Stored with `data` set to {@link unset} and `at` set to `null`.\n * @internal\n */\nexport function empty<T>(): Stored<T> {\n return { data: unset, at: null };\n}\n\n/**\n * Constructs a {@link Stored} wrapping a present payload and timestamp.\n *\n * @template T The payload type carried by the Stored.\n * @param data The payload value to wrap.\n * @param at The instant the payload was recorded — flows through to the\n * Resource cache as the entry's `at` timestamp.\n * @internal\n */\nexport function present<T>(data: T, at: Temporal.Instant): Stored<T> {\n return { data, at };\n}\n","import type { Task } from \"../boundary/components/tasks/types.ts\";\n\n/**\n * Reasons why an action error occurred.\n */\nexport enum Reason {\n /** Action was aborted &mdash; superseded by a newer dispatch, the\n * component unmounted, or `task.controller.abort()` was called. */\n Aborted,\n /** A generic error thrown in the user's action handler. */\n Errored,\n}\n\n/**\n * Details about an error that occurred during action execution.\n *\n * Faults are delivered through the global `Lifecycle.Fault` broadcast.\n * Subscribe with `actions.useAction(Lifecycle.Fault, handler)` near the\n * root of your application for app-level concerns (logging, sign-out on\n * auth failure, abort cascades). For component-local recovery, use a\n * `Lifecycle.Error()` factory instead.\n *\n * @template E Custom error types to include in the union with Error.\n */\nexport type Fault<E extends Error = never> = {\n /** The reason for the error. */\n reason: Reason;\n /** The Error object that was thrown. */\n error: Error | E;\n /** The name of the action that caused the error (e.g., \"Increment\"). */\n action: string;\n /** Whether the component has a `Lifecycle.Error()` handler registered. */\n handled: boolean;\n /**\n * All currently running tasks across the application.\n * Use this to programmatically abort in-flight actions during error recovery\n * (e.g., on 403/500 responses to prevent cascading failures).\n *\n * @example\n * ```ts\n * actions.useAction(Lifecycle.Fault, (context, fault) => {\n * if (fault.reason === Reason.Errored) {\n * for (const task of fault.tasks) task.controller.abort();\n * }\n * });\n * ```\n */\n tasks: ReadonlySet<Task>;\n /**\n * Re-dispatches the failed action with the original payload and channel,\n * routed through the same emitter (broadcast, multicast, or unicast) as the\n * original dispatch. Resolves when every triggered handler has settled.\n *\n * `retry` is independent of the failed task's `AbortController`: even when\n * the failure was an `Aborted` reason, calling `retry()` fires a fresh\n * dispatch with a new task. The closure stays callable after the fault\n * handler returns, which makes it safe to surface from a UI &mdash; e.g. a\n * \"Retry\" button bound to `fault.retry`.\n *\n * @example\n * ```ts\n * actions.useAction(Lifecycle.Fault, (_context, fault) => {\n * if (fault.reason === Reason.Errored && isTransient(fault.error)) {\n * void fault.retry();\n * }\n * });\n * ```\n */\n retry: () => Promise<void>;\n};\n","export { Reason } from \"./types\";\nexport type { Fault } from \"./types\";\n\n/**\n * Error thrown when an action is aborted, e.g., when a component unmounts\n * or when a newer dispatch cancels a previous run. Works across all platforms\n * including React Native where `DOMException` is unavailable.\n *\n * The instance's `name` field stays as `\"AbortError\"` so it can be\n * pattern-matched alongside native `DOMException`s and ky/fetch aborts.\n *\n * @example\n * ```ts\n * throw new Aborted(\"User cancelled the request\");\n * ```\n */\nexport class Aborted extends Error {\n override name = \"AbortError\";\n constructor(message = \"Aborted\") {\n super(message);\n }\n}\n","import type { ScopeContext, ScopeEntry } from \"./types.ts\";\nimport * as React from \"react\";\n\n/**\n * React context for the nearest multicast scope. `null` at the root.\n *\n * @internal\n */\nexport const Context = React.createContext<ScopeContext>(null);\n\n/**\n * Hook that returns the nearest multicast scope entry. `null` when\n * the caller is not rendered inside any `<app.Scope().Boundary>`.\n *\n * @internal\n */\nexport function useScope(): ScopeContext {\n return React.useContext(Context);\n}\n\n/**\n * Pass-through accessor. Kept for the dispatch/subscribe sites that\n * previously needed an action-keyed lookup; now the scope is a single\n * entry (or `null`), so this returns it as-is.\n *\n * @internal\n */\nexport function getScope(context: ScopeContext): ScopeEntry | null {\n return context;\n}\n","import type { Adapter, Encoded, Stored } from \"./types.ts\";\nimport type { Env } from \"../boundary/components/env/types.ts\";\nimport { empty, present, unset } from \"../utils/utils.ts\";\nimport { G } from \"@mobily/ts-belt\";\n\nexport type { Adapter, Encoded } from \"./types.ts\";\n\n/**\n * Context passed to {@link CacheConfig.key}. Mirrors the shape an\n * `app.Resource` fetcher receives, restricted to the field the cache\n * needs to scope on: the live per-`<Boundary>` Env. Future-extensible\n * &mdash; new fields can land here without breaking the call shape.\n *\n * @template E The Env shape the cache is parameterised by.\n */\nexport type CacheContext<E extends object> = {\n readonly env: E;\n};\n\n/**\n * Configuration accepted by the {@link Cache} factory. Combines the\n * synchronous {@link Adapter} (`get`/`set`/`remove`/`clear`/`keys?`)\n * with an optional `key(context)` callback in a single flat object,\n * so all the cache's plumbing lives in one literal at the call site.\n *\n * - `key` &mdash; derives a per-context cache scope. Called every time\n * a cache key is assembled with the same `{ env }` shape an\n * `app.Resource` fetcher receives; the returned string is prepended\n * to the per-resource namespace and params so different scopes\n * (e.g. one cache slot per access token, locale, or tenant id) can\n * coexist in the same backing store. Return `\"\"`, `null`, or\n * `undefined` to skip prefixing &mdash; useful for \"not signed in\"\n * gaps where the scope is genuinely empty.\n */\nexport type CacheConfig<E extends object> = Adapter & {\n readonly key?: (context: CacheContext<E>) => string | null | undefined;\n};\n\n/**\n * Persistence-aware cache for a single {@link Resource}. Wraps a\n * **strictly synchronous** {@link Adapter} (localStorage, MMKV,\n * chrome.storage with a sync facade, etc.) and traffics in {@link\n * Stored} envelopes &mdash; storage entries serialise as {@link\n * Encoded}`<T>` so the `Temporal.Instant` timestamp survives the\n * string round-trip and `.exceeds({...})` can short-circuit on the\n * persisted timestamp after a reload.\n *\n * Every method on the Cache is sync &mdash; the model-literal sync\n * read has no place to wait, so the adapter contract foregoes\n * `Promise` entirely. Async backends (IndexedDB, AsyncStorage,\n * `chrome.storage.local`) need a sync facade hydrated at app entry;\n * see `recipes/storage.md` for the pattern. React Native projects\n * should reach for {@link https://github.com/mrousavy/react-native-mmkv\n * `react-native-mmkv`} &mdash; it's synchronous out of the box and\n * drops straight into the Adapter contract.\n *\n * Call with no arguments for an in-memory cache scoped to this\n * instance &mdash; useful for tests, ephemeral state, or when you\n * want a first-class cache object to share between Resources without\n * persistence. Pass an {@link Adapter} to back the cache with a\n * persistent store; when supplied, the adapter is the **only** tier\n * &mdash; the Cache does not maintain a separate in-memory mirror.\n *\n * Pass `key(context)` alongside the adapter methods to scope cache\n * slots by the per-`<Boundary>` Env. The returned string is prepended\n * to every cache key the Resource layer assembles, so different\n * tenants / sessions / locales share the adapter without stepping on\n * each other.\n *\n * The `E` generic lives on the {@link Cache} factory and on\n * {@link CacheConfig}: it parameterises the `key(context)` callback\n * at construction time so the caller can read `context.env.X` with\n * full typing. The returned {@link Cache} value is itself\n * env-agnostic &mdash; the runtime `scope(env)` method takes the\n * loose {@link Env} record and narrows internally before invoking\n * the callback &mdash; which keeps it freely assignable across\n * differently-typed Apps without variance gymnastics.\n *\n * @example\n * ```ts\n * // In-memory, scoped to this instance.\n * const cache = Cache();\n *\n * // Persisted via localStorage.\n * const cache = Cache({\n * get: (key) => localStorage.getItem(key),\n * set: (key, value) => localStorage.setItem(key, value),\n * remove: (key) => localStorage.removeItem(key),\n * clear: () => localStorage.clear(),\n * });\n *\n * // Multi-tenant: writes go under `${accessToken}:…`.\n * type AppEnv = { session: { accessToken: string } | null };\n * const cache = Cache<AppEnv>({\n * get: (key) => localStorage.getItem(key),\n * set: (key, value) => localStorage.setItem(key, value),\n * remove: (key) => localStorage.removeItem(key),\n * clear: () => localStorage.clear(),\n * key: ({ env }) => env.session?.accessToken ?? \"\",\n * });\n *\n * // Wire it into a Resource — successful runs write through automatically.\n * export const cat = Resource({\n * cache,\n * fetch: (context) => fetchCat(context.controller.signal),\n * });\n * ```\n */\nexport type Cache = {\n /**\n * Returns the {@link Stored} envelope for `key`. The envelope is\n * `empty()` when nothing is persisted; otherwise it carries the\n * decoded payload and the timestamp recorded at write-time.\n *\n * @template T The payload type expected at `key`.\n * @param key Cache slot identifier &mdash; usually the JSON-stringified\n * call-site params, prefixed by the Resource's namespace.\n */\n get<T>(key: string): Stored<T>;\n /**\n * Writes `value` to `key`. Skipped when the envelope has no concrete\n * payload (e.g. an `empty()` slot), since there is nothing meaningful\n * to persist. Serialisation, quota errors, and unserialisable payloads\n * are swallowed &mdash; writes are best-effort.\n *\n * @template T The payload type contained in `value`.\n * @param key Cache slot identifier &mdash; usually the JSON-stringified\n * call-site params, prefixed by the Resource's namespace.\n * @param value Stored envelope carrying the payload and its\n * write-time `Temporal.Instant`.\n */\n set<T>(key: string, value: Stored<T>): void;\n /**\n * Drops a single cache slot. Best-effort &mdash; backing-store errors\n * are swallowed.\n *\n * @param key Cache slot identifier.\n */\n remove(key: string): void;\n /**\n * Drops every cache slot in the backing store. Best-effort &mdash;\n * backing-store errors are swallowed.\n */\n clear(): void;\n /**\n * Returns every key currently held by the backing store. Used by\n * partial-match eviction (`evict(where)`) to iterate slots whose\n * stored params satisfy a `where` pattern.\n */\n keys(): Iterable<string>;\n /**\n * Returns the per-context prefix derived from the configured\n * `key(context)`. The returned string is appended with `:` by the\n * Resource layer to compose the full cache key. Always `\"\"` when\n * no `key` option was supplied or when the callback returned an\n * empty value &mdash; \"no scope\" is encoded as the empty string.\n *\n * Takes the loose {@link Env} record at runtime &mdash; the typed\n * `E` lives on the `key(context)` callback registered at\n * construction time, which the cache narrows to `E` internally\n * before invoking.\n *\n * @internal Public surface lives on the Resource layer; consumers\n * should not need to call this directly.\n */\n scope(env: Env | undefined): string;\n};\n\n/**\n * In-memory {@link Adapter} backed by a `Map`. Created on demand inside\n * {@link Cache} when no adapter is supplied; tests and ephemeral use\n * cases get an isolated slot without touching storage.\n *\n * @internal\n */\nfunction memoryAdapter(): Adapter {\n const memory = new Map<string, string>();\n return {\n get: (key) => memory.get(key) ?? null,\n set: (key, value) => {\n memory.set(key, value);\n },\n remove: (key) => {\n memory.delete(key);\n },\n clear: () => {\n memory.clear();\n },\n keys: () => memory.keys(),\n };\n}\n\n/**\n * Constructs a {@link Cache} from `config`. The config object carries\n * the synchronous adapter methods (`get`/`set`/`remove`/`clear`/`keys?`)\n * and, optionally, a `key(context)` callback that scopes every cache\n * slot by the live per-`<Boundary>` Env. Omit `config` entirely for an\n * in-memory cache scoped to this instance.\n *\n * When `key` is supplied, it runs each time the Resource layer\n * assembles a cache key, receiving the same `{ env }` shape an\n * `app.Resource` fetcher sees; its return value is prepended\n * (separated by `:`) to the per-resource namespace and params JSON.\n *\n * @template E The Env shape `config.key` is typed against. Defaults\n * to the loose {@link Env} record so callers that don't scope by\n * env can keep using `Cache({ ...adapter })` without supplying a\n * generic.\n * @param config Optional adapter-plus-options literal. Omit for an\n * in-memory cache; supply adapter methods alone for a persisted\n * cache; add `key` to also scope writes by the live Env.\n */\nexport function Cache<E extends object = Env>(config?: CacheConfig<E>): Cache {\n const backing: Adapter = G.isUndefined(config) ? memoryAdapter() : config;\n const scopeFn = config?.key;\n\n return {\n /**\n * Reads `key` from the backing store, parses the {@link Encoded}\n * envelope, and re-hydrates the `Temporal.Instant`. Returns\n * `empty()` when the slot is missing or the stored JSON is\n * malformed.\n */\n get<T>(key: string): Stored<T> {\n try {\n const raw = backing.get(key);\n if (G.isNull(raw)) return empty<T>();\n const parsed = <Encoded<T>>JSON.parse(raw);\n return present(parsed.data, Temporal.Instant.from(parsed.at));\n } catch {\n return empty<T>();\n }\n },\n /**\n * Serialises `value` to JSON and writes it under `key`. Skips\n * envelopes whose payload is unset or whose timestamp is missing,\n * and swallows quota / encoding / private-mode errors.\n */\n set<T>(key: string, value: Stored<T>): void {\n if (value.data === unset || G.isNull(value.at)) return;\n try {\n backing.set(\n key,\n JSON.stringify(<Encoded<T>>{\n data: value.data,\n at: value.at.toString(),\n }),\n );\n } catch {\n return;\n }\n },\n /**\n * Removes a single slot. Backing-store errors are swallowed\n * &mdash; eviction is best-effort.\n */\n remove(key: string): void {\n try {\n backing.remove(key);\n } catch {\n return;\n }\n },\n /**\n * Clears every slot in the backing store. Backing-store errors are\n * swallowed &mdash; clear is best-effort.\n */\n clear(): void {\n try {\n backing.clear();\n } catch {\n return;\n }\n },\n /**\n * Returns every key the backing store currently holds, or an empty\n * iterable when the adapter does not expose `keys` (legacy adapters)\n * or throws while enumerating.\n */\n keys(): Iterable<string> {\n try {\n return backing.keys?.() ?? [];\n } catch {\n return [];\n }\n },\n scope(env: Env | undefined): string {\n if (G.isUndefined(scopeFn) || G.isNullable(env)) return \"\";\n try {\n const prefix = scopeFn({ env: <E>(<unknown>env) });\n return G.isNullable(prefix) ? \"\" : prefix;\n } catch {\n return \"\";\n }\n },\n };\n}\n","import { Cache } from \"../cache/index.ts\";\nimport { present, unset } from \"../utils/utils.ts\";\nimport type { Env } from \"../boundary/components/env/types.ts\";\nimport type {\n Args,\n Dispatch,\n Fetcher,\n Invocation,\n ResourceEvictor,\n ResourceHandle,\n} from \"./types.ts\";\nimport { G } from \"@mobily/ts-belt\";\n\nexport { Cache } from \"../cache/index.ts\";\n\n/**\n * Default in-memory `Cache` used when {@link Resource} is constructed\n * without an explicit one. Each fetcher gets its own slot via the\n * outer `WeakMap` so unrelated Resources don't share a string-key\n * namespace.\n *\n * @internal\n */\nexport const defaults = new WeakMap<object, Cache>();\n\n/**\n * Returns the {@link Cache} bound to `fetcher`, allocating a fresh\n * in-memory Cache on first access.\n *\n * @internal\n */\nexport function defaultCache(fetcher: object): Cache {\n const existing = defaults.get(fetcher);\n if (G.isNotNullable(existing)) return existing;\n const cache = Cache();\n defaults.set(fetcher, cache);\n return cache;\n}\n\n/**\n * Stable string key derived from the call-site `params`. Two calls with\n * the same logical params (same key order, same primitive values) hit\n * the same slot. JSON.stringify is sufficient for the March Hare params\n * convention (primitive-leaf objects); callers who need order-stable\n * keying should normalise the object before passing it in.\n *\n * @internal\n */\nexport function key(params: object): string {\n return JSON.stringify(params);\n}\n\n/**\n * Re-export of the shared `unset` sentinel from {@link \"../utils/index.ts\"}.\n *\n * @internal\n */\nexport const config = <const>{\n unset,\n};\n\n/**\n * Per-fetcher namespace registry. Each declared Resource takes a stable\n * id derived from the order of insertion (`namespaces.size`), used to\n * prefix cache keys when an App-shared {@link Cache} is configured.\n *\n * @internal\n */\nconst namespaces = new Map<object, string>();\n\n/**\n * Per-Resource eviction callbacks. Each `Resource` declaration registers\n * one entry on construction; the public `nuke(...)` (defined in\n * {@link \"./index.ts\"}) iterates them to drop cache slots across every\n * Resource in the process.\n *\n * @internal\n */\nexport const evictors: Array<ResourceEvictor> = [];\n\n/**\n * Mints the next namespace id for an app-shared cache. Each `app.Resource`\n * declaration consumes one id so the shared {@link Cache} can keep\n * resource-specific slots from colliding on shared params keys.\n *\n * @internal\n */\nexport function nextResourceId(fetcher: object): string {\n const existing = namespaces.get(fetcher);\n if (G.isNotNullable(existing)) return existing;\n const namespace = String(namespaces.size);\n namespaces.set(fetcher, namespace);\n return namespace;\n}\n\n/**\n * Allocates the per-Resource closure shared by `app.Resource` and\n * `shared.Resource`. The returned callable produces an\n * {@link Invocation} on every call &mdash; pass it to\n * `context.actions.resource(...)` for fetch/evict. `.get(params)` reads\n * the per-params cache slot synchronously.\n *\n * `getEnv` is the App-supplied accessor used to resolve the live env at\n * sync read time (`.get(params)`) and at App-side eviction (when the\n * handler context isn't available). It returns `undefined` when no\n * Boundary has mounted yet &mdash; in which case `cache.scope(undefined)`\n * yields the empty prefix and the read/evict targets the unscoped slot.\n *\n * @internal\n */\nexport function build<T, P extends object>(\n ƒ: Fetcher<T, P>,\n backing: Cache,\n namespace: string | null,\n getEnv: () => Env | undefined,\n): ResourceHandle<T, P> {\n const suffix = G.isNull(namespace) ? \"\" : `${namespace}:`;\n const composeKey = (env: Env | undefined, params: P) => {\n const scope = backing.scope(env);\n const prefix = scope === \"\" ? \"\" : `${scope}:`;\n return `${prefix}${suffix}${key(params)}`;\n };\n\n const read = (params: P, env: Env | undefined) => {\n const stored = backing.get<T>(composeKey(env, params));\n if (stored.data === unset || G.isNull(stored.at)) {\n return { data: unset, at: null };\n }\n return { data: <T>stored.data, at: stored.at };\n };\n\n const run = (\n env: Env,\n controller: AbortController,\n params: P,\n dispatch: Dispatch,\n ): Promise<T> =>\n ƒ(<Args<P>>{ env, controller, params, dispatch }).then((resolved) => {\n backing.set(\n composeKey(env, params),\n present(resolved, Temporal.Now.instant()),\n );\n return resolved;\n });\n\n const evict = (where: object): void => {\n const env = getEnv();\n const scope = backing.scope(env);\n const fullPrefix = scope === \"\" ? suffix : `${scope}:${suffix}`;\n const entries = Object.entries(where);\n for (const cacheKey of [...backing.keys()]) {\n if (!cacheKey.startsWith(fullPrefix)) continue;\n try {\n const parsed = <Record<string, unknown>>(\n JSON.parse(cacheKey.slice(fullPrefix.length))\n );\n if (entries.every(([field, value]) => parsed[field] === value))\n backing.remove(cacheKey);\n } catch {\n continue;\n }\n }\n };\n\n evictors.push(evict);\n\n function call(params?: P): Invocation<T, P> {\n const effective = <P>(params ?? {});\n return <Invocation<T, P>>{\n run,\n read: (params: P) => read(params, getEnv()),\n evict,\n params: effective,\n };\n }\n\n function get(params?: P): T | null {\n const { data } = read(<P>(params ?? {}), getEnv());\n return data === unset ? null : <T>data;\n }\n\n Object.defineProperty(call, \"get\", { value: get, enumerable: false });\n\n return <ResourceHandle<T, P>>(<unknown>call);\n}\n","import type { Fetcher, ResourceHandle } from \"./types.ts\";\nimport {\n Cache,\n build,\n defaultCache,\n evictors,\n nextResourceId,\n} from \"./utils.ts\";\nimport type { AppFetcher } from \"../app/types.ts\";\nimport type { Env } from \"../boundary/components/env/types.ts\";\nimport { G } from \"@mobily/ts-belt\";\n\nexport type { Coalesce, Fetcher, Invocation, ResourceHandle } from \"./types.ts\";\n\n/**\n * Evicts cache entries across every Resource constructed in the\n * current process. Resources register themselves on declaration, so\n * `nuke` covers both `app.Resource` and `shared.Resource`. Pass a\n * `where` pattern to drop only slots whose stored params satisfy the\n * pattern's keys (partial match &mdash; extra keys in the stored\n * params are ignored). Pass nothing to clear every known slot.\n *\n * @internal Public surface lives on `context.actions.resource.nuke(...)`.\n */\nexport function nuke(where?: object): void {\n const pattern = where ?? {};\n for (const evict of evictors) evict(pattern);\n}\n\n/**\n * Defines a remote resource &mdash; declared at module scope and used\n * directly. Exported as `shared.Resource` and (via the app factory) as\n * `app.Resource`. Calling the returned handle with `params` produces an\n * {@link Invocation} suitable for `context.actions.resource(...)` (fetch\n * path) or `context.actions.resource(...).evict(where?)` (partial-match\n * invalidation). Use `.get(params)` on the handle for a synchronous\n * cache read returning `T | null`. Persistence happens automatically\n * when the App is declared with `App({ cache })`.\n *\n * Takes the **Env shape `E` as a mandatory first generic** &mdash;\n * `context.env` inside the fetcher is typed as `E`. Pass a union of\n * every App's Env if the resource is shared across reusable\n * components. For single-app resources, prefer `app.Resource` &mdash;\n * the Env is captured from `app` automatically and you only need the\n * payload generic.\n *\n * The fetcher receives a single `context` argument carrying `env`,\n * `controller`, `params`, and a broadcast/multicast-only `dispatch`.\n * `env` is a live handle &mdash; dot reads inside the fetcher always\n * see the latest per-`<Boundary>` Env, even after `await` boundaries.\n *\n * Cache behaviour is decided at the App level: when `App({ cache })`\n * is supplied, every `app.Resource` declaration on that App writes\n * through to (and seeds from) the shared cache, isolated per resource\n * by a stable module-order namespace. When the App is constructed\n * without a `cache`, every resource keeps its own in-memory slot.\n * Standalone `shared.Resource` declarations always use an in-memory\n * cache &mdash; reach for `app.Resource` when persistence is required.\n *\n * Concurrent calls fire fresh requests by default. Opt in to in-flight\n * sharing per call via `.coalesce(key)` on the thenable returned from\n * `context.actions.resource(...)`.\n *\n * @template E The Env shape (or union) the fetcher's `context.env` is\n * typed against.\n * @template T The payload type the fetcher resolves to.\n * @template P The call-time params type.\n *\n * @example\n * ```ts\n * import { shared } from \"march-hare\";\n *\n * type WebEnv = { session: Session | null };\n *\n * export const user = shared.Resource<WebEnv, User, { id: number }>((context) =>\n * ky\n * .get(`users/${context.params.id}`, {\n * headers: context.env.session\n * ? { Authorization: `Bearer ${context.env.session.accessToken}` }\n * : {},\n * signal: context.controller.signal,\n * })\n * .json<User>(),\n * );\n * ```\n *\n * @internal The optional `cache` argument is reserved for `app.Resource`\n * &mdash; consumers should use `App({ cache })` instead of passing it\n * directly.\n */\nexport function Resource<\n E extends object,\n T,\n P extends object = Record<never, never>,\n>(\n ƒ: AppFetcher<E, T, P>,\n cache?: Cache,\n getEnv?: () => Env | undefined,\n): ResourceHandle<T, P> {\n const inner = <Fetcher<T, P>>(<unknown>ƒ);\n const resolveEnv = getEnv ?? (() => undefined);\n if (G.isUndefined(cache)) {\n return build(inner, defaultCache(inner), null, resolveEnv);\n }\n return build(inner, cache, nextResourceId(inner), resolveEnv);\n}\n","import type { Coalesce } from \"../resource/types.ts\";\n\n/**\n * Sentinel token used when `.coalesce()` is called with no explicit\n * argument. Every untokened caller for the same `(Resource, params)`\n * slot collapses onto this single key, so multiple callers chaining\n * `.coalesce()` share one in-flight fetch.\n *\n * The symbol description follows the `march-hare.{category}/{name}`\n * convention used by the rest of the library's internal symbols.\n *\n * @internal\n */\nexport const token: unique symbol = Symbol(\"march-hare.coalesce/default\");\n\n/**\n * Builds the per-call dedupe key for `.coalesce(token)`.\n *\n * The full registry key (constructed at the call site) is\n * `${JSON.stringify(params)}|${coalesceKey(token)}`; this function is\n * responsible only for the trailing token segment. Every supported\n * `Coalesce` primitive (`string`, `number`, `bigint`, `boolean`,\n * `symbol`) is prefixed with a single-character type tag so that\n * structurally identical values from different types stay distinct\n * &mdash; e.g. the string `\"5\"` does not collide with the number `5`,\n * and `Symbol(\"X\")` does not collide with the string `\"X\"`.\n *\n * Symbols are keyed by their `description` (falling back to\n * `String(value)` for description-less symbols) so two `Symbol(\"X\")`\n * instances declared in separate modules still hash to the same key.\n * That is intentional: the public contract is \"same description &rarr;\n * same coalesce group\", which keeps the API friendly for the common\n * enum-token pattern at call sites.\n *\n * Any unrecognised value falls through to the object branch and is\n * keyed by its JSON shape; `Coalesce` is constrained to primitives at\n * the type level, so this branch is reachable only from `unknown`\n * coercion in tests.\n *\n * @internal\n */\nexport function coalesceKey(value: Coalesce): string {\n switch (typeof value) {\n case \"string\":\n return `s:${value}`;\n case \"number\":\n return `n:${value}`;\n case \"bigint\":\n return `i:${value.toString()}`;\n case \"boolean\":\n return `b:${value}`;\n case \"symbol\":\n return `y:${value.description ?? String(value)}`;\n default:\n return `o:${JSON.stringify(value)}`;\n }\n}\n\n/**\n * Wraps `promise` so that aborting `signal` rejects the returned\n * promise with `signal.reason`, even when `promise` itself never\n * settles. The original promise is left alone &mdash; the underlying\n * work continues (other awaiters keep their grip) and only this\n * caller's view of it is severed.\n *\n * Used by the `.coalesce(token)` chainable: the shared in-flight fetch\n * runs on a detached `AbortController` so one caller's abort does not\n * cancel work the others are still waiting on, while each caller's own\n * `context.task.controller` still aborts its personal await via this\n * wrapper. The `{ once: true }` listener and the cleanup on settle keep\n * the wrapper free of leaks across long-lived signals.\n *\n * @internal\n */\nexport function withAbort<T>(\n promise: Promise<T>,\n signal: AbortSignal,\n): Promise<T> {\n return new Promise<T>((resolve, reject) => {\n if (signal.aborted) {\n reject(signal.reason);\n return;\n }\n const onAbort = (): void => reject(signal.reason);\n signal.addEventListener(\"abort\", onAbort, { once: true });\n promise.then(\n (value) => {\n signal.removeEventListener(\"abort\", onAbort);\n resolve(value);\n },\n (error: unknown) => {\n signal.removeEventListener(\"abort\", onAbort);\n reject(error);\n },\n );\n });\n}\n","import{immerable as t,enablePatches as e,Immer as r}from\"immer\";import{G as i,A as n}from\"@mobily/ts-belt\";let s=(t=21)=>{let e=\"\",r=crypto.getRandomValues(new Uint8Array(t|=0));for(;t--;)e+=\"useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict\"[63&r[t]];return e};var o=/* @__PURE__ */(t=>(t[t.Add=1]=\"Add\",t[t.Remove=2]=\"Remove\",t[t.Update=4]=\"Update\",t[t.Move=8]=\"Move\",t[t.Replace=16]=\"Replace\",t[t.Sort=32]=\"Sort\",t[t.Create=64]=\"Create\",t[t.Fetch=128]=\"Fetch\",t[t.Clone=256]=\"Clone\",t[t.Archive=512]=\"Archive\",t[t.Restore=1024]=\"Restore\",t[t.Merge=2048]=\"Merge\",t[t.Reorder=4096]=\"Reorder\",t[t.Sync=8192]=\"Sync\",t[t.Publish=16384]=\"Publish\",t[t.Link=32768]=\"Link\",t[t.Unlink=65536]=\"Unlink\",t[t.Lock=131072]=\"Lock\",t[t.Unlock=262144]=\"Unlock\",t[t.Import=524288]=\"Import\",t[t.Export=1048576]=\"Export\",t[t.Transfer=2097152]=\"Transfer\",t))(o||{}),a=/* @__PURE__ */(t=>(t[t.Produce=0]=\"Produce\",t[t.Hydrate=1]=\"Hydrate\",t))(a||{}),c=/* @__PURE__ */(t=>(t.Property=\"property\",t.Process=\"process\",t.Value=\"value\",t.Operation=\"operation\",t))(c||{});class u{[t]=!0;static keys=new Set(Object.values(c));property=null;process=null;value;operation;constructor(t,e){this.value=t,this.operation=e}assign(t,e){const r=new u(this.value,this.operation);return r.property=t,r.process=e,r}}class l{static immer=(()=>{e();const t=new r;return t.setAutoFreeze(!1),t})();static tag=\"κ\";static id=s}const p=Symbol(\"Box\");function y(t,e){const r=\"string\"==typeof e?\"\"===e?[]:e.split(\".\"):e;let i=t;for(const n of r){if(null==i)return;i=i[n]}return i}function f(t){if(i.isNullable(t)||m(t))return t;if(i.isArray(t))return t.map(t=>f(t));if(i.isObject(t)&&h(t)){const e=Object.entries(t).map(([t,e])=>[t,f(e)]);return{...Object.fromEntries(e),[l.tag]:t[l.tag]??l.id()}}return t}function d(t){if(Array.isArray(t))return t.filter(t=>l.tag in t).map(t=>t[l.tag]??\"\").join(\",\");const e=t[l.tag];if(e)return e;try{return JSON.stringify(t)}catch{return`[unserializable:${typeof t}]`}}function h(t){const e=Object.getPrototypeOf(t);return e===Object.prototype||null===e}function m(t){return i.isNullable(t)||i.isString(t)||i.isNumber(t)||i.isBoolean(t)||\"symbol\"==typeof t||\"bigint\"==typeof t}function b(t){return i.isObject(t)&&p in t}function g(t,e,r,n,s,o){return function c(l,p=e.path){if(l instanceof u){const e=y(r,p.join(\".\"));if(Object.entries(l).filter(([t,e])=>!u.keys.has(t)&&e instanceof u).forEach(([t,e])=>c(e,p.concat(t))),m(l.value)){if(t===a.Hydrate)return l.value;const c=p.slice(0,-1),u=c.length>0?y(r,c.join(\".\")):r;return i.isNullable(u)||v(u,l,p.at(-1),n,s,o),e??l.value}if(t===a.Hydrate){const t=f(c(l.value,p));return v(t,l,null,n,s,o),t}const d=e??f(l.value);return v(d,l,null,n,s,o),i.isNullable(e)?d:(c(l.value,p),e)}if(i.isArray(l))return l.map((t,e)=>c(t,p.concat(e)));if(i.isObject(l)&&!h(l))return l;if(i.isObject(l)){const e=Object.entries(l).map(([t,e])=>[t,c(e,p.concat(t))]),r=Object.fromEntries(e);if(t===a.Hydrate){const t=f(r);return Object.entries(l).forEach(([e,r])=>{r instanceof u&&m(r.value)&&v(t,r,e,n,s,o)}),t}return r}return l}(e.value)}function v(t,e,r,i,n,s){const o=s(t),a=n.get(o)??[];n.set(o,[e.assign(r,i),...a])}class O{#t={};#e;#r=/* @__PURE__ */new Map;#i=/* @__PURE__ */new Set;#n=!1;constructor(t=d){this.#e=t}static pk(){return s()}static\"κ\"=O.pk;annotate(t,e){return new u(e,t)}\"δ\"=this.annotate;get model(){return this.#t}get inspect(){return function(t,e,r,s,o){function a(s){const o=s.at(-1),a=y(t(),s),c=s.slice(0,-1),u=n.isNotEmpty(c)?y(t(),c):t();return[...i.isObject(a)||i.isArray(a)?e.get(r(a))?.filter(t=>i.isNullable(t.property))??[]:[],...i.isObject(u)?e.get(r(u))?.filter(t=>t.property===o)??[]:[]]}return function e(r){return new Proxy(()=>{},{get:(i,c)=>\"pending\"===c?()=>!n.isEmpty(a(r)):\"remaining\"===c?()=>n.length(a(r)):\"box\"===c?()=>({value:y(t(),r),inspect:e(r),[p]:!0}):\"is\"===c?t=>a(r).some(e=>0!==(e.operation&t)):\"draft\"===c?()=>n.head(a(r))?.value??y(t(),r):\"settled\"===c?()=>new Promise(e=>{if(n.isEmpty(a(r)))return e(y(t(),r));const i=()=>{n.isEmpty(a(r))&&(o(i),e(y(t(),r)))};s(i)}):e([...r,String(c)])})}([])}(()=>this.#t,this.#r,this.#e,t=>this.#i.add(t),t=>this.#i.delete(t))}hydrate(t){return this.#n=!0,this.#s(a.Hydrate,()=>t)}produce(t){if(!this.#n)throw new Error(\"State must be hydrated using hydrate() before calling produce()\");return this.#s(a.Produce,t)}#s(t,e){const r=Symbol(\"process\"),[,i]=l.immer.produceWithPatches(this.#t,e);return this.#t=i.reduce((e,i)=>l.immer.applyPatches(e,[{...i,value:g(t,i,e,r,this.#r,this.#e)}]),this.#t),this.#t=f(this.#t),this.#o(),r}prune(t){this.#r.forEach((e,r)=>{const i=e.filter(e=>e.process!==t);n.isEmpty(i)?this.#r.delete(r):this.#r.set(r,i)}),this.#o()}#o(){this.#i.forEach(t=>t())}observe(t){const e=()=>t(this.#t);return this.#i.add(e),()=>this.#i.delete(e)}}export{o as Op,o as Operation,O as State,b as isBox};\n","import * as React from \"react\";\nimport { State, Inspect } from \"immertation\";\nimport { G } from \"@mobily/ts-belt\";\nimport { useBroadcast } from \"../../../broadcast/index.tsx\";\nimport { useConsumer } from \"../../utils.ts\";\nimport { useRerender } from \"../../../../../utils/utils.ts\";\nimport { Entry, Model } from \"../../types.ts\";\nimport { Props } from \"./types.ts\";\n\n/**\n * Renders output for the `stream()` method by subscribing to distributed action events.\n *\n * This component manages a subscription to the broadcast emitter for distributed actions,\n * storing the latest dispatched value in the Consumer context. When a new value arrives,\n * all mounted Partition instances for that action re-render with the updated value.\n *\n * On mount, if a value was previously dispatched for this action, it renders immediately\n * with that cached value. If no value exists yet, it renders `null` until the first dispatch.\n *\n * Uses Immertation's State class internally to manage consumed values, providing real\n * annotation tracking through the `inspect` proxy. When a payload containing annotated\n * values is dispatched, the annotations are preserved and accessible via `inspect`.\n *\n * The renderer callback receives two arguments:\n * - `value`: The latest dispatched payload\n * - `inspect`: A proxy for checking annotation status (pending, is, draft, settled, etc.)\n *\n * @template T - The payload type for the action (must be an object type)\n * @param props.action - The distributed action symbol to subscribe to\n * @param props.renderer - Callback that receives value and inspect, returns React nodes\n * @returns The result of calling renderer, or null if no value exists\n * @internal\n */\nexport function Partition<T extends object>({\n action,\n renderer,\n}: Props<T>): React.ReactNode {\n const broadcast = useBroadcast();\n const consumer = useConsumer();\n const rerender = useRerender();\n\n const entry = React.useMemo(() => {\n const existing = consumer.get(action);\n if (existing) return existing as Entry<T>;\n\n const state = new State<Model<T>>();\n const cached = broadcast.getCached(action);\n if (G.isNotNullable(cached)) state.hydrate({ value: cached as T });\n const entry: Entry<T> = { state, listeners: new Set() };\n consumer.set(action, entry as unknown as Entry);\n return entry;\n }, [action, broadcast, consumer]);\n\n React.useLayoutEffect(() => {\n entry.listeners.add(rerender);\n\n function handlePayload(payload: T) {\n entry.state.hydrate({ value: payload });\n entry.listeners.forEach((listener) => listener());\n }\n\n broadcast.on(action, handlePayload);\n\n return () => {\n entry.listeners.delete(rerender);\n broadcast.off(action, handlePayload);\n };\n }, [action, broadcast, entry]);\n\n const value = entry.state.model?.value;\n if (G.isNullable(value)) return null;\n\n const inspect = entry.state.inspect as unknown as { value: Inspect<T> };\n\n return renderer(value, inspect.value);\n}\n","import type { Actions, HandlerContext, Model, Props } from \"../types/index.ts\";\nimport type { Env } from \"../boundary/components/env/types.ts\";\nimport type { WithHandle } from \"./types.ts\";\n\n/**\n * Walks the lodash-style dotted `path` on `target`, stopping one segment\n * short so callers can mutate or read the leaf via the returned `cursor`\n * and `key`. Used by every assignment helper below to avoid duplicating\n * the per-segment descent.\n *\n * @internal\n */\nexport function walk(\n target: unknown,\n path: string,\n): { cursor: Record<string, unknown>; key: string } {\n const segments = path.split(\".\");\n let cursor = <Record<string, unknown>>target;\n for (let i = 0; i < segments.length - 1; i++) {\n cursor = <Record<string, unknown>>cursor[segments[i]];\n }\n return { cursor, key: segments[segments.length - 1] };\n}\n\n/**\n * Assigns `value` to the leaf of `target` reached by lodash-style `path`.\n * Mutates in place &mdash; expected to be called from inside an Immer\n * `produce` draft.\n *\n * @internal\n */\nexport function setPath(target: unknown, path: string, value: unknown): void {\n const { cursor, key } = walk(target, path);\n cursor[key] = value;\n}\n\n/**\n * Flips the boolean leaf of `target` reached by lodash-style `path`.\n * Mutates in place &mdash; expected to be called from inside an Immer\n * `produce` draft.\n *\n * @internal\n */\nexport function invertPath(target: unknown, path: string): void {\n const { cursor, key } = walk(target, path);\n cursor[key] = !cursor[key];\n}\n\n/**\n * Returns a handler that assigns the dispatched payload to the model\n * leaf at lodash-style `key`. Underlies both `context.with.update` and\n * the top-level `With.Update`.\n *\n * @internal\n */\nexport function makeUpdate(key: string) {\n return (\n context: HandlerContext<Model, Actions, Props, Env>,\n payload: unknown,\n ) => {\n context.actions.produce((draft) => {\n setPath(draft.model, key, payload);\n });\n };\n}\n\n/**\n * Returns a handler that flips the boolean model leaf at lodash-style\n * `key`. Underlies both `context.with.invert` and `With.Invert`.\n *\n * @internal\n */\nexport function makeInvert(key: string) {\n return (context: HandlerContext<Model, Actions, Props, Env>) => {\n context.actions.produce((draft) => {\n invertPath(draft.model, key);\n });\n };\n}\n\n/**\n * Returns a handler that assigns the constant `value` to the model\n * leaf at lodash-style `key`, ignoring any dispatched payload.\n * Underlies both `context.with.always` and `With.Always`.\n *\n * @internal\n */\nexport function makeAlways(key: string, value: unknown) {\n return (context: HandlerContext<Model, Actions, Props, Env>) => {\n context.actions.produce((draft) => {\n setPath(draft.model, key, value);\n });\n };\n}\n\n/**\n * Builds the {@link WithHandle} object returned via `context.with`. The\n * runtime is identical for any model &mdash; only the call-site types differ.\n *\n * @internal\n */\nexport function bindWith<M extends Model | void>(): WithHandle<M> {\n return <WithHandle<M>>(<unknown>{\n update<K extends string>(key: K) {\n return makeUpdate(key);\n },\n invert<K extends string>(key: K) {\n return makeInvert(key);\n },\n always<K extends string>(key: K, value: unknown) {\n return makeAlways(key, value);\n },\n });\n}\n","import * as React from \"react\";\nimport { useActions } from \"../actions/index.ts\";\nimport { bindWith } from \"../with/utils.ts\";\nimport type {\n Actions,\n Context as ContextHandle,\n Model,\n Props,\n UseActions,\n} from \"../types/index.ts\";\nimport type { DispatchTarget } from \"./types.ts\";\n\n/**\n * Returns a stable, typed controller handle up-front &mdash; before a\n * model is declared via `context.useActions(...)`. Use this when an\n * external imperative library (form, animation, third-party SDK) needs a\n * dispatch callback at construction time, while the value that library\n * returns must flow back into the controller's data callback.\n *\n * The handle exposes `dispatch(action, payload?)`, a `useActions(...)`\n * method that materialises the component-local model and reactive data\n * &mdash; the M and D pair of `useContext<M, AC, D>` &mdash; and\n * returns the `[model, actions, data]` tuple with `useAction`, `dispatch`,\n * `inspect`, and `stream` attached, plus `with` &mdash; a bag of handler\n * factories (`update`/`invert`/`always`) typed against the declared model\n * and accepting lodash-style dotted paths and array indices. The first\n * invocation of `context.actions.dispatch(...)` must come from an event\n * handler &mdash; not synchronously during render &mdash; because the\n * underlying dispatch target is wired up when `context.useActions(...)`\n * runs in the same render pass.\n *\n * @template M The model type representing the component's state.\n * @template AC The actions class containing action definitions.\n * @template D The data type for reactive external values.\n *\n * @example\n * ```ts\n * const context = useContext<Model, typeof Actions, Data>();\n *\n * const form = useForm({\n * onSubmit: () => void context.actions.dispatch(Actions.Submit),\n * });\n *\n * const actions = context.useActions(\n * { user: resource.user.get() },\n * () => ({ form }),\n * );\n * ```\n *\n * @internal\n */\nexport function useContext<\n M extends Model | void = void,\n AC extends Actions | void = void,\n D extends Props = Props,\n>(): ContextHandle<M, AC, D> {\n const ref = React.useRef<DispatchTarget | null>(null);\n\n return React.useMemo(() => {\n function dispatch(action: unknown, payload?: unknown): Promise<void> {\n const target = ref.current;\n if (!target) {\n throw new Error(\n \"march-hare: useContext handle dispatched before its paired \" +\n \"context.useActions(...) ran. Call context.actions.dispatch from \" +\n \"event handlers, not synchronously during render.\",\n );\n }\n return target(action, payload);\n }\n\n function useActionsMethod(...args: unknown[]): unknown {\n const invoke = <(...passed: unknown[]) => UseActions<M, AC, D>>(\n (<unknown>useActions)\n );\n const result = invoke(...args);\n ref.current = <DispatchTarget>(<unknown>result.dispatch);\n return result;\n }\n\n return <ContextHandle<M, AC, D>>(<unknown>{\n actions: { dispatch },\n useActions: useActionsMethod,\n with: bindWith<M>(),\n });\n }, []);\n}\n","import * as React from \"react\";\nimport {\n useLifecycles,\n useData,\n isChanneledAction,\n getActionSymbol,\n matchesChannel,\n useRegisterHandler,\n useDispatchers,\n findLifecycleAction,\n isGenerator,\n emitAsync,\n replay,\n} from \"./utils.ts\";\nimport { useRerender } from \"../utils/utils.ts\";\nimport type { Data, Handler, Scope } from \"./types.ts\";\nimport {\n HandlerContext,\n Phase,\n Model,\n HandlerPayload,\n Props,\n Actions,\n ActionId,\n UseActions,\n Result,\n Task,\n Filter,\n ChanneledAction,\n ActionOrChanneled,\n AnyAction,\n FaultSymbol,\n EnvSymbol,\n} from \"../types/index.ts\";\n\nimport { getReason, getError } from \"../error/utils.ts\";\nimport { Aborted } from \"../error/index.ts\";\nimport EventEmitter from \"eventemitter3\";\nimport { useBroadcast } from \"../boundary/components/broadcast/index.tsx\";\nimport { useScope, getScope } from \"../boundary/components/scope/index.tsx\";\nimport { useEnv, useEnvRef } from \"../boundary/components/env/utils.ts\";\nimport type { Env } from \"../boundary/components/env/types.ts\";\nimport { produce as produceImmer } from \"immer\";\nimport { nuke } from \"../resource/index.ts\";\nimport type { Coalesce, Invocation } from \"../resource/types.ts\";\nimport {\n coalesceKey,\n withAbort,\n token as defaultCoalesceToken,\n} from \"../coalesce/index.ts\";\nimport { unset } from \"../utils/utils.ts\";\nimport {\n isBroadcastAction,\n isMulticastAction,\n getName,\n} from \"../action/index.ts\";\nimport { State, Operation, Process, Inspect } from \"immertation\";\nimport { useTasks } from \"../boundary/components/tasks/utils.ts\";\nimport { Partition } from \"../boundary/components/consumer/index.tsx\";\nimport type { ConsumerRenderer } from \"../boundary/components/consumer/types.ts\";\nimport { G } from \"@mobily/ts-belt\";\nimport { useSharing } from \"../boundary/components/sharing/index.tsx\";\nimport { useTap } from \"../boundary/components/tap/utils.ts\";\n\n/**\n * A hook for managing state with actions.\n *\n * Call `useActions` first, then use `actions.useAction` to bind handlers\n * to action symbols. Types are pre-baked from the generic parameters, so\n * no additional type annotations are needed on handler calls.\n *\n * The hook returns a result containing:\n * 1. The current model state\n * 2. An actions object with `dispatch`, `inspect`, and `useAction`\n * 3. A read-only snapshot of the data values produced by `getData` &mdash;\n * the same values handlers read via `context.data`, exposed here for\n * JSX consumption so the view and the handler share one named source.\n *\n * The `inspect` property provides access to Immertation's annotation system,\n * allowing you to check for pending operations on model properties.\n *\n * @template M The model type representing the component's state.\n * @template AC The actions class containing action definitions.\n * @template D The data type for reactive external values.\n * @param model The initial model state.\n * @param getData Optional function that returns reactive values as data.\n * Values returned are accessible via `context.data` in action handlers,\n * always reflecting the latest values even after await operations.\n * @returns A result `[model, actions, data]` with pre-typed `useAction` method.\n *\n * @example\n * ```typescript\n * // Basic usage\n * const [model, actions] = useActions<Model, typeof Actions>(model);\n *\n * // Without a model (actions-only)\n * const [, actions] = useActions<void, typeof Actions>();\n *\n * // With reactive data &mdash; consumed in JSX and handlers alike.\n * const [model, actions, data] = useActions<\n * Model,\n * typeof Actions,\n * { query: string }\n * >(model, () => ({ query: props.query }));\n * ```\n */\nexport function useActions<\n M extends void = void,\n A extends Actions | void = void,\n D extends Props = Props,\n>(getData?: Data<D>): UseActions<M, A, D>;\nexport function useActions<\n M extends Model,\n A extends Actions | void = void,\n D extends Props = Props,\n>(model: M, getData?: Data<D>): UseActions<M, A, D>;\nexport function useActions<\n M extends Model | void,\n A extends Actions | void,\n D extends Props = Props,\n>(...args: unknown[]): unknown {\n const isVoidModel = G.isUndefined(args[0]) || G.isFunction(args[0]);\n const initialModel = <Model>(isVoidModel ? {} : args[0]);\n const getData: Data<D> = G.isFunction(args[0])\n ? <Data<D>>args[0]\n : <Data<D>>(args[1] ?? (() => <D>{}));\n\n const broadcast = useBroadcast();\n const scope = useScope();\n const tasks = useTasks();\n const env = useEnv();\n const slot = useEnvRef();\n const sharing = useSharing();\n const tap = useTap();\n const rerender = useRerender();\n const initialised = React.useRef(false);\n const hydration = React.useRef<Process | null>(null);\n const state = React.useRef(new State<Model>());\n\n if (!initialised.current) {\n initialised.current = true;\n hydration.current = state.current.hydrate(initialModel);\n }\n const [model, setModel] = React.useState<M>(\n () => <M>(<unknown>state.current.model),\n );\n const data = useData(getData());\n const unicast = React.useMemo(() => new EventEmitter(), []);\n const registry = React.useRef<Scope<M, A, D>>({ handlers: new Map() });\n registry.current.handlers = new Map();\n const dispatchers = useDispatchers();\n const phase = React.useRef<Phase>(Phase.Mounting);\n const localTasks = React.useRef<Set<Task>>(new Set());\n const unmountGeneration = React.useRef(0);\n\n /**\n * Creates the context object passed to action handlers during dispatch.\n *\n * @param action The action symbol being dispatched.\n * @param payload The payload passed with the action.\n * @param result Container for tracking Immertation processes created during execution.\n * @returns A fully-typed Context object for the action handler.\n */\n const getContext = React.useCallback(\n (action: ActionId, payload: unknown, result: Result) => {\n const controller = new AbortController();\n const task: Task = { controller, action, payload };\n tasks.add(task);\n localTasks.current.add(task);\n\n return <HandlerContext<M, A, D>>(<unknown>{\n model: state.current.model,\n get phase() {\n return phase.current;\n },\n task,\n data,\n tasks,\n env,\n actions: {\n produce(\n f: (draft: {\n model: M;\n readonly inspect: Readonly<Inspect<M>>;\n env: Env;\n }) => void,\n ) {\n if (controller.signal.aborted) return;\n const slotBefore = slot.current;\n const process = state.current.produce((draft) => {\n slot.current = produceImmer(slot.current, (envDraft) => {\n f({\n model: <M>(<unknown>draft),\n inspect: <Readonly<Inspect<M>>>(\n (<unknown>state.current.inspect)\n ),\n env: <Env>envDraft,\n });\n });\n });\n setModel(<M>(<unknown>state.current.model));\n if (slot.current !== slotBefore) {\n broadcast.emit(EnvSymbol, slot.current);\n }\n result.processes.add(process);\n if (hydration.current) {\n result.processes.add(hydration.current);\n hydration.current = null;\n }\n },\n dispatch(\n action: ActionOrChanneled,\n payload?: HandlerPayload,\n ): Promise<void> {\n if (controller.signal.aborted) return Promise.resolve();\n const base = getActionSymbol(action);\n const channel = isChanneledAction(action)\n ? action.channel\n : undefined;\n\n if (isMulticastAction(action)) {\n const scoped = getScope(scope);\n if (scoped)\n return emitAsync(scoped.emitter, base, payload, channel);\n return Promise.resolve();\n }\n\n const emitter = isBroadcastAction(action) ? broadcast : unicast;\n return emitAsync(emitter, base, payload, channel);\n },\n annotate<T>(value: T, operation: Operation = Operation.Update): T {\n return state.current.annotate(operation, value);\n },\n get inspect() {\n return state.current.inspect;\n },\n resource: Object.assign(\n function resourceCall<T, P extends object>(call: Invocation<T, P>) {\n const dispatchFromResource = (\n action: unknown,\n payload?: unknown,\n ): Promise<void> => {\n if (controller.signal.aborted) return Promise.resolve();\n const a = <AnyAction>action;\n const base = getActionSymbol(a);\n if (isMulticastAction(a)) {\n const scoped = getScope(scope);\n if (scoped)\n return emitAsync(scoped.emitter, base, payload, undefined);\n return Promise.resolve();\n }\n if (isBroadcastAction(a)) {\n return emitAsync(broadcast, base, payload, undefined);\n }\n return Promise.resolve();\n };\n const options: {\n exceedsWindow: Temporal.DurationLike | null;\n coalesceToken: Coalesce | undefined;\n } = { exceedsWindow: null, coalesceToken: undefined };\n const fetch = (): Promise<T> => {\n if (G.isNotNullable(options.exceedsWindow)) {\n const { data, at } = call.read(call.params);\n if (data !== unset && G.isNotNullable(at)) {\n const elapsed = Temporal.Now.instant().since(at);\n const window = Temporal.Duration.from(\n options.exceedsWindow,\n );\n if (Temporal.Duration.compare(elapsed, window) <= 0) {\n return Promise.resolve(<T>data);\n }\n }\n }\n if (G.isUndefined(options.coalesceToken)) {\n return <Promise<T>>(\n call.run(env, controller, call.params, dispatchFromResource)\n );\n }\n let mutable = sharing.get(call.run);\n if (G.isUndefined(mutable)) {\n mutable = new Map<string, Promise<unknown>>();\n sharing.set(call.run, mutable);\n }\n const bucket = mutable;\n const key = `${JSON.stringify(call.params)}|${coalesceKey(options.coalesceToken)}`;\n const existing = <Promise<T> | undefined>bucket.get(key);\n if (existing) return withAbort(existing, controller.signal);\n const detached = new AbortController();\n const shared = (<Promise<T>>(\n call.run(env, detached, call.params, dispatchFromResource)\n )).finally(() => {\n bucket.delete(key);\n });\n bucket.set(key, shared);\n return withAbort(shared, controller.signal);\n };\n const handle = {\n then<U = T, V = never>(\n onFulfilled?:\n | ((value: T) => U | PromiseLike<U>)\n | null\n | undefined,\n onRejected?:\n | ((reason: unknown) => V | PromiseLike<V>)\n | null\n | undefined,\n ): Promise<U | V> {\n return fetch().then(onFulfilled, onRejected);\n },\n exceeds(duration: Temporal.DurationLike) {\n options.exceedsWindow = duration;\n return handle;\n },\n coalesce(token?: Coalesce) {\n options.coalesceToken = token ?? defaultCoalesceToken;\n return handle;\n },\n evict(where?: object): void {\n call.evict(where ?? call.params);\n },\n };\n return handle;\n },\n {\n nuke: (where?: object): void => nuke(where),\n },\n ),\n async final(action: AnyAction) {\n if (controller.signal.aborted) return null;\n const key = getActionSymbol(action);\n const emitter = isMulticastAction(action)\n ? (getScope(scope)?.emitter ?? null)\n : broadcast;\n if (!emitter) return null;\n const cached = emitter.getCached(key);\n if (G.isUndefined(cached)) return null;\n const inspector = state.current.inspect;\n if (inspector.pending()) {\n await new Promise<void>((resolve, reject) => {\n if (controller.signal.aborted)\n return void reject(controller.signal.reason);\n const onAbort = () => reject(controller.signal.reason);\n controller.signal.addEventListener(\"abort\", onAbort, {\n once: true,\n });\n void inspector.settled().then(() => {\n controller.signal.removeEventListener(\"abort\", onAbort);\n resolve();\n });\n });\n }\n return emitter.getCached(key) ?? null;\n },\n peek(action: AnyAction) {\n if (controller.signal.aborted) return null;\n const key = getActionSymbol(action);\n const emitter = isMulticastAction(action)\n ? (getScope(scope)?.emitter ?? null)\n : broadcast;\n if (!emitter) return null;\n return emitter.getCached(key) ?? null;\n },\n },\n });\n },\n [model],\n );\n\n React.useLayoutEffect(() => {\n unmountGeneration.current++;\n\n function createHandler(\n action: ActionId,\n actionHandler: Handler<M, A, D>,\n getChannel: () => Filter | undefined,\n ) {\n return function handler(\n payload: HandlerPayload,\n dispatchChannel?: Filter | typeof replay,\n ) {\n const registeredChannel = getChannel();\n\n // Skip channeled handlers during replay — they require specific\n // channel context and cannot process a replay without it.\n if (dispatchChannel === replay && G.isNotNullable(registeredChannel))\n return;\n\n if (\n G.isNotNullable(dispatchChannel) &&\n dispatchChannel !== replay &&\n G.isNotNullable(registeredChannel)\n ) {\n if (!matchesChannel(dispatchChannel, registeredChannel)) return;\n }\n\n const result = <Result>{ processes: new Set<Process>() };\n const completion = Promise.withResolvers<void>();\n const context = getContext(action, payload, result);\n const actionName = getName(action);\n const startedAt = performance.now();\n const modelBefore = <unknown>state.current.model;\n const envBefore = <unknown>slot.current;\n let errored = false;\n\n function mutations() {\n const modelAfter = <unknown>state.current.model;\n const envAfter = <unknown>slot.current;\n return {\n model:\n modelBefore === modelAfter\n ? null\n : { before: modelBefore, after: modelAfter },\n env:\n envBefore === envAfter\n ? null\n : { before: envBefore, after: envAfter },\n };\n }\n\n tap({\n stage: \"start\",\n action: { name: actionName, payload },\n details: { task: context.task },\n });\n\n function retry(): Promise<void> {\n const channel: Filter | undefined =\n dispatchChannel === replay ? undefined : dispatchChannel;\n if (isMulticastAction(action)) {\n const scoped = getScope(scope);\n if (!scoped) return Promise.resolve();\n return emitAsync(scoped.emitter, action, payload, channel);\n }\n const emitter = isBroadcastAction(action) ? broadcast : unicast;\n return emitAsync(emitter, action, payload, channel);\n }\n\n function onError(caught: unknown) {\n errored = true;\n const errorAction = findLifecycleAction(\n registry.current.handlers,\n \"Error\",\n );\n const handled = G.isNotNullable(errorAction);\n const reason = getReason(caught);\n const error = getError(caught);\n const details = {\n reason,\n error,\n action: actionName,\n handled,\n tasks,\n retry,\n };\n broadcast.fire(FaultSymbol, details);\n if (handled && errorAction) unicast.emit(errorAction, details);\n tap({\n stage: \"end\",\n result: \"error\",\n action: { name: actionName, payload },\n details: {\n task: context.task,\n elapsed: performance.now() - startedAt,\n mutations: mutations(),\n error,\n reason,\n },\n });\n }\n\n function onSettled() {\n for (const task of tasks) {\n if (task === context.task) {\n tasks.delete(task);\n localTasks.current.delete(task);\n break;\n }\n }\n result.processes.forEach((process) => state.current.prune(process));\n if (result.processes.size > 0) rerender();\n if (!errored) {\n tap({\n stage: \"end\",\n result: \"success\",\n action: { name: actionName, payload },\n details: {\n task: context.task,\n elapsed: performance.now() - startedAt,\n mutations: mutations(),\n },\n });\n }\n completion.resolve();\n }\n\n let returnValue: ReturnType<Handler<M, A, D>>;\n try {\n returnValue = actionHandler(context, payload);\n } catch (caught) {\n onError(caught);\n onSettled();\n return completion.promise;\n }\n\n if (isGenerator(returnValue)) {\n (async () => {\n for await (const _ of returnValue) void 0;\n })()\n .catch(onError)\n .finally(onSettled);\n return completion.promise;\n }\n\n Promise.resolve(returnValue).catch(onError).finally(onSettled);\n return completion.promise;\n };\n }\n\n const cleanups = new Set<() => void>();\n\n registry.current.handlers.forEach((entries, action) => {\n for (const { getChannel, handler: actionHandler } of entries) {\n const handler = createHandler(action, actionHandler, getChannel);\n\n if (isMulticastAction(action)) {\n if (scope) {\n const emitter = scope.emitter;\n emitter.on(action, handler);\n cleanups.add(() => emitter.off(action, handler));\n }\n unicast.on(action, handler);\n dispatchers.multicast.add(action);\n cleanups.add(() => unicast.off(action, handler));\n } else if (isBroadcastAction(action)) {\n broadcast.on(action, handler);\n unicast.on(action, handler);\n dispatchers.broadcast.add(action);\n cleanups.add(() => {\n broadcast.off(action, handler);\n unicast.off(action, handler);\n });\n } else {\n unicast.on(action, handler);\n cleanups.add(() => unicast.off(action, handler));\n }\n }\n });\n\n return () => {\n const generation = ++unmountGeneration.current;\n const pendingCleanups = new Set(cleanups);\n\n queueMicrotask(() => {\n if (unmountGeneration.current !== generation) {\n for (const cleanup of pendingCleanups) cleanup();\n return;\n }\n\n for (const task of localTasks.current) {\n task.controller.abort(new Aborted(\"Component unmounted\"));\n tasks.delete(task);\n }\n localTasks.current.clear();\n\n phase.current = Phase.Unmounting;\n const unmountAction = findLifecycleAction(\n registry.current.handlers,\n \"Unmount\",\n );\n if (unmountAction) unicast.emit(unmountAction);\n phase.current = Phase.Unmounted;\n\n for (const cleanup of pendingCleanups) cleanup();\n });\n };\n }, [unicast]);\n\n useLifecycles({\n unicast,\n broadcast,\n tasks,\n dispatchers,\n scope,\n phase,\n data: getData(),\n handlers: registry.current.handlers,\n });\n\n const actionsApi = React.useMemo(\n () => ({\n dispatch(\n action: ActionOrChanneled,\n payload?: HandlerPayload,\n ): Promise<void> {\n const base = getActionSymbol(action);\n const channel = isChanneledAction(action) ? action.channel : undefined;\n\n if (isMulticastAction(action)) {\n const scoped = getScope(scope);\n if (scoped) return emitAsync(scoped.emitter, base, payload, channel);\n return Promise.resolve();\n }\n\n const emitter = isBroadcastAction(action) ? broadcast : unicast;\n return emitAsync(emitter, base, payload, channel);\n },\n get inspect() {\n return state.current.inspect;\n },\n stream(\n action: AnyAction,\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n renderer: ConsumerRenderer<any>,\n ): React.ReactNode {\n return React.createElement(Partition, {\n action: <symbol>getActionSymbol(action),\n renderer,\n });\n },\n }),\n [model, unicast],\n );\n\n const result = React.useMemo(\n () => <UseActions<M, A, D>>(<unknown>[model, actionsApi, data]),\n [model, actionsApi, data],\n );\n\n // The public `useAction` signature constrains the action argument to\n // `Subscribable<AC>` (leaf actions on `AC` plus `Lifecycle.Fault`) split\n // into no-payload / with-payload overloads. The runtime is AC-agnostic,\n // so the impl is typed against the loose `ActionOrChanneled` union and\n // cast back to the strict public type.\n const useActionImpl = (\n action: ActionId | HandlerPayload | ChanneledAction,\n handler: Handler<M, A, D>,\n ): void => {\n useRegisterHandler<M, A, D>(registry, action, handler);\n };\n (<UseActions<M, A, D>>result).useAction = <UseActions<M, A, D>[\"useAction\"]>(\n (<unknown>useActionImpl)\n );\n (<UseActions<M, A, D>>result).dispatch = <UseActions<M, A, D>[\"dispatch\"]>(\n (<unknown>result[1].dispatch)\n );\n\n return <UseActions<M, A, D>>result;\n}\n","import { Reason } from \"./types.ts\";\n\n/**\n * Determines the error reason based on what was thrown.\n *\n * @param error - The value that was thrown.\n * @returns The appropriate Reason enum value.\n */\nexport function getReason(error: unknown): Reason {\n const isAborted = error instanceof Error && error.name === \"AbortError\";\n return isAborted ? Reason.Aborted : Reason.Errored;\n}\n\n/**\n * Gets an Error instance from a thrown value.\n *\n * @param error - The value that was thrown.\n * @returns An Error instance (original if already Error, wrapped otherwise).\n */\nexport function getError(error: unknown): Error {\n return error instanceof Error ? error : new Error(String(error));\n}\n","import * as React from \"react\";\nimport { BroadcastEmitter } from \"../boundary/components/broadcast/utils.ts\";\nimport { Context as ScopeReactContext } from \"../boundary/components/scope/utils.ts\";\nimport type { ScopeEntry } from \"../boundary/components/scope/types.ts\";\nimport { useContext as baseUseContext } from \"../context/index.ts\";\nimport { useEnv as baseUseEnv } from \"../boundary/components/env/utils.ts\";\nimport { Resource as BaseResource } from \"../resource/index.ts\";\nimport type { ResourceHandle } from \"../resource/types.ts\";\nimport type { Cache } from \"../cache/index.ts\";\nimport type { Env } from \"../boundary/components/env/types.ts\";\nimport type { AppContextHandle, AppFetcher } from \"../app/types.ts\";\nimport type { Actions, Model, Props } from \"../types/index.ts\";\nimport type { ScopeHandle } from \"./types.ts\";\n\n/**\n * Internal constructor for a {@link ScopeHandle}. Called from inside\n * `App<E>()` so the enclosing Env shape `E` is captured at the type\n * level. The optional `cache` is the same value `App({ cache })` was\n * constructed with &mdash; resources declared via `scope.Resource`\n * share that cache. `getEnv` resolves the live Env from the enclosing\n * `app.Boundary` so cache-key scoping works for sync `.get()` reads.\n *\n * @internal\n */\nexport function createScope<E extends object, MulticastActions>(\n cache?: Cache,\n getEnv?: () => Env | undefined,\n): ScopeHandle<E, MulticastActions> {\n function Boundary({\n children,\n }: {\n children: React.ReactNode;\n }): React.ReactElement {\n const entry = React.useMemo<ScopeEntry>(\n () => ({\n id: Symbol(\"march-hare.scope/instance\"),\n emitter: new BroadcastEmitter(),\n }),\n [],\n );\n return (\n <ScopeReactContext.Provider value={entry}>\n {children}\n </ScopeReactContext.Provider>\n );\n }\n\n function useTypedContext<\n LocalModel extends Model | void = void,\n AC extends Actions | void = void,\n D extends Props = Props,\n >(): AppContextHandle<\n LocalModel,\n MulticastActions extends Actions\n ? AC extends Actions\n ? AC & MulticastActions\n : MulticastActions\n : AC,\n D,\n E\n > {\n return baseUseContext() as unknown as AppContextHandle<\n LocalModel,\n MulticastActions extends Actions\n ? AC extends Actions\n ? AC & MulticastActions\n : MulticastActions\n : AC,\n D,\n E\n >;\n }\n\n function useTypedEnv(): Readonly<E> {\n return baseUseEnv() as unknown as Readonly<E>;\n }\n\n function Resource<T, P extends object = Record<never, never>>(\n fetcher: AppFetcher<E, T, P>,\n ): ResourceHandle<T, P> {\n return BaseResource<E, T, P>(fetcher, cache, getEnv);\n }\n\n return {\n Boundary,\n useContext: useTypedContext,\n useEnv: useTypedEnv,\n Resource,\n };\n}\n","import * as React from \"react\";\nimport { Boundary as BaseBoundary } from \"../boundary/index.tsx\";\nimport { useContext as baseUseContext } from \"../context/index.ts\";\nimport { useEnv as baseUseEnv } from \"../boundary/components/env/utils.ts\";\nimport type { Env } from \"../boundary/components/env/types.ts\";\nimport { Resource as BaseResource } from \"../resource/index.ts\";\nimport type { ResourceHandle } from \"../resource/types.ts\";\nimport type { Cache } from \"../cache/index.ts\";\nimport type { Actions, Model, Props } from \"../types/index.ts\";\nimport { createScope } from \"../scope/utils.tsx\";\nimport type { AppHandle, AppContextHandle, AppFetcher } from \"./types.ts\";\nimport type { Tap } from \"../boundary/components/tap/types.ts\";\n\nexport type {\n AppArgs,\n AppContextHandle,\n AppFetcher,\n AppResource,\n} from \"./types.ts\";\n\nexport type { AppHandle } from \"./types.ts\";\n\n/**\n * Creates an `App` &mdash; the entrypoint for a typed Env shape `E`,\n * inferred from `config.env`. `App<E>` exposes `Boundary`, hooks, and\n * a `Resource` factory all wired against the same shape.\n *\n * Each `<app.Boundary>` instance owns its own Env, so different `App`s\n * can coexist in the same tree with completely independent shapes.\n *\n * Pass `tap` to subscribe to every action handler's dispatch / settle /\n * error inside the boundary &mdash; useful for analytics, audit logging,\n * Sentry breadcrumbs. See `recipes/tap.md`. Pass `cache` to persist\n * every `app.Resource(fetcher)` declaration through a single\n * {@link Cache} &mdash; each resource is namespaced inside the cache by\n * its declaration order, so reloads seed from storage automatically and\n * resources do not collide on shared params keys. Omit `cache` to keep\n * each resource's payloads in an isolated in-memory slot.\n *\n * `env`, `tap`, and `cache` are all fixed at `App()` time;\n * `<app.Boundary>` does not accept overrides. Mutate the live Env\n * through `context.actions.produce(({ env }) => …)`, and declare a\n * separate `App` when a test or storybook needs a different initial\n * value.\n *\n * @example\n * ```tsx\n * import { App, Cache, type Taps } from \"march-hare\";\n *\n * type Session = { accessToken: string };\n *\n * function tap(event: Taps) {\n * if (event.type === \"error\") {\n * Sentry.captureException(event.error, { tags: { action: event.action } });\n * }\n * }\n *\n * export const app = App({\n * env: {\n * session: null as Session | null,\n * operating: \"idle\" as \"idle\" | \"signing-out\",\n * },\n * tap,\n * cache: Cache({\n * get: (key) => localStorage.getItem(key),\n * set: (key, value) => localStorage.setItem(key, value),\n * remove: (key) => localStorage.removeItem(key),\n * clear: () => localStorage.clear(),\n * }),\n * });\n *\n * // Root render.\n * <app.Boundary>\n * <Root />\n * </app.Boundary>;\n *\n * // In resources.ts &mdash; persisted via the App's cache.\n * export const user = app.Resource<User>((context) =>\n * ky\n * .get(\"/api/user\", {\n * headers: context.env.session\n * ? { Authorization: `Bearer ${context.env.session.accessToken}` }\n * : {},\n * signal: context.controller.signal,\n * })\n * .json<User>(),\n * );\n * ```\n */\nexport function App<E extends object = Env>(config?: {\n env?: E;\n tap?: Tap;\n cache?: Cache;\n}): AppHandle<E> {\n const envHolder: { current: Env | undefined } = { current: undefined };\n\n function Boundary({\n children,\n }: {\n children: React.ReactNode;\n }): React.ReactElement {\n return (\n <BaseBoundary env={config?.env as Env} tap={config?.tap}>\n <SyncEnvHolder holder={envHolder} />\n {children}\n </BaseBoundary>\n );\n }\n\n function useTypedContext<\n M extends Model | void = void,\n AC extends Actions | void = void,\n D extends Props = Props,\n >(): AppContextHandle<M, AC, D, E> {\n return baseUseContext() as unknown as AppContextHandle<M, AC, D, E>;\n }\n\n function useTypedEnv(): Readonly<E> {\n return baseUseEnv() as unknown as Readonly<E>;\n }\n\n function Resource<T, P extends object = Record<never, never>>(\n fetcher: AppFetcher<E, T, P>,\n ): ResourceHandle<T, P> {\n return BaseResource<E, T, P>(\n fetcher,\n config?.cache,\n () => envHolder.current,\n );\n }\n\n return {\n Boundary,\n useContext: useTypedContext,\n useEnv: useTypedEnv,\n Resource,\n Scope<MulticastActions>() {\n return createScope<E, MulticastActions>(\n config?.cache,\n () => envHolder.current,\n );\n },\n };\n}\n\n/**\n * Side-effect-only child of `app.Boundary` that captures the live Env\n * proxy from the enclosing `<Env>` provider and writes it into the\n * App's `envHolder` on every render. The proxy itself is stable per\n * boundary &mdash; subsequent renders re-assign the same reference, so\n * the holder behaves like a `ref.current` slot the App's `Resource`\n * factory can read from at any time (including from sync `.get()`\n * calls executed outside of action handlers).\n *\n * @internal\n */\nfunction SyncEnvHolder({\n holder,\n}: {\n holder: { current: Env | undefined };\n}): null {\n const env = baseUseEnv();\n holder.current = env;\n return null;\n}\n\n/**\n * Standalone counterpart to `app.useContext`, exported as\n * `shared.useContext` &mdash; same call shape, but takes the **Env\n * shape `E` as a mandatory first generic** so the caller can be a\n * reusable component that isn't tied to a single `App` import.\n *\n * `E` is the Env type your component expects to see &mdash; usually\n * a union of every App's Env shape it might run under. Inside the\n * handler, `context.env` is typed as `E`; reach for `in` / `typeof`\n * narrowing for keys present on only a subset.\n *\n * Pass `app` directly if you only need to talk to one App &mdash;\n * `app.useContext<Model, typeof Actions>()` is shorter and infers the\n * Env from the value. Reach for the standalone form only when a\n * component must support more than one App.\n *\n * @template E The Env shape (or union) the component supports.\n * @template M The model type, or `void`.\n * @template AC The Actions class, or `void`.\n * @template D The reactive data type returned from the `useActions`\n * data callback.\n *\n * @example\n * ```tsx\n * import { Action, shared } from \"march-hare\";\n *\n * type WebEnv = { session: Session | null; locale: string };\n * type MobileEnv = { session: Session | null; platform: \"ios\" | \"android\" };\n * type Envs = WebEnv | MobileEnv;\n *\n * type Model = { name: string | null };\n * const model: Model = { name: null };\n *\n * class Actions {\n * static Sign = Action<string>(\"Sign\");\n * }\n *\n * function useProfileActions() {\n * const context = shared.useContext<Envs, Model, typeof Actions>();\n * const actions = context.useActions(model);\n *\n * actions.useAction(Actions.Sign, (context, name) =>\n * context.actions.produce(({ model }) => void (model.name = name)),\n * );\n *\n * return actions;\n * }\n * ```\n */\nexport function useContext<\n E extends object,\n M extends Model | void = void,\n A extends Actions | void = void,\n D extends Props = Props,\n>(): AppContextHandle<M, A, D, E> {\n return baseUseContext() as unknown as AppContextHandle<M, A, D, E>;\n}\n\n/**\n * Standalone counterpart to `app.useEnv`, exported as `shared.useEnv`\n * &mdash; reads the nearest `<app.Boundary>`'s Env, typed against the\n * Env shape `E` supplied at the call site. For reusable components\n * that need an Env read outside any action handler (e.g. to hand a\n * closure to an external library at module bridge time).\n *\n * @template E The Env shape (or union) the component supports.\n *\n * @example\n * ```tsx\n * import { shared } from \"march-hare\";\n *\n * type WebEnv = { session: Session | null };\n * type MobileEnv = { session: Session | null };\n *\n * function SessionBadge() {\n * const env = shared.useEnv<WebEnv | MobileEnv>();\n * return <span>{env.session ? env.session.user.name : \"Signed out\"}</span>;\n * }\n * ```\n */\nexport function useEnv<E extends object>(): Readonly<E> {\n return baseUseEnv() as unknown as Readonly<E>;\n}\n","import type { Actions, HandlerContext, Model, Props } from \"../types/index.ts\";\nimport type { Env } from \"../boundary/components/env/types.ts\";\nimport type { BooleanPaths, Get, Paths } from \"./types.ts\";\nimport { makeAlways, makeInvert, makeUpdate } from \"./utils.ts\";\n\n/**\n * Handler factories that wire an action directly to a model field. Prefer\n * `context.with` from `useContext<Model>()` for first-class autocompletion\n * over dotted paths; this top-level form is kept for callers that don't have\n * a typed `context` in scope.\n *\n * - {@link With.Update} assigns the dispatched payload to a model path.\n * - {@link With.Invert} flips a boolean leaf at a model path.\n * - {@link With.Always} assigns a fixed value to a model path, ignoring any\n * dispatched payload.\n *\n * Keys may be lodash-style dotted paths (`\"a.b.c\"`) and support array\n * indices (`\"items.0.name\"`). The model type is inferred at handler-bind\n * time; an invalid path or mismatched payload fails to compile when the\n * handler is registered with `useAction`.\n *\n * @example\n * ```ts\n * import { With } from \"march-hare\";\n *\n * type Model = {\n * name: string;\n * sidebar: boolean;\n * nested: { open: boolean };\n * items: { id: number }[];\n * };\n *\n * actions.useAction(Actions.SetName, With.Update(\"name\"));\n * actions.useAction(Actions.SetFirstId, With.Update(\"items.0.id\"));\n * actions.useAction(Actions.ToggleSidebar, With.Invert(\"sidebar\"));\n * actions.useAction(Actions.ToggleNested, With.Invert(\"nested.open\"));\n * actions.useAction(Actions.Open, With.Always(\"nested.open\", true));\n * ```\n */\nexport const With = {\n /**\n * Returns a handler that assigns the action payload to the model leaf at\n * the given lodash-style path. The payload type must match `Get<M, K>`,\n * and the path must exist on the model.\n *\n * @template K The dotted-path string indexing into the model.\n * @param key The lodash-style path to the model leaf being assigned.\n */\n Update<K extends string>(\n key: K,\n ): <\n M extends Model,\n A extends Actions | void,\n D extends Props,\n P extends K extends Paths<M> ? Get<M, K> : never,\n E extends Env = Env,\n >(\n context: HandlerContext<M, A, D, E>,\n payload: P,\n ) => void {\n return <(context: unknown, payload: unknown) => void>makeUpdate(key);\n },\n /**\n * Returns a handler that inverts a boolean leaf at the given lodash-style\n * path. The leaf must be a `boolean` on the model.\n *\n * @template K The dotted-path string indexing into a boolean leaf.\n * @param key The lodash-style path to the boolean leaf being toggled.\n */\n Invert<K extends string>(\n key: K,\n ): <\n M extends Model,\n A extends Actions | void,\n D extends Props,\n E extends Env = Env,\n >(\n context: K extends BooleanPaths<M> ? HandlerContext<M, A, D, E> : never,\n ) => void {\n return <(context: unknown) => void>makeInvert(key);\n },\n /**\n * Returns a handler that assigns a fixed `value` to the model leaf at the\n * given lodash-style path. The dispatched payload (if any) is ignored.\n *\n * @template K The dotted-path string indexing into the model.\n * @template V The constant value type; must be assignable to the leaf at `K`.\n * @param key The lodash-style path to the model leaf being assigned.\n * @param value The constant value pinned to the leaf.\n */\n Always<K extends string, V>(\n key: K,\n value: V,\n ): <\n M extends Model,\n A extends Actions | void,\n D extends Props,\n E extends Env = Env,\n >(\n context: K extends Paths<M>\n ? V extends Get<M, K>\n ? HandlerContext<M, A, D, E>\n : never\n : never,\n ) => void {\n return <(context: unknown) => void>makeAlways(key, value);\n },\n};\n","import { State, Operation } from \"immertation\";\n\n/**\n * Module-level Immertation state instance used to annotate initial model values\n * with operation metadata (e.g., {@link Operation}) before hydration.\n *\n * This is intentionally a singleton — it exists solely to provide the\n * {@link annotate} helper with access to `State.annotate`, without requiring\n * consumers to instantiate their own `State` object.\n */\nconst state = new State();\n\n/**\n * Wraps a value with an operation annotation for use in initial model definitions.\n * When passed as part of the initial model to `useActions`, the annotation is\n * registered during hydration so that `actions.inspect` reports the field as pending\n * from the very first render.\n *\n * @param value - The value to annotate.\n * @param operation - The operation type (defaults to {@link Operation.Update}).\n * @returns The annotated value (typed as T for assignment compatibility).\n *\n * @example\n * ```ts\n * import { annotate } from \"march-hare\";\n *\n * type Model = { user: User | null };\n *\n * const model: Model = {\n * user: annotate(null),\n * };\n *\n * // actions.inspect.user.pending() === true from the first render\n * ```\n */\nexport function annotate<T>(\n value: T,\n operation: Operation = Operation.Update,\n): T {\n return state.annotate(operation, value);\n}\n","import { Pk } from \"../types/index.ts\";\nimport { Aborted } from \"../error/index.ts\";\n\nexport { unset } from \"./utils.ts\";\nexport type { Stored, Unset } from \"./types.ts\";\n\n/**\n * Returns a promise that resolves after the specified number of\n * milliseconds, or rejects with an {@link Aborted} when the signal is aborted. Use to inject a cancellable\n * delay into an action handler.\n *\n * @param ms How long to wait before resolving.\n * @param signal Optional {@link AbortSignal} that cancels the sleep early.\n * Pass `context.task.controller.signal` to tie the wait to\n * the lifetime of the current action.\n * @returns A promise that resolves after `ms` milliseconds or rejects with\n * an {@link Aborted} if `signal` aborts first.\n */\nexport function sleep(\n ms: number,\n signal: AbortSignal | undefined,\n): Promise<void> {\n return new Promise((resolve, reject) => {\n if (signal?.aborted) {\n reject(new Aborted());\n return;\n }\n\n const timer = setTimeout(resolve, ms);\n\n signal?.addEventListener(\n \"abort\",\n () => {\n clearTimeout(timer);\n reject(new Aborted());\n },\n { once: true },\n );\n });\n}\n\n/**\n * Repeatedly calls a function at a fixed interval until it returns `true`\n * or the signal is aborted. The function is invoked immediately on the\n * first iteration, then after each interval.\n *\n * @param ms Interval in milliseconds between invocations of `fn`.\n * @param signal Optional {@link AbortSignal} that cancels polling early.\n * Aborts propagate as an {@link Aborted} rejection.\n * @param fn Predicate invoked each iteration. Return `true` to stop\n * polling, `false` to schedule another invocation after `ms`.\n * May be sync or async.\n * @returns A promise that resolves when `fn` returns `true`, or rejects\n * with a `DOMException(\"aborted\", \"Aborted\")` if `signal`\n * aborts first.\n */\nexport async function poll(\n ms: number,\n signal: AbortSignal | undefined,\n fn: () => boolean | Promise<boolean>,\n): Promise<void> {\n if (signal?.aborted) throw new Aborted();\n\n while (true) {\n const done = await fn();\n if (done) return;\n await sleep(ms, signal);\n }\n}\n\n/**\n * Generates a unique primary key.\n *\n * @returns A new unique symbol representing the primary key.\n */\nexport function pk(): symbol;\n/**\n * Checks if the provided ID is a valid primary key. A valid primary key\n * is any value that is not a symbol.\n *\n * @template T The model type the key identifies.\n * @param id The primary key to validate.\n * @returns `true` if `id` is a non-symbol value, `false` otherwise.\n */\nexport function pk<T>(id: Pk<T>): boolean;\nexport function pk<T>(id?: Pk<T>): boolean | symbol {\n if (id) return Boolean(id && typeof id !== \"symbol\");\n return Symbol(`pk.${Date.now()}.${crypto.randomUUID()}`);\n}\n\n/** Shorthand alias for {@link sleep}. */\nexport const ζ = sleep;\n\n/** Shorthand alias for {@link poll}. */\nexport const π = poll;\n\n/** Shorthand alias for {@link pk}. */\nexport const κ = pk;\n","/**\n * `shared` namespace &mdash; standalone counterparts to the `app.X`\n * factories returned by `App<E>()`. Each export takes the Env shape\n * `E` as a mandatory first generic so reusable components can run\n * under more than one App without binding to a single `app` import.\n *\n * Reach for `shared.X` only when a component must support more than\n * one App. Single-app code should keep using `app.X` &mdash; the Env\n * is captured from `app` automatically and the call site is one\n * generic shorter.\n *\n * | Bound to an App | Standalone (`shared.X`) |\n * | -------------------------------- | ---------------------------------------- |\n * | `app.useContext<M, A, D>()` | `shared.useContext<E, M, A, D>()` |\n * | `app.useEnv()` | `shared.useEnv<E>()` |\n * | `app.Resource<T, P>(...)` | `shared.Resource<E, T, P>(...)` |\n * | `app.Scope<A>()` | `shared.Scope<E, A>()` |\n *\n * `shared.Resource` declarations always read from and write to an\n * in-memory cache &mdash; persistence is an App-level concern wired up\n * via `App({ cache })`. Reach for `app.Resource` instead when a resource\n * needs to survive reloads.\n *\n * @see {@link ./app/index.tsx App}\n */\n\nimport { Resource as InternalResource } from \"../resource/index.ts\";\nimport type { AppFetcher } from \"../app/types.ts\";\nimport type { ResourceHandle } from \"../resource/types.ts\";\n\nexport { useContext, useEnv } from \"../app/index.tsx\";\nexport { Scope } from \"../scope/index.tsx\";\n\n/**\n * Standalone counterpart to `app.Resource`, exported as\n * `shared.Resource`. Takes the **Env shape `E` as a mandatory first\n * generic** so the fetcher's `context.env` is typed even when the\n * resource isn't bound to a single App.\n *\n * Always uses an isolated in-memory cache &mdash; persistent caching\n * is an App-level concern wired through `App({ cache })`, so reach for\n * `app.Resource` when a resource needs to survive reloads.\n */\nexport function Resource<\n E extends object,\n T,\n P extends object = Record<never, never>,\n>(fetcher: AppFetcher<E, T, P>): ResourceHandle<T, P> {\n return InternalResource<E, T, P>(fetcher);\n}\n","import type { ScopeHandle } from \"./types.ts\";\nimport { createScope } from \"./utils.tsx\";\n\nexport type { ScopeHandle } from \"./types.ts\";\nexport { createScope } from \"./utils.tsx\";\n\n/**\n * Standalone counterpart to `app.Scope<MulticastActions>()`, exported\n * as `shared.Scope` &mdash; opens a typed multicast scope without\n * going through an `App` handle. Takes the **Env shape `E` as a\n * mandatory first generic**, mirroring the other standalone exports\n * (`shared.useContext`, `shared.useEnv`, `shared.Resource`). The Env\n * carried by `scope.useContext()` is typed as `E`.\n *\n * Use this in reusable feature modules that need to open their own\n * multicast scope without binding to one App's `app.Scope` factory.\n * For single-app code, prefer `app.Scope<MulticastActions>()` &mdash;\n * the Env is captured from `app` automatically.\n *\n * @template E The Env shape (or union) the scope's `useContext` types\n * `context.env` against.\n * @template A The multicast Actions class (or union of classes) the\n * scope's dispatch surface is widened to include.\n *\n * @example\n * ```tsx\n * import { Action, Distribution, shared } from \"march-hare\";\n *\n * class MulticastActions {\n * static Mood = Action<\"happy\" | \"sad\">(\n * \"Mood\",\n * Distribution.Multicast,\n * );\n * }\n *\n * type MoodEnv = { tracker: string };\n *\n * export const scope = shared.Scope<MoodEnv, typeof MulticastActions>();\n * ```\n */\nexport function Scope<E extends object, A>(): ScopeHandle<E, A> {\n return createScope<E, A>();\n}\n"],"names":["has","Object","prototype","hasOwnProperty","prefix","Events","EE","fn","context","once","this","addListener","emitter","event","TypeError","listener","evt","_events","push","_eventsCount","clearEvent","EventEmitter","create","__proto__","eventNames","events","name","names","call","slice","getOwnPropertySymbols","concat","listeners","handlers","i","l","length","ee","Array","listenerCount","emit","a1","a2","a3","a4","a5","args","len","arguments","removeListener","apply","j","on","removeAllListeners","off","prefixed","module","BroadcastEmitter","cache","Map","set","super","setCache","value","getCached","get","fire","Context","React","createContext","useBroadcast","useContext","Broadcaster","children","useMemo","Provider","Set","Tasks","tasks","current","useEnv","ref","Proxy","_target","key","Reflect","ownKeys","getOwnPropertyDescriptor","descriptor","G","isUndefined","configurable","describe","action","broadcast","multicast","lifecycle","Brand","static","Symbol","createLifecycleAction","symbol","channel","Action","Payload","undefined","Channel","Name","defineProperty","enumerable","Lifecycle","FaultSymbol","EnvSymbol","Mount","Unmount","Error","Update","Broadcast","Distribution","Unicast","Multicast","Phase","Mounting","Mounted","Unmounting","Unmounted","Env","initial","useRef","WeakMap","SharingProvider","registry","noop","Tappable","tap","useLayoutEffect","Boundary","env","consumer","jsx","ConsumerContext","isSymbol","getActionSymbol","isString","isObject","isFunction","isBroadcastAction","startsWith","description","actionSymbol","isChanneledAction","getLifecycleType","isMulticastAction","distribution","replay","emitAsync","Promise","resolve","all","map","then","findLifecycleAction","type","keys","unset","useRerender","rerender","useReducer","x","empty","data","at","present","Reason","Aborted","Errored","constructor","message","Cache","config","backing","memory","remove","delete","clear","memoryAdapter","scopeFn","raw","isNull","parsed","JSON","parse","Temporal","Instant","from","stringify","toString","scope","isNullable","defaults","namespaces","evictors","build","ƒ","namespace","getEnv","suffix","composeKey","params","read","stored","run","controller","dispatch","resolved","Now","instant","evict","where","fullPrefix","entries","cacheKey","every","field","Resource","inner","resolveEnv","fetcher","existing","isNotNullable","defaultCache","String","size","nextResourceId","token","withAbort","promise","signal","reject","aborted","reason","onAbort","addEventListener","removeEventListener","error","s","t","e","r","crypto","getRandomValues","Uint8Array","o","Add","Remove","Move","Replace","Sort","Create","Fetch","Clone","Archive","Restore","Merge","Reorder","Sync","Publish","Link","Unlink","Lock","Unlock","Import","Export","Transfer","a","Produce","Hydrate","c","Property","Process","Value","Operation","u","immerable","values","property","process","operation","assign","setAutoFreeze","p","y","split","n","f","m","isArray","h","fromEntries","tag","id","d","filter","join","getPrototypeOf","isNumber","isBoolean","b","g","path","forEach","v","O","pk","annotate","model","inspect","isNotEmpty","isEmpty","some","head","add","hydrate","produce","immer","produceWithPatches","reduce","applyPatches","prune","observe","Partition","renderer","entry","state","State","cached","handlePayload","payload","walk","target","segments","cursor","setPath","makeUpdate","actions","draft","makeInvert","invertPath","makeAlways","useActions","result","initialModel","getData","slot","sharing","initialised","hydration","setModel","useState","props","withGetters","proxy","useData","unicast","dispatchers","useDispatchers","phase","localTasks","unmountGeneration","getContext","useCallback","AbortController","task","slotBefore","produceImmer","envDraft","processes","base","resource","dispatchFromResource","options","exceedsWindow","coalesceToken","handle","onFulfilled","onRejected","fetch","elapsed","since","window","Duration","compare","mutable","bucket","coalesceKey","detached","shared","finally","exceeds","duration","coalesce","defaultCoalesceToken","nuke","pattern","final","inspector","pending","settled","peek","createHandler","actionHandler","getChannel","dispatchChannel","registeredChannel","matchesChannel","completion","withResolvers","actionName","lastIndexOf","getName","startedAt","performance","now","modelBefore","envBefore","returnValue","errored","mutations","modelAfter","envAfter","before","after","retry","onError","caught","errorAction","handled","getReason","getError","details","stage","onSettled","isGenerator","_","catch","cleanups","handler","generation","pendingCleanups","queueMicrotask","cleanup","abort","unmountAction","previous","mountAction","differences","next","key2","changes","A","updateAction","useLifecycles","actionsApi","stream","createElement","useAction","useActionImpl","handlerRef","actionRef","stableHandler","useRegisterHandler","invoke","with","update","invert","always","createScope","ScopeReactContext","baseUseContext","baseUseEnv","BaseResource","App","envHolder","BaseBoundary","SyncEnvHolder","holder","Scope","With","Invert","Always","sleep","ms","timer","setTimeout","clearTimeout","async","poll","Boolean","Date","randomUUID","InternalResource"],"mappings":"yWAEA,IAAIA,EAAMC,OAAOC,UAAUC,eACvBC,EAAS,IASb,SAASC,IAAS,CA4BlB,SAASC,EAAGC,EAAIC,EAASC,GACvBC,KAAKH,GAAKA,EACVG,KAAKF,QAAUA,EACfE,KAAKD,KAAOA,IAAQ,CACtB,CAaA,SAASE,EAAYC,EAASC,EAAON,EAAIC,EAASC,GAChD,GAAkB,mBAAPF,EACT,MAAM,IAAIO,UAAU,mCAGtB,IAAIC,E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R,GAA0BjR,EACnC,QCTO,WACL,OAAOyP,IACT,aL6KO,WAML,OAAOE,IACT,SAwBO,WACL,OAAOC,GACT","x_google_ignoreList":[0,25]}
1
+ {"version":3,"file":"march-hare.js","sources":["../node_modules/eventemitter3/index.js","../src/library/boundary/components/broadcast/utils.ts","../src/library/boundary/components/broadcast/index.tsx","../src/library/boundary/components/tasks/utils.ts","../src/library/boundary/components/tasks/index.tsx","../src/library/boundary/components/env/utils.ts","../src/library/utils.ts","../src/library/types/index.ts","../src/library/boundary/components/env/index.tsx","../src/library/boundary/components/sharing/index.tsx","../src/library/boundary/components/tap/utils.ts","../src/library/boundary/components/tap/index.tsx","../src/library/boundary/components/consumer/utils.ts","../src/library/boundary/index.tsx","../src/library/action/utils.ts","../src/library/action/index.ts","../src/library/actions/utils.ts","../src/library/utils/utils.ts","../src/library/error/types.ts","../src/library/error/index.ts","../src/library/boundary/components/scope/utils.ts","../src/library/cache/index.ts","../src/library/resource/utils.ts","../src/library/resource/index.ts","../src/library/coalesce/index.ts","../node_modules/immertation/dist/immertation.mjs","../src/library/boundary/components/consumer/components/partition/index.tsx","../src/library/with/utils.ts","../src/library/context/index.ts","../src/library/actions/index.ts","../src/library/error/utils.ts","../src/library/scope/utils.tsx","../src/library/app/index.tsx","../src/library/with/index.ts","../src/library/annotate/index.ts","../src/library/utils/index.ts","../src/library/shared/index.ts","../src/library/scope/index.tsx"],"sourcesContent":["'use strict';\n\nvar has = Object.prototype.hasOwnProperty\n , prefix = '~';\n\n/**\n * Constructor to create a storage for our `EE` objects.\n * An `Events` instance is a plain object whose properties are event names.\n *\n * @constructor\n * @private\n */\nfunction Events() {}\n\n//\n// We try to not inherit from `Object.prototype`. In some engines creating an\n// instance in this way is faster than calling `Object.create(null)` directly.\n// If `Object.create(null)` is not supported we prefix the event names with a\n// character to make sure that the built-in object properties are not\n// overridden or used as an attack vector.\n//\nif (Object.create) {\n Events.prototype = Object.create(null);\n\n //\n // This hack is needed because the `__proto__` property is still inherited in\n // some old browsers like Android 4, iPhone 5.1, Opera 11 and Safari 5.\n //\n if (!new Events().__proto__) prefix = false;\n}\n\n/**\n * Representation of a single event listener.\n *\n * @param {Function} fn The listener function.\n * @param {*} context The context to invoke the listener with.\n * @param {Boolean} [once=false] Specify if the listener is a one-time listener.\n * @constructor\n * @private\n */\nfunction EE(fn, context, once) {\n this.fn = fn;\n this.context = context;\n this.once = once || false;\n}\n\n/**\n * Add a listener for a given event.\n *\n * @param {EventEmitter} emitter Reference to the `EventEmitter` instance.\n * @param {(String|Symbol)} event The event name.\n * @param {Function} fn The listener function.\n * @param {*} context The context to invoke the listener with.\n * @param {Boolean} once Specify if the listener is a one-time listener.\n * @returns {EventEmitter}\n * @private\n */\nfunction addListener(emitter, event, fn, context, once) {\n if (typeof fn !== 'function') {\n throw new TypeError('The listener must be a function');\n }\n\n var listener = new EE(fn, context || emitter, once)\n , evt = prefix ? prefix + event : event;\n\n if (!emitter._events[evt]) emitter._events[evt] = listener, emitter._eventsCount++;\n else if (!emitter._events[evt].fn) emitter._events[evt].push(listener);\n else emitter._events[evt] = [emitter._events[evt], listener];\n\n return emitter;\n}\n\n/**\n * Clear event by name.\n *\n * @param {EventEmitter} emitter Reference to the `EventEmitter` instance.\n * @param {(String|Symbol)} evt The Event name.\n * @private\n */\nfunction clearEvent(emitter, evt) {\n if (--emitter._eventsCount === 0) emitter._events = new Events();\n else delete emitter._events[evt];\n}\n\n/**\n * Minimal `EventEmitter` interface that is molded against the Node.js\n * `EventEmitter` interface.\n *\n * @constructor\n * @public\n */\nfunction EventEmitter() {\n this._events = new Events();\n this._eventsCount = 0;\n}\n\n/**\n * Return an array listing the events for which the emitter has registered\n * listeners.\n *\n * @returns {Array}\n * @public\n */\nEventEmitter.prototype.eventNames = function eventNames() {\n var names = []\n , events\n , name;\n\n if (this._eventsCount === 0) return names;\n\n for (name in (events = this._events)) {\n if (has.call(events, name)) names.push(prefix ? name.slice(1) : name);\n }\n\n if (Object.getOwnPropertySymbols) {\n return names.concat(Object.getOwnPropertySymbols(events));\n }\n\n return names;\n};\n\n/**\n * Return the listeners registered for a given event.\n *\n * @param {(String|Symbol)} event The event name.\n * @returns {Array} The registered listeners.\n * @public\n */\nEventEmitter.prototype.listeners = function listeners(event) {\n var evt = prefix ? prefix + event : event\n , handlers = this._events[evt];\n\n if (!handlers) return [];\n if (handlers.fn) return [handlers.fn];\n\n for (var i = 0, l = handlers.length, ee = new Array(l); i < l; i++) {\n ee[i] = handlers[i].fn;\n }\n\n return ee;\n};\n\n/**\n * Return the number of listeners listening to a given event.\n *\n * @param {(String|Symbol)} event The event name.\n * @returns {Number} The number of listeners.\n * @public\n */\nEventEmitter.prototype.listenerCount = function listenerCount(event) {\n var evt = prefix ? prefix + event : event\n , listeners = this._events[evt];\n\n if (!listeners) return 0;\n if (listeners.fn) return 1;\n return listeners.length;\n};\n\n/**\n * Calls each of the listeners registered for a given event.\n *\n * @param {(String|Symbol)} event The event name.\n * @returns {Boolean} `true` if the event had listeners, else `false`.\n * @public\n */\nEventEmitter.prototype.emit = function emit(event, a1, a2, a3, a4, a5) {\n var evt = prefix ? prefix + event : event;\n\n if (!this._events[evt]) return false;\n\n var listeners = this._events[evt]\n , len = arguments.length\n , args\n , i;\n\n if (listeners.fn) {\n if (listeners.once) this.removeListener(event, listeners.fn, undefined, true);\n\n switch (len) {\n case 1: return listeners.fn.call(listeners.context), true;\n case 2: return listeners.fn.call(listeners.context, a1), true;\n case 3: return listeners.fn.call(listeners.context, a1, a2), true;\n case 4: return listeners.fn.call(listeners.context, a1, a2, a3), true;\n case 5: return listeners.fn.call(listeners.context, a1, a2, a3, a4), true;\n case 6: return listeners.fn.call(listeners.context, a1, a2, a3, a4, a5), true;\n }\n\n for (i = 1, args = new Array(len -1); i < len; i++) {\n args[i - 1] = arguments[i];\n }\n\n listeners.fn.apply(listeners.context, args);\n } else {\n var length = listeners.length\n , j;\n\n for (i = 0; i < length; i++) {\n if (listeners[i].once) this.removeListener(event, listeners[i].fn, undefined, true);\n\n switch (len) {\n case 1: listeners[i].fn.call(listeners[i].context); break;\n case 2: listeners[i].fn.call(listeners[i].context, a1); break;\n case 3: listeners[i].fn.call(listeners[i].context, a1, a2); break;\n case 4: listeners[i].fn.call(listeners[i].context, a1, a2, a3); break;\n default:\n if (!args) for (j = 1, args = new Array(len -1); j < len; j++) {\n args[j - 1] = arguments[j];\n }\n\n listeners[i].fn.apply(listeners[i].context, args);\n }\n }\n }\n\n return true;\n};\n\n/**\n * Add a listener for a given event.\n *\n * @param {(String|Symbol)} event The event name.\n * @param {Function} fn The listener function.\n * @param {*} [context=this] The context to invoke the listener with.\n * @returns {EventEmitter} `this`.\n * @public\n */\nEventEmitter.prototype.on = function on(event, fn, context) {\n return addListener(this, event, fn, context, false);\n};\n\n/**\n * Add a one-time listener for a given event.\n *\n * @param {(String|Symbol)} event The event name.\n * @param {Function} fn The listener function.\n * @param {*} [context=this] The context to invoke the listener with.\n * @returns {EventEmitter} `this`.\n * @public\n */\nEventEmitter.prototype.once = function once(event, fn, context) {\n return addListener(this, event, fn, context, true);\n};\n\n/**\n * Remove the listeners of a given event.\n *\n * @param {(String|Symbol)} event The event name.\n * @param {Function} fn Only remove the listeners that match this function.\n * @param {*} context Only remove the listeners that have this context.\n * @param {Boolean} once Only remove one-time listeners.\n * @returns {EventEmitter} `this`.\n * @public\n */\nEventEmitter.prototype.removeListener = function removeListener(event, fn, context, once) {\n var evt = prefix ? prefix + event : event;\n\n if (!this._events[evt]) return this;\n if (!fn) {\n clearEvent(this, evt);\n return this;\n }\n\n var listeners = this._events[evt];\n\n if (listeners.fn) {\n if (\n listeners.fn === fn &&\n (!once || listeners.once) &&\n (!context || listeners.context === context)\n ) {\n clearEvent(this, evt);\n }\n } else {\n for (var i = 0, events = [], length = listeners.length; i < length; i++) {\n if (\n listeners[i].fn !== fn ||\n (once && !listeners[i].once) ||\n (context && listeners[i].context !== context)\n ) {\n events.push(listeners[i]);\n }\n }\n\n //\n // Reset the array, or remove it completely if we have no more listeners.\n //\n if (events.length) this._events[evt] = events.length === 1 ? events[0] : events;\n else clearEvent(this, evt);\n }\n\n return this;\n};\n\n/**\n * Remove all listeners, or those of the specified event.\n *\n * @param {(String|Symbol)} [event] The event name.\n * @returns {EventEmitter} `this`.\n * @public\n */\nEventEmitter.prototype.removeAllListeners = function removeAllListeners(event) {\n var evt;\n\n if (event) {\n evt = prefix ? prefix + event : event;\n if (this._events[evt]) clearEvent(this, evt);\n } else {\n this._events = new Events();\n this._eventsCount = 0;\n }\n\n return this;\n};\n\n//\n// Alias methods names because people roll like that.\n//\nEventEmitter.prototype.off = EventEmitter.prototype.removeListener;\nEventEmitter.prototype.addListener = EventEmitter.prototype.on;\n\n//\n// Expose the prefix.\n//\nEventEmitter.prefixed = prefix;\n\n//\n// Allow `EventEmitter` to be imported as module namespace.\n//\nEventEmitter.EventEmitter = EventEmitter;\n\n//\n// Expose the module.\n//\nif ('undefined' !== typeof module) {\n module.exports = EventEmitter;\n}\n","import EventEmitter from \"eventemitter3\";\nimport * as React from \"react\";\n\n/**\n * EventEmitter subclass that caches the latest payload per event.\n *\n * When a broadcast or multicast action is dispatched, the payload is\n * stored so that late-mounting components can replay it via\n * {@link useLifecycles} and handlers can read it via\n * `context.actions.final()`.\n */\nexport class BroadcastEmitter extends EventEmitter {\n private cache = new Map<string | symbol, unknown>();\n\n override emit(event: string | symbol, ...args: unknown[]): boolean {\n this.cache.set(event, args[0]);\n return super.emit(event, ...args);\n }\n\n /**\n * Cache a value for a given event without emitting to listeners.\n * Used by {@link emitAsync} to preserve caching when bypassing `emit()`.\n */\n setCache(event: string | symbol, value: unknown): void {\n this.cache.set(event, value);\n }\n\n /**\n * Retrieve the last emitted payload for a given event.\n */\n getCached(event: string | symbol): unknown {\n return this.cache.get(event);\n }\n\n /**\n * Emit without caching the payload. Used by the framework to publish\n * fire-and-forget events (such as `Lifecycle.Fault`) where late-mounting\n * subscribers must not replay a stale value.\n */\n fire(event: string | symbol, ...args: unknown[]): boolean {\n return super.emit(event, ...args);\n }\n}\n\n/**\n * React context for broadcasting distributed actions across components.\n */\nexport const Context = React.createContext<BroadcastEmitter>(\n new BroadcastEmitter(),\n);\n\n/**\n * Hook to access the broadcast EventEmitter for emitting and listening to distributed actions.\n *\n * @returns The BroadcastEmitter instance for distributed actions.\n */\nexport function useBroadcast(): BroadcastEmitter {\n return React.useContext(Context);\n}\n","import { Props } from \"./types.ts\";\nimport { Context, BroadcastEmitter } from \"./utils.ts\";\nimport * as React from \"react\";\n\nexport { useBroadcast, BroadcastEmitter } from \"./utils.ts\";\n\n/**\n * Creates a new broadcast context for distributed actions. Only needed if you\n * want to isolate a broadcast context, useful for libraries that want to provide\n * their own broadcast context without interfering with the app's broadcast context.\n *\n * @param props.children - The children to render within the broadcast context.\n * @returns The children wrapped in a broadcast context provider.\n */\nexport function Broadcaster({ children }: Props): React.ReactNode {\n const context = React.useMemo(() => new BroadcastEmitter(), []);\n\n return <Context.Provider value={context}>{children}</Context.Provider>;\n}\n","import { Tasks } from \"./types.ts\";\nimport * as React from \"react\";\n\n/**\n * React context for the shared tasks Set.\n * Tasks are ordered by creation time (oldest first) since Sets maintain insertion order.\n */\nexport const Context = React.createContext<Tasks>(new Set());\n\n/**\n * Hook to access the shared tasks Set from context.\n * Returns the Set of all currently running tasks across all components in the context.\n *\n * @returns The Set of Task instances in the current context.\n *\n * @example\n * ```ts\n * const tasks = useTasks();\n *\n * // Abort all tasks for a specific action\n * for (const task of tasks) {\n * if (task.action === Actions.Fetch) {\n * task.controller.abort();\n * }\n * }\n * ```\n */\nexport function useTasks(): Tasks {\n return React.useContext(Context);\n}\n","import { Context } from \"./utils.ts\";\nimport type { Props, Tasks } from \"./types.ts\";\nimport * as React from \"react\";\n\nexport type { Task } from \"./types.ts\";\n\n/**\n * Creates a new tasks context for action control. Only needed if you\n * want to isolate a tasks context, useful for libraries that want to provide\n * their own tasks context without interfering with the app's tasks context.\n *\n * Tasks added within this context are isolated from tasks in other contexts.\n *\n * @param props.children - The children to render within the tasks context.\n * @returns The children wrapped in a tasks context provider.\n */\nexport function Tasks({ children }: Props): React.ReactNode {\n const tasks = React.useMemo<Tasks>(() => new Set(), []);\n\n return <Context.Provider value={tasks}>{children}</Context.Provider>;\n}\n","import * as React from \"react\";\nimport type { RefObject } from \"react\";\nimport { G } from \"@mobily/ts-belt\";\nimport type { Env } from \"./types.ts\";\n\n/**\n * Internal singleton fallback used when `useEnv` is read outside any\n * `<Boundary>` (or `<Env>` provider). Reads see `{}`; writes through\n * `context.actions.produce(({ env }) => ...)` mutate this slot but\n * are not observed by any handler.\n *\n * @internal\n */\nconst fallback: RefObject<Env> = { current: <Env>{} };\n\n/**\n * React context exposing the per-Boundary Env ref. The ref itself is\n * stable across renders &mdash; readers grab `.current` at call time.\n *\n * @internal\n */\nexport const Context = React.createContext<RefObject<Env>>(fallback);\n\n/**\n * Hook that returns a read-only handle to the per-Boundary {@link Env}.\n * Reads use plain dot notation (`env.session`) and always reflect the\n * latest value, even after `await` boundaries &mdash; the handle is a\n * `Proxy` that delegates property access to the live ref.\n *\n * Writes are not exposed here. Mutate the Env inside an action handler\n * via `context.actions.produce(({ model, env }) => { env.x = ... })`\n * &mdash; the same Immer-style recipe used for the model. Mutations do\n * **not** trigger a re-render; drive view state through the model.\n *\n * Prefer `app.useEnv()` from an {@link App} instance &mdash; the App\n * factory infers the Env's shape from `app.env` and types every\n * read/write against it. The bare `useEnv()` exists for non-App\n * call sites and returns the loose {@link Env} record type.\n */\nexport function useEnv(): Env {\n const ref = React.useContext(Context);\n return React.useMemo<Env>(\n () =>\n new Proxy(<Env>{}, {\n get(_target, key) {\n return Reflect.get(ref.current, key);\n },\n has(_target, key) {\n return key in ref.current;\n },\n ownKeys() {\n return Reflect.ownKeys(ref.current);\n },\n getOwnPropertyDescriptor(_target, key) {\n const descriptor = Object.getOwnPropertyDescriptor(ref.current, key);\n if (G.isUndefined(descriptor)) return undefined;\n return { ...descriptor, configurable: true };\n },\n set() {\n throw new TypeError(\n \"Env is read-only outside `context.actions.produce`. \" +\n \"Mutate via produce(({ env }) => { env.x = ... }) instead.\",\n );\n },\n }),\n [ref],\n );\n}\n\n/**\n * Internal accessor for the per-Boundary Env ref &mdash; used by the\n * Resource layer to pass a fresh snapshot to each fetcher invocation\n * and by the action layer to write through `context.actions.produce`.\n * Not exported from the library.\n *\n * @internal\n */\nexport function useEnvRef(): RefObject<Env> {\n return React.useContext(Context);\n}\n","/**\n * Internal symbol description factories. Each function returns a namespaced\n * string suitable for `Symbol()` descriptions or `startsWith` checks.\n *\n * @internal\n */\nexport const describe = {\n /** Unicast action description. `describe.action(\"Fetch\")` &rarr; `\"march-hare.action/Fetch\"` */\n action: (name = \"\") => `march-hare.action/${name}`,\n /** Broadcast action description. `describe.broadcast(\"User\")` &rarr; `\"march-hare.action/broadcast/User\"` */\n broadcast: (name = \"\") => `march-hare.action/broadcast/${name}`,\n /** Multicast action description. `describe.multicast(\"Update\")` &rarr; `\"march-hare.action/multicast/Update\"` */\n multicast: (name = \"\") => `march-hare.action/multicast/${name}`,\n /** Channeled action description. `describe.channel(\"user\")` &rarr; `\"march-hare.channel/user\"` */\n channel: (name = \"\") => `march-hare.channel/${name}`,\n /** Cache entry description. `describe.cache(\"users\")` &rarr; `\"march-hare.cache/users\"` */\n cache: (name = \"\") => `march-hare.cache/${name}`,\n /** Lifecycle action description. `describe.lifecycle(\"Mount\")` &rarr; `\"march-hare.action.lifecycle/Mount\"` */\n lifecycle: (name = \"\") => `march-hare.action.lifecycle/${name}`,\n /** Mount replay sentinel description. Used to create the {@link replay} symbol. */\n replay: (name = \"\") => `march-hare/replay${name}`,\n};\n\n/**\n * Flat record used for shallow property comparison in {@link changes}.\n * @internal\n */\ntype Changes = Record<string, unknown>;\n\n/**\n * Get high-level changed paths between two objects.\n * Returns an object containing only the properties that were added or updated.\n *\n * @param previous - The previous state object\n * @param next - The next state object\n * @returns Object with changed property keys and their new values\n */\nexport function changes(previous: Changes, next: Changes): Changes {\n return <Changes>(\n Object.keys(next).reduce(\n (result, key) =>\n previous[key] !== next[key] ? { ...result, [key]: next[key] } : result,\n {},\n )\n );\n}\n","import * as React from \"react\";\nimport { Operation } from \"immertation\";\nimport { Process, Inspect as ImmInspect, Box } from \"immertation\";\nimport type {\n ActionId,\n Task,\n Tasks,\n} from \"../boundary/components/tasks/types.ts\";\nimport type { Fault } from \"../error/types.ts\";\nimport type { Env } from \"../boundary/components/env/types.ts\";\nimport type { Coalesce, Invocation } from \"../resource/types.ts\";\nimport type { WithHandle } from \"../with/types.ts\";\n\n/**\n * Bounded recursion depths for {@link Inspect}. Matches Immertation's\n * `DepthLimiter` shape so the two stay in lock-step.\n */\ntype DepthLimiter = [never, 0, 1, 2, 3, 4, 5, 6, 7, 8];\n\n/** Union of all keys across each arm of `T`. */\ntype UnionKeys<T> = T extends unknown ? keyof T : never;\n\n/** The value at `K` for each arm of `T`, falling back to `undefined` if `K` is absent on that arm. */\ntype ValueAt<T, K extends PropertyKey> = T extends unknown\n ? K extends keyof T\n ? T[K]\n : undefined\n : never;\n\n/**\n * March-hare's `Inspect<T>` wraps Immertation's so that property\n * navigation works when `T` is a discriminated union (e.g. the App's\n * Env union). For each key that appears on **any** union arm, the\n * resulting Inspect is `Inspect<ValueAt<T, K>>` &mdash; arms missing\n * the key contribute `undefined`, so optional chaining stays sound.\n *\n * For a single concrete `T`, the wrapper is transparent.\n */\nexport type Inspect<T, D extends number = 8> = ImmInspect<T> &\n ([D] extends [0]\n ? object\n : {\n [K in UnionKeys<T> as ValueAt<T, K> extends (\n ...args: unknown[]\n ) => unknown\n ? never\n : K]: Inspect<ValueAt<T, K>, DepthLimiter[D]>;\n });\n\n/**\n * Chainable handle returned from `context.actions.resource(invocation)`.\n *\n * - `.exceeds(duration)` short-circuits the fetch when the per-params\n * cache age is within the supplied freshness window.\n * - `.coalesce(token)` opts the call into in-flight sharing: any other\n * caller with the same Resource, same structural params, and equal\n * `token` joins the same promise.\n *\n * Awaiting the handle (`await context.actions.resource(...)`) triggers\n * the fetch with whichever options have been set on the chain.\n */\n/**\n * Fetch-configured chain returned from `.exceeds(...)` and\n * `.coalesce(...)`. Awaiting the chain runs the fetch with whichever\n * options are set; `.evict()` is intentionally absent because the\n * \"configured a fetch then evicted instead\" sequence has no coherent\n * meaning &mdash; eviction is always available off the bare\n * `context.actions.resource(...)` call.\n */\nexport type ResourceFetch<T> = PromiseLike<T> & {\n /**\n * Skip the fetch when the cached payload is within `duration`.\n * Accepts a `Temporal.Duration`, a `DurationLike` object\n * (`{ minutes: 5 }`), or an ISO 8601 string (`\"PT5M\"`).\n */\n readonly exceeds: (duration: Temporal.DurationLike) => ResourceFetch<T>;\n /**\n * Join an in-flight fetch for the same `(resource, params, token)`\n * tuple. The shared fetch runs against a detached `AbortController`\n * so a single caller's abort never cancels work other callers are\n * waiting on; each caller still sees its own `context.task.controller`\n * abort as a rejection of its personal await.\n *\n * `token` is optional &mdash; omit it to share with every other\n * untokened caller for the same `(resource, params)` slot.\n */\n readonly coalesce: (token?: Coalesce) => ResourceFetch<T>;\n};\n\n/**\n * Chainable handle returned from `context.actions.resource(invocation)`.\n * Either resolve to the fetched value (`.exceeds`/`.coalesce` + await)\n * or drop the cache slot (`.evict`) &mdash; the two paths are mutually\n * exclusive, so once `.exceeds` or `.coalesce` runs the chain narrows\n * to {@link ResourceFetch} and `.evict` is no longer available.\n */\nexport type ResourceCall<T> = ResourceFetch<T> & {\n /**\n * Drop cache entries for the primed resource without fetching. With\n * no argument, uses the params from the originating call as the\n * pattern. With an argument, evicts every stored entry whose params\n * satisfy the pattern's keys (partial match &mdash; extra keys in\n * the stored params are ignored).\n *\n * Strictly synchronous &mdash; the Adapter contract is sync, so the\n * warm-start `Map` and the user adapter both settle in the current\n * tick. Async backends fire-and-forget their underlying delete from\n * inside the adapter body; the call site doesn't `await` anything.\n *\n * The `where` pattern is typed as `Record<string, unknown>` rather\n * than `Partial<P>` because the resource's params type `P` isn't\n * threaded through the chain. Pass the literal you'd pass to the\n * underlying fetcher &mdash; TypeScript won't catch typos in pattern\n * keys, so prefer the no-argument form when possible.\n *\n * ```ts\n * // Drop the {id: 5} slot.\n * context.actions.resource(resource.user({ id: 5 })).evict();\n *\n * // Drop every user slot whose stored params include name \"Adam\".\n * context.actions.resource(resource.user()).evict({ name: \"Adam\" });\n * ```\n */\n readonly evict: (where?: Record<string, unknown>) => void;\n};\nimport { describe } from \"../utils.ts\";\n\nexport type { ActionId, Box, Task, Tasks };\n/**\n * Type for objects with a Brand.Action symbol property.\n * Used for type-safe access to the action symbol.\n */\nexport type BrandedAction = { readonly [K in typeof Brand.Action]: symbol };\n\n/**\n * Type for objects with a Brand.Broadcast symbol property.\n * Used for type-safe access to the broadcast flag.\n */\nexport type BrandedBroadcast = {\n readonly [K in typeof Brand.Broadcast]: boolean;\n};\n\n/**\n * Type for objects with a Brand.Multicast symbol property.\n * Used for type-safe access to the multicast flag.\n */\nexport type BrandedMulticast = {\n readonly [K in typeof Brand.Multicast]: boolean;\n};\n\n/**\n * Base type for any object that may contain branded symbol properties.\n * Used as a permissive input type for action utilities.\n */\nexport type BrandedObject = { readonly [x: symbol]: unknown };\n\n/**\n * Recursive readonly. Locks every nested property so that read-only\n * projections on `context` (model, data, env) reject direct assignment\n * &mdash; mutation must go through `context.actions.produce(...)`.\n *\n * Function types pass through untouched so method calls (e.g.\n * `AbortController#abort`) remain callable. Built-in mutable containers\n * are mapped to their readonly counterparts.\n *\n * @internal\n */\nexport type DeepReadonly<T> = T extends (...args: never) => unknown\n ? T\n : T extends ReadonlyArray<infer U>\n ? ReadonlyArray<DeepReadonly<U>>\n : T extends ReadonlyMap<infer K, infer V>\n ? ReadonlyMap<DeepReadonly<K>, DeepReadonly<V>>\n : T extends ReadonlySet<infer U>\n ? ReadonlySet<DeepReadonly<U>>\n : T extends object\n ? { readonly [K in keyof T]: DeepReadonly<T[K]> }\n : T;\n\n/**\n * Union type representing any valid action that can be passed to action utilities.\n * This includes raw ActionIds (symbol/string), and any branded object.\n */\nexport type AnyAction = ActionId | BrandedObject;\n\n/**\n * Internal symbols used as brand keys to distinguish typed objects at runtime.\n * These enable TypeScript to differentiate between HandlerPayload, BroadcastPayload,\n * and channeled actions through branded types.\n * @internal\n */\nexport class Brand {\n /** Brand key for HandlerPayload type */\n static readonly Payload = Symbol(\"march-hare.brand/Payload\");\n /** Brand key for BroadcastPayload type */\n static readonly Broadcast = Symbol(\"march-hare.brand/Broadcast\");\n /** Brand key for MulticastPayload type */\n static readonly Multicast = Symbol(\"march-hare.brand/Multicast\");\n /** Access the underlying symbol from an action */\n static readonly Action = Symbol(\"march-hare.brand/Action\");\n /** Identifies channeled actions (result of calling Action(channel)) */\n static readonly Channel = Symbol(\"march-hare.brand/Channel\");\n /**\n * Phantom brand carrying the action's literal name. Used purely at the\n * type level to make `Action(\"X\")` and `Action(\"Y\")` produce\n * structurally-distinct types so `dispatch`/`useAction` can reject\n * symbols imported from a class outside `AC`.\n */\n static readonly Name = Symbol(\"march-hare.brand/Name\");\n /**\n * Phantom brand identifying lifecycle actions returned by\n * `Lifecycle.Mount()`, `Lifecycle.Paint()`, `Lifecycle.Unmount()`,\n * `Lifecycle.Error()`, and `Lifecycle.Update()`. Carries the lifecycle's\n * literal kind so that `useAction` can pick distinct overloads &mdash; in\n * particular,\n * `Lifecycle.Update` resolves its payload to `Partial<DeepReadonly<D>>`\n * against the surrounding `useActions` data generic instead of the\n * factory-level `Record<string, unknown>` placeholder. Without this\n * brand a user-defined `Action<P>(\"Update\")` would collide with the\n * lifecycle overload.\n */\n static readonly Lifecycle = Symbol(\"march-hare.brand/Lifecycle\");\n}\n\n/**\n * Creates a lifecycle action with the given name.\n * Produces a branded `HandlerPayload` backed by a fresh\n * `Symbol(\"march-hare.action.lifecycle/${name}\")` on each call.\n *\n * @internal\n */\nfunction createLifecycleAction<\n P = never,\n C extends Filter = never,\n K extends string = string,\n>(name: K): LifecyclePayload<P, C, K> {\n const symbol = Symbol(`march-hare.action.lifecycle/${name}`);\n const action = function (channel: C): ChanneledAction<P, C, K> {\n return {\n [Brand.Action]: symbol,\n [Brand.Payload]: <P>undefined,\n [Brand.Channel]: channel,\n [Brand.Name]: name,\n channel,\n };\n };\n // eslint-disable-next-line fp/no-mutating-methods\n Object.defineProperty(action, Brand.Action, {\n value: symbol,\n enumerable: false,\n });\n // eslint-disable-next-line fp/no-mutating-methods\n Object.defineProperty(action, Brand.Payload, {\n value: undefined,\n enumerable: false,\n });\n // eslint-disable-next-line fp/no-mutating-methods\n Object.defineProperty(action, Brand.Name, { value: name, enumerable: false });\n // eslint-disable-next-line fp/no-mutating-methods\n Object.defineProperty(action, Brand.Lifecycle, {\n value: name,\n enumerable: false,\n });\n return <LifecyclePayload<P, C, K>>action;\n}\n\n/**\n * Internal symbol for the global `Lifecycle.Fault` broadcast. Exposed so the\n * dispatch pipeline can fire faults without depending on the `Lifecycle`\n * class at runtime.\n *\n * @internal\n */\nexport const FaultSymbol: unique symbol = <typeof FaultSymbol>(\n Symbol(describe.broadcast(\"Fault\"))\n);\n\n/**\n * Internal symbol for the global `Lifecycle.Env` broadcast. The env\n * mutation path in `useActions` fires this symbol whenever a\n * `produce({ env })` call changes the slot reference.\n *\n * @internal\n */\nexport const EnvSymbol: unique symbol = <typeof EnvSymbol>(\n Symbol(describe.broadcast(\"Env\"))\n);\n\n/**\n * Factory functions for lifecycle actions.\n *\n * Each call returns a **unique** action symbol so that each component can\n * subscribe independently. Assign the result as a static property in your\n * Actions class:\n *\n * @example\n * ```ts\n * export class Actions {\n * static Mount = Lifecycle.Mount();\n * static Paint = Lifecycle.Paint();\n * static Unmount = Lifecycle.Unmount();\n * static Error = Lifecycle.Error();\n * static Update = Lifecycle.Update();\n *\n * static Increment = Action(\"Increment\");\n * }\n * ```\n *\n * `Lifecycle.Fault` and `Lifecycle.Env` are singleton broadcasts (not\n * factories). All components subscribe to the same shared symbol &mdash;\n * `Fault` delivers global fault notifications, `Env` delivers per-`Boundary`\n * env-change notifications.\n */\nexport class Lifecycle {\n /** Creates a Mount lifecycle action. Triggered once on component mount (`useLayoutEffect`). */\n static Mount(): LifecyclePayload<never, never, \"Mount\"> {\n return createLifecycleAction<never, never, \"Mount\">(\"Mount\");\n }\n\n /**\n * Creates a Paint lifecycle action. Triggered once after the browser has\n * committed the first frame (`useEffect`). Pairs with {@link Lifecycle.Mount}\n * (pre-paint) &mdash; use Paint for work that should not delay the first\n * paint: analytics &ldquo;viewed&rdquo; events, focus management, scroll-into-view,\n * non-blocking prefetch, etc.\n */\n static Paint(): LifecyclePayload<never, never, \"Paint\"> {\n return createLifecycleAction<never, never, \"Paint\">(\"Paint\");\n }\n\n /** Creates an Unmount lifecycle action. Triggered when the component unmounts. */\n static Unmount(): LifecyclePayload<never, never, \"Unmount\"> {\n return createLifecycleAction<never, never, \"Unmount\">(\"Unmount\");\n }\n\n /** Creates an Error lifecycle action. Triggered when an action throws. Receives `Fault` as payload. */\n static Error(): LifecyclePayload<Fault, never, \"Error\"> {\n return createLifecycleAction<Fault, never, \"Error\">(\"Error\");\n }\n\n /**\n * Creates an Update lifecycle action. Triggered when `context.data` changes\n * (not on initial mount). The handler payload is typed as\n * `Partial<DeepReadonly<D>>` at the subscription site &mdash; only the keys\n * whose values changed between the previous and current render are present.\n */\n static Update(): LifecyclePayload<Record<string, unknown>, never, \"Update\"> {\n return createLifecycleAction<Record<string, unknown>, never, \"Update\">(\n \"Update\",\n );\n }\n\n /**\n * Global fault broadcast. Receives a `Fault` whenever any action in the\n * `<Boundary>` errors, times out, or is supplanted. Subscribe via\n * `actions.useAction(Lifecycle.Fault, handler)`.\n *\n * Unlike the per-component `Lifecycle.Error()` factory, `Fault` is a single\n * shared broadcast — every subscriber points at the same symbol.\n *\n * @example\n * ```tsx\n * const actions = useActions<void, typeof Actions>();\n *\n * actions.useAction(Lifecycle.Fault, (context, fault) => {\n * if (fault.reason === Reason.Errored) {\n * console.error(`Action \"${fault.action}\" failed`, fault.error);\n * }\n * });\n * ```\n */\n static Fault: BroadcastPayload<Fault, never, \"Fault\"> = (() => {\n const action: Record<symbol, unknown> = {};\n // eslint-disable-next-line fp/no-mutating-methods\n Object.defineProperty(action, Brand.Action, {\n value: FaultSymbol,\n enumerable: false,\n });\n // eslint-disable-next-line fp/no-mutating-methods\n Object.defineProperty(action, Brand.Payload, {\n value: undefined,\n enumerable: false,\n });\n // eslint-disable-next-line fp/no-mutating-methods\n Object.defineProperty(action, Brand.Broadcast, {\n value: true,\n enumerable: false,\n });\n // eslint-disable-next-line fp/no-mutating-methods\n Object.defineProperty(action, Brand.Name, {\n value: \"Fault\",\n enumerable: false,\n });\n return <BroadcastPayload<Fault, never, \"Fault\">>(<unknown>action);\n })();\n\n /**\n * Global env-change broadcast. Receives the latest {@link Env}\n * snapshot whenever a `context.actions.produce(({ env }) => ...)` call\n * mutates the slot. Subscribe via\n * `actions.useAction(Lifecycle.Env, handler)` &mdash; or render against\n * it directly with `actions.stream(Lifecycle.Env, (env) => ...)`.\n *\n * Like `Lifecycle.Fault`, this is a singleton broadcast (not a factory):\n * every subscriber points at the same shared symbol. The latest value is\n * cached on the broadcast emitter so that late-mounting handlers and\n * streams receive the current env on mount.\n *\n * @example\n * ```tsx\n * actions.useAction(Lifecycle.Env, (context, env) => {\n * console.log(\"env changed\", env);\n * });\n *\n * // In JSX:\n * {actions.stream(Lifecycle.Env, (env) => (\n * <span>{env.locale}</span>\n * ))}\n * ```\n */\n static Env: BroadcastPayload<Env, never, \"Env\"> = (() => {\n const action: Record<symbol, unknown> = {};\n // eslint-disable-next-line fp/no-mutating-methods\n Object.defineProperty(action, Brand.Action, {\n value: EnvSymbol,\n enumerable: false,\n });\n // eslint-disable-next-line fp/no-mutating-methods\n Object.defineProperty(action, Brand.Payload, {\n value: undefined,\n enumerable: false,\n });\n // eslint-disable-next-line fp/no-mutating-methods\n Object.defineProperty(action, Brand.Broadcast, {\n value: true,\n enumerable: false,\n });\n // eslint-disable-next-line fp/no-mutating-methods\n Object.defineProperty(action, Brand.Name, {\n value: \"Env\",\n enumerable: false,\n });\n return <BroadcastPayload<Env, never, \"Env\">>(<unknown>action);\n })();\n}\n\n/**\n * Distribution modes for actions.\n *\n * - **Unicast** &ndash; Action is scoped to the component that defines it and cannot be\n * consumed by other components. This is the default behaviour.\n * - **Broadcast** &ndash; Action is distributed to all mounted components that have\n * defined a handler for it. Values are cached for late-mounting components.\n * - **Multicast** &ndash; Action defines its own scope. Components reach it by\n * rendering inside a `<scope.Boundary>` produced by `app.Scope<MulticastActions>()`.\n *\n * @example\n * ```ts\n * export class MulticastActions {\n * static Mood = Action<Mood>(\"Mood\", Distribution.Multicast);\n * }\n *\n * export const scope = app.Scope<typeof MulticastActions>();\n *\n * // Wrap the subtree where the scope applies.\n * export default function Mood() {\n * return (\n * <scope.Boundary>\n * <Happy />\n * <Sad />\n * </scope.Boundary>\n * );\n * }\n *\n * // Dispatch / subscribe — no extra options.\n * actions.dispatch(MulticastActions.Mood, mood);\n * actions.useAction(MulticastActions.Mood, (context, mood) => { ... });\n * ```\n */\nexport enum Distribution {\n /** Action is scoped to the component that defines it. This is the default. */\n Unicast = \"unicast\",\n /** Action is broadcast to all mounted components and can be consumed. */\n Broadcast = \"broadcast\",\n /** Action is multicast to every component inside its `<scope.Boundary>`. */\n Multicast = \"multicast\",\n}\n\n/**\n * Lifecycle phase of a component using useActions.\n * Tracks whether the component is in the process of mounting, fully mounted,\n * unmounting, or completely unmounted.\n *\n * @example\n * ```ts\n * actions.useAction(Actions.Counter, (context, payload) => {\n * if (context.phase === Phase.Mounting) {\n * // Handler called during mount (e.g., cached distributed action value)\n * } else if (context.phase === Phase.Mounted) {\n * // Handler called after component is fully mounted\n * }\n * });\n * ```\n */\nexport enum Phase {\n /** Component is in the process of mounting (before useLayoutEffect completes). */\n Mounting = \"mounting\",\n /** Component has fully mounted (after useLayoutEffect). */\n Mounted = \"mounted\",\n /** Component is in the process of unmounting. */\n Unmounting = \"unmounting\",\n /** Component has fully unmounted. */\n Unmounted = \"unmounted\",\n}\n\n/**\n * Primary key type for identifying entities in collections.\n * Can be undefined (not yet assigned), a symbol (temporary/local), or a concrete value T.\n *\n * @template T - The concrete primary key type (e.g., string, number)\n */\nexport type Pk<T> = undefined | symbol | T;\n\n/**\n * Maybe-present field type &mdash; a value that may be a concrete `T`,\n * or `null` / `undefined` while loading, awaiting a fetch, or before\n * upstream data has arrived. Use this for model fields whose presence\n * is determined by async or external state.\n *\n * @template T - The concrete value type\n */\nexport type Maybe<T> = T | null | undefined;\n\n/**\n * Base constraint type for model state objects.\n * Models must be plain objects with string keys.\n *\n * @template M - The specific model shape\n */\nexport type Model<M = Record<string, unknown>> = M;\n\n/**\n * Branded type for action objects created with `Action()`.\n * The phantom type parameters carry the payload and channel types at the type level.\n *\n * Actions wrap an internal symbol (used as event emitter keys) in a callable object.\n * When a channel type is specified, the action can be called to create a channeled dispatch.\n *\n * @template P - The payload type for the action\n * @template C - The channel type for channeled dispatches (defaults to never = no channel)\n *\n * @example\n * ```ts\n * // Action without channel support\n * const Increment = Action<number>(\"Increment\");\n * dispatch(Increment, 5);\n *\n * // Action with channel support\n * const UserUpdated = Action<User, { UserId: number }>(\"UserUpdated\");\n * dispatch(UserUpdated, user); // broadcast to all handlers\n * dispatch(UserUpdated({ UserId: 5 }), user); // channeled dispatch\n * ```\n */\nexport type HandlerPayload<\n P = unknown,\n C extends Filter = never,\n Name extends string = string,\n> = {\n readonly [Brand.Action]: symbol;\n readonly [Brand.Payload]: P;\n readonly [Brand.Name]: Name;\n readonly [Brand.Broadcast]?: boolean;\n} & ([C] extends [never]\n ? unknown\n : {\n (channel: C): ChanneledAction<P, C, Name>;\n });\n\n/**\n * Branded type returned by `Lifecycle.Mount`, `Lifecycle.Paint`,\n * `Lifecycle.Unmount`, `Lifecycle.Error`, and `Lifecycle.Update`.\n * Structurally identical to a `HandlerPayload` but carries a phantom\n * `Brand.Lifecycle` brand whose value is the lifecycle's literal kind. The\n * brand is what lets `useAction` and `Handlers` resolve `Lifecycle.Update`'s\n * payload to `Partial<DeepReadonly<D>>` (against the surrounding `useActions`\n * data generic) instead of the factory-level `Record<string, unknown>`\n * placeholder &mdash; a user-defined `Action<P>(\"Update\")` would have\n * `Name = \"Update\"` but no `Brand.Lifecycle`, so it falls into the generic\n * payload overload as expected.\n *\n * @template P Payload type for the lifecycle.\n * @template C Channel filter (always `never` for lifecycles &mdash; they are\n * not channeled).\n * @template Name Literal name (`\"Mount\"`, `\"Paint\"`, `\"Unmount\"`, `\"Error\"`, `\"Update\"`).\n */\nexport type LifecyclePayload<\n P = unknown,\n C extends Filter = never,\n Name extends string = string,\n> = HandlerPayload<P, C, Name> & {\n readonly [Brand.Lifecycle]: Name;\n};\n\n/**\n * Result of calling an action with a channel argument.\n * Contains the action reference and the channel data for filtered dispatch.\n *\n * @template P - The payload type for the action\n * @template C - The channel type\n *\n * @example\n * ```ts\n * const UserUpdated = Action<User, { UserId: number }>(\"UserUpdated\");\n *\n * // UserUpdated({ UserId: 5 }) returns ChanneledAction<User, { UserId: number }>\n * dispatch(UserUpdated({ UserId: 5 }), user);\n * ```\n */\nexport type ChanneledAction<\n P = unknown,\n C = unknown,\n Name extends string = string,\n> = {\n readonly [Brand.Action]: symbol;\n readonly [Brand.Payload]: P;\n readonly [Brand.Channel]: C;\n readonly [Brand.Name]: Name;\n readonly channel: C;\n};\n\n/**\n * Branded type for broadcast action objects created with `Action()` and `Distribution.Broadcast`.\n * Broadcast actions are sent to all mounted components. Values are cached so that\n * late-mounting components receive the most recent payload.\n *\n * Late-mounting components receive the most recent cached payload via their\n * `useAction` handler during mount. Use `peek()` in a `Lifecycle.Mount` handler\n * to check whether a cached value exists before performing default fetches.\n *\n * This type extends `HandlerPayload<P, C>` with an additional brand to enforce at compile-time\n * that only broadcast actions can be passed to `context.actions.final()`.\n *\n * @template P - The payload type for the action\n * @template C - The channel type for channeled dispatches (defaults to never)\n *\n * @example\n * ```ts\n * const SignedOut = Action<User>(\"SignedOut\", Distribution.Broadcast);\n *\n * // Resolve the latest value inside a handler\n * const user = await context.actions.final(SignedOut);\n * ```\n */\nexport type BroadcastPayload<\n P = unknown,\n C extends Filter = never,\n Name extends string = string,\n> = HandlerPayload<P, C, Name> & {\n readonly [Brand.Broadcast]: true;\n};\n\n/**\n * Branded type for multicast action objects created with `Action()` and `Distribution.Multicast`.\n * Multicast actions are dispatched to all components within a named scope boundary.\n *\n * When dispatching a multicast action, you MUST provide the scope name as the third argument:\n * ```ts\n * actions.dispatch(Actions.Multicast.Update, payload, { scope: Actions.Multicast.Scope });\n * ```\n *\n * Components receive multicast events only if they are descendants of a `<Scope of={...}>`.\n *\n * @template P - The payload type for the action\n * @template C - The channel type for channeled dispatches (defaults to never)\n *\n * @example\n * ```tsx\n * export enum Scope {\n * Counter = \"counter\",\n * }\n *\n * class MulticastActions {\n * static Update = Action<number>(\"Update\", Distribution.Multicast(Scope.Counter));\n * }\n *\n * // Reference from component-level Actions\n * class Actions {\n * static Multicast = MulticastActions;\n * }\n *\n * // Wrap the subtree where the scope applies via the withScope HOC.\n * export default withScope(Scope.Counter, function Counters() {\n * return (\n * <>\n * <CounterA />\n * <CounterB />\n * </>\n * );\n * });\n *\n * // Dispatch — the scope is read from the action itself.\n * actions.dispatch(Actions.Multicast.Update, 42);\n * ```\n */\nexport type MulticastPayload<\n P = unknown,\n C extends Filter = never,\n Name extends string = string,\n> = HandlerPayload<P, C, Name> & {\n readonly [Brand.Multicast]: true;\n};\n\n/**\n * Extracts the payload type `P` from a `HandlerPayload<P>` or `ChanneledAction<P, C>`.\n * Use this in handler signatures to get the action's payload type.\n *\n * Works with both plain actions and channeled actions:\n * - `Payload<Action<User>>` → `User`\n * - `Payload<ChanneledAction<User, { UserId: number }>>` → `User`\n *\n * @template A - The action type (HandlerPayload or ChanneledAction)\n */\n\nexport type Payload<A> = A extends { readonly [Brand.Payload]: infer P }\n ? P\n : never;\n\n/**\n * Filter object for channeled actions.\n * Must be an object where each value is a non-nullable primitive.\n *\n * By convention, use uppercase keys (e.g., `{UserId: 4}` not `{userId: 4}`)\n * to distinguish filter keys from payload properties.\n *\n * When dispatching, handlers are invoked if ALL properties in the dispatch filter\n * match the corresponding properties in the registered filter.\n *\n * @example\n * ```ts\n * // Register a handler for a specific user\n * actions.useAction([Actions.User, { UserId: 1 }], handler);\n *\n * // Dispatch matches if all dispatch properties match registered properties\n * dispatch([Actions.User, { UserId: 1 }], payload); // Matches\n * dispatch([Actions.User, { UserId: 2 }], payload); // No match\n * dispatch([Actions.User, { UserId: 1, Role: \"admin\" }], payload); // Matches\n * dispatch([Actions.User, {}], payload); // Matches all\n * dispatch(Actions.User, payload); // Matches ALL handlers\n * ```\n */\nexport type Filter = Record<\n string,\n string | number | bigint | boolean | symbol\n>;\n\n/**\n * Union type representing either a plain action or a channeled action.\n * Used in `useAction` and `dispatch` signatures to accept both forms.\n *\n * @template A - The action type\n *\n * @example\n * ```ts\n * class Actions {\n * static UserUpdated = Action<User, { UserId: number }>(\"UserUpdated\", Distribution.Broadcast);\n * }\n *\n * // Subscribe to updates for a specific user (channeled)\n * actions.useAction(Actions.UserUpdated({ UserId: props.userId }), (context, user) => {\n * context.actions.produce((draft) => {\n * draft.model.user = user;\n * });\n * });\n *\n * // Dispatch to specific user (channeled)\n * actions.dispatch(Actions.UserUpdated({ UserId: user.id }), user);\n *\n * // Dispatch to ALL handlers (plain)\n * actions.dispatch(Actions.UserUpdated, user);\n * ```\n */\nexport type ActionOrChanneled<A extends HandlerPayload = HandlerPayload> =\n | A\n | ChanneledAction;\n\n/**\n * Type guard that produces a compile-time error if an async function is\n * passed. Used to enforce synchronous callbacks in `produce()`.\n *\n * The `[F]` tuple wrapping prevents distribution over function unions, and\n * checking the actual signature (`(...args: never[]) => Promise<unknown>`)\n * sidesteps TypeScript's lenient `Promise<void>`→`void` assignability that\n * would otherwise let an async recipe satisfy a `(draft) => void`\n * constraint. Async F collapses the argument type to `never`, which no\n * function value can satisfy.\n *\n * @internal\n */\ntype AssertSync<F> = [F] extends [(...args: never[]) => Promise<unknown>]\n ? never\n : F;\n\n/**\n * Base type for data props passed to useActions.\n * Represents any object that can be captured as reactive data.\n */\nexport type Props = Record<string, unknown>;\n\n/**\n * Constraint type for action containers.\n * Actions are symbols grouped in an object (typically a class with static properties).\n */\nexport type Actions = object;\n\n/**\n * Internal result container for tracking Immertation processes during action execution.\n * @internal\n */\nexport type Result = {\n processes: Set<Process>;\n};\n\nexport type HandlerContext<\n M extends Model | void,\n AC extends Actions | void,\n D extends Props = Props,\n E extends Env = Env,\n> = {\n readonly model: DeepReadonly<M>;\n readonly phase: Phase;\n readonly task: Task;\n readonly data: DeepReadonly<D>;\n readonly tasks: ReadonlySet<Task>;\n readonly env: Readonly<E>;\n readonly actions: {\n produce<\n F extends (draft: {\n model: M;\n env: E;\n readonly inspect: Readonly<Inspect<M>>;\n }) => void,\n >(\n ƒ: F & AssertSync<F>,\n ): void;\n dispatch(action: NoPayloadActions<Dispatchable<AC>>): Promise<void>;\n dispatch<A extends WithPayloadActions<Dispatchable<AC>>>(\n action: A,\n payload: Payload<A>,\n ): Promise<void>;\n annotate<T>(value: T, operation?: Operation): T;\n readonly inspect: Readonly<Inspect<M>>;\n resource: (<T, P extends object>(\n invocation: Invocation<T, P>,\n ) => ResourceCall<T>) & {\n nuke(where?: Record<string, unknown>): void;\n };\n final<T>(\n action: BroadcastPayload<T> | MulticastPayload<T>,\n ): Promise<T | null>;\n peek<T>(action: BroadcastPayload<T> | MulticastPayload<T>): T | null;\n };\n};\n\n/**\n * Return type for the useActions hook.\n *\n * A tuple containing:\n * 1. The current model state of type M\n * 2. An actions object with dispatch and inspect capabilities\n * 3. The current data snapshot of type D &mdash; the same React-owned values\n * that handlers read via `context.data`, exposed here for JSX consumption\n * so the view and the handler share a single named source of truth.\n *\n * @template M - The model type representing the component's state\n * @template AC - The actions class containing action definitions\n * @template D - The data type for reactive external values\n *\n * @example\n * ```tsx\n * const [model, actions, data] = useActions<Model, typeof Actions, Data>(\n * model,\n * () => ({ user, theme }),\n * );\n *\n * // Access state\n * model.count;\n *\n * // Dispatch actions\n * actions.dispatch(Actions.Increment, 5);\n *\n * // Read React-owned dependencies in JSX (same values as context.data)\n * data.user.name;\n *\n * // Check pending state\n * actions.inspect.count.pending();\n * ```\n */\n/**\n * Utility type for defining a single action handler function.\n * Use this when you need to type a specific handler directly.\n *\n * @template M - The model type\n * @template AC - The actions class type\n * @template K - The action key (keyof AC) — determines payload type via lookup\n * @template D - Optional data/props type (defaults to Props)\n *\n * @see {@link Handlers} for the recommended HKT pattern\n */\nexport type Handler<\n M extends Model | void,\n AC extends Actions | void,\n K extends keyof AC & string,\n D extends Props = Props,\n E extends Env = Env,\n> = (\n context: HandlerContext<M, AC, D, E>,\n ...args: [Payload<AC[K] & HandlerPayload<unknown>>] extends [never]\n ? []\n : [payload: Payload<AC[K] & HandlerPayload<unknown>>]\n) => void | Promise<void> | AsyncGenerator | Generator;\n\n/**\n * String keys of `AC` excluding inherited `prototype` from class constructors.\n * When action containers are classes (`typeof MyActions`), TypeScript includes\n * `\"prototype\"` in `keyof`. Excluding it prevents `prototype` from appearing\n * as a handler key and avoids recursion into Function internals.\n */\ntype OwnKeys<AC> = Exclude<keyof AC & string, \"prototype\">;\n\n/**\n * Recursively flattens an actions class into the union of its leaf action\n * types. A \"leaf\" is any property whose own string keys are empty &mdash; the\n * branded `HandlerPayload` / `BroadcastPayload` / `MulticastPayload` values\n * produced by `Action(...)` and `Lifecycle.*()`. Nested namespace classes\n * (e.g. `static Broadcast = BroadcastActions`) are descended into.\n *\n * Used to constrain `dispatch` and `useAction` so that only actions owned by\n * the component's `AC` (plus the global `Lifecycle.Fault` /\n * `Lifecycle.Env`) can be referenced.\n */\nexport type LeafActions<AC> = AC extends void\n ? never\n : {\n [K in OwnKeys<AC>]: OwnKeys<AC[K]> extends never\n ? AC[K]\n : LeafActions<AC[K]>;\n }[OwnKeys<AC>];\n\n/**\n * Maps each action in a union to its channeled-call variant, when one exists.\n * Distributes over unions so a mixed bag of leaf actions produces the union\n * of their `ChanneledAction<P, C>` results.\n */\nexport type ChanneledOf<A> =\n A extends HandlerPayload<infer P, infer C>\n ? [C] extends [never]\n ? never\n : ChanneledAction<P, C>\n : never;\n\n/**\n * Everything `dispatch` accepts for a given `AC`: leaf actions on the class\n * and their channeled-call variants. The shared `Lifecycle.Fault` broadcast\n * is excluded — it's library-internal and not user-dispatchable.\n */\nexport type Dispatchable<AC> = LeafActions<AC> | ChanneledOf<LeafActions<AC>>;\n\n/**\n * Everything `useAction` will subscribe to for a given `AC`: same as\n * `Dispatchable<AC>` plus the shared `Lifecycle.Fault` and `Lifecycle.Env`\n * broadcasts which live outside `AC` but are subscribable by any component.\n */\nexport type Subscribable<AC> =\n | Dispatchable<AC>\n | typeof Lifecycle.Fault\n | typeof Lifecycle.Env;\n\n/**\n * Subset of a union of actions whose payload type is `never`. Used to split\n * `dispatch`/`useAction` into a no-payload and a with-payload overload so\n * TypeScript reports a clear \"no overload matches\" error instead of widening\n * the inferred action type when constraints don't match.\n */\nexport type NoPayloadActions<U> = Extract<\n U,\n { readonly [Brand.Payload]: never }\n>;\n\n/** Subset of a union of actions whose payload type is non-`never`. */\nexport type WithPayloadActions<U> = Exclude<\n U,\n { readonly [Brand.Payload]: never }\n>;\n\n/**\n * Recursive mapped type for action handlers that mirrors the action class hierarchy.\n *\n * For leaf actions (values with no own string keys, i.e. `HandlerPayload`), produces\n * a handler function signature. For namespace objects (containing nested actions),\n * produces a nested `Handlers` object.\n *\n * Access handlers using bracket notation matching the action structure:\n *\n * @template M - The model type\n * @template AC - The actions class type\n * @template D - Optional data/props type (defaults to Props)\n *\n * @example\n * ```ts\n * import { Action, Distribution, type Handlers } from \"march-hare\";\n *\n * class BroadcastActions {\n * static PaymentSent = Action(\"PaymentSent\", Distribution.Broadcast);\n * static PaymentLink = Action<PaymentLinkData>(\n * \"PaymentLink\",\n * Distribution.Broadcast,\n * );\n * }\n *\n * class Actions {\n * static SetName = Action<string>(\"SetName\");\n * static Broadcast = BroadcastActions;\n * }\n *\n * type H = Handlers<Model, typeof Actions>;\n *\n * // Flat actions\n * export const handleSetName: H[\"SetName\"] = (context, name) => { ... };\n *\n * // Nested actions use chained bracket notation\n * export const handlePaymentSent: H[\"Broadcast\"][\"PaymentSent\"] = (context) => { ... };\n * ```\n */\nexport type Handlers<\n M extends Model | void,\n AC extends Actions | void,\n D extends Props = Props,\n RootAC extends Actions | void = AC,\n E extends Env = Env,\n> = {\n [K in OwnKeys<AC>]: OwnKeys<AC[K]> extends never\n ? AC[K] extends { readonly [Brand.Lifecycle]: \"Update\" }\n ? (\n context: HandlerContext<M, RootAC, D, E>,\n changes: Partial<DeepReadonly<D>>,\n ) => void | Promise<void> | AsyncGenerator | Generator\n : (\n context: HandlerContext<M, RootAC, D, E>,\n ...args: [Payload<AC[K] & HandlerPayload<unknown>>] extends [never]\n ? []\n : [payload: Payload<AC[K] & HandlerPayload<unknown>>]\n ) => void | Promise<void> | AsyncGenerator | Generator\n : Handlers<M, AC[K] & Actions, D, RootAC, E>;\n};\n\nexport type UseActions<\n M extends Model | void,\n AC extends Actions | void,\n D extends Props = Props,\n E extends Env = Env,\n> = [\n Readonly<M>,\n {\n /**\n * Dispatches an action with an optional payload. Multicast actions read\n * their scope from the action declaration, so no extra options are\n * required at the call site.\n */\n dispatch(action: NoPayloadActions<Dispatchable<AC>>): Promise<void>;\n dispatch<A extends WithPayloadActions<Dispatchable<AC>>>(\n action: A,\n payload: Payload<A>,\n ): Promise<void>;\n inspect: Inspect<M>;\n /**\n * Streams broadcast values declaratively in JSX using a render-prop pattern.\n *\n * Subscribes to the given broadcast action and re-renders when a new value\n * is dispatched. Returns `null` until the first dispatch. The renderer\n * receives the value and an inspect proxy for annotation tracking.\n *\n * @param action - The broadcast action to subscribe to.\n * @param renderer - Callback that receives value and inspect, returns React nodes.\n * @returns React nodes from the renderer, or null if no value has been dispatched.\n *\n * @example\n * ```tsx\n * return (\n * <div>\n * {actions.stream(Actions.Broadcast.User, (user, inspect) => (\n * <span>{user.name}</span>\n * ))}\n * </div>\n * );\n * ```\n */\n stream(\n action: typeof Lifecycle.Env,\n renderer: (value: Readonly<E>, inspect: Inspect<E>) => React.ReactNode,\n ): React.ReactNode;\n stream<T extends object>(\n action: BroadcastPayload<T>,\n renderer: (value: T, inspect: Inspect<T>) => React.ReactNode,\n ): React.ReactNode;\n },\n DeepReadonly<D>,\n] & {\n /**\n * Dispatches an action with an optional payload &mdash; same as\n * `result[1].dispatch`, exposed on the tuple itself so call sites that\n * already have `actions` in scope can write `actions.dispatch(...)`\n * without indexing into `actions[1]`.\n */\n dispatch(action: NoPayloadActions<Dispatchable<AC>>): Promise<void>;\n dispatch<A extends WithPayloadActions<Dispatchable<AC>>>(\n action: A,\n payload: Payload<A>,\n ): Promise<void>;\n\n /**\n * Registers an action handler with the current scope.\n * Types are pre-baked from the `channel.use(...)` call, so no type\n * parameter is needed.\n *\n * Supports two subscription patterns:\n * 1. **Plain action** - Receives ALL dispatches for that action (including channeled ones)\n * 2. **Channeled action** `Action(channel)` - Receives only dispatches matching the channel\n *\n * @param action - The action or channeled action (e.g., `Action({ UserId: 1 })`)\n * @param handler - The handler function receiving context and payload\n *\n * @example\n * ```ts\n * const context = useContext<Model, typeof Actions>();\n * const actions = context.useActions(model);\n *\n * // Subscribe to ALL UserUpdated events\n * actions.useAction(Actions.UserUpdated, (context, user) => {\n * // Fires for any UserUpdated dispatch\n * });\n *\n * // Subscribe to UserUpdated for a specific user only (channeled)\n * actions.useAction(Actions.UserUpdated({ UserId: props.userId }), (context, user) => {\n * // Only fires when dispatched with matching channel\n * });\n * ```\n */\n useAction(\n action: NoPayloadActions<Subscribable<AC>>,\n handler: (\n context: HandlerContext<M, AC, D, E>,\n ) => void | Promise<void> | AsyncGenerator | Generator,\n ): void;\n useAction(\n action: typeof Lifecycle.Env,\n handler: (\n context: HandlerContext<M, AC, D, E>,\n env: Readonly<E>,\n ) => void | Promise<void> | AsyncGenerator | Generator,\n ): void;\n useAction<\n A extends Extract<\n Subscribable<AC>,\n { readonly [Brand.Lifecycle]: \"Update\" }\n >,\n >(\n action: A,\n handler: (\n context: HandlerContext<M, AC, D, E>,\n changes: Partial<DeepReadonly<D>>,\n ) => void | Promise<void> | AsyncGenerator | Generator,\n ): void;\n useAction<A extends WithPayloadActions<Subscribable<AC>>>(\n action: A,\n handler: (\n context: HandlerContext<M, AC, D, E>,\n payload: Payload<A>,\n ) => void | Promise<void> | AsyncGenerator | Generator,\n ): void;\n};\n\n/**\n * Stable, typed dispatch function for the actions class `AC`. Same call\n * signatures as `actions.dispatch` returned by `useActions`, available\n * before the paired `useActions` has run via {@link Context}.\n */\nexport type Dispatch<AC extends Actions | void> = {\n (action: NoPayloadActions<Dispatchable<AC>>): Promise<void>;\n <A extends WithPayloadActions<Dispatchable<AC>>>(\n action: A,\n payload: Payload<A>,\n ): Promise<void>;\n};\n\n/**\n * Handle returned by `useContext<M, AC, D>()`. Exposes\n * `dispatch(action, payload?)` and a `useActions` method that materialises\n * the component-local model and reactive data against the same dispatch\n * target. Generics are declared on `useContext`; `useActions` inherits\n * them &mdash; the call site does not re-state `Model` / `Actions` /\n * `Data`.\n *\n * Note: this `Context` type is distinct from React's `useContext` /\n * `React.Context` &mdash; it's the March Hare action surface returned by\n * the `useContext` hook of this library.\n */\nexport type Context<\n M extends Model | void,\n AC extends Actions | void,\n D extends Props = Props,\n E extends Env = Env,\n> = {\n readonly actions: { dispatch: Dispatch<AC> };\n /**\n * Typed bag of handler factories bound to `M`. Methods accept lodash-style\n * dotted paths with array indices (e.g. `\"a.b.c\"`, `\"items.0.id\"`) and\n * autocomplete from the model. See {@link WithHandle}.\n */\n readonly with: WithHandle<M>;\n useActions(getData?: () => D): UseActions<M, AC, D, E>;\n useActions(\n model: M extends void ? never : M,\n getData?: () => D,\n ): UseActions<M, AC, D, E>;\n};\n","import * as React from \"react\";\nimport { G } from \"@mobily/ts-belt\";\nimport type { Env as EnvType, Props } from \"./types.ts\";\nimport { Context } from \"./utils.ts\";\nimport { useBroadcast } from \"../broadcast/index.tsx\";\nimport { EnvSymbol } from \"../../../types/index.ts\";\n\nexport { useEnv } from \"./utils.ts\";\n\n/**\n * Provides a per-Boundary {@link EnvType} value to every component inside\n * the boundary. Usually wired in via the `<Boundary env={initial}>`\n * prop rather than used directly.\n *\n * The Env is **not** reactive. Mutating it does not trigger a\n * re-render. Drive view state through the model; use the Env for\n * cross-handler coordination.\n */\n\nexport function Env({ initial, children }: Props): React.ReactNode {\n const ref = React.useRef<EnvType>(initial);\n const broadcast = useBroadcast();\n\n if (G.isUndefined(broadcast.getCached(EnvSymbol))) {\n broadcast.setCache(EnvSymbol, ref.current);\n }\n\n return <Context.Provider value={ref}>{children}</Context.Provider>;\n}\n","import * as React from \"react\";\nimport type { Invocation } from \"../../../resource/index.ts\";\n\n/**\n * Per-`<Boundary>` registry for `.coalesce(token)` sharing. Outer map\n * keys on the `Invocation.run` function identity (stable per Resource\n * via the `build()` closure); inner map keys on\n * `${paramsKey}|${coalesceKey(token)}`. While an entry exists every\n * caller awaiting `.coalesce(token)` for the same Resource + params +\n * token receives the same promise.\n *\n * Lifted into React context so each `<app.Boundary>` owns its own\n * registry &mdash; two `App` instances in the same tree cannot collide\n * on a shared token like `.coalesce(\"k\")`.\n *\n * @internal\n */\nexport type Sharing = WeakMap<\n Invocation<unknown, object>[\"run\"],\n Map<string, Promise<unknown>>\n>;\n\nconst fallback: Sharing = new WeakMap();\n\n/**\n * React context exposing the per-Boundary sharing registry. The\n * fallback is a fresh `WeakMap` used when `useSharing()` is read\n * outside any `<Boundary>` &mdash; calls work but never share with any\n * other component.\n *\n * @internal\n */\nexport const Context = React.createContext<Sharing>(fallback);\n\n/**\n * Wraps children with a Boundary-scoped sharing registry for\n * `.coalesce(token)`. Rendered as part of {@link Boundary}; not\n * exposed standalone.\n *\n * @internal\n */\nexport function SharingProvider({\n children,\n}: {\n children: React.ReactNode;\n}): React.ReactElement {\n const registry = React.useMemo<Sharing>(() => new WeakMap(), []);\n return <Context.Provider value={registry}>{children}</Context.Provider>;\n}\n\n/**\n * Hook returning the per-Boundary sharing registry. Used by the\n * `.coalesce(token)` chainable inside `useActions`.\n *\n * @internal\n */\nexport function useSharing(): Sharing {\n return React.useContext(Context);\n}\n","import * as React from \"react\";\nimport type { Tap } from \"./types.ts\";\n\nconst noop: Tap = () => {};\n\n/**\n * React context carrying the active {@link Tap} observer for the\n * surrounding `<Boundary>`. Defaults to a no-op so `useTap()` callers\n * never need to null-check.\n */\nexport const Context = React.createContext<Tap>(noop);\n\n/**\n * Hook returning the active tap observer. Always returns a callable\n * &mdash; if no `<Boundary tap={...}>` is mounted above, calls are\n * silent no-ops with no allocation cost beyond the function call itself.\n */\nexport function useTap(): Tap {\n return React.useContext(Context);\n}\n","import * as React from \"react\";\nimport { Context } from \"./utils.ts\";\nimport type { Props, Tap } from \"./types.ts\";\n\nexport { useTap } from \"./utils.ts\";\nexport type {\n Tap,\n Taps,\n Invocation,\n Failure,\n Mutations,\n Snapshot,\n} from \"./types.ts\";\n\n/**\n * Internal provider that wires a {@link Tap} observer into the React\n * context consumed by `useActions` during dispatch. Rendered by the\n * top-level `<Boundary>` (and indirectly by `<app.Boundary>`); not\n * exposed on the public surface &mdash; consumers should pass the\n * callback via the `tap` prop of either boundary instead of mounting\n * this provider directly.\n *\n * The supplied `tap` callback is held in a `useRef` and indirected\n * through a stable `useMemo` wrapper. The ref is synchronised inside a\n * `useLayoutEffect` &mdash; React's sanctioned write-after-commit\n * window &mdash; so the provider stays compatible with Concurrent\n * rendering, where the render function may be invoked more than once\n * per commit and direct mutation during render would race the\n * scheduler.\n *\n * Keeping the context value referentially constant for the lifetime of\n * the boundary means callers may pass inline arrow functions without\n * invalidating the dispatch pipeline on every render &mdash; the\n * latest callback is read at fire time, not at provider-render time.\n * When `tap` is `undefined`, the wrapper short-circuits via optional\n * chaining: no allocation per event beyond the wrapper call itself.\n *\n * @param props.tap Observer to receive lifecycle events for every action\n * handler dispatched inside the boundary. See {@link Tap}.\n * @param props.children Subtree that should observe the supplied tap.\n * @returns Children rendered inside the tap context provider.\n *\n * @see {@link Tap} &mdash; the observer signature.\n * @see {@link Taps} &mdash; the discriminated union of event shapes.\n */\nexport function Tappable({ tap, children }: Props): React.ReactNode {\n const ref = React.useRef<Tap | undefined>(tap);\n React.useLayoutEffect(() => void (ref.current = tap), [tap]);\n\n const value = React.useMemo<Tap>(() => (event) => ref.current?.(event), []);\n\n return <Context.Provider value={value}>{children}</Context.Provider>;\n}\n","import type { ConsumerContext } from \"./types.ts\";\nimport * as React from \"react\";\n\n/**\n * React context for the consumer store.\n * Stores the latest value for each distributed action with full annotation support.\n */\nexport const Context = React.createContext<ConsumerContext>(new Map());\n\n/**\n * Hook to access the consumer store from context.\n *\n * @returns The Map of action symbols to their State entries.\n */\nexport function useConsumer(): ConsumerContext {\n return React.useContext(Context);\n}\n","import * as React from \"react\";\nimport { Broadcaster } from \"./components/broadcast/index.tsx\";\nimport { Tasks } from \"./components/tasks/index.tsx\";\nimport { Env } from \"./components/env/index.tsx\";\nimport type { Env as EnvType } from \"./components/env/types.ts\";\nimport { SharingProvider } from \"./components/sharing/index.tsx\";\nimport { Tappable } from \"./components/tap/index.tsx\";\nimport { Context as ConsumerContext } from \"./components/consumer/utils.ts\";\nimport type { ConsumerContext as ConsumerStore } from \"./components/consumer/types.ts\";\nimport type { Props } from \"./types.ts\";\n\n/**\n * Low-level boundary primitive. Wraps children with the Broadcaster,\n * Env, and Tasks providers required by every March Hare hook.\n *\n * Most applications should reach for {@link App} instead &mdash;\n * `App<E>({ env })` returns a typed `app.Boundary` along with\n * matching `useContext` / `useEnv` / `Resource` factories that all\n * close over the App's inferred env shape `E`. The bare `Boundary`\n * is exposed for advanced or library-internal use where the loose\n * Env record type is sufficient.\n *\n * @example\n * ```tsx\n * <Boundary env={{ session: null, locale: \"en-GB\" }}>\n * <App />\n * </Boundary>\n * ```\n */\nexport function Boundary({ env, tap, children }: Props): React.ReactNode {\n const consumer = React.useMemo<ConsumerStore>(() => new Map(), []);\n return (\n <Broadcaster>\n <ConsumerContext.Provider value={consumer}>\n <Env initial={env ?? ({} as EnvType)}>\n <Tasks>\n <Tappable tap={tap}>\n <SharingProvider>{children}</SharingProvider>\n </Tappable>\n </Tasks>\n </Env>\n </ConsumerContext.Provider>\n </Broadcaster>\n );\n}\n","import {\n ChanneledAction,\n Brand,\n BrandedAction,\n BrandedBroadcast,\n BrandedMulticast,\n AnyAction,\n} from \"../types/index.ts\";\nimport type { ActionId } from \"../boundary/components/tasks/types.ts\";\nimport { describe } from \"../utils.ts\";\nimport { G } from \"@mobily/ts-belt\";\n\nconst isSymbol = (value: unknown): value is symbol => typeof value === \"symbol\";\n\n/**\n * Extracts the underlying symbol from an action or channeled action.\n * This symbol is used as the event emitter key for dispatching.\n *\n * @param action The action or channeled action to extract the symbol from.\n * @returns The underlying symbol, or the action itself if it's already a symbol/string.\n *\n * @example\n * ```typescript\n * const Increment = Action<number>(\"Increment\");\n * getActionSymbol(Increment); // Symbol(march-hare.action/Increment)\n * getActionSymbol(Increment({ UserId: 5 })); // Symbol(march-hare.action/Increment)\n * ```\n */\nexport function getActionSymbol(action: AnyAction): ActionId {\n if (G.isString(action)) return action;\n if (isSymbol(action)) return action;\n if ((G.isObject(action) || G.isFunction(action)) && Brand.Action in action) {\n return (<BrandedAction>action)[Brand.Action];\n }\n return <ActionId>(<unknown>action);\n}\n\n/**\n * Checks whether an action is a broadcast action.\n * Broadcast actions are sent to all mounted components that have defined a handler for them.\n *\n * @param action The action to check.\n * @returns True if the action is a broadcast action, false otherwise.\n */\nexport function isBroadcastAction(action: AnyAction): boolean {\n if (G.isString(action)) return action.startsWith(describe.broadcast());\n\n if (isSymbol(action))\n return action.description?.startsWith(describe.broadcast()) ?? false;\n\n if (G.isObject(action) || G.isFunction(action)) {\n if (\n Brand.Broadcast in action &&\n (<BrandedBroadcast>action)[Brand.Broadcast]\n ) {\n return true;\n }\n\n if (Brand.Action in action) {\n const actionSymbol = (<BrandedAction>action)[Brand.Action];\n return (\n actionSymbol.description?.startsWith(describe.broadcast()) ?? false\n );\n }\n }\n\n return false;\n}\n\n/**\n * Extracts the action name from an action.\n *\n * Parses both regular actions (`march-hare.action/Name`) and\n * distributed actions (`march-hare.action/distributed/Name`)\n * to extract just the name portion.\n *\n * @param action The action to extract the name from.\n * @returns The extracted action name, or \"unknown\" if parsing fails.\n *\n * @example\n * ```typescript\n * const Increment = Action(\"Increment\");\n * getName(Increment); // \"Increment\"\n *\n * const SignedOut = Action(\"SignedOut\", Distribution.Broadcast);\n * getName(SignedOut); // \"SignedOut\"\n * ```\n */\nexport function getName(action: AnyAction): string {\n const symbol = getActionSymbol(action);\n const description = G.isString(symbol) ? symbol : (symbol.description ?? \"\");\n if (!description.startsWith(describe.action())) return \"unknown\";\n const name = description.slice(description.lastIndexOf(\"/\") + 1);\n return name || \"unknown\";\n}\n\n/**\n * Checks if the given action is a channeled action (result of calling `Action(channel)`).\n *\n * @param action - The action to check\n * @returns `true` if the action is a channeled action with a channel property, `false` otherwise\n *\n * @example\n * ```ts\n * const UserUpdated = Action<User, { UserId: number }>(\"UserUpdated\");\n *\n * isChanneledAction(UserUpdated); // false\n * isChanneledAction(UserUpdated({ UserId: 1 })); // true\n * ```\n */\nexport function isChanneledAction(\n action: AnyAction,\n): action is ChanneledAction {\n return G.isObject(action) && Brand.Channel in action && \"channel\" in action;\n}\n\n/**\n * Extracts the lifecycle type from an action's symbol description.\n *\n * Returns the lifecycle name (`\"Mount\"`, `\"Paint\"`, `\"Unmount\"`, `\"Error\"`,\n * `\"Update\"`) when the action symbol's description starts with the lifecycle\n * prefix, or `null` for non-lifecycle actions.\n *\n * @param action The action to inspect.\n * @returns The lifecycle name, or `null` if not a lifecycle action.\n *\n * @example\n * ```typescript\n * class Actions {\n * static Mount = Lifecycle.Mount();\n * }\n *\n * getLifecycleType(Actions.Mount); // \"Mount\"\n * getLifecycleType(Action(\"Increment\")); // null\n * ```\n */\nexport function getLifecycleType(action: AnyAction): string | null {\n const symbol = getActionSymbol(action);\n const description = isSymbol(symbol) ? (symbol.description ?? \"\") : symbol;\n if (!description.startsWith(describe.lifecycle())) return null;\n return description.slice(describe.lifecycle().length) || null;\n}\n\n/**\n * Checks whether an action is a multicast action.\n * Multicast actions are dispatched to all components within a named scope boundary.\n *\n * @param action The action to check.\n * @returns True if the action is a multicast action, false otherwise.\n */\nexport function isMulticastAction(action: AnyAction): boolean {\n if (G.isString(action)) return action.startsWith(describe.multicast());\n\n if (isSymbol(action))\n return action.description?.startsWith(describe.multicast()) ?? false;\n\n if (G.isObject(action) || G.isFunction(action)) {\n if (\n Brand.Multicast in action &&\n (<BrandedMulticast>action)[Brand.Multicast]\n ) {\n return true;\n }\n\n if (Brand.Action in action) {\n const actionSymbol = (<BrandedAction>action)[Brand.Action];\n return (\n actionSymbol.description?.startsWith(describe.multicast()) ?? false\n );\n }\n }\n\n return false;\n}\n","import {\n HandlerPayload,\n BroadcastPayload,\n MulticastPayload,\n Distribution,\n ChanneledAction,\n Brand,\n Filter,\n} from \"../types/index.ts\";\nimport { describe } from \"../utils.ts\";\n\nexport {\n getActionSymbol,\n getLifecycleType,\n isBroadcastAction,\n isMulticastAction,\n getName,\n isChanneledAction,\n} from \"./utils.ts\";\n\n/**\n * Interface for the Action factory function.\n */\ntype ActionFactory = {\n /**\n * Creates a new unicast action with an optional name.\n *\n * `K` is the literal type of the action name and is captured as a phantom\n * brand so `Action(\"A\")` and `Action(\"B\")` produce structurally-distinct\n * types. **Note:** when the caller supplies any explicit generic\n * (`Action<P>(\"Name\")`), TypeScript fills `K` from its default and the\n * literal is lost. The Name brand still helps for `Action(\"Name\")` calls\n * (e.g. lifecycle / no-payload actions) which is the most common source of\n * foreign-class collisions.\n *\n * Omitting the name produces an action whose symbol description has no\n * suffix. Symbol identity (and therefore dispatch routing) is unaffected\n * — names are only used for fault reporting and debugger readability.\n *\n * @template P The payload type for the action.\n * @template C The channel type for channeled dispatches.\n * @template K The literal type of the action name (inferred when no other\n * generics are supplied; defaults to `string` otherwise).\n */\n <P = never, C extends Filter = never, K extends string = string>(\n name?: K,\n ): HandlerPayload<P, C, K>;\n\n /**\n * Creates a new action with the specified distribution mode.\n */\n <P = never, C extends Filter = never, K extends string = string>(\n name: K | undefined,\n distribution: Distribution.Broadcast,\n ): BroadcastPayload<P, C, K>;\n <P = never, C extends Filter = never, K extends string = string>(\n name: K | undefined,\n distribution: Distribution.Multicast,\n ): MulticastPayload<P, C, K>;\n <P = never, C extends Filter = never, K extends string = string>(\n name: K | undefined,\n distribution: Distribution.Unicast,\n ): HandlerPayload<P, C, K>;\n <P = never, C extends Filter = never, K extends string = string>(\n name: K | undefined,\n distribution: Distribution,\n ):\n | HandlerPayload<P, C, K>\n | BroadcastPayload<P, C, K>\n | MulticastPayload<P, C, K>;\n};\n\n/**\n * Creates a new action with a given payload type, optional channel type, and optional distribution mode.\n *\n * Actions are strongly typed identifiers used to dispatch and handle state changes.\n * By default, actions use `Distribution.Unicast` (local to the defining component).\n * Use `Distribution.Broadcast` for actions that need to be shared across components.\n *\n * When a channel type is specified, the action becomes callable to create channeled dispatches:\n * - `Action({ UserId: 5 })` creates a channeled action targeting that specific channel\n * - Plain `Action` (uncalled) broadcasts to all handlers\n *\n * @template P The type of the payload that the action will carry.\n * @template C The type of the channel for channeled dispatches (defaults to never).\n *\n * @example\n * ```ts\n * export class Actions {\n * // Unicast action with no payload\n * static Reset = Action(\"Reset\");\n *\n * // Unicast action with typed payload\n * static Increment = Action<number>(\"Increment\");\n *\n * // Action with channel support for targeted dispatches\n * static UserUpdated = Action<User, { UserId: number }>(\"UserUpdated\");\n *\n * // Broadcast action - can be read across components\n * static Counter = Action<number>(\"Counter\", Distribution.Broadcast);\n * }\n *\n * // Usage\n * actions.dispatch(Actions.Reset);\n * actions.dispatch(Actions.Increment, 5);\n * actions.dispatch(Actions.UserUpdated, user); // broadcast to all\n * actions.dispatch(Actions.UserUpdated({ UserId: 5 }), user); // channeled dispatch\n * actions.stream(Actions.Counter, (box) => box.value);\n * ```\n */\nexport const Action = <ActionFactory>(<unknown>(<\n P = never,\n C extends Filter = never,\n>(\n name: string = \"\",\n distribution: Distribution = Distribution.Unicast,\n): HandlerPayload<P, C> | BroadcastPayload<P, C> | MulticastPayload<P, C> => {\n const symbol =\n distribution === Distribution.Broadcast\n ? Symbol(describe.broadcast(name))\n : distribution === Distribution.Multicast\n ? Symbol(describe.multicast(name))\n : Symbol(describe.action(name));\n\n const action = function (channel: C): ChanneledAction<P, C> {\n return {\n [Brand.Action]: symbol,\n [Brand.Payload]: <P>undefined,\n [Brand.Channel]: channel,\n [Brand.Name]: name,\n channel,\n };\n };\n\n // eslint-disable-next-line fp/no-mutating-methods\n Object.defineProperty(action, Brand.Action, {\n value: symbol,\n enumerable: false,\n });\n // eslint-disable-next-line fp/no-mutating-methods\n Object.defineProperty(action, Brand.Payload, {\n value: undefined,\n enumerable: false,\n });\n // eslint-disable-next-line fp/no-mutating-methods\n Object.defineProperty(action, Brand.Name, { value: name, enumerable: false });\n if (distribution === Distribution.Broadcast) {\n // eslint-disable-next-line fp/no-mutating-methods\n Object.defineProperty(action, Brand.Broadcast, {\n value: true,\n enumerable: false,\n });\n }\n if (distribution === Distribution.Multicast) {\n // eslint-disable-next-line fp/no-mutating-methods\n Object.defineProperty(action, Brand.Multicast, {\n value: true,\n enumerable: false,\n });\n }\n\n return <\n HandlerPayload<P, C> | BroadcastPayload<P, C> | MulticastPayload<P, C>\n >action;\n}));\n","import * as React from \"react\";\nimport { RefObject } from \"react\";\nimport {\n Props,\n Phase,\n Model,\n Actions,\n Filter,\n ActionId,\n HandlerPayload,\n ChanneledAction,\n HandlerContext,\n} from \"../types/index.ts\";\nimport EventEmitter from \"eventemitter3\";\nimport { BroadcastEmitter } from \"../boundary/components/broadcast/index.tsx\";\nimport { describe } from \"../utils.ts\";\n\nimport type { Dispatchers, LifecycleConfig, Handler, Scope } from \"./types.ts\";\nimport { A, G } from \"@mobily/ts-belt\";\nimport { changes } from \"../utils.ts\";\nimport {\n isChanneledAction,\n getActionSymbol,\n getLifecycleType,\n} from \"../action/index.ts\";\n\n/**\n * Creates a new object with getters for each property of the input object.\n * The getters retrieve the current value from a ref, ensuring that the latest value is always accessed.\n */\nexport function withGetters<P extends Props>(a: P, b: RefObject<P>): P {\n return Object.keys(a).reduce(\n (proxy, key) => {\n Object.defineProperty(proxy, key, {\n get() {\n return b.current[key];\n },\n enumerable: true,\n });\n\n return proxy;\n },\n <P>{},\n );\n}\n\n/**\n * Checks if the given result is a generator or async generator object.\n * Uses `Object.prototype.toString` which reliably returns\n * `\"[object Generator]\"` or `\"[object AsyncGenerator]\"` regardless of\n * the generator function's name.\n */\nexport function isGenerator(\n result: unknown,\n): result is Generator | AsyncGenerator {\n if (!result || typeof result !== \"object\") return false;\n const tag = Object.prototype.toString.call(result);\n return tag === \"[object Generator]\" || tag === \"[object AsyncGenerator]\";\n}\n\n/**\n * Sentinel passed as the dispatch channel during mount replay. Channeled\n * handlers check for this to skip replay &mdash; they require specific\n * channel context and cannot meaningfully process a replay without it.\n *\n * @internal\n */\nexport const replay: unique symbol = Symbol(describe.replay());\n\n/**\n * Invokes all listeners for an event and returns a promise that resolves\n * when every handler has settled. For {@link BroadcastEmitter} instances the\n * payload is cached before listeners fire so late-mounting components still\n * see the latest value.\n *\n * @internal\n */\nexport function emitAsync(\n emitter: EventEmitter,\n event: string | symbol,\n ...args: unknown[]\n): Promise<void> {\n if (emitter instanceof BroadcastEmitter) emitter.setCache(event, args[0]);\n\n const listeners = emitter.listeners(event);\n if (listeners.length === 0) return Promise.resolve();\n\n return Promise.all(listeners.map((fn) => Promise.resolve(fn(...args)))).then(\n () => {},\n );\n}\n\n/**\n * Emits lifecycle events for component mount and DOM attachment.\n * Also invokes broadcast action handlers with cached values on mount.\n * Updates the phase ref to track the component's current lifecycle state.\n *\n * The Mount effect skips when `phase` is already `Mounted` — this catches\n * Strict Mode's dev-only double-invocation. It accepts both `Mounting` (first\n * mount) and `Unmounted` (re-mount after `<Activity>` show) as entry states\n * so that hidden-then-shown subtrees correctly re-emit Mount.\n *\n * The Paint effect runs as a passive `useEffect` so it fires after the\n * browser has committed the first frame. It tracks its own ref-guard so it\n * fires exactly once per mount cycle (re-firing after `<Activity>` show).\n *\n * Phase transitions:\n * - First mount: Mounting → Mounted\n * - Activity hide / show: Mounted → Unmounting → Unmounted → Mounting → Mounted\n */\nexport function useLifecycles({\n unicast,\n broadcast,\n dispatchers,\n scope,\n phase,\n data,\n handlers,\n}: LifecycleConfig): void {\n const previous = React.useRef<Props | null>(null);\n const painted = React.useRef<boolean>(false);\n\n React.useLayoutEffect(() => {\n if (phase.current === Phase.Mounted) return;\n phase.current = Phase.Mounting;\n\n const mountAction = findLifecycleAction(handlers, \"Mount\");\n if (mountAction) unicast.emit(mountAction);\n\n dispatchers.broadcast.forEach((action) => {\n const cached = broadcast.getCached(action);\n if (!G.isNullable(cached)) unicast.emit(action, cached, replay);\n });\n\n if (scope) {\n dispatchers.multicast.forEach((action) => {\n const cached = scope.emitter.getCached(action);\n if (!G.isNullable(cached)) unicast.emit(action, cached, replay);\n });\n }\n\n phase.current = Phase.Mounted;\n painted.current = false;\n }, []);\n\n React.useEffect(() => {\n if (painted.current) return;\n painted.current = true;\n\n const paintAction = findLifecycleAction(handlers, \"Paint\");\n if (paintAction) unicast.emit(paintAction);\n }, []);\n\n React.useLayoutEffect(() => {\n if (G.isNotNullable(previous.current)) {\n const differences = changes(previous.current, data);\n if (A.isNotEmpty(Object.keys(differences))) {\n const updateAction = findLifecycleAction(handlers, \"Update\");\n if (updateAction) unicast.emit(updateAction, differences);\n }\n }\n\n previous.current = data;\n }, [data, unicast]);\n}\n\n/**\n * Creates a data proxy for a given object, returning a memoized version.\n * The proxy provides stable access to the object's properties,\n * even as the original object changes across renders.\n *\n * The ref is updated synchronously during render so the proxy is current\n * both during the render itself (for JSX reading the third tuple element\n * returned by {@link useActions}) and afterwards (for handler reads via\n * `context.data` across `await` boundaries).\n *\n * @template P The type of the object.\n * @param props The object to create a data proxy for.\n * @returns A memoized data proxy of the object.\n */\nexport function useData<P extends Props>(props: P): P {\n const ref = React.useRef<P>(props);\n ref.current = props;\n return React.useMemo(() => withGetters<P>(props, ref), [props]);\n}\n\n/**\n * Scans a handler registry for a lifecycle action of the given type.\n *\n * When lifecycle actions become per-class instances (via `Lifecycle.Mount()`),\n * each Actions class has its own unique symbol. Emission sites can no longer\n * emit to a shared singleton — they must discover the component's lifecycle\n * action by scanning the registry keys for matching lifecycle prefixes.\n *\n * Handler maps typically contain 5–15 entries, so the O(n) scan is trivial.\n *\n * @param handlers The handler map from a component's scope.\n * @param type The lifecycle type to find (e.g. `\"Mount\"`, `\"Unmount\"`, `\"Error\"`).\n * @returns The matching ActionId, or `null` if no lifecycle action of that type is registered.\n *\n * @internal\n */\nexport function findLifecycleAction(\n handlers: Map<ActionId, Set<unknown>>,\n type: string,\n): ActionId | null {\n for (const action of handlers.keys()) {\n if (getLifecycleType(action) === type) return action;\n }\n return null;\n}\n\n// Re-export isChanneledAction and getActionSymbol for convenience\nexport { isChanneledAction, getActionSymbol };\n\n/**\n * Manages sets of broadcast and multicast action IDs.\n *\n * This hook creates stable refs for tracking which actions have been registered\n * as broadcast or multicast within a component. These sets are used to:\n * - Replay cached broadcast values on mount\n * - Track multicast subscriptions for scope-based dispatch\n *\n * @returns Object with `broadcast` and `multicast` Sets for action tracking\n *\n * @example\n * ```ts\n * const actions = useDispatchers();\n *\n * // Register a broadcast action\n * actions.broadcast.add(getActionSymbol(MyBroadcastAction));\n *\n * // Check if an action is registered as multicast\n * if (actions.multicast.has(actionId)) {\n * // Handle multicast dispatch\n * }\n * ```\n *\n * @internal\n */\nexport function useDispatchers(): Dispatchers {\n const broadcast = React.useRef<Set<ActionId>>(new Set());\n const multicast = React.useRef<Set<ActionId>>(new Set());\n\n return React.useMemo(\n () => ({\n broadcast: broadcast.current,\n multicast: multicast.current,\n }),\n [],\n );\n}\n\n/**\n * Registers an action handler within a component's scope.\n *\n * This hook binds a handler function to an action, supporting both regular and channeled\n * actions. The handler is wrapped with `useEffectEvent` to ensure it always has access\n * to the latest closure values while maintaining a stable reference.\n *\n * For generator handlers (sync or async), the hook automatically iterates through\n * all yielded values to completion.\n *\n * @template M - The model type representing the component's state\n * @template AC - The actions class containing action definitions\n * @template D - The data type for reactive external values\n *\n * @param scope - Ref to the component's handler scope containing registered handlers\n * @param action - The action to register (ActionId, HandlerPayload, or ChanneledAction)\n * @param handler - The handler function to invoke when the action is dispatched\n *\n * @example\n * ```ts\n * useRegisterHandler(scope, Actions.Increment, async (context, payload) => {\n * context.actions.produce((draft) => {\n * draft.model.count += payload;\n * });\n * });\n *\n * // With channeled action\n * useRegisterHandler(scope, Actions.UserUpdated({ UserId: 5 }), (context, user) => {\n * // Only called when UserId matches 5\n * });\n * ```\n *\n * @internal\n */\nexport function useRegisterHandler<\n M extends Model | void,\n A extends Actions | void,\n D extends Props,\n>(\n scope: React.RefObject<Scope<M, A, D>>,\n action: ActionId | HandlerPayload | ChanneledAction,\n handler: (\n context: HandlerContext<M, A, D>,\n payload: unknown,\n ) => void | Promise<void> | AsyncGenerator | Generator,\n): void {\n // Store latest handler in ref to avoid stale closures (replaces useEffectEvent)\n const handlerRef = React.useRef(handler);\n React.useLayoutEffect(() => {\n handlerRef.current = handler;\n });\n\n // Store latest action for channel resolution\n const actionRef = React.useRef(action);\n React.useLayoutEffect(() => {\n actionRef.current = action;\n });\n\n // Stable handler wrapper that always calls the latest handler.\n // Generator detection and iteration is handled by createHandler in hooks/index.ts\n // so that generators can be excluded from the awaitable dispatch promise.\n const stableHandler = React.useCallback(\n (context: HandlerContext<M, A, D>, payload: unknown) =>\n handlerRef.current(context, payload),\n [],\n );\n\n // Stable channel getter\n const getChannel = React.useCallback(\n (): Filter | undefined =>\n isChanneledAction(actionRef.current)\n ? <Filter>actionRef.current.channel\n : undefined,\n [],\n );\n\n const base = getActionSymbol(action);\n const entries = scope.current.handlers.get(base) ?? new Set();\n if (entries.size === 0) scope.current.handlers.set(base, entries);\n entries.add({ getChannel, handler: <Handler<M, A, D>>stableHandler });\n}\n\n/**\n * Checks if a dispatch channel matches a registered handler channel.\n * All properties in the dispatch channel must match the corresponding properties in the registered channel.\n *\n * @param dispatchChannel - The channel from the dispatch call (from ChanneledAction)\n * @param registeredChannel - The channel registered with useAction\n * @returns `true` if all dispatch channel properties match the registered channel\n *\n * @example\n * ```ts\n * matchesChannel({ UserId: 1 }, { UserId: 1 }); // true\n * matchesChannel({ UserId: 1 }, { UserId: 2 }); // false\n * matchesChannel({ UserId: 1 }, { UserId: 1, Role: \"admin\" }); // true (subset match)\n * matchesChannel({ UserId: 1, Role: \"admin\" }, { UserId: 1 }); // false (missing Role)\n * ```\n */\nexport function matchesChannel(\n dispatchChannel: Filter,\n registeredChannel: Filter,\n): boolean {\n for (const key of Object.keys(dispatchChannel)) {\n if (registeredChannel[key] !== dispatchChannel[key]) return false;\n }\n return true;\n}\n","import * as React from \"react\";\nimport type { Stored } from \"./types.ts\";\n\n/**\n * Sentinel symbol marking \"no value present yet\". Shared by the Resource\n * cache and by storage handles so callers can distinguish \"nothing has been\n * recorded\" from \"a legitimately stored null\".\n */\nexport const unset: unique symbol = Symbol(\"march-hare.unset\");\n\n/**\n * Returns a function to force a component re-render. Useful when state is\n * managed externally (e.g., refs) but the UI needs updating.\n *\n * @returns A zero-arg callback that schedules a re-render of the host\n * component when invoked.\n */\nexport function useRerender(): () => void {\n const [, rerender] = React.useReducer((x: number) => x + 1, 0);\n return rerender;\n}\n\n/**\n * Constructs a {@link Stored} in the empty state. Internal helper shared\n * by the storage layer and the Resource snapshot accessor.\n *\n * @template T The payload type the resulting Stored would carry if populated.\n * @returns A Stored with `data` set to {@link unset} and `at` set to `null`.\n * @internal\n */\nexport function empty<T>(): Stored<T> {\n return { data: unset, at: null };\n}\n\n/**\n * Constructs a {@link Stored} wrapping a present payload and timestamp.\n *\n * @template T The payload type carried by the Stored.\n * @param data The payload value to wrap.\n * @param at The instant the payload was recorded — flows through to the\n * Resource cache as the entry's `at` timestamp.\n * @internal\n */\nexport function present<T>(data: T, at: Temporal.Instant): Stored<T> {\n return { data, at };\n}\n","import type { Task } from \"../boundary/components/tasks/types.ts\";\n\n/**\n * Reasons why an action error occurred.\n */\nexport enum Reason {\n /** Action was aborted &mdash; superseded by a newer dispatch, the\n * component unmounted, or `task.controller.abort()` was called. */\n Aborted,\n /** A generic error thrown in the user's action handler. */\n Errored,\n}\n\n/**\n * Details about an error that occurred during action execution.\n *\n * Faults are delivered through the global `Lifecycle.Fault` broadcast.\n * Subscribe with `actions.useAction(Lifecycle.Fault, handler)` near the\n * root of your application for app-level concerns (logging, sign-out on\n * auth failure, abort cascades). For component-local recovery, use a\n * `Lifecycle.Error()` factory instead.\n *\n * @template E Custom error types to include in the union with Error.\n */\nexport type Fault<E extends Error = never> = {\n /** The reason for the error. */\n reason: Reason;\n /** The Error object that was thrown. */\n error: Error | E;\n /** The name of the action that caused the error (e.g., \"Increment\"). */\n action: string;\n /** Whether the component has a `Lifecycle.Error()` handler registered. */\n handled: boolean;\n /**\n * All currently running tasks across the application.\n * Use this to programmatically abort in-flight actions during error recovery\n * (e.g., on 403/500 responses to prevent cascading failures).\n *\n * @example\n * ```ts\n * actions.useAction(Lifecycle.Fault, (context, fault) => {\n * if (fault.reason === Reason.Errored) {\n * for (const task of fault.tasks) task.controller.abort();\n * }\n * });\n * ```\n */\n tasks: ReadonlySet<Task>;\n /**\n * Re-dispatches the failed action with the original payload and channel,\n * routed through the same emitter (broadcast, multicast, or unicast) as the\n * original dispatch. Resolves when every triggered handler has settled.\n *\n * `retry` is independent of the failed task's `AbortController`: even when\n * the failure was an `Aborted` reason, calling `retry()` fires a fresh\n * dispatch with a new task. The closure stays callable after the fault\n * handler returns, which makes it safe to surface from a UI &mdash; e.g. a\n * \"Retry\" button bound to `fault.retry`.\n *\n * @example\n * ```ts\n * actions.useAction(Lifecycle.Fault, (_context, fault) => {\n * if (fault.reason === Reason.Errored && isTransient(fault.error)) {\n * void fault.retry();\n * }\n * });\n * ```\n */\n retry: () => Promise<void>;\n};\n","export { Reason } from \"./types\";\nexport type { Fault } from \"./types\";\n\n/**\n * Error thrown when an action is aborted, e.g., when a component unmounts\n * or when a newer dispatch cancels a previous run. Works across all platforms\n * including React Native where `DOMException` is unavailable.\n *\n * The instance's `name` field stays as `\"AbortError\"` so it can be\n * pattern-matched alongside native `DOMException`s and ky/fetch aborts.\n *\n * @example\n * ```ts\n * throw new Aborted(\"User cancelled the request\");\n * ```\n */\nexport class Aborted extends Error {\n override name = \"AbortError\";\n constructor(message = \"Aborted\") {\n super(message);\n }\n}\n","import type { ScopeContext, ScopeEntry } from \"./types.ts\";\nimport * as React from \"react\";\n\n/**\n * React context for the nearest multicast scope. `null` at the root.\n *\n * @internal\n */\nexport const Context = React.createContext<ScopeContext>(null);\n\n/**\n * Hook that returns the nearest multicast scope entry. `null` when\n * the caller is not rendered inside any `<app.Scope().Boundary>`.\n *\n * @internal\n */\nexport function useScope(): ScopeContext {\n return React.useContext(Context);\n}\n\n/**\n * Pass-through accessor. Kept for the dispatch/subscribe sites that\n * previously needed an action-keyed lookup; now the scope is a single\n * entry (or `null`), so this returns it as-is.\n *\n * @internal\n */\nexport function getScope(context: ScopeContext): ScopeEntry | null {\n return context;\n}\n","import type { Adapter, Encoded, Stored } from \"./types.ts\";\nimport type { Env } from \"../boundary/components/env/types.ts\";\nimport { empty, present, unset } from \"../utils/utils.ts\";\nimport { G } from \"@mobily/ts-belt\";\n\nexport type { Adapter, Encoded } from \"./types.ts\";\n\n/**\n * Context passed to {@link CacheConfig.key}. Mirrors the shape an\n * `app.Resource` fetcher receives, restricted to the field the cache\n * needs to scope on: the live per-`<Boundary>` Env. Future-extensible\n * &mdash; new fields can land here without breaking the call shape.\n *\n * @template E The Env shape the cache is parameterised by.\n */\nexport type CacheContext<E extends object> = {\n readonly env: E;\n};\n\n/**\n * Configuration accepted by the {@link Cache} factory. Combines the\n * synchronous {@link Adapter} (`get`/`set`/`remove`/`clear`/`keys?`)\n * with an optional `key(context)` callback in a single flat object,\n * so all the cache's plumbing lives in one literal at the call site.\n *\n * - `key` &mdash; derives a per-context cache scope. Called every time\n * a cache key is assembled with the same `{ env }` shape an\n * `app.Resource` fetcher receives; the returned string is prepended\n * to the per-resource namespace and params so different scopes\n * (e.g. one cache slot per access token, locale, or tenant id) can\n * coexist in the same backing store. Return `\"\"`, `null`, or\n * `undefined` to skip prefixing &mdash; useful for \"not signed in\"\n * gaps where the scope is genuinely empty.\n */\nexport type CacheConfig<E extends object> = Adapter & {\n readonly key?: (context: CacheContext<E>) => string | null | undefined;\n};\n\n/**\n * Persistence-aware cache for a single {@link Resource}. Wraps a\n * **strictly synchronous** {@link Adapter} (localStorage, MMKV,\n * chrome.storage with a sync facade, etc.) and traffics in {@link\n * Stored} envelopes &mdash; storage entries serialise as {@link\n * Encoded}`<T>` so the `Temporal.Instant` timestamp survives the\n * string round-trip and `.exceeds({...})` can short-circuit on the\n * persisted timestamp after a reload.\n *\n * Every method on the Cache is sync &mdash; the model-literal sync\n * read has no place to wait, so the adapter contract foregoes\n * `Promise` entirely. Async backends (IndexedDB, AsyncStorage,\n * `chrome.storage.local`) need a sync facade hydrated at app entry;\n * see `recipes/storage.md` for the pattern. React Native projects\n * should reach for {@link https://github.com/mrousavy/react-native-mmkv\n * `react-native-mmkv`} &mdash; it's synchronous out of the box and\n * drops straight into the Adapter contract.\n *\n * Call with no arguments for an in-memory cache scoped to this\n * instance &mdash; useful for tests, ephemeral state, or when you\n * want a first-class cache object to share between Resources without\n * persistence. Pass an {@link Adapter} to back the cache with a\n * persistent store; when supplied, the adapter is the **only** tier\n * &mdash; the Cache does not maintain a separate in-memory mirror.\n *\n * Pass `key(context)` alongside the adapter methods to scope cache\n * slots by the per-`<Boundary>` Env. The returned string is prepended\n * to every cache key the Resource layer assembles, so different\n * tenants / sessions / locales share the adapter without stepping on\n * each other.\n *\n * The `E` generic lives on the {@link Cache} factory and on\n * {@link CacheConfig}: it parameterises the `key(context)` callback\n * at construction time so the caller can read `context.env.X` with\n * full typing. The returned {@link Cache} value is itself\n * env-agnostic &mdash; the runtime `scope(env)` method takes the\n * loose {@link Env} record and narrows internally before invoking\n * the callback &mdash; which keeps it freely assignable across\n * differently-typed Apps without variance gymnastics.\n *\n * @example\n * ```ts\n * // In-memory, scoped to this instance.\n * const cache = Cache();\n *\n * // Persisted via localStorage.\n * const cache = Cache({\n * get: (key) => localStorage.getItem(key),\n * set: (key, value) => localStorage.setItem(key, value),\n * remove: (key) => localStorage.removeItem(key),\n * clear: () => localStorage.clear(),\n * });\n *\n * // Multi-tenant: writes go under `${accessToken}:…`.\n * type AppEnv = { session: { accessToken: string } | null };\n * const cache = Cache<AppEnv>({\n * get: (key) => localStorage.getItem(key),\n * set: (key, value) => localStorage.setItem(key, value),\n * remove: (key) => localStorage.removeItem(key),\n * clear: () => localStorage.clear(),\n * key: ({ env }) => env.session?.accessToken ?? \"\",\n * });\n *\n * // Wire it into a Resource — successful runs write through automatically.\n * export const cat = Resource({\n * cache,\n * fetch: (context) => fetchCat(context.controller.signal),\n * });\n * ```\n */\nexport type Cache = {\n /**\n * Returns the {@link Stored} envelope for `key`. The envelope is\n * `empty()` when nothing is persisted; otherwise it carries the\n * decoded payload and the timestamp recorded at write-time.\n *\n * @template T The payload type expected at `key`.\n * @param key Cache slot identifier &mdash; usually the JSON-stringified\n * call-site params, prefixed by the Resource's namespace.\n */\n get<T>(key: string): Stored<T>;\n /**\n * Writes `value` to `key`. Skipped when the envelope has no concrete\n * payload (e.g. an `empty()` slot), since there is nothing meaningful\n * to persist. Serialisation, quota errors, and unserialisable payloads\n * are swallowed &mdash; writes are best-effort.\n *\n * @template T The payload type contained in `value`.\n * @param key Cache slot identifier &mdash; usually the JSON-stringified\n * call-site params, prefixed by the Resource's namespace.\n * @param value Stored envelope carrying the payload and its\n * write-time `Temporal.Instant`.\n */\n set<T>(key: string, value: Stored<T>): void;\n /**\n * Drops a single cache slot. Best-effort &mdash; backing-store errors\n * are swallowed.\n *\n * @param key Cache slot identifier.\n */\n remove(key: string): void;\n /**\n * Drops every cache slot in the backing store. Best-effort &mdash;\n * backing-store errors are swallowed.\n */\n clear(): void;\n /**\n * Returns every key currently held by the backing store. Used by\n * partial-match eviction (`evict(where)`) to iterate slots whose\n * stored params satisfy a `where` pattern.\n */\n keys(): Iterable<string>;\n /**\n * Returns the per-context prefix derived from the configured\n * `key(context)`. The returned string is appended with `:` by the\n * Resource layer to compose the full cache key. Always `\"\"` when\n * no `key` option was supplied or when the callback returned an\n * empty value &mdash; \"no scope\" is encoded as the empty string.\n *\n * Takes the loose {@link Env} record at runtime &mdash; the typed\n * `E` lives on the `key(context)` callback registered at\n * construction time, which the cache narrows to `E` internally\n * before invoking.\n *\n * @internal Public surface lives on the Resource layer; consumers\n * should not need to call this directly.\n */\n scope(env: Env | undefined): string;\n};\n\n/**\n * In-memory {@link Adapter} backed by a `Map`. Created on demand inside\n * {@link Cache} when no adapter is supplied; tests and ephemeral use\n * cases get an isolated slot without touching storage.\n *\n * @internal\n */\nfunction memoryAdapter(): Adapter {\n const memory = new Map<string, string>();\n return {\n get: (key) => memory.get(key) ?? null,\n set: (key, value) => {\n memory.set(key, value);\n },\n remove: (key) => {\n memory.delete(key);\n },\n clear: () => {\n memory.clear();\n },\n keys: () => memory.keys(),\n };\n}\n\n/**\n * Constructs a {@link Cache} from `config`. The config object carries\n * the synchronous adapter methods (`get`/`set`/`remove`/`clear`/`keys?`)\n * and, optionally, a `key(context)` callback that scopes every cache\n * slot by the live per-`<Boundary>` Env. Omit `config` entirely for an\n * in-memory cache scoped to this instance.\n *\n * When `key` is supplied, it runs each time the Resource layer\n * assembles a cache key, receiving the same `{ env }` shape an\n * `app.Resource` fetcher sees; its return value is prepended\n * (separated by `:`) to the per-resource namespace and params JSON.\n *\n * @template E The Env shape `config.key` is typed against. Defaults\n * to the loose {@link Env} record so callers that don't scope by\n * env can keep using `Cache({ ...adapter })` without supplying a\n * generic.\n * @param config Optional adapter-plus-options literal. Omit for an\n * in-memory cache; supply adapter methods alone for a persisted\n * cache; add `key` to also scope writes by the live Env.\n */\nexport function Cache<E extends object = Env>(config?: CacheConfig<E>): Cache {\n const backing: Adapter = G.isUndefined(config) ? memoryAdapter() : config;\n const scopeFn = config?.key;\n\n return {\n /**\n * Reads `key` from the backing store, parses the {@link Encoded}\n * envelope, and re-hydrates the `Temporal.Instant`. Returns\n * `empty()` when the slot is missing or the stored JSON is\n * malformed.\n */\n get<T>(key: string): Stored<T> {\n try {\n const raw = backing.get(key);\n if (G.isNull(raw)) return empty<T>();\n const parsed = <Encoded<T>>JSON.parse(raw);\n return present(parsed.data, Temporal.Instant.from(parsed.at));\n } catch {\n return empty<T>();\n }\n },\n /**\n * Serialises `value` to JSON and writes it under `key`. Skips\n * envelopes whose payload is unset or whose timestamp is missing,\n * and swallows quota / encoding / private-mode errors.\n */\n set<T>(key: string, value: Stored<T>): void {\n if (value.data === unset || G.isNull(value.at)) return;\n try {\n backing.set(\n key,\n JSON.stringify(<Encoded<T>>{\n data: value.data,\n at: value.at.toString(),\n }),\n );\n } catch {\n return;\n }\n },\n /**\n * Removes a single slot. Backing-store errors are swallowed\n * &mdash; eviction is best-effort.\n */\n remove(key: string): void {\n try {\n backing.remove(key);\n } catch {\n return;\n }\n },\n /**\n * Clears every slot in the backing store. Backing-store errors are\n * swallowed &mdash; clear is best-effort.\n */\n clear(): void {\n try {\n backing.clear();\n } catch {\n return;\n }\n },\n /**\n * Returns every key the backing store currently holds, or an empty\n * iterable when the adapter does not expose `keys` (legacy adapters)\n * or throws while enumerating.\n */\n keys(): Iterable<string> {\n try {\n return backing.keys?.() ?? [];\n } catch {\n return [];\n }\n },\n scope(env: Env | undefined): string {\n if (G.isUndefined(scopeFn) || G.isNullable(env)) return \"\";\n try {\n const prefix = scopeFn({ env: <E>(<unknown>env) });\n return G.isNullable(prefix) ? \"\" : prefix;\n } catch {\n return \"\";\n }\n },\n };\n}\n","import { Cache } from \"../cache/index.ts\";\nimport { present, unset } from \"../utils/utils.ts\";\nimport type { Env } from \"../boundary/components/env/types.ts\";\nimport type {\n Args,\n Dispatch,\n Fetcher,\n Invocation,\n ResourceEvictor,\n ResourceHandle,\n} from \"./types.ts\";\nimport { G } from \"@mobily/ts-belt\";\n\nexport { Cache } from \"../cache/index.ts\";\n\n/**\n * Default in-memory `Cache` used when {@link Resource} is constructed\n * without an explicit one. Each fetcher gets its own slot via the\n * outer `WeakMap` so unrelated Resources don't share a string-key\n * namespace.\n *\n * @internal\n */\nexport const defaults = new WeakMap<object, Cache>();\n\n/**\n * Returns the {@link Cache} bound to `fetcher`, allocating a fresh\n * in-memory Cache on first access.\n *\n * @internal\n */\nexport function defaultCache(fetcher: object): Cache {\n const existing = defaults.get(fetcher);\n if (G.isNotNullable(existing)) return existing;\n const cache = Cache();\n defaults.set(fetcher, cache);\n return cache;\n}\n\n/**\n * Stable string key derived from the call-site `params`. Two calls with\n * the same logical params (same key order, same primitive values) hit\n * the same slot. JSON.stringify is sufficient for the March Hare params\n * convention (primitive-leaf objects); callers who need order-stable\n * keying should normalise the object before passing it in.\n *\n * @internal\n */\nexport function key(params: object): string {\n return JSON.stringify(params);\n}\n\n/**\n * Re-export of the shared `unset` sentinel from {@link \"../utils/index.ts\"}.\n *\n * @internal\n */\nexport const config = <const>{\n unset,\n};\n\n/**\n * Per-fetcher namespace registry. Each declared Resource takes a stable\n * id derived from the order of insertion (`namespaces.size`), used to\n * prefix cache keys when an App-shared {@link Cache} is configured.\n *\n * @internal\n */\nconst namespaces = new Map<object, string>();\n\n/**\n * Per-Resource eviction callbacks. Each `Resource` declaration registers\n * one entry on construction; the public `nuke(...)` (defined in\n * {@link \"./index.ts\"}) iterates them to drop cache slots across every\n * Resource in the process.\n *\n * @internal\n */\nexport const evictors: Array<ResourceEvictor> = [];\n\n/**\n * Mints the next namespace id for an app-shared cache. Each `app.Resource`\n * declaration consumes one id so the shared {@link Cache} can keep\n * resource-specific slots from colliding on shared params keys.\n *\n * @internal\n */\nexport function nextResourceId(fetcher: object): string {\n const existing = namespaces.get(fetcher);\n if (G.isNotNullable(existing)) return existing;\n const namespace = String(namespaces.size);\n namespaces.set(fetcher, namespace);\n return namespace;\n}\n\n/**\n * Allocates the per-Resource closure shared by `app.Resource` and\n * `shared.Resource`. The returned callable produces an\n * {@link Invocation} on every call &mdash; pass it to\n * `context.actions.resource(...)` for fetch/evict. `.get(params)` reads\n * the per-params cache slot synchronously.\n *\n * `getEnv` is the App-supplied accessor used to resolve the live env at\n * sync read time (`.get(params)`) and at App-side eviction (when the\n * handler context isn't available). It returns `undefined` when no\n * Boundary has mounted yet &mdash; in which case `cache.scope(undefined)`\n * yields the empty prefix and the read/evict targets the unscoped slot.\n *\n * @internal\n */\nexport function build<T, P extends object>(\n ƒ: Fetcher<T, P>,\n backing: Cache,\n namespace: string | null,\n getEnv: () => Env | undefined,\n): ResourceHandle<T, P> {\n const suffix = G.isNull(namespace) ? \"\" : `${namespace}:`;\n const composeKey = (env: Env | undefined, params: P) => {\n const scope = backing.scope(env);\n const prefix = scope === \"\" ? \"\" : `${scope}:`;\n return `${prefix}${suffix}${key(params)}`;\n };\n\n const read = (params: P, env: Env | undefined) => {\n const stored = backing.get<T>(composeKey(env, params));\n if (stored.data === unset || G.isNull(stored.at)) {\n return { data: unset, at: null };\n }\n return { data: <T>stored.data, at: stored.at };\n };\n\n const run = (\n env: Env,\n controller: AbortController,\n params: P,\n dispatch: Dispatch,\n ): Promise<T> =>\n ƒ(<Args<P>>{ env, controller, params, dispatch }).then((resolved) => {\n backing.set(\n composeKey(env, params),\n present(resolved, Temporal.Now.instant()),\n );\n return resolved;\n });\n\n const evict = (where: object): void => {\n const env = getEnv();\n const scope = backing.scope(env);\n const fullPrefix = scope === \"\" ? suffix : `${scope}:${suffix}`;\n const entries = Object.entries(where);\n for (const cacheKey of [...backing.keys()]) {\n if (!cacheKey.startsWith(fullPrefix)) continue;\n try {\n const parsed = <Record<string, unknown>>(\n JSON.parse(cacheKey.slice(fullPrefix.length))\n );\n if (entries.every(([field, value]) => parsed[field] === value))\n backing.remove(cacheKey);\n } catch {\n continue;\n }\n }\n };\n\n evictors.push(evict);\n\n function call(params?: P): Invocation<T, P> {\n const effective = <P>(params ?? {});\n return <Invocation<T, P>>{\n run,\n read: (params: P) => read(params, getEnv()),\n evict,\n params: effective,\n };\n }\n\n function get(params?: P): T | null {\n const { data } = read(<P>(params ?? {}), getEnv());\n return data === unset ? null : <T>data;\n }\n\n Object.defineProperty(call, \"get\", { value: get, enumerable: false });\n\n return <ResourceHandle<T, P>>(<unknown>call);\n}\n","import type { Fetcher, ResourceHandle } from \"./types.ts\";\nimport {\n Cache,\n build,\n defaultCache,\n evictors,\n nextResourceId,\n} from \"./utils.ts\";\nimport type { AppFetcher } from \"../app/types.ts\";\nimport type { Env } from \"../boundary/components/env/types.ts\";\nimport { G } from \"@mobily/ts-belt\";\n\nexport type { Coalesce, Fetcher, Invocation, ResourceHandle } from \"./types.ts\";\n\n/**\n * Evicts cache entries across every Resource constructed in the\n * current process. Resources register themselves on declaration, so\n * `nuke` covers both `app.Resource` and `shared.Resource`. Pass a\n * `where` pattern to drop only slots whose stored params satisfy the\n * pattern's keys (partial match &mdash; extra keys in the stored\n * params are ignored). Pass nothing to clear every known slot.\n *\n * @internal Public surface lives on `context.actions.resource.nuke(...)`.\n */\nexport function nuke(where?: object): void {\n const pattern = where ?? {};\n for (const evict of evictors) evict(pattern);\n}\n\n/**\n * Defines a remote resource &mdash; declared at module scope and used\n * directly. Exported as `shared.Resource` and (via the app factory) as\n * `app.Resource`. Calling the returned handle with `params` produces an\n * {@link Invocation} suitable for `context.actions.resource(...)` (fetch\n * path) or `context.actions.resource(...).evict(where?)` (partial-match\n * invalidation). Use `.get(params)` on the handle for a synchronous\n * cache read returning `T | null`. Persistence happens automatically\n * when the App is declared with `App({ cache })`.\n *\n * Takes the **Env shape `E` as a mandatory first generic** &mdash;\n * `context.env` inside the fetcher is typed as `E`. Pass a union of\n * every App's Env if the resource is shared across reusable\n * components. For single-app resources, prefer `app.Resource` &mdash;\n * the Env is captured from `app` automatically and you only need the\n * payload generic.\n *\n * The fetcher receives a single `context` argument carrying `env`,\n * `controller`, `params`, and a broadcast/multicast-only `dispatch`.\n * `env` is a live handle &mdash; dot reads inside the fetcher always\n * see the latest per-`<Boundary>` Env, even after `await` boundaries.\n *\n * Cache behaviour is decided at the App level: when `App({ cache })`\n * is supplied, every `app.Resource` declaration on that App writes\n * through to (and seeds from) the shared cache, isolated per resource\n * by a stable module-order namespace. When the App is constructed\n * without a `cache`, every resource keeps its own in-memory slot.\n * Standalone `shared.Resource` declarations always use an in-memory\n * cache &mdash; reach for `app.Resource` when persistence is required.\n *\n * Concurrent calls fire fresh requests by default. Opt in to in-flight\n * sharing per call via `.coalesce(key)` on the thenable returned from\n * `context.actions.resource(...)`.\n *\n * @template E The Env shape (or union) the fetcher's `context.env` is\n * typed against.\n * @template T The payload type the fetcher resolves to.\n * @template P The call-time params type.\n *\n * @example\n * ```ts\n * import { shared } from \"march-hare\";\n *\n * type WebEnv = { session: Session | null };\n *\n * export const user = shared.Resource<WebEnv, User, { id: number }>((context) =>\n * ky\n * .get(`users/${context.params.id}`, {\n * headers: context.env.session\n * ? { Authorization: `Bearer ${context.env.session.accessToken}` }\n * : {},\n * signal: context.controller.signal,\n * })\n * .json<User>(),\n * );\n * ```\n *\n * @internal The optional `cache` argument is reserved for `app.Resource`\n * &mdash; consumers should use `App({ cache })` instead of passing it\n * directly.\n */\nexport function Resource<\n E extends object,\n T,\n P extends object = Record<never, never>,\n>(\n ƒ: AppFetcher<E, T, P>,\n cache?: Cache,\n getEnv?: () => Env | undefined,\n): ResourceHandle<T, P> {\n const inner = <Fetcher<T, P>>(<unknown>ƒ);\n const resolveEnv = getEnv ?? (() => undefined);\n if (G.isUndefined(cache)) {\n return build(inner, defaultCache(inner), null, resolveEnv);\n }\n return build(inner, cache, nextResourceId(inner), resolveEnv);\n}\n","import type { Coalesce } from \"../resource/types.ts\";\n\n/**\n * Sentinel token used when `.coalesce()` is called with no explicit\n * argument. Every untokened caller for the same `(Resource, params)`\n * slot collapses onto this single key, so multiple callers chaining\n * `.coalesce()` share one in-flight fetch.\n *\n * The symbol description follows the `march-hare.{category}/{name}`\n * convention used by the rest of the library's internal symbols.\n *\n * @internal\n */\nexport const token: unique symbol = Symbol(\"march-hare.coalesce/default\");\n\n/**\n * Builds the per-call dedupe key for `.coalesce(token)`.\n *\n * The full registry key (constructed at the call site) is\n * `${JSON.stringify(params)}|${coalesceKey(token)}`; this function is\n * responsible only for the trailing token segment. Every supported\n * `Coalesce` primitive (`string`, `number`, `bigint`, `boolean`,\n * `symbol`) is prefixed with a single-character type tag so that\n * structurally identical values from different types stay distinct\n * &mdash; e.g. the string `\"5\"` does not collide with the number `5`,\n * and `Symbol(\"X\")` does not collide with the string `\"X\"`.\n *\n * Symbols are keyed by their `description` (falling back to\n * `String(value)` for description-less symbols) so two `Symbol(\"X\")`\n * instances declared in separate modules still hash to the same key.\n * That is intentional: the public contract is \"same description &rarr;\n * same coalesce group\", which keeps the API friendly for the common\n * enum-token pattern at call sites.\n *\n * Any unrecognised value falls through to the object branch and is\n * keyed by its JSON shape; `Coalesce` is constrained to primitives at\n * the type level, so this branch is reachable only from `unknown`\n * coercion in tests.\n *\n * @internal\n */\nexport function coalesceKey(value: Coalesce): string {\n switch (typeof value) {\n case \"string\":\n return `s:${value}`;\n case \"number\":\n return `n:${value}`;\n case \"bigint\":\n return `i:${value.toString()}`;\n case \"boolean\":\n return `b:${value}`;\n case \"symbol\":\n return `y:${value.description ?? String(value)}`;\n default:\n return `o:${JSON.stringify(value)}`;\n }\n}\n\n/**\n * Wraps `promise` so that aborting `signal` rejects the returned\n * promise with `signal.reason`, even when `promise` itself never\n * settles. The original promise is left alone &mdash; the underlying\n * work continues (other awaiters keep their grip) and only this\n * caller's view of it is severed.\n *\n * Used by the `.coalesce(token)` chainable: the shared in-flight fetch\n * runs on a detached `AbortController` so one caller's abort does not\n * cancel work the others are still waiting on, while each caller's own\n * `context.task.controller` still aborts its personal await via this\n * wrapper. The `{ once: true }` listener and the cleanup on settle keep\n * the wrapper free of leaks across long-lived signals.\n *\n * @internal\n */\nexport function withAbort<T>(\n promise: Promise<T>,\n signal: AbortSignal,\n): Promise<T> {\n return new Promise<T>((resolve, reject) => {\n if (signal.aborted) {\n reject(signal.reason);\n return;\n }\n const onAbort = (): void => reject(signal.reason);\n signal.addEventListener(\"abort\", onAbort, { once: true });\n promise.then(\n (value) => {\n signal.removeEventListener(\"abort\", onAbort);\n resolve(value);\n },\n (error: unknown) => {\n signal.removeEventListener(\"abort\", onAbort);\n reject(error);\n },\n );\n });\n}\n","import{immerable as t,enablePatches as e,Immer as r}from\"immer\";import{G as i,A as n}from\"@mobily/ts-belt\";let s=(t=21)=>{let e=\"\",r=crypto.getRandomValues(new Uint8Array(t|=0));for(;t--;)e+=\"useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict\"[63&r[t]];return e};var o=/* @__PURE__ */(t=>(t[t.Add=1]=\"Add\",t[t.Remove=2]=\"Remove\",t[t.Update=4]=\"Update\",t[t.Move=8]=\"Move\",t[t.Replace=16]=\"Replace\",t[t.Sort=32]=\"Sort\",t[t.Create=64]=\"Create\",t[t.Fetch=128]=\"Fetch\",t[t.Clone=256]=\"Clone\",t[t.Archive=512]=\"Archive\",t[t.Restore=1024]=\"Restore\",t[t.Merge=2048]=\"Merge\",t[t.Reorder=4096]=\"Reorder\",t[t.Sync=8192]=\"Sync\",t[t.Publish=16384]=\"Publish\",t[t.Link=32768]=\"Link\",t[t.Unlink=65536]=\"Unlink\",t[t.Lock=131072]=\"Lock\",t[t.Unlock=262144]=\"Unlock\",t[t.Import=524288]=\"Import\",t[t.Export=1048576]=\"Export\",t[t.Transfer=2097152]=\"Transfer\",t))(o||{}),a=/* @__PURE__ */(t=>(t[t.Produce=0]=\"Produce\",t[t.Hydrate=1]=\"Hydrate\",t))(a||{}),c=/* @__PURE__ */(t=>(t.Property=\"property\",t.Process=\"process\",t.Value=\"value\",t.Operation=\"operation\",t))(c||{});class u{[t]=!0;static keys=new Set(Object.values(c));property=null;process=null;value;operation;constructor(t,e){this.value=t,this.operation=e}assign(t,e){const r=new u(this.value,this.operation);return r.property=t,r.process=e,r}}class l{static immer=(()=>{e();const t=new r;return t.setAutoFreeze(!1),t})();static tag=\"κ\";static id=s}const p=Symbol(\"Box\");function y(t,e){const r=\"string\"==typeof e?\"\"===e?[]:e.split(\".\"):e;let i=t;for(const n of r){if(null==i)return;i=i[n]}return i}function f(t){if(i.isNullable(t)||m(t))return t;if(i.isArray(t))return t.map(t=>f(t));if(i.isObject(t)&&h(t)){const e=Object.entries(t).map(([t,e])=>[t,f(e)]);return{...Object.fromEntries(e),[l.tag]:t[l.tag]??l.id()}}return t}function d(t){if(Array.isArray(t))return t.filter(t=>l.tag in t).map(t=>t[l.tag]??\"\").join(\",\");const e=t[l.tag];if(e)return e;try{return JSON.stringify(t)}catch{return`[unserializable:${typeof t}]`}}function h(t){const e=Object.getPrototypeOf(t);return e===Object.prototype||null===e}function m(t){return i.isNullable(t)||i.isString(t)||i.isNumber(t)||i.isBoolean(t)||\"symbol\"==typeof t||\"bigint\"==typeof t}function b(t){return i.isObject(t)&&p in t}function g(t,e,r,n,s,o){return function c(l,p=e.path){if(l instanceof u){const e=y(r,p.join(\".\"));if(Object.entries(l).filter(([t,e])=>!u.keys.has(t)&&e instanceof u).forEach(([t,e])=>c(e,p.concat(t))),m(l.value)){if(t===a.Hydrate)return l.value;const c=p.slice(0,-1),u=c.length>0?y(r,c.join(\".\")):r;return i.isNullable(u)||v(u,l,p.at(-1),n,s,o),e??l.value}if(t===a.Hydrate){const t=f(c(l.value,p));return v(t,l,null,n,s,o),t}const d=e??f(l.value);return v(d,l,null,n,s,o),i.isNullable(e)?d:(c(l.value,p),e)}if(i.isArray(l))return l.map((t,e)=>c(t,p.concat(e)));if(i.isObject(l)&&!h(l))return l;if(i.isObject(l)){const e=Object.entries(l).map(([t,e])=>[t,c(e,p.concat(t))]),r=Object.fromEntries(e);if(t===a.Hydrate){const t=f(r);return Object.entries(l).forEach(([e,r])=>{r instanceof u&&m(r.value)&&v(t,r,e,n,s,o)}),t}return r}return l}(e.value)}function v(t,e,r,i,n,s){const o=s(t),a=n.get(o)??[];n.set(o,[e.assign(r,i),...a])}class O{#t={};#e;#r=/* @__PURE__ */new Map;#i=/* @__PURE__ */new Set;#n=!1;constructor(t=d){this.#e=t}static pk(){return s()}static\"κ\"=O.pk;annotate(t,e){return new u(e,t)}\"δ\"=this.annotate;get model(){return this.#t}get inspect(){return function(t,e,r,s,o){function a(s){const o=s.at(-1),a=y(t(),s),c=s.slice(0,-1),u=n.isNotEmpty(c)?y(t(),c):t();return[...i.isObject(a)||i.isArray(a)?e.get(r(a))?.filter(t=>i.isNullable(t.property))??[]:[],...i.isObject(u)?e.get(r(u))?.filter(t=>t.property===o)??[]:[]]}return function e(r){return new Proxy(()=>{},{get:(i,c)=>\"pending\"===c?()=>!n.isEmpty(a(r)):\"remaining\"===c?()=>n.length(a(r)):\"box\"===c?()=>({value:y(t(),r),inspect:e(r),[p]:!0}):\"is\"===c?t=>a(r).some(e=>0!==(e.operation&t)):\"draft\"===c?()=>n.head(a(r))?.value??y(t(),r):\"settled\"===c?()=>new Promise(e=>{if(n.isEmpty(a(r)))return e(y(t(),r));const i=()=>{n.isEmpty(a(r))&&(o(i),e(y(t(),r)))};s(i)}):e([...r,String(c)])})}([])}(()=>this.#t,this.#r,this.#e,t=>this.#i.add(t),t=>this.#i.delete(t))}hydrate(t){return this.#n=!0,this.#s(a.Hydrate,()=>t)}produce(t){if(!this.#n)throw new Error(\"State must be hydrated using hydrate() before calling produce()\");return this.#s(a.Produce,t)}#s(t,e){const r=Symbol(\"process\"),[,i]=l.immer.produceWithPatches(this.#t,e);return this.#t=i.reduce((e,i)=>l.immer.applyPatches(e,[{...i,value:g(t,i,e,r,this.#r,this.#e)}]),this.#t),this.#t=f(this.#t),this.#o(),r}prune(t){this.#r.forEach((e,r)=>{const i=e.filter(e=>e.process!==t);n.isEmpty(i)?this.#r.delete(r):this.#r.set(r,i)}),this.#o()}#o(){this.#i.forEach(t=>t())}observe(t){const e=()=>t(this.#t);return this.#i.add(e),()=>this.#i.delete(e)}}export{o as Op,o as Operation,O as State,b as isBox};\n","import * as React from \"react\";\nimport { State, Inspect } from \"immertation\";\nimport { G } from \"@mobily/ts-belt\";\nimport { useBroadcast } from \"../../../broadcast/index.tsx\";\nimport { useConsumer } from \"../../utils.ts\";\nimport { useRerender } from \"../../../../../utils/utils.ts\";\nimport { Entry, Model } from \"../../types.ts\";\nimport { Props } from \"./types.ts\";\n\n/**\n * Renders output for the `stream()` method by subscribing to distributed action events.\n *\n * This component manages a subscription to the broadcast emitter for distributed actions,\n * storing the latest dispatched value in the Consumer context. When a new value arrives,\n * all mounted Partition instances for that action re-render with the updated value.\n *\n * On mount, if a value was previously dispatched for this action, it renders immediately\n * with that cached value. If no value exists yet, it renders `null` until the first dispatch.\n *\n * Uses Immertation's State class internally to manage consumed values, providing real\n * annotation tracking through the `inspect` proxy. When a payload containing annotated\n * values is dispatched, the annotations are preserved and accessible via `inspect`.\n *\n * The renderer callback receives two arguments:\n * - `value`: The latest dispatched payload\n * - `inspect`: A proxy for checking annotation status (pending, is, draft, settled, etc.)\n *\n * @template T - The payload type for the action (must be an object type)\n * @param props.action - The distributed action symbol to subscribe to\n * @param props.renderer - Callback that receives value and inspect, returns React nodes\n * @returns The result of calling renderer, or null if no value exists\n * @internal\n */\nexport function Partition<T extends object>({\n action,\n renderer,\n}: Props<T>): React.ReactNode {\n const broadcast = useBroadcast();\n const consumer = useConsumer();\n const rerender = useRerender();\n\n const entry = React.useMemo(() => {\n const existing = consumer.get(action);\n if (existing) return existing as Entry<T>;\n\n const state = new State<Model<T>>();\n const cached = broadcast.getCached(action);\n if (G.isNotNullable(cached)) state.hydrate({ value: cached as T });\n const entry: Entry<T> = { state, listeners: new Set() };\n consumer.set(action, entry as unknown as Entry);\n return entry;\n }, [action, broadcast, consumer]);\n\n React.useLayoutEffect(() => {\n entry.listeners.add(rerender);\n\n function handlePayload(payload: T) {\n entry.state.hydrate({ value: payload });\n entry.listeners.forEach((listener) => listener());\n }\n\n broadcast.on(action, handlePayload);\n\n return () => {\n entry.listeners.delete(rerender);\n broadcast.off(action, handlePayload);\n };\n }, [action, broadcast, entry]);\n\n const value = entry.state.model?.value;\n if (G.isNullable(value)) return null;\n\n const inspect = entry.state.inspect as unknown as { value: Inspect<T> };\n\n return renderer(value, inspect.value);\n}\n","import type { Actions, HandlerContext, Model, Props } from \"../types/index.ts\";\nimport type { Env } from \"../boundary/components/env/types.ts\";\nimport type { WithHandle } from \"./types.ts\";\n\n/**\n * Walks the lodash-style dotted `path` on `target`, stopping one segment\n * short so callers can mutate or read the leaf via the returned `cursor`\n * and `key`. Used by every assignment helper below to avoid duplicating\n * the per-segment descent.\n *\n * @internal\n */\nexport function walk(\n target: unknown,\n path: string,\n): { cursor: Record<string, unknown>; key: string } {\n const segments = path.split(\".\");\n let cursor = <Record<string, unknown>>target;\n for (let i = 0; i < segments.length - 1; i++) {\n cursor = <Record<string, unknown>>cursor[segments[i]];\n }\n return { cursor, key: segments[segments.length - 1] };\n}\n\n/**\n * Assigns `value` to the leaf of `target` reached by lodash-style `path`.\n * Mutates in place &mdash; expected to be called from inside an Immer\n * `produce` draft.\n *\n * @internal\n */\nexport function setPath(target: unknown, path: string, value: unknown): void {\n const { cursor, key } = walk(target, path);\n cursor[key] = value;\n}\n\n/**\n * Flips the boolean leaf of `target` reached by lodash-style `path`.\n * Mutates in place &mdash; expected to be called from inside an Immer\n * `produce` draft.\n *\n * @internal\n */\nexport function invertPath(target: unknown, path: string): void {\n const { cursor, key } = walk(target, path);\n cursor[key] = !cursor[key];\n}\n\n/**\n * Returns a handler that assigns the dispatched payload to the model\n * leaf at lodash-style `key`. Underlies both `context.with.update` and\n * the top-level `With.Update`.\n *\n * @internal\n */\nexport function makeUpdate(key: string) {\n return (\n context: HandlerContext<Model, Actions, Props, Env>,\n payload: unknown,\n ) => {\n context.actions.produce((draft) => {\n setPath(draft.model, key, payload);\n });\n };\n}\n\n/**\n * Returns a handler that flips the boolean model leaf at lodash-style\n * `key`. Underlies both `context.with.invert` and `With.Invert`.\n *\n * @internal\n */\nexport function makeInvert(key: string) {\n return (context: HandlerContext<Model, Actions, Props, Env>) => {\n context.actions.produce((draft) => {\n invertPath(draft.model, key);\n });\n };\n}\n\n/**\n * Returns a handler that assigns the constant `value` to the model\n * leaf at lodash-style `key`, ignoring any dispatched payload.\n * Underlies both `context.with.always` and `With.Always`.\n *\n * @internal\n */\nexport function makeAlways(key: string, value: unknown) {\n return (context: HandlerContext<Model, Actions, Props, Env>) => {\n context.actions.produce((draft) => {\n setPath(draft.model, key, value);\n });\n };\n}\n\n/**\n * Builds the {@link WithHandle} object returned via `context.with`. The\n * runtime is identical for any model &mdash; only the call-site types differ.\n *\n * @internal\n */\nexport function bindWith<M extends Model | void>(): WithHandle<M> {\n return <WithHandle<M>>(<unknown>{\n update<K extends string>(key: K) {\n return makeUpdate(key);\n },\n invert<K extends string>(key: K) {\n return makeInvert(key);\n },\n always<K extends string>(key: K, value: unknown) {\n return makeAlways(key, value);\n },\n });\n}\n","import * as React from \"react\";\nimport { useActions } from \"../actions/index.ts\";\nimport { bindWith } from \"../with/utils.ts\";\nimport type {\n Actions,\n Context as ContextHandle,\n Model,\n Props,\n UseActions,\n} from \"../types/index.ts\";\nimport type { DispatchTarget } from \"./types.ts\";\n\n/**\n * Returns a stable, typed controller handle up-front &mdash; before a\n * model is declared via `context.useActions(...)`. Use this when an\n * external imperative library (form, animation, third-party SDK) needs a\n * dispatch callback at construction time, while the value that library\n * returns must flow back into the controller's data callback.\n *\n * The handle exposes `dispatch(action, payload?)`, a `useActions(...)`\n * method that materialises the component-local model and reactive data\n * &mdash; the M and D pair of `useContext<M, AC, D>` &mdash; and\n * returns the `[model, actions, data]` tuple with `useAction`, `dispatch`,\n * `inspect`, and `stream` attached, plus `with` &mdash; a bag of handler\n * factories (`update`/`invert`/`always`) typed against the declared model\n * and accepting lodash-style dotted paths and array indices. The first\n * invocation of `context.actions.dispatch(...)` must come from an event\n * handler &mdash; not synchronously during render &mdash; because the\n * underlying dispatch target is wired up when `context.useActions(...)`\n * runs in the same render pass.\n *\n * @template M The model type representing the component's state.\n * @template AC The actions class containing action definitions.\n * @template D The data type for reactive external values.\n *\n * @example\n * ```ts\n * const context = useContext<Model, typeof Actions, Data>();\n *\n * const form = useForm({\n * onSubmit: () => void context.actions.dispatch(Actions.Submit),\n * });\n *\n * const actions = context.useActions(\n * { user: resource.user.get() },\n * () => ({ form }),\n * );\n * ```\n *\n * @internal\n */\nexport function useContext<\n M extends Model | void = void,\n AC extends Actions | void = void,\n D extends Props = Props,\n>(): ContextHandle<M, AC, D> {\n const ref = React.useRef<DispatchTarget | null>(null);\n\n return React.useMemo(() => {\n function dispatch(action: unknown, payload?: unknown): Promise<void> {\n const target = ref.current;\n if (!target) {\n throw new Error(\n \"march-hare: useContext handle dispatched before its paired \" +\n \"context.useActions(...) ran. Call context.actions.dispatch from \" +\n \"event handlers, not synchronously during render.\",\n );\n }\n return target(action, payload);\n }\n\n function useActionsMethod(...args: unknown[]): unknown {\n const invoke = <(...passed: unknown[]) => UseActions<M, AC, D>>(\n (<unknown>useActions)\n );\n const result = invoke(...args);\n ref.current = <DispatchTarget>(<unknown>result.dispatch);\n return result;\n }\n\n return <ContextHandle<M, AC, D>>(<unknown>{\n actions: { dispatch },\n useActions: useActionsMethod,\n with: bindWith<M>(),\n });\n }, []);\n}\n","import * as React from \"react\";\nimport {\n useLifecycles,\n useData,\n isChanneledAction,\n getActionSymbol,\n matchesChannel,\n useRegisterHandler,\n useDispatchers,\n findLifecycleAction,\n isGenerator,\n emitAsync,\n replay,\n} from \"./utils.ts\";\nimport { useRerender } from \"../utils/utils.ts\";\nimport type { Data, Handler, Scope } from \"./types.ts\";\nimport {\n HandlerContext,\n Phase,\n Model,\n HandlerPayload,\n Props,\n Actions,\n ActionId,\n UseActions,\n Result,\n Task,\n Filter,\n ChanneledAction,\n ActionOrChanneled,\n AnyAction,\n FaultSymbol,\n EnvSymbol,\n} from \"../types/index.ts\";\n\nimport { getReason, getError } from \"../error/utils.ts\";\nimport { Aborted } from \"../error/index.ts\";\nimport EventEmitter from \"eventemitter3\";\nimport { useBroadcast } from \"../boundary/components/broadcast/index.tsx\";\nimport { useScope, getScope } from \"../boundary/components/scope/index.tsx\";\nimport { useEnv, useEnvRef } from \"../boundary/components/env/utils.ts\";\nimport type { Env } from \"../boundary/components/env/types.ts\";\nimport { produce as produceImmer } from \"immer\";\nimport { nuke } from \"../resource/index.ts\";\nimport type { Coalesce, Invocation } from \"../resource/types.ts\";\nimport {\n coalesceKey,\n withAbort,\n token as defaultCoalesceToken,\n} from \"../coalesce/index.ts\";\nimport { unset } from \"../utils/utils.ts\";\nimport {\n isBroadcastAction,\n isMulticastAction,\n getName,\n} from \"../action/index.ts\";\nimport { State, Operation, Process, Inspect } from \"immertation\";\nimport { useTasks } from \"../boundary/components/tasks/utils.ts\";\nimport { Partition } from \"../boundary/components/consumer/index.tsx\";\nimport type { ConsumerRenderer } from \"../boundary/components/consumer/types.ts\";\nimport { G } from \"@mobily/ts-belt\";\nimport { useSharing } from \"../boundary/components/sharing/index.tsx\";\nimport { useTap } from \"../boundary/components/tap/utils.ts\";\n\n/**\n * A hook for managing state with actions.\n *\n * Call `useActions` first, then use `actions.useAction` to bind handlers\n * to action symbols. Types are pre-baked from the generic parameters, so\n * no additional type annotations are needed on handler calls.\n *\n * The hook returns a result containing:\n * 1. The current model state\n * 2. An actions object with `dispatch`, `inspect`, and `useAction`\n * 3. A read-only snapshot of the data values produced by `getData` &mdash;\n * the same values handlers read via `context.data`, exposed here for\n * JSX consumption so the view and the handler share one named source.\n *\n * The `inspect` property provides access to Immertation's annotation system,\n * allowing you to check for pending operations on model properties.\n *\n * @template M The model type representing the component's state.\n * @template AC The actions class containing action definitions.\n * @template D The data type for reactive external values.\n * @param model The initial model state.\n * @param getData Optional function that returns reactive values as data.\n * Values returned are accessible via `context.data` in action handlers,\n * always reflecting the latest values even after await operations.\n * @returns A result `[model, actions, data]` with pre-typed `useAction` method.\n *\n * @example\n * ```typescript\n * // Basic usage\n * const [model, actions] = useActions<Model, typeof Actions>(model);\n *\n * // Without a model (actions-only)\n * const [, actions] = useActions<void, typeof Actions>();\n *\n * // With reactive data &mdash; consumed in JSX and handlers alike.\n * const [model, actions, data] = useActions<\n * Model,\n * typeof Actions,\n * { query: string }\n * >(model, () => ({ query: props.query }));\n * ```\n */\nexport function useActions<\n M extends void = void,\n A extends Actions | void = void,\n D extends Props = Props,\n>(getData?: Data<D>): UseActions<M, A, D>;\nexport function useActions<\n M extends Model,\n A extends Actions | void = void,\n D extends Props = Props,\n>(model: M, getData?: Data<D>): UseActions<M, A, D>;\nexport function useActions<\n M extends Model | void,\n A extends Actions | void,\n D extends Props = Props,\n>(...args: unknown[]): unknown {\n const isVoidModel = G.isUndefined(args[0]) || G.isFunction(args[0]);\n const initialModel = <Model>(isVoidModel ? {} : args[0]);\n const getData: Data<D> = G.isFunction(args[0])\n ? <Data<D>>args[0]\n : <Data<D>>(args[1] ?? (() => <D>{}));\n\n const broadcast = useBroadcast();\n const scope = useScope();\n const tasks = useTasks();\n const env = useEnv();\n const slot = useEnvRef();\n const sharing = useSharing();\n const tap = useTap();\n const rerender = useRerender();\n const initialised = React.useRef(false);\n const hydration = React.useRef<Process | null>(null);\n const state = React.useRef(new State<Model>());\n\n if (!initialised.current) {\n initialised.current = true;\n hydration.current = state.current.hydrate(initialModel);\n }\n const [model, setModel] = React.useState<M>(\n () => <M>(<unknown>state.current.model),\n );\n const data = useData(getData());\n const unicast = React.useMemo(() => new EventEmitter(), []);\n const registry = React.useRef<Scope<M, A, D>>({ handlers: new Map() });\n registry.current.handlers = new Map();\n const dispatchers = useDispatchers();\n const phase = React.useRef<Phase>(Phase.Mounting);\n const localTasks = React.useRef<Set<Task>>(new Set());\n const unmountGeneration = React.useRef(0);\n\n /**\n * Creates the context object passed to action handlers during dispatch.\n *\n * @param action The action symbol being dispatched.\n * @param payload The payload passed with the action.\n * @param result Container for tracking Immertation processes created during execution.\n * @returns A fully-typed Context object for the action handler.\n */\n const getContext = React.useCallback(\n (action: ActionId, payload: unknown, result: Result) => {\n const controller = new AbortController();\n const task: Task = { controller, action, payload };\n tasks.add(task);\n localTasks.current.add(task);\n\n return <HandlerContext<M, A, D>>(<unknown>{\n model: state.current.model,\n get phase() {\n return phase.current;\n },\n task,\n data,\n tasks,\n env,\n actions: {\n produce(\n f: (draft: {\n model: M;\n readonly inspect: Readonly<Inspect<M>>;\n env: Env;\n }) => void,\n ) {\n if (controller.signal.aborted) return;\n const slotBefore = slot.current;\n const process = state.current.produce((draft) => {\n slot.current = produceImmer(slot.current, (envDraft) => {\n f({\n model: <M>(<unknown>draft),\n inspect: <Readonly<Inspect<M>>>(\n (<unknown>state.current.inspect)\n ),\n env: <Env>envDraft,\n });\n });\n });\n setModel(<M>(<unknown>state.current.model));\n if (slot.current !== slotBefore) {\n broadcast.emit(EnvSymbol, slot.current);\n }\n result.processes.add(process);\n if (hydration.current) {\n result.processes.add(hydration.current);\n hydration.current = null;\n }\n },\n dispatch(\n action: ActionOrChanneled,\n payload?: HandlerPayload,\n ): Promise<void> {\n if (controller.signal.aborted) return Promise.resolve();\n const base = getActionSymbol(action);\n const channel = isChanneledAction(action)\n ? action.channel\n : undefined;\n\n if (isMulticastAction(action)) {\n const scoped = getScope(scope);\n if (scoped)\n return emitAsync(scoped.emitter, base, payload, channel);\n return Promise.resolve();\n }\n\n const emitter = isBroadcastAction(action) ? broadcast : unicast;\n return emitAsync(emitter, base, payload, channel);\n },\n annotate<T>(value: T, operation: Operation = Operation.Update): T {\n return state.current.annotate(operation, value);\n },\n get inspect() {\n return state.current.inspect;\n },\n resource: Object.assign(\n function resourceCall<T, P extends object>(call: Invocation<T, P>) {\n const dispatchFromResource = (\n action: unknown,\n payload?: unknown,\n ): Promise<void> => {\n if (controller.signal.aborted) return Promise.resolve();\n const a = <AnyAction>action;\n const base = getActionSymbol(a);\n if (isMulticastAction(a)) {\n const scoped = getScope(scope);\n if (scoped)\n return emitAsync(scoped.emitter, base, payload, undefined);\n return Promise.resolve();\n }\n if (isBroadcastAction(a)) {\n return emitAsync(broadcast, base, payload, undefined);\n }\n return Promise.resolve();\n };\n const options: {\n exceedsWindow: Temporal.DurationLike | null;\n coalesceToken: Coalesce | undefined;\n } = { exceedsWindow: null, coalesceToken: undefined };\n const fetch = (): Promise<T> => {\n if (G.isNotNullable(options.exceedsWindow)) {\n const { data, at } = call.read(call.params);\n if (data !== unset && G.isNotNullable(at)) {\n const elapsed = Temporal.Now.instant().since(at);\n const window = Temporal.Duration.from(\n options.exceedsWindow,\n );\n if (Temporal.Duration.compare(elapsed, window) <= 0) {\n return Promise.resolve(<T>data);\n }\n }\n }\n if (G.isUndefined(options.coalesceToken)) {\n return <Promise<T>>(\n call.run(env, controller, call.params, dispatchFromResource)\n );\n }\n let mutable = sharing.get(call.run);\n if (G.isUndefined(mutable)) {\n mutable = new Map<string, Promise<unknown>>();\n sharing.set(call.run, mutable);\n }\n const bucket = mutable;\n const key = `${JSON.stringify(call.params)}|${coalesceKey(options.coalesceToken)}`;\n const existing = <Promise<T> | undefined>bucket.get(key);\n if (existing) return withAbort(existing, controller.signal);\n const detached = new AbortController();\n const shared = (<Promise<T>>(\n call.run(env, detached, call.params, dispatchFromResource)\n )).finally(() => {\n bucket.delete(key);\n });\n bucket.set(key, shared);\n return withAbort(shared, controller.signal);\n };\n const handle = {\n then<U = T, V = never>(\n onFulfilled?:\n | ((value: T) => U | PromiseLike<U>)\n | null\n | undefined,\n onRejected?:\n | ((reason: unknown) => V | PromiseLike<V>)\n | null\n | undefined,\n ): Promise<U | V> {\n return fetch().then(onFulfilled, onRejected);\n },\n exceeds(duration: Temporal.DurationLike) {\n options.exceedsWindow = duration;\n return handle;\n },\n coalesce(token?: Coalesce) {\n options.coalesceToken = token ?? defaultCoalesceToken;\n return handle;\n },\n evict(where?: object): void {\n call.evict(where ?? call.params);\n },\n };\n return handle;\n },\n {\n nuke: (where?: object): void => nuke(where),\n },\n ),\n async final(action: AnyAction) {\n if (controller.signal.aborted) return null;\n const key = getActionSymbol(action);\n const emitter = isMulticastAction(action)\n ? (getScope(scope)?.emitter ?? null)\n : broadcast;\n if (!emitter) return null;\n const cached = emitter.getCached(key);\n if (G.isUndefined(cached)) return null;\n const inspector = state.current.inspect;\n if (inspector.pending()) {\n await new Promise<void>((resolve, reject) => {\n if (controller.signal.aborted)\n return void reject(controller.signal.reason);\n const onAbort = () => reject(controller.signal.reason);\n controller.signal.addEventListener(\"abort\", onAbort, {\n once: true,\n });\n void inspector.settled().then(() => {\n controller.signal.removeEventListener(\"abort\", onAbort);\n resolve();\n });\n });\n }\n return emitter.getCached(key) ?? null;\n },\n peek(action: AnyAction) {\n if (controller.signal.aborted) return null;\n const key = getActionSymbol(action);\n const emitter = isMulticastAction(action)\n ? (getScope(scope)?.emitter ?? null)\n : broadcast;\n if (!emitter) return null;\n return emitter.getCached(key) ?? null;\n },\n },\n });\n },\n [model],\n );\n\n React.useLayoutEffect(() => {\n unmountGeneration.current++;\n\n function createHandler(\n action: ActionId,\n actionHandler: Handler<M, A, D>,\n getChannel: () => Filter | undefined,\n ) {\n return function handler(\n payload: HandlerPayload,\n dispatchChannel?: Filter | typeof replay,\n ) {\n const registeredChannel = getChannel();\n\n // Skip channeled handlers during replay — they require specific\n // channel context and cannot process a replay without it.\n if (dispatchChannel === replay && G.isNotNullable(registeredChannel))\n return;\n\n if (\n G.isNotNullable(dispatchChannel) &&\n dispatchChannel !== replay &&\n G.isNotNullable(registeredChannel)\n ) {\n if (!matchesChannel(dispatchChannel, registeredChannel)) return;\n }\n\n const result = <Result>{ processes: new Set<Process>() };\n const completion = Promise.withResolvers<void>();\n const context = getContext(action, payload, result);\n const actionName = getName(action);\n const startedAt = performance.now();\n const modelBefore = <unknown>state.current.model;\n const envBefore = <unknown>slot.current;\n let errored = false;\n\n function mutations() {\n const modelAfter = <unknown>state.current.model;\n const envAfter = <unknown>slot.current;\n return {\n model:\n modelBefore === modelAfter\n ? null\n : { before: modelBefore, after: modelAfter },\n env:\n envBefore === envAfter\n ? null\n : { before: envBefore, after: envAfter },\n };\n }\n\n tap({\n stage: \"start\",\n action: { name: actionName, payload },\n details: { task: context.task },\n });\n\n function retry(): Promise<void> {\n const channel: Filter | undefined =\n dispatchChannel === replay ? undefined : dispatchChannel;\n if (isMulticastAction(action)) {\n const scoped = getScope(scope);\n if (!scoped) return Promise.resolve();\n return emitAsync(scoped.emitter, action, payload, channel);\n }\n const emitter = isBroadcastAction(action) ? broadcast : unicast;\n return emitAsync(emitter, action, payload, channel);\n }\n\n function onError(caught: unknown) {\n errored = true;\n const errorAction = findLifecycleAction(\n registry.current.handlers,\n \"Error\",\n );\n const handled = G.isNotNullable(errorAction);\n const reason = getReason(caught);\n const error = getError(caught);\n const details = {\n reason,\n error,\n action: actionName,\n handled,\n tasks,\n retry,\n };\n broadcast.fire(FaultSymbol, details);\n if (handled && errorAction) unicast.emit(errorAction, details);\n tap({\n stage: \"end\",\n result: \"error\",\n action: { name: actionName, payload },\n details: {\n task: context.task,\n elapsed: performance.now() - startedAt,\n mutations: mutations(),\n error,\n reason,\n },\n });\n }\n\n function onSettled() {\n for (const task of tasks) {\n if (task === context.task) {\n tasks.delete(task);\n localTasks.current.delete(task);\n break;\n }\n }\n result.processes.forEach((process) => state.current.prune(process));\n if (result.processes.size > 0) rerender();\n if (!errored) {\n tap({\n stage: \"end\",\n result: \"success\",\n action: { name: actionName, payload },\n details: {\n task: context.task,\n elapsed: performance.now() - startedAt,\n mutations: mutations(),\n },\n });\n }\n completion.resolve();\n }\n\n let returnValue: ReturnType<Handler<M, A, D>>;\n try {\n returnValue = actionHandler(context, payload);\n } catch (caught) {\n onError(caught);\n onSettled();\n return completion.promise;\n }\n\n if (isGenerator(returnValue)) {\n (async () => {\n for await (const _ of returnValue) void 0;\n })()\n .catch(onError)\n .finally(onSettled);\n return completion.promise;\n }\n\n Promise.resolve(returnValue).catch(onError).finally(onSettled);\n return completion.promise;\n };\n }\n\n const cleanups = new Set<() => void>();\n\n registry.current.handlers.forEach((entries, action) => {\n for (const { getChannel, handler: actionHandler } of entries) {\n const handler = createHandler(action, actionHandler, getChannel);\n\n if (isMulticastAction(action)) {\n if (scope) {\n const emitter = scope.emitter;\n emitter.on(action, handler);\n cleanups.add(() => emitter.off(action, handler));\n }\n unicast.on(action, handler);\n dispatchers.multicast.add(action);\n cleanups.add(() => unicast.off(action, handler));\n } else if (isBroadcastAction(action)) {\n broadcast.on(action, handler);\n unicast.on(action, handler);\n dispatchers.broadcast.add(action);\n cleanups.add(() => {\n broadcast.off(action, handler);\n unicast.off(action, handler);\n });\n } else {\n unicast.on(action, handler);\n cleanups.add(() => unicast.off(action, handler));\n }\n }\n });\n\n return () => {\n const generation = ++unmountGeneration.current;\n const pendingCleanups = new Set(cleanups);\n\n queueMicrotask(() => {\n if (unmountGeneration.current !== generation) {\n for (const cleanup of pendingCleanups) cleanup();\n return;\n }\n\n for (const task of localTasks.current) {\n task.controller.abort(new Aborted(\"Component unmounted\"));\n tasks.delete(task);\n }\n localTasks.current.clear();\n\n phase.current = Phase.Unmounting;\n const unmountAction = findLifecycleAction(\n registry.current.handlers,\n \"Unmount\",\n );\n if (unmountAction) unicast.emit(unmountAction);\n phase.current = Phase.Unmounted;\n\n for (const cleanup of pendingCleanups) cleanup();\n });\n };\n }, [unicast]);\n\n useLifecycles({\n unicast,\n broadcast,\n tasks,\n dispatchers,\n scope,\n phase,\n data: getData(),\n handlers: registry.current.handlers,\n });\n\n const actionsApi = React.useMemo(\n () => ({\n dispatch(\n action: ActionOrChanneled,\n payload?: HandlerPayload,\n ): Promise<void> {\n const base = getActionSymbol(action);\n const channel = isChanneledAction(action) ? action.channel : undefined;\n\n if (isMulticastAction(action)) {\n const scoped = getScope(scope);\n if (scoped) return emitAsync(scoped.emitter, base, payload, channel);\n return Promise.resolve();\n }\n\n const emitter = isBroadcastAction(action) ? broadcast : unicast;\n return emitAsync(emitter, base, payload, channel);\n },\n get inspect() {\n return state.current.inspect;\n },\n stream(\n action: AnyAction,\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n renderer: ConsumerRenderer<any>,\n ): React.ReactNode {\n return React.createElement(Partition, {\n action: <symbol>getActionSymbol(action),\n renderer,\n });\n },\n }),\n [model, unicast],\n );\n\n const result = React.useMemo(\n () => <UseActions<M, A, D>>(<unknown>[model, actionsApi, data]),\n [model, actionsApi, data],\n );\n\n // The public `useAction` signature constrains the action argument to\n // `Subscribable<AC>` (leaf actions on `AC` plus `Lifecycle.Fault`) split\n // into no-payload / with-payload overloads. The runtime is AC-agnostic,\n // so the impl is typed against the loose `ActionOrChanneled` union and\n // cast back to the strict public type.\n const useActionImpl = (\n action: ActionId | HandlerPayload | ChanneledAction,\n handler: Handler<M, A, D>,\n ): void => {\n useRegisterHandler<M, A, D>(registry, action, handler);\n };\n (<UseActions<M, A, D>>result).useAction = <UseActions<M, A, D>[\"useAction\"]>(\n (<unknown>useActionImpl)\n );\n (<UseActions<M, A, D>>result).dispatch = <UseActions<M, A, D>[\"dispatch\"]>(\n (<unknown>result[1].dispatch)\n );\n\n return <UseActions<M, A, D>>result;\n}\n","import { Reason } from \"./types.ts\";\n\n/**\n * Determines the error reason based on what was thrown.\n *\n * @param error - The value that was thrown.\n * @returns The appropriate Reason enum value.\n */\nexport function getReason(error: unknown): Reason {\n const isAborted = error instanceof Error && error.name === \"AbortError\";\n return isAborted ? Reason.Aborted : Reason.Errored;\n}\n\n/**\n * Gets an Error instance from a thrown value.\n *\n * @param error - The value that was thrown.\n * @returns An Error instance (original if already Error, wrapped otherwise).\n */\nexport function getError(error: unknown): Error {\n return error instanceof Error ? error : new Error(String(error));\n}\n","import * as React from \"react\";\nimport { BroadcastEmitter } from \"../boundary/components/broadcast/utils.ts\";\nimport { Context as ScopeReactContext } from \"../boundary/components/scope/utils.ts\";\nimport type { ScopeEntry } from \"../boundary/components/scope/types.ts\";\nimport { useContext as baseUseContext } from \"../context/index.ts\";\nimport { useEnv as baseUseEnv } from \"../boundary/components/env/utils.ts\";\nimport { Resource as BaseResource } from \"../resource/index.ts\";\nimport type { ResourceHandle } from \"../resource/types.ts\";\nimport type { Cache } from \"../cache/index.ts\";\nimport type { Env } from \"../boundary/components/env/types.ts\";\nimport type { AppContextHandle, AppFetcher } from \"../app/types.ts\";\nimport type { Actions, Model, Props } from \"../types/index.ts\";\nimport type { ScopeHandle } from \"./types.ts\";\n\n/**\n * Internal constructor for a {@link ScopeHandle}. Called from inside\n * `App<E>()` so the enclosing Env shape `E` is captured at the type\n * level. The optional `cache` is the same value `App({ cache })` was\n * constructed with &mdash; resources declared via `scope.Resource`\n * share that cache. `getEnv` resolves the live Env from the enclosing\n * `app.Boundary` so cache-key scoping works for sync `.get()` reads.\n *\n * @internal\n */\nexport function createScope<E extends object, MulticastActions>(\n cache?: Cache,\n getEnv?: () => Env | undefined,\n): ScopeHandle<E, MulticastActions> {\n function Boundary({\n children,\n }: {\n children: React.ReactNode;\n }): React.ReactElement {\n const entry = React.useMemo<ScopeEntry>(\n () => ({\n id: Symbol(\"march-hare.scope/instance\"),\n emitter: new BroadcastEmitter(),\n }),\n [],\n );\n return (\n <ScopeReactContext.Provider value={entry}>\n {children}\n </ScopeReactContext.Provider>\n );\n }\n\n function useTypedContext<\n LocalModel extends Model | void = void,\n AC extends Actions | void = void,\n D extends Props = Props,\n >(): AppContextHandle<\n LocalModel,\n MulticastActions extends Actions\n ? AC extends Actions\n ? AC & MulticastActions\n : MulticastActions\n : AC,\n D,\n E\n > {\n return baseUseContext() as unknown as AppContextHandle<\n LocalModel,\n MulticastActions extends Actions\n ? AC extends Actions\n ? AC & MulticastActions\n : MulticastActions\n : AC,\n D,\n E\n >;\n }\n\n function useTypedEnv(): Readonly<E> {\n return baseUseEnv() as unknown as Readonly<E>;\n }\n\n function Resource<T, P extends object = Record<never, never>>(\n fetcher: AppFetcher<E, T, P>,\n ): ResourceHandle<T, P> {\n return BaseResource<E, T, P>(fetcher, cache, getEnv);\n }\n\n return {\n Boundary,\n useContext: useTypedContext,\n useEnv: useTypedEnv,\n Resource,\n };\n}\n","import * as React from \"react\";\nimport { Boundary as BaseBoundary } from \"../boundary/index.tsx\";\nimport { useContext as baseUseContext } from \"../context/index.ts\";\nimport { useEnv as baseUseEnv } from \"../boundary/components/env/utils.ts\";\nimport type { Env } from \"../boundary/components/env/types.ts\";\nimport { Resource as BaseResource } from \"../resource/index.ts\";\nimport type { ResourceHandle } from \"../resource/types.ts\";\nimport type { Cache } from \"../cache/index.ts\";\nimport type { Actions, Model, Props } from \"../types/index.ts\";\nimport { createScope } from \"../scope/utils.tsx\";\nimport type { AppHandle, AppContextHandle, AppFetcher } from \"./types.ts\";\nimport type { Tap } from \"../boundary/components/tap/types.ts\";\n\nexport type {\n AppArgs,\n AppContextHandle,\n AppFetcher,\n AppResource,\n} from \"./types.ts\";\n\nexport type { AppHandle } from \"./types.ts\";\n\n/**\n * Creates an `App` &mdash; the entrypoint for a typed Env shape `E`,\n * inferred from `config.env`. `App<E>` exposes `Boundary`, hooks, and\n * a `Resource` factory all wired against the same shape.\n *\n * Each `<app.Boundary>` instance owns its own Env, so different `App`s\n * can coexist in the same tree with completely independent shapes.\n *\n * Pass `tap` to subscribe to every action handler's dispatch / settle /\n * error inside the boundary &mdash; useful for analytics, audit logging,\n * Sentry breadcrumbs. See `recipes/tap.md`. Pass `cache` to persist\n * every `app.Resource(fetcher)` declaration through a single\n * {@link Cache} &mdash; each resource is namespaced inside the cache by\n * its declaration order, so reloads seed from storage automatically and\n * resources do not collide on shared params keys. Omit `cache` to keep\n * each resource's payloads in an isolated in-memory slot.\n *\n * `env`, `tap`, and `cache` are all fixed at `App()` time;\n * `<app.Boundary>` does not accept overrides. Mutate the live Env\n * through `context.actions.produce(({ env }) => …)`, and declare a\n * separate `App` when a test or storybook needs a different initial\n * value.\n *\n * @example\n * ```tsx\n * import { App, Cache, type Taps } from \"march-hare\";\n *\n * type Session = { accessToken: string };\n *\n * function tap(event: Taps) {\n * if (event.type === \"error\") {\n * Sentry.captureException(event.error, { tags: { action: event.action } });\n * }\n * }\n *\n * export const app = App({\n * env: {\n * session: null as Session | null,\n * operating: \"idle\" as \"idle\" | \"signing-out\",\n * },\n * tap,\n * cache: Cache({\n * get: (key) => localStorage.getItem(key),\n * set: (key, value) => localStorage.setItem(key, value),\n * remove: (key) => localStorage.removeItem(key),\n * clear: () => localStorage.clear(),\n * }),\n * });\n *\n * // Root render.\n * <app.Boundary>\n * <Root />\n * </app.Boundary>;\n *\n * // In resources.ts &mdash; persisted via the App's cache.\n * export const user = app.Resource<User>((context) =>\n * ky\n * .get(\"/api/user\", {\n * headers: context.env.session\n * ? { Authorization: `Bearer ${context.env.session.accessToken}` }\n * : {},\n * signal: context.controller.signal,\n * })\n * .json<User>(),\n * );\n * ```\n */\nexport function App<E extends object = Env>(config?: {\n env?: E;\n tap?: Tap;\n cache?: Cache;\n}): AppHandle<E> {\n const envHolder: { current: Env | undefined } = { current: undefined };\n\n function Boundary({\n children,\n }: {\n children: React.ReactNode;\n }): React.ReactElement {\n return (\n <BaseBoundary env={config?.env as Env} tap={config?.tap}>\n <SyncEnvHolder holder={envHolder} />\n {children}\n </BaseBoundary>\n );\n }\n\n function useTypedContext<\n M extends Model | void = void,\n AC extends Actions | void = void,\n D extends Props = Props,\n >(): AppContextHandle<M, AC, D, E> {\n return baseUseContext() as unknown as AppContextHandle<M, AC, D, E>;\n }\n\n function useTypedEnv(): Readonly<E> {\n return baseUseEnv() as unknown as Readonly<E>;\n }\n\n function Resource<T, P extends object = Record<never, never>>(\n fetcher: AppFetcher<E, T, P>,\n ): ResourceHandle<T, P> {\n return BaseResource<E, T, P>(\n fetcher,\n config?.cache,\n () => envHolder.current,\n );\n }\n\n return {\n Boundary,\n useContext: useTypedContext,\n useEnv: useTypedEnv,\n Resource,\n Scope<MulticastActions>() {\n return createScope<E, MulticastActions>(\n config?.cache,\n () => envHolder.current,\n );\n },\n };\n}\n\n/**\n * Side-effect-only child of `app.Boundary` that captures the live Env\n * proxy from the enclosing `<Env>` provider and writes it into the\n * App's `envHolder` on every render. The proxy itself is stable per\n * boundary &mdash; subsequent renders re-assign the same reference, so\n * the holder behaves like a `ref.current` slot the App's `Resource`\n * factory can read from at any time (including from sync `.get()`\n * calls executed outside of action handlers).\n *\n * @internal\n */\nfunction SyncEnvHolder({\n holder,\n}: {\n holder: { current: Env | undefined };\n}): null {\n const env = baseUseEnv();\n holder.current = env;\n return null;\n}\n\n/**\n * Standalone counterpart to `app.useContext`, exported as\n * `shared.useContext` &mdash; same call shape, but takes the **Env\n * shape `E` as a mandatory first generic** so the caller can be a\n * reusable component that isn't tied to a single `App` import.\n *\n * `E` is the Env type your component expects to see &mdash; usually\n * a union of every App's Env shape it might run under. Inside the\n * handler, `context.env` is typed as `E`; reach for `in` / `typeof`\n * narrowing for keys present on only a subset.\n *\n * Pass `app` directly if you only need to talk to one App &mdash;\n * `app.useContext<Model, typeof Actions>()` is shorter and infers the\n * Env from the value. Reach for the standalone form only when a\n * component must support more than one App.\n *\n * @template E The Env shape (or union) the component supports.\n * @template M The model type, or `void`.\n * @template AC The Actions class, or `void`.\n * @template D The reactive data type returned from the `useActions`\n * data callback.\n *\n * @example\n * ```tsx\n * import { Action, shared } from \"march-hare\";\n *\n * type WebEnv = { session: Session | null; locale: string };\n * type MobileEnv = { session: Session | null; platform: \"ios\" | \"android\" };\n * type Envs = WebEnv | MobileEnv;\n *\n * type Model = { name: string | null };\n * const model: Model = { name: null };\n *\n * class Actions {\n * static Sign = Action<string>(\"Sign\");\n * }\n *\n * function useProfileActions() {\n * const context = shared.useContext<Envs, Model, typeof Actions>();\n * const actions = context.useActions(model);\n *\n * actions.useAction(Actions.Sign, (context, name) =>\n * context.actions.produce(({ model }) => void (model.name = name)),\n * );\n *\n * return actions;\n * }\n * ```\n */\nexport function useContext<\n E extends object,\n M extends Model | void = void,\n A extends Actions | void = void,\n D extends Props = Props,\n>(): AppContextHandle<M, A, D, E> {\n return baseUseContext() as unknown as AppContextHandle<M, A, D, E>;\n}\n\n/**\n * Standalone counterpart to `app.useEnv`, exported as `shared.useEnv`\n * &mdash; reads the nearest `<app.Boundary>`'s Env, typed against the\n * Env shape `E` supplied at the call site. For reusable components\n * that need an Env read outside any action handler (e.g. to hand a\n * closure to an external library at module bridge time).\n *\n * @template E The Env shape (or union) the component supports.\n *\n * @example\n * ```tsx\n * import { shared } from \"march-hare\";\n *\n * type WebEnv = { session: Session | null };\n * type MobileEnv = { session: Session | null };\n *\n * function SessionBadge() {\n * const env = shared.useEnv<WebEnv | MobileEnv>();\n * return <span>{env.session ? env.session.user.name : \"Signed out\"}</span>;\n * }\n * ```\n */\nexport function useEnv<E extends object>(): Readonly<E> {\n return baseUseEnv() as unknown as Readonly<E>;\n}\n","import type { Actions, HandlerContext, Model, Props } from \"../types/index.ts\";\nimport type { Env } from \"../boundary/components/env/types.ts\";\nimport type { BooleanPaths, Get, Paths } from \"./types.ts\";\nimport { makeAlways, makeInvert, makeUpdate } from \"./utils.ts\";\n\n/**\n * Handler factories that wire an action directly to a model field. Prefer\n * `context.with` from `useContext<Model>()` for first-class autocompletion\n * over dotted paths; this top-level form is kept for callers that don't have\n * a typed `context` in scope.\n *\n * - {@link With.Update} assigns the dispatched payload to a model path.\n * - {@link With.Invert} flips a boolean leaf at a model path.\n * - {@link With.Always} assigns a fixed value to a model path, ignoring any\n * dispatched payload.\n *\n * Keys may be lodash-style dotted paths (`\"a.b.c\"`) and support array\n * indices (`\"items.0.name\"`). The model type is inferred at handler-bind\n * time; an invalid path or mismatched payload fails to compile when the\n * handler is registered with `useAction`.\n *\n * @example\n * ```ts\n * import { With } from \"march-hare\";\n *\n * type Model = {\n * name: string;\n * sidebar: boolean;\n * nested: { open: boolean };\n * items: { id: number }[];\n * };\n *\n * actions.useAction(Actions.SetName, With.Update(\"name\"));\n * actions.useAction(Actions.SetFirstId, With.Update(\"items.0.id\"));\n * actions.useAction(Actions.ToggleSidebar, With.Invert(\"sidebar\"));\n * actions.useAction(Actions.ToggleNested, With.Invert(\"nested.open\"));\n * actions.useAction(Actions.Open, With.Always(\"nested.open\", true));\n * ```\n */\nexport const With = {\n /**\n * Returns a handler that assigns the action payload to the model leaf at\n * the given lodash-style path. The payload type must match `Get<M, K>`,\n * and the path must exist on the model.\n *\n * @template K The dotted-path string indexing into the model.\n * @param key The lodash-style path to the model leaf being assigned.\n */\n Update<K extends string>(\n key: K,\n ): <\n M extends Model,\n A extends Actions | void,\n D extends Props,\n P extends K extends Paths<M> ? Get<M, K> : never,\n E extends Env = Env,\n >(\n context: HandlerContext<M, A, D, E>,\n payload: P,\n ) => void {\n return <(context: unknown, payload: unknown) => void>makeUpdate(key);\n },\n /**\n * Returns a handler that inverts a boolean leaf at the given lodash-style\n * path. The leaf must be a `boolean` on the model.\n *\n * @template K The dotted-path string indexing into a boolean leaf.\n * @param key The lodash-style path to the boolean leaf being toggled.\n */\n Invert<K extends string>(\n key: K,\n ): <\n M extends Model,\n A extends Actions | void,\n D extends Props,\n E extends Env = Env,\n >(\n context: K extends BooleanPaths<M> ? HandlerContext<M, A, D, E> : never,\n ) => void {\n return <(context: unknown) => void>makeInvert(key);\n },\n /**\n * Returns a handler that assigns a fixed `value` to the model leaf at the\n * given lodash-style path. The dispatched payload (if any) is ignored.\n *\n * @template K The dotted-path string indexing into the model.\n * @template V The constant value type; must be assignable to the leaf at `K`.\n * @param key The lodash-style path to the model leaf being assigned.\n * @param value The constant value pinned to the leaf.\n */\n Always<K extends string, V>(\n key: K,\n value: V,\n ): <\n M extends Model,\n A extends Actions | void,\n D extends Props,\n E extends Env = Env,\n >(\n context: K extends Paths<M>\n ? V extends Get<M, K>\n ? HandlerContext<M, A, D, E>\n : never\n : never,\n ) => void {\n return <(context: unknown) => void>makeAlways(key, value);\n },\n};\n","import { State, Operation } from \"immertation\";\n\n/**\n * Module-level Immertation state instance used to annotate initial model values\n * with operation metadata (e.g., {@link Operation}) before hydration.\n *\n * This is intentionally a singleton — it exists solely to provide the\n * {@link annotate} helper with access to `State.annotate`, without requiring\n * consumers to instantiate their own `State` object.\n */\nconst state = new State();\n\n/**\n * Wraps a value with an operation annotation for use in initial model definitions.\n * When passed as part of the initial model to `useActions`, the annotation is\n * registered during hydration so that `actions.inspect` reports the field as pending\n * from the very first render.\n *\n * @param value - The value to annotate.\n * @param operation - The operation type (defaults to {@link Operation.Update}).\n * @returns The annotated value (typed as T for assignment compatibility).\n *\n * @example\n * ```ts\n * import { annotate } from \"march-hare\";\n *\n * type Model = { user: User | null };\n *\n * const model: Model = {\n * user: annotate(null),\n * };\n *\n * // actions.inspect.user.pending() === true from the first render\n * ```\n */\nexport function annotate<T>(\n value: T,\n operation: Operation = Operation.Update,\n): T {\n return state.annotate(operation, value);\n}\n","import { Pk } from \"../types/index.ts\";\nimport { Aborted } from \"../error/index.ts\";\n\nexport { unset } from \"./utils.ts\";\nexport type { Stored, Unset } from \"./types.ts\";\n\n/**\n * Returns a promise that resolves after the specified number of\n * milliseconds, or rejects with an {@link Aborted} when the signal is aborted. Use to inject a cancellable\n * delay into an action handler.\n *\n * @param ms How long to wait before resolving.\n * @param signal Optional {@link AbortSignal} that cancels the sleep early.\n * Pass `context.task.controller.signal` to tie the wait to\n * the lifetime of the current action.\n * @returns A promise that resolves after `ms` milliseconds or rejects with\n * an {@link Aborted} if `signal` aborts first.\n */\nexport function sleep(\n ms: number,\n signal: AbortSignal | undefined,\n): Promise<void> {\n return new Promise((resolve, reject) => {\n if (signal?.aborted) {\n reject(new Aborted());\n return;\n }\n\n const timer = setTimeout(resolve, ms);\n\n signal?.addEventListener(\n \"abort\",\n () => {\n clearTimeout(timer);\n reject(new Aborted());\n },\n { once: true },\n );\n });\n}\n\n/**\n * Repeatedly calls a function at a fixed interval until it returns `true`\n * or the signal is aborted. The function is invoked immediately on the\n * first iteration, then after each interval.\n *\n * @param ms Interval in milliseconds between invocations of `fn`.\n * @param signal Optional {@link AbortSignal} that cancels polling early.\n * Aborts propagate as an {@link Aborted} rejection.\n * @param fn Predicate invoked each iteration. Return `true` to stop\n * polling, `false` to schedule another invocation after `ms`.\n * May be sync or async.\n * @returns A promise that resolves when `fn` returns `true`, or rejects\n * with a `DOMException(\"aborted\", \"Aborted\")` if `signal`\n * aborts first.\n */\nexport async function poll(\n ms: number,\n signal: AbortSignal | undefined,\n fn: () => boolean | Promise<boolean>,\n): Promise<void> {\n if (signal?.aborted) throw new Aborted();\n\n while (true) {\n const done = await fn();\n if (done) return;\n await sleep(ms, signal);\n }\n}\n\n/**\n * Generates a unique primary key.\n *\n * @returns A new unique symbol representing the primary key.\n */\nexport function pk(): symbol;\n/**\n * Checks if the provided ID is a valid primary key. A valid primary key\n * is any value that is not a symbol.\n *\n * @template T The model type the key identifies.\n * @param id The primary key to validate.\n * @returns `true` if `id` is a non-symbol value, `false` otherwise.\n */\nexport function pk<T>(id: Pk<T>): boolean;\nexport function pk<T>(id?: Pk<T>): boolean | symbol {\n if (id) return Boolean(id && typeof id !== \"symbol\");\n return Symbol(`pk.${Date.now()}.${crypto.randomUUID()}`);\n}\n\n/** Shorthand alias for {@link sleep}. */\nexport const ζ = sleep;\n\n/** Shorthand alias for {@link poll}. */\nexport const π = poll;\n\n/** Shorthand alias for {@link pk}. */\nexport const κ = pk;\n","/**\n * `shared` namespace &mdash; standalone counterparts to the `app.X`\n * factories returned by `App<E>()`. Each export takes the Env shape\n * `E` as a mandatory first generic so reusable components can run\n * under more than one App without binding to a single `app` import.\n *\n * Reach for `shared.X` only when a component must support more than\n * one App. Single-app code should keep using `app.X` &mdash; the Env\n * is captured from `app` automatically and the call site is one\n * generic shorter.\n *\n * | Bound to an App | Standalone (`shared.X`) |\n * | -------------------------------- | ---------------------------------------- |\n * | `app.useContext<M, A, D>()` | `shared.useContext<E, M, A, D>()` |\n * | `app.useEnv()` | `shared.useEnv<E>()` |\n * | `app.Resource<T, P>(...)` | `shared.Resource<E, T, P>(...)` |\n * | `app.Scope<A>()` | `shared.Scope<E, A>()` |\n *\n * `shared.Resource` declarations always read from and write to an\n * in-memory cache &mdash; persistence is an App-level concern wired up\n * via `App({ cache })`. Reach for `app.Resource` instead when a resource\n * needs to survive reloads.\n *\n * @see {@link ./app/index.tsx App}\n */\n\nimport { Resource as InternalResource } from \"../resource/index.ts\";\nimport type { AppFetcher } from \"../app/types.ts\";\nimport type { ResourceHandle } from \"../resource/types.ts\";\n\nexport { useContext, useEnv } from \"../app/index.tsx\";\nexport { Scope } from \"../scope/index.tsx\";\n\n/**\n * Standalone counterpart to `app.Resource`, exported as\n * `shared.Resource`. Takes the **Env shape `E` as a mandatory first\n * generic** so the fetcher's `context.env` is typed even when the\n * resource isn't bound to a single App.\n *\n * Always uses an isolated in-memory cache &mdash; persistent caching\n * is an App-level concern wired through `App({ cache })`, so reach for\n * `app.Resource` when a resource needs to survive reloads.\n */\nexport function Resource<\n E extends object,\n T,\n P extends object = Record<never, never>,\n>(fetcher: AppFetcher<E, T, P>): ResourceHandle<T, P> {\n return InternalResource<E, T, P>(fetcher);\n}\n","import type { ScopeHandle } from \"./types.ts\";\nimport { createScope } from \"./utils.tsx\";\n\nexport type { ScopeHandle } from \"./types.ts\";\nexport { createScope } from \"./utils.tsx\";\n\n/**\n * Standalone counterpart to `app.Scope<MulticastActions>()`, exported\n * as `shared.Scope` &mdash; opens a typed multicast scope without\n * going through an `App` handle. Takes the **Env shape `E` as a\n * mandatory first generic**, mirroring the other standalone exports\n * (`shared.useContext`, `shared.useEnv`, `shared.Resource`). The Env\n * carried by `scope.useContext()` is typed as `E`.\n *\n * Use this in reusable feature modules that need to open their own\n * multicast scope without binding to one App's `app.Scope` factory.\n * For single-app code, prefer `app.Scope<MulticastActions>()` &mdash;\n * the Env is captured from `app` automatically.\n *\n * @template E The Env shape (or union) the scope's `useContext` types\n * `context.env` against.\n * @template A The multicast Actions class (or union of classes) the\n * scope's dispatch surface is widened to include.\n *\n * @example\n * ```tsx\n * import { Action, Distribution, shared } from \"march-hare\";\n *\n * class MulticastActions {\n * static Mood = Action<\"happy\" | \"sad\">(\n * \"Mood\",\n * Distribution.Multicast,\n * );\n * }\n *\n * type MoodEnv = { tracker: string };\n *\n * export const scope = shared.Scope<MoodEnv, typeof MulticastActions>();\n * ```\n */\nexport function Scope<E extends object, A>(): ScopeHandle<E, A> {\n return createScope<E, A>();\n}\n"],"names":["has","Object","prototype","hasOwnProperty","prefix","Events","EE","fn","context","once","this","addListener","emitter","event","TypeError","listener","evt","_events","push","_eventsCount","clearEvent","EventEmitter","create","__proto__","eventNames","events","name","names","call","slice","getOwnPropertySymbols","concat","listeners","handlers","i","l","length","ee","Array","listenerCount","emit","a1","a2","a3","a4","a5","args","len","arguments","removeListener","apply","j","on","removeAllListeners","off","prefixed","module","BroadcastEmitter","cache","Map","set","super","setCache","value","getCached","get","fire","Context","React","createContext","useBroadcast","useContext","Broadcaster","children","useMemo","Provider","Set","Tasks","tasks","current","useEnv","ref","Proxy","_target","key","Reflect","ownKeys","getOwnPropertyDescriptor","descriptor","G","isUndefined","configurable","describe","action","broadcast","multicast","lifecycle","Brand","static","Symbol","createLifecycleAction","symbol","channel","Action","Payload","undefined","Channel","Name","defineProperty","enumerable","Lifecycle","FaultSymbol","EnvSymbol","Mount","Paint","Unmount","Error","Update","Broadcast","Distribution","Unicast","Multicast","Phase","Mounting","Mounted","Unmounting","Unmounted","Env","initial","useRef","WeakMap","SharingProvider","registry","noop","Tappable","tap","useLayoutEffect","Boundary","env","consumer","jsx","ConsumerContext","isSymbol","getActionSymbol","isString","isObject","isFunction","isBroadcastAction","startsWith","description","actionSymbol","isChanneledAction","getLifecycleType","isMulticastAction","distribution","replay","emitAsync","Promise","resolve","all","map","then","findLifecycleAction","type","keys","unset","useRerender","rerender","useReducer","x","empty","data","at","present","Reason","Aborted","Errored","constructor","message","Cache","config","backing","memory","remove","delete","clear","memoryAdapter","scopeFn","raw","isNull","parsed","JSON","parse","Temporal","Instant","from","stringify","toString","scope","isNullable","defaults","namespaces","evictors","build","ƒ","namespace","getEnv","suffix","composeKey","params","read","stored","run","controller","dispatch","resolved","Now","instant","evict","where","fullPrefix","entries","cacheKey","every","field","Resource","inner","resolveEnv","fetcher","existing","isNotNullable","defaultCache","String","size","nextResourceId","token","withAbort","promise","signal","reject","aborted","reason","onAbort","addEventListener","removeEventListener","error","s","t","e","r","crypto","getRandomValues","Uint8Array","o","Add","Remove","Move","Replace","Sort","Create","Fetch","Clone","Archive","Restore","Merge","Reorder","Sync","Publish","Link","Unlink","Lock","Unlock","Import","Export","Transfer","a","Produce","Hydrate","c","Property","Process","Value","Operation","u","immerable","values","property","process","operation","assign","setAutoFreeze","p","y","split","n","f","m","isArray","h","fromEntries","tag","id","d","filter","join","getPrototypeOf","isNumber","isBoolean","b","g","path","forEach","v","O","pk","annotate","model","inspect","isNotEmpty","isEmpty","some","head","add","hydrate","produce","immer","produceWithPatches","reduce","applyPatches","prune","observe","Partition","renderer","entry","state","State","cached","handlePayload","payload","walk","target","segments","cursor","setPath","makeUpdate","actions","draft","makeInvert","invertPath","makeAlways","useActions","result","initialModel","getData","slot","sharing","initialised","hydration","setModel","useState","props","withGetters","proxy","useData","unicast","dispatchers","useDispatchers","phase","localTasks","unmountGeneration","getContext","useCallback","AbortController","task","slotBefore","produceImmer","envDraft","processes","base","resource","dispatchFromResource","options","exceedsWindow","coalesceToken","handle","onFulfilled","onRejected","fetch","elapsed","since","window","Duration","compare","mutable","bucket","coalesceKey","detached","shared","finally","exceeds","duration","coalesce","defaultCoalesceToken","nuke","pattern","final","inspector","pending","settled","peek","createHandler","actionHandler","getChannel","dispatchChannel","registeredChannel","matchesChannel","completion","withResolvers","actionName","lastIndexOf","getName","startedAt","performance","now","modelBefore","envBefore","returnValue","errored","mutations","modelAfter","envAfter","before","after","retry","onError","caught","errorAction","handled","getReason","getError","details","stage","onSettled","isGenerator","_","catch","cleanups","handler","generation","pendingCleanups","queueMicrotask","cleanup","abort","unmountAction","previous","painted","mountAction","useEffect","paintAction","differences","next","key2","changes","A","updateAction","useLifecycles","actionsApi","stream","createElement","useAction","useActionImpl","handlerRef","actionRef","stableHandler","useRegisterHandler","invoke","with","update","invert","always","createScope","ScopeReactContext","baseUseContext","baseUseEnv","BaseResource","App","envHolder","BaseBoundary","SyncEnvHolder","holder","Scope","With","Invert","Always","sleep","ms","timer","setTimeout","clearTimeout","async","poll","Boolean","Date","randomUUID","InternalResource"],"mappings":"yWAEA,IAAIA,EAAMC,OAAOC,UAAUC,eACvBC,EAAS,IASb,SAASC,IAAS,CA4BlB,SAASC,EAAGC,EAAIC,EAASC,GACvBC,KAAKH,GAAKA,EACVG,KAAKF,QAAUA,EACfE,KAAKD,KAAOA,IAAQ,CACtB,CAaA,SAASE,EAAYC,EAASC,EAAON,EAAIC,EAASC,GAChD,GAAkB,mBAAPF,EACT,MAAM,IAAIO,UAAU,mCAGtB,IAAIC,EAAW,IAAIT,EAAGC,EAAIC,GAAWI,EAASH,GAC1CO,EAAMZ,EAASA,EAASS,EAAQA,EAMpC,OAJKD,EAAQK,QAAQD,GACXJ,EAAQK,QAAQD,GAAKT,GAC1BK,EAAQK,QAAQD,GAAO,CAACJ,EAAQK,QAAQD,GAAMD,GADhBH,EAAQK,QAAQD,GAAKE,KAAKH,MAD1BE,QAAQD,GAAOD,EAAUH,EAAQO,gBAI7DP,CACT,CASA,SAASQ,EAAWR,EAASI,GACI,MAAzBJ,EAAQO,aAAoBP,EAAQK,QAAU,IAAIZ,SAC5CO,EAAQK,QAAQD,EAC9B,CASA,SAASK,IACPX,KAAKO,QAAU,IAAIZ,EACnBK,KAAKS,aAAe,CACtB,CAzEIlB,OAAOqB,SACTjB,EAAOH,yBAAYD,OAAOqB,OAAO,OAM5B,IAAIjB,GAASkB,YAAWnB,GAAS,IA2ExCiB,EAAanB,UAAUsB,WAAa,WAClC,IACIC,EACAC,EAFAC,EAAQ,GAIZ,GAA0B,IAAtBjB,K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