chizu 0.2.67 → 0.2.71

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -118,9 +118,13 @@ Both the model and actions type parameters default to `void`, so you can call `u
118
118
  ```tsx
119
119
  import { useActions, Lifecycle } from "chizu";
120
120
 
121
- const actions = useActions();
121
+ class Actions {
122
+ static Mount = Lifecycle.Mount();
123
+ }
122
124
 
123
- actions.useAction(Lifecycle.Mount, () => {
125
+ const actions = useActions<void, typeof Actions>();
126
+
127
+ actions.useAction(Actions.Mount, () => {
124
128
  console.log("Mounted!");
125
129
  });
126
130
  ```
@@ -211,6 +215,22 @@ actions.useAction(Actions.Check, (context) => {
211
215
  });
212
216
  ```
213
217
 
218
+ Dispatch is awaitable &ndash; `context.actions.dispatch` returns a `Promise<void>` that resolves when all triggered handlers have completed. This prevents UI flashes where local state changes before upstream handlers finish:
219
+
220
+ ```tsx
221
+ actions.useAction(Actions.Mount, async (context) => {
222
+ // Wait for all PaymentSent handlers across the app to finish.
223
+ await context.actions.dispatch(Actions.Broadcast.PaymentSent);
224
+
225
+ // Safe to update local state now — upstream work is done.
226
+ context.actions.produce(({ model }) => {
227
+ model.loading = false;
228
+ });
229
+ });
230
+ ```
231
+
232
+ Generator handlers are excluded from the await &mdash; they run in the background and do not block the dispatch promise, since they are typically long-lived (polling, SSE streams, etc.).
233
+
214
234
  You can also render broadcast values declaratively in JSX with `actions.stream`. The renderer callback receives `(value, inspect)` and returns React nodes:
215
235
 
216
236
  ```tsx
@@ -227,7 +247,7 @@ function Dashboard() {
227
247
  }
228
248
  ```
229
249
 
230
- Components that mount after a broadcast has already been dispatched automatically receive the cached value via their `useAction` handler. If you also fetch data in `Lifecycle.Mount`, see the [mount deduplication recipe](./recipes/mount-broadcast-deduplication.md) to avoid duplicate requests.
250
+ Components that mount after a broadcast has already been dispatched automatically receive the cached value via their `useAction` handler. If you also fetch data in `Lifecycle.Mount()`, see the [mount deduplication recipe](./recipes/mount-broadcast-deduplication.md) to avoid duplicate requests.
231
251
 
232
252
  For targeted event delivery, use channeled actions. Define a channel type as the second generic argument and call the action with a channel object &ndash; handlers fire when the dispatch channel matches:
233
253
 
@@ -301,7 +321,7 @@ function App() {
301
321
  actions.dispatch(Actions.Multicast.Update, 42, { scope: "TeamA" });
302
322
  ```
303
323
 
304
- Unlike broadcast which reaches all components, multicast is scoped to the named boundary &ndash; perfect for isolated widget groups, form sections, or distinct UI regions. Like broadcast, multicast caches dispatched values per scope &ndash; components that mount later automatically receive the cached value. See the [mount deduplication recipe](./recipes/mount-broadcast-deduplication.md) if you also fetch data in `Lifecycle.Mount`.
324
+ Unlike broadcast which reaches all components, multicast is scoped to the named boundary &ndash; perfect for isolated widget groups, form sections, or distinct UI regions. Like broadcast, multicast caches dispatched values per scope &ndash; components that mount later automatically receive the cached value. See the [mount deduplication recipe](./recipes/mount-broadcast-deduplication.md) if you also fetch data in `Lifecycle.Mount()`.
305
325
 
306
326
  For components that always render inside a scope, use the `withScope` HOC to eliminate the manual `<Scope>` wrapper:
307
327
 
@@ -376,3 +396,45 @@ context.actions.invalidate(CacheStore.User({ UserId: 5 }));
376
396
  ```
377
397
 
378
398
  The cache is scoped to the nearest `<Boundary>`. See the [caching recipe](./recipes/caching.md) for more details.
399
+
400
+ The action regulator lets handlers control which actions may be dispatched across all components within a `<Boundary>`. Use `context.regulator` to block or allow actions:
401
+
402
+ ```ts
403
+ actions.useAction(Actions.Checkout, async (context) => {
404
+ // Allow only the cancel action during checkout
405
+ context.regulator.allow(Actions.Cancel);
406
+
407
+ try {
408
+ await processPayment(context.task.controller.signal);
409
+ } finally {
410
+ context.regulator.allow();
411
+ }
412
+ });
413
+ ```
414
+
415
+ `disallow()` blocks all, `disallow(A, B)` blocks specific actions, `allow()` allows all (reset), and `allow(A, B)` allows only those actions. Each call replaces the previous policy (last-write-wins). Blocked actions fire `Reason.Disallowed` through the error system without allocating resources. See the [action regulator recipe](./recipes/action-regulator.md) for more details.
416
+
417
+ Toggling boolean UI state &ndash; modals, sidebars, drawers &ndash; is one of the most common patterns. Instead of defining actions and handlers, use `actions.feature()` with the `Feature` enum:
418
+
419
+ ```tsx
420
+ import { Feature, useActions } from "chizu";
421
+
422
+ type Model = {
423
+ name: string;
424
+ features: { paymentDialog: boolean; sidebar: boolean };
425
+ };
426
+
427
+ const [model, actions] = useFeatureActions();
428
+
429
+ // Mutate via actions.feature()
430
+ actions.feature("paymentDialog", Feature.Toggle);
431
+ actions.feature("paymentDialog", Feature.On);
432
+ actions.feature("paymentDialog", Feature.Off);
433
+
434
+ // Read from model
435
+ {
436
+ model.features.paymentDialog && <PaymentDialog />;
437
+ }
438
+ ```
439
+
440
+ The method also works inside action handlers via `context.actions.feature()`. See the [feature toggles recipe](./recipes/feature-toggles.md) for more details.
@@ -1,5 +1,5 @@
1
1
  import { HandlerPayload, BroadcastPayload, MulticastPayload, Distribution, Filter } from '../types/index.ts';
2
- export { getActionSymbol, isBroadcastAction, isMulticastAction, getName, isChanneledAction, } from './utils.ts';
2
+ export { getActionSymbol, getLifecycleType, isBroadcastAction, isMulticastAction, getName, isChanneledAction, } from './utils.ts';
3
3
  /**
4
4
  * Interface for the Action factory function.
5
5
  */
@@ -58,6 +58,27 @@ export declare function getName(action: AnyAction): string;
58
58
  * ```
59
59
  */
60
60
  export declare function isChanneledAction(action: AnyAction): action is ChanneledAction;
61
+ /**
62
+ * Extracts the lifecycle type from an action's symbol description.
63
+ *
64
+ * Returns the lifecycle name (`"Mount"`, `"Unmount"`, `"Error"`, `"Update"`,
65
+ * `"Node"`) when the action symbol's description starts with the lifecycle
66
+ * prefix, or `null` for non-lifecycle actions.
67
+ *
68
+ * @param action The action to inspect.
69
+ * @returns The lifecycle name, or `null` if not a lifecycle action.
70
+ *
71
+ * @example
72
+ * ```typescript
73
+ * class Actions {
74
+ * static Mount = Lifecycle.Mount();
75
+ * }
76
+ *
77
+ * getLifecycleType(Actions.Mount); // "Mount"
78
+ * getLifecycleType(Action("Increment")); // null
79
+ * ```
80
+ */
81
+ export declare function getLifecycleType(action: AnyAction): string | null;
61
82
  /**
62
83
  * Checks whether an action is a multicast action.
63
84
  * Multicast actions are dispatched to all components within a named scope boundary.
@@ -11,6 +11,11 @@ import * as React from "react";
11
11
  export declare class BroadcastEmitter extends EventEmitter {
12
12
  private cache;
13
13
  emit(event: string | symbol, ...args: unknown[]): boolean;
14
+ /**
15
+ * Cache a value for a given event without emitting to listeners.
16
+ * Used by {@link emitAsync} to preserve caching when bypassing `emit()`.
17
+ */
18
+ setCache(event: string | symbol, value: unknown): void;
14
19
  /**
15
20
  * Retrieve the last emitted payload for a given event.
16
21
  */
@@ -0,0 +1,14 @@
1
+ import { Props } from './types.ts';
2
+ import * as React from "react";
3
+ export { useRegulators, isAllowed } from './utils.ts';
4
+ export type { Regulator, RegulatorPolicy } from './types.ts';
5
+ /**
6
+ * Provides a shared regulator policy to all descendant components.
7
+ *
8
+ * Wrap this around your component tree (or use `<Boundary>` which includes it)
9
+ * to enable action regulation via `context.regulator`.
10
+ *
11
+ * @param props.children - The children to render within the regulator context.
12
+ * @returns The children wrapped in a regulator context provider.
13
+ */
14
+ export declare function Regulators({ children }: Props): React.ReactNode;
@@ -0,0 +1,52 @@
1
+ import { ActionId } from '../tasks/types.ts';
2
+ import type * as React from "react";
3
+ /**
4
+ * The four policy modes that the regulator supports.
5
+ *
6
+ * - `allow-all` (default) &ndash; every action is permitted (`allow()` with no args).
7
+ * - `disallow-all` &ndash; every action is blocked (`disallow()` with no args).
8
+ * - `disallow-matching` &ndash; only the listed actions are blocked (`disallow(A, B)`).
9
+ * - `allow-matching` &ndash; only the listed actions are permitted (`allow(A, B)`).
10
+ *
11
+ * For "except" patterns, compose two calls:
12
+ * - Block all except X: `disallow()` then `allow(X)`.
13
+ * - Allow all except X: `allow()` then `disallow(X)`.
14
+ */
15
+ export type RegulatorMode = "allow-all" | "disallow-all" | "disallow-matching" | "allow-matching";
16
+ /**
17
+ * Mutable policy object shared across all components in a `<Boundary>`.
18
+ * Mutated in-place by the `context.regulator` API &ndash; last write wins.
19
+ */
20
+ export type RegulatorPolicy = {
21
+ mode: RegulatorMode;
22
+ actions: Set<ActionId>;
23
+ };
24
+ /**
25
+ * The `context.regulator` API shape exposed to action handlers.
26
+ *
27
+ * - `disallow()` &ndash; block all actions.
28
+ * - `disallow(A, B)` &ndash; block only the listed actions.
29
+ * - `allow()` &ndash; allow all actions (reset to default).
30
+ * - `allow(A, B)` &ndash; allow only the listed actions.
31
+ *
32
+ * Each call replaces the previous policy entirely (last-write-wins).
33
+ */
34
+ export type Regulator = {
35
+ /**
36
+ * Block actions. Called with no arguments, blocks everything.
37
+ * Called with specific actions, blocks only those actions.
38
+ */
39
+ disallow(...actions: ReadonlyArray<{
40
+ readonly [x: symbol]: unknown;
41
+ }>): void;
42
+ /**
43
+ * Allow actions. Called with no arguments, allows everything (reset).
44
+ * Called with specific actions, allows only those actions.
45
+ */
46
+ allow(...actions: ReadonlyArray<{
47
+ readonly [x: symbol]: unknown;
48
+ }>): void;
49
+ };
50
+ export type Props = {
51
+ children: React.ReactNode;
52
+ };
@@ -0,0 +1,21 @@
1
+ import { ActionId } from '../tasks/types.ts';
2
+ import { RegulatorPolicy } from './types.ts';
3
+ import * as React from "react";
4
+ /**
5
+ * React context holding the shared, mutable regulator policy.
6
+ */
7
+ export declare const Context: React.Context<RegulatorPolicy>;
8
+ /**
9
+ * Hook to access the regulator policy from the nearest `<Regulators>` provider.
10
+ *
11
+ * @returns The mutable `RegulatorPolicy` object from context.
12
+ */
13
+ export declare function useRegulators(): RegulatorPolicy;
14
+ /**
15
+ * Determines whether a given action is allowed under the current policy.
16
+ *
17
+ * @param action - The action identifier (symbol) to check.
18
+ * @param policy - The current regulator policy.
19
+ * @returns `true` if the action may proceed, `false` if it should be blocked.
20
+ */
21
+ export declare function isAllowed(action: ActionId, policy: RegulatorPolicy): boolean;
package/dist/chizu.js CHANGED
@@ -1,7 +1,8 @@
1
- import{G as e,A as t}from"@mobily/ts-belt";import{jsx as n}from"react/jsx-runtime";import*as r from"react";import{createContext as o,useContext as c}from"react";import{immerable as i,enablePatches as s,Immer as a}from"immer";class u{static Payload=/* @__PURE__ */Symbol("chizu.brand/Payload");static Broadcast=/* @__PURE__ */Symbol("chizu.brand/Broadcast");static Multicast=/* @__PURE__ */Symbol("chizu.brand/Multicast");static Action=/* @__PURE__ */Symbol("chizu.brand/Action");static Channel=/* @__PURE__ */Symbol("chizu.brand/Channel");static Node=/* @__PURE__ */Symbol("chizu.action.lifecycle/Node");static Cache=/* @__PURE__ */Symbol("chizu.brand/Cache")}class l{static Mount=/* @__PURE__ */Symbol("chizu.action.lifecycle/Mount");static Unmount=/* @__PURE__ */Symbol("chizu.action.lifecycle/Unmount");static Error=/* @__PURE__ */Symbol("chizu.action.lifecycle/Error");static Update=/* @__PURE__ */Symbol("chizu.action.lifecycle/Update");static Node=(()=>{const e=u.Node,t=function(t){return{[u.Action]:e,[u.Payload]:void 0,[u.Channel]:t,channel:t}};return Object.defineProperty(t,u.Action,{value:e,enumerable:!1}),Object.defineProperty(t,u.Payload,{value:void 0,enumerable:!1}),t})()}var f=/* @__PURE__ */(e=>(e.Unicast="unicast",e.Broadcast="broadcast",e.Multicast="multicast",e))(f||{}),d=/* @__PURE__ */(e=>(e.Mounting="mounting",e.Mounted="mounted",e.Unmounting="unmounting",e.Unmounted="unmounted",e))(d||{}),p=/* @__PURE__ */(e=>(e[e.Timedout=0]="Timedout",e[e.Supplanted=1]="Supplanted",e[e.Disallowed=2]="Disallowed",e[e.Errored=3]="Errored",e[e.Unmounted=4]="Unmounted",e))(p||{});class h extends Error{name="AbortError";constructor(e="Aborted"){super(e)}}const m={actionPrefix:"chizu.action/",broadcastActionPrefix:"chizu.action/broadcast/",multicastActionPrefix:"chizu.action/multicast/",channelPrefix:"chizu.channel/",cachePrefix:"chizu.cache/"};function y(e,t){return new Promise((n,r)=>{if(t?.aborted)return void r(new h);const o=setTimeout(n,e);t?.addEventListener("abort",()=>{clearTimeout(o),r(new h)},{once:!0})})}async function b(e,t,n){if(t?.aborted)throw new h;for(;;){if(await n())return;await y(e,t)}}function v(e){return e?Boolean(e&&"symbol"!=typeof e):/* @__PURE__ */Symbol(`pk.${Date.now()}.${crypto.randomUUID()}`)}const g=/* @__PURE__ */Object.freeze(/* @__PURE__ */Object.defineProperty({__proto__:null,config:m,pk:v,poll:b,sleep:y,"ζ":y,"κ":v,"π":b},Symbol.toStringTag,{value:"Module"})),w=e=>"symbol"==typeof e;function x(t){return e.isString(t)||w(t)?t:(e.isObject(t)||e.isFunction(t))&&u.Action in t?t[u.Action]:t}function S(t){if(e.isString(t))return t.startsWith(m.broadcastActionPrefix);if(w(t))return t.description?.startsWith(m.broadcastActionPrefix)??!1;if(e.isObject(t)||e.isFunction(t)){if(u.Broadcast in t&&t[u.Broadcast])return!0;if(u.Action in t){const e=t[u.Action];return e.description?.startsWith(m.broadcastActionPrefix)??!1}}return!1}function P(t){const n=x(t),r=e.isString(n)?n:n.description??"";return r.startsWith(m.actionPrefix)&&r.slice(r.lastIndexOf("/")+1)||"unknown"}function E(t){return e.isObject(t)&&u.Channel in t&&"channel"in t}function O(t){if(e.isString(t))return t.startsWith(m.multicastActionPrefix);if(w(t))return t.description?.startsWith(m.multicastActionPrefix)??!1;if(e.isObject(t)||e.isFunction(t)){if(u.Multicast in t&&t[u.Multicast])return!0;if(u.Action in t){const e=t[u.Action];return e.description?.startsWith(m.multicastActionPrefix)??!1}}return!1}const j=(e,t=f.Unicast)=>{const n=t===f.Broadcast?/* @__PURE__ */Symbol(`${m.broadcastActionPrefix}${e}`):t===f.Multicast?/* @__PURE__ */Symbol(`${m.multicastActionPrefix}${e}`):/* @__PURE__ */Symbol(`${m.actionPrefix}${e}`),r=function(e){return{[u.Action]:n,[u.Payload]:void 0,[u.Channel]:e,channel:e}};return Object.defineProperty(r,u.Action,{value:n,enumerable:!1}),Object.defineProperty(r,u.Payload,{value:void 0,enumerable:!1}),t===f.Broadcast&&Object.defineProperty(r,u.Broadcast,{value:!0,enumerable:!1}),t===f.Multicast&&Object.defineProperty(r,u.Multicast,{value:!0,enumerable:!1}),r};function A(){const e=/* @__PURE__ */Symbol("chizu.cache/Entry"),t=function(t){return{[u.Cache]:e,channel:t}};return Object.defineProperty(t,u.Cache,{value:e,enumerable:!1}),t}function C(e){const t=function(e){return e[u.Cache]}(e),n=function(e){return"channel"in e}(e)&&(r=e.channel)?[...Object.keys(r)].toSorted().map(e=>`${e}=${String(r[e])}`).join("&"):"";var r;return`${String(t)}:${n}`}function M(e){if(e instanceof Error){if("TimeoutError"===e.name)return p.Timedout;if("AbortError"===e.name)return p.Supplanted}return p.Errored}function k(e){return e instanceof Error?e:new Error(String(e))}const _=o(void 0);function R({handler:e,children:t}){/* @__PURE__ */
2
- return n(_.Provider,{value:e,children:t})}let N=(e=21)=>{let t="",n=crypto.getRandomValues(new Uint8Array(e|=0));for(;e--;)t+="useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict"[63&n[e]];return t};var U=/* @__PURE__ */(e=>(e[e.Add=1]="Add",e[e.Remove=2]="Remove",e[e.Update=4]="Update",e[e.Move=8]="Move",e[e.Replace=16]="Replace",e[e.Sort=32]="Sort",e[e.Create=64]="Create",e[e.Fetch=128]="Fetch",e[e.Clone=256]="Clone",e[e.Archive=512]="Archive",e[e.Restore=1024]="Restore",e[e.Merge=2048]="Merge",e[e.Reorder=4096]="Reorder",e[e.Sync=8192]="Sync",e[e.Publish=16384]="Publish",e[e.Link=32768]="Link",e[e.Unlink=65536]="Unlink",e[e.Lock=131072]="Lock",e[e.Unlock=262144]="Unlock",e[e.Import=524288]="Import",e[e.Export=1048576]="Export",e[e.Transfer=2097152]="Transfer",e))(U||{}),z=/* @__PURE__ */(e=>(e[e.Produce=0]="Produce",e[e.Hydrate=1]="Hydrate",e))(z||{}),L=/* @__PURE__ */(e=>(e.Property="property",e.Process="process",e.Value="value",e.Operation="operation",e))(L||{});class T{[i]=!0;static keys=new Set(Object.values(L));property=null;process=null;value;operation;constructor(e,t){this.value=e,this.operation=t}assign(e,t){const n=new T(this.value,this.operation);return n.property=e,n.process=t,n}}class ${static immer=(()=>{s();const e=new a;return e.setAutoFreeze(!1),e})();static tag="κ";static id=N}function B(e,t){const n="string"==typeof t?""===t?[]:t.split("."):t;let r=e;for(const o of n){if(null==r)return;r=r[o]}return r}function F(t){if(e.isNullable(t)||H(t))return t;if(e.isArray(t))return t.map(e=>F(e));if(e.isObject(t)&&D(t)){const e=Object.entries(t).map(([e,t])=>[e,F(t)]);return{...Object.fromEntries(e),[$.tag]:t[$.tag]??$.id()}}return t}function W(e){if(Array.isArray(e))return e.filter(e=>$.tag in e).map(e=>e[$.tag]??"").join(",");const t=e[$.tag];if(t)return t;try{return JSON.stringify(e)}catch{return`[unserializable:${typeof e}]`}}function D(e){const t=Object.getPrototypeOf(e);return t===Object.prototype||null===t}function H(t){return e.isNullable(t)||e.isString(t)||e.isNumber(t)||e.isBoolean(t)||"symbol"==typeof t||"bigint"==typeof t}function G(t,n,r,o,c,i){return function s(a,u=n.path){if(a instanceof T){const n=B(r,u.join("."));if(Object.entries(a).filter(([e,t])=>!T.keys.has(e)&&t instanceof T).forEach(([e,t])=>s(t,u.concat(e))),H(a.value)){if(t===z.Hydrate)return a.value;const s=u.slice(0,-1),l=s.length>0?B(r,s.join(".")):r;return e.isNullable(l)||I(l,a,u.at(-1),o,c,i),n??a.value}if(t===z.Hydrate){const e=F(s(a.value,u));return I(e,a,null,o,c,i),e}const l=n??F(a.value);return I(l,a,null,o,c,i),e.isNullable(n)?l:(s(a.value,u),n)}if(e.isArray(a))return a.map((e,t)=>s(e,u.concat(t)));if(e.isObject(a)&&!D(a))return a;if(e.isObject(a)){const e=Object.entries(a).map(([e,t])=>[e,s(t,u.concat(e))]),n=Object.fromEntries(e);if(t===z.Hydrate){const e=F(n);return Object.entries(a).forEach(([t,n])=>{n instanceof T&&H(n.value)&&I(e,n,t,o,c,i)}),e}return n}return a}(n.value)}function I(e,t,n,r,o,c){const i=c(e),s=o.get(i)??[];o.set(i,[t.assign(n,r),...s])}class V{#e={};#t;#n=/* @__PURE__ */new Map;#r=/* @__PURE__ */new Set;#o=!1;constructor(e=W){this.#t=e}static pk(){return N()}static"κ"=V.pk;annotate(e,t){return new T(t,e)}"δ"=this.annotate;get model(){return this.#e}get inspect(){return function(n,r,o,c,i){function s(c){const i=c.at(-1),s=B(n(),c),a=c.slice(0,-1),u=t.isNotEmpty(a)?B(n(),a):n();return[...e.isObject(s)||e.isArray(s)?r.get(o(s))?.filter(t=>e.isNullable(t.property))??[]:[],...e.isObject(u)?r.get(o(u))?.filter(e=>e.property===i)??[]:[]]}return function e(r){return new Proxy(()=>{},{get:(o,a)=>"pending"===a?()=>!t.isEmpty(s(r)):"remaining"===a?()=>t.length(s(r)):"box"===a?()=>({value:B(n(),r),inspect:e(r)}):"is"===a?e=>s(r).some(t=>0!==(t.operation&e)):"draft"===a?()=>t.head(s(r))?.value??B(n(),r):"settled"===a?()=>new Promise(e=>{if(t.isEmpty(s(r)))return e(B(n(),r));const o=()=>{t.isEmpty(s(r))&&(i(o),e(B(n(),r)))};c(o)}):e([...r,String(a)])})}([])}(()=>this.#e,this.#n,this.#t,e=>this.#r.add(e),e=>this.#r.delete(e))}hydrate(e){return this.#o=!0,this.#c(z.Hydrate,()=>e)}produce(e){if(!this.#o)throw new Error("State must be hydrated using hydrate() before calling produce()");return this.#c(z.Produce,e)}#c(e,t){const n=/* @__PURE__ */Symbol("process"),[,r]=$.immer.produceWithPatches(this.#e,t);return this.#e=r.reduce((t,r)=>$.immer.applyPatches(t,[{...r,value:G(e,r,t,n,this.#n,this.#t)}]),this.#e),this.#e=F(this.#e),this.#i(),n}prune(e){this.#n.forEach((n,r)=>{const o=n.filter(t=>t.process!==e);t.isEmpty(o)?this.#n.delete(r):this.#n.set(r,o)}),this.#i()}#i(){this.#r.forEach(e=>e())}observe(e){const t=()=>e(this.#e);return this.#r.add(t),()=>this.#r.delete(t)}}const q=new V;function J(e,t){return q.annotate(e,t)}function K(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var Q,X={exports:{}};const Y=/* @__PURE__ */K((Q||(Q=1,function(e){var t=Object.prototype.hasOwnProperty,n="~";function r(){}function o(e,t,n){this.fn=e,this.context=t,this.once=n||!1}function c(e,t,r,c,i){if("function"!=typeof r)throw new TypeError("The listener must be a function");var s=new o(r,c||e,i),a=n?n+t:t;return e._events[a]?e._events[a].fn?e._events[a]=[e._events[a],s]:e._events[a].push(s):(e._events[a]=s,e._eventsCount++),e}function i(e,t){0===--e._eventsCount?e._events=new r:delete e._events[t]}function s(){this._events=new r,this._eventsCount=0}Object.create&&(r.prototype=/* @__PURE__ */Object.create(null),(new r).__proto__||(n=!1)),s.prototype.eventNames=function(){var e,r,o=[];if(0===this._eventsCount)return o;for(r in e=this._events)t.call(e,r)&&o.push(n?r.slice(1):r);return Object.getOwnPropertySymbols?o.concat(Object.getOwnPropertySymbols(e)):o},s.prototype.listeners=function(e){var t=this._events[n?n+e:e];if(!t)return[];if(t.fn)return[t.fn];for(var r=0,o=t.length,c=new Array(o);r<o;r++)c[r]=t[r].fn;return c},s.prototype.listenerCount=function(e){var t=this._events[n?n+e:e];return t?t.fn?1:t.length:0},s.prototype.emit=function(e,t,r,o,c,i){var s=n?n+e:e;if(!this._events[s])return!1;var a,u,l=this._events[s],f=arguments.length;if(l.fn){switch(l.once&&this.removeListener(e,l.fn,void 0,!0),f){case 1:return l.fn.call(l.context),!0;case 2:return l.fn.call(l.context,t),!0;case 3:return l.fn.call(l.context,t,r),!0;case 4:return l.fn.call(l.context,t,r,o),!0;case 5:return l.fn.call(l.context,t,r,o,c),!0;case 6:return l.fn.call(l.context,t,r,o,c,i),!0}for(u=1,a=new Array(f-1);u<f;u++)a[u-1]=arguments[u];l.fn.apply(l.context,a)}else{var d,p=l.length;for(u=0;u<p;u++)switch(l[u].once&&this.removeListener(e,l[u].fn,void 0,!0),f){case 1:l[u].fn.call(l[u].context);break;case 2:l[u].fn.call(l[u].context,t);break;case 3:l[u].fn.call(l[u].context,t,r);break;case 4:l[u].fn.call(l[u].context,t,r,o);break;default:if(!a)for(d=1,a=new Array(f-1);d<f;d++)a[d-1]=arguments[d];l[u].fn.apply(l[u].context,a)}}return!0},s.prototype.on=function(e,t,n){return c(this,e,t,n,!1)},s.prototype.once=function(e,t,n){return c(this,e,t,n,!0)},s.prototype.removeListener=function(e,t,r,o){var c=n?n+e:e;if(!this._events[c])return this;if(!t)return i(this,c),this;var s=this._events[c];if(s.fn)s.fn!==t||o&&!s.once||r&&s.context!==r||i(this,c);else{for(var a=0,u=[],l=s.length;a<l;a++)(s[a].fn!==t||o&&!s[a].once||r&&s[a].context!==r)&&u.push(s[a]);u.length?this._events[c]=1===u.length?u[0]:u:i(this,c)}return this},s.prototype.removeAllListeners=function(e){var t;return e?this._events[t=n?n+e:e]&&i(this,t):(this._events=new r,this._eventsCount=0),this},s.prototype.off=s.prototype.removeListener,s.prototype.addListener=s.prototype.on,s.prefixed=n,s.EventEmitter=s,e.exports=s}(X)),X.exports));class Z extends Y{cache=/* @__PURE__ */new Map;emit(e,...t){return this.cache.set(e,t[0]),super.emit(e,...t)}getCached(e){return this.cache.get(e)}}const ee=r.createContext(new Z);function te(){return r.useContext(ee)}function ne({children:e}){const t=r.useMemo(()=>new Z,[]);/* @__PURE__ */
3
- return n(ee.Provider,{value:t,children:e})}const re=r.createContext(/* @__PURE__ */new Map);function oe({children:e}){const t=r.useMemo(()=>/* @__PURE__ */new Map,[]);/* @__PURE__ */
4
- return n(re.Provider,{value:t,children:e})}const ce=r.createContext(/* @__PURE__ */new Set);function ie({children:e}){const t=r.useMemo(()=>/* @__PURE__ */new Set,[]);/* @__PURE__ */
5
- return n(ce.Provider,{value:t,children:e})}function se({children:e}){/* @__PURE__ */
6
- return n(ne,{children:/* @__PURE__ */n(oe,{children:/* @__PURE__ */n(ie,{children:e})})})}const ae=r.createContext(null);function ue(){return r.useContext(ae)}function le(e,t){return e?.get(t)??null}function fe({name:e,children:t}){const o=ue(),c=r.useMemo(()=>({name:e,emitter:new Z}),[]),i=r.useMemo(()=>{const t=new Map(o??[]);return t.set(e,c),t},[o,e,c]);/* @__PURE__ */
7
- return n(ae.Provider,{value:i,children:t})}function de(e,t){const r=`Scoped${t.displayName||t.name||"Component"}`;return{[r]:r=>/* @__PURE__ */n(fe,{name:e,children:/* @__PURE__ */n(t,{...r})})}[r]}function pe(e){return(t,n)=>{t.actions.produce(t=>{t.model[e]=n})}}function he(){const[,e]=r.useReducer(e=>e+1,0);return e}const me=r.createContext(/* @__PURE__ */new Map);function ye({action:t,renderer:n}){const o=te(),c=r.useContext(me),i=he(),s=r.useMemo(()=>{const e=c.get(t);if(e)return e;const n={state:new V,listeners:/* @__PURE__ */new Set};return c.set(t,n),n},[t,c]);r.useLayoutEffect(()=>{function e(e){s.state.hydrate({value:e}),s.listeners.forEach(e=>e())}return s.listeners.add(i),o.on(t,e),()=>{s.listeners.delete(i),o.off(t,e)}},[t,o,s]);const a=s.state.model?.value;return e.isNullable(a)?null:n(a,s.state.inspect.value)}function be(...n){const o=e.isUndefined(n[0])||e.isFunction(n[0])?{}:n[0],i=e.isFunction(n[0])?n[0]:n[1]??(()=>({})),s=te(),a=ue(),f=c(_),p=r.useContext(ce),h=r.useContext(re),m=he(),y=r.useRef(!1),b=r.useRef(null),v=r.useRef(new V);y.current||(y.current=!0,b.current=v.current.hydrate(o));const[g,w]=r.useState(()=>v.current.model),j=function(e){const t=r.useRef(e);return r.useLayoutEffect(()=>{t.current=e},[e]),r.useMemo(()=>{return n=t,Object.keys(e).reduce((e,t)=>(Object.defineProperty(e,t,{get:()=>n.current[t],enumerable:!0}),e),{});var n},[e])}(i()),A=r.useMemo(()=>new Y,[]),R=r.useRef({handlers:/* @__PURE__ */new Map});R.current.handlers=/* @__PURE__ */new Map;const N=function(){const e=r.useRef(/* @__PURE__ */new Set),t=r.useRef(/* @__PURE__ */new Set);return r.useMemo(()=>({broadcast:e.current,multicast:t.current}),[])}(),U=r.useRef(d.Mounting),z=function(){const e=r.useRef({}),t=r.useRef(/* @__PURE__ */new Map),n=r.useRef(/* @__PURE__ */new Map);return r.useMemo(()=>({refs:e,pending:t,emitted:n}),[])}(),L=r.useRef(/* @__PURE__ */new Set),T=r.useRef(0),$=r.useCallback((e,t,n)=>{const r=new AbortController,o={controller:r,action:e,payload:t};return p.add(o),L.current.add(o),{model:v.current.model,get phase(){return U.current},task:o,data:j,tasks:p,nodes:z.refs.current,actions:{produce(e){if(r.signal.aborted)return;const t=v.current.produce(t=>e({model:t,inspect:v.current.inspect}));w(v.current.model),n.processes.add(t),b.current&&(n.processes.add(b.current),b.current=null)},dispatch(e,t,n){if(r.signal.aborted)return;const o=x(e),c=E(e)?e.channel:void 0;if(O(e)&&n?.scope){const e=le(a,n.scope);return void(e&&e.emitter.emit(o,t,c))}(S(e)?s:A).emit(o,t,c)},annotate:(e,t)=>v.current.annotate(e,t),async cacheable(e,t,n){if(r.signal.aborted)return{data:null};const o=C(e),c=h.get(o);if(c&&Date.now()<c.expiry)return{data:c.value};const i=function(e){return null!=e&&"object"==typeof e&&"TAG"in e?0===e.TAG?{ok:!0,value:e._0}:{ok:!1}:null==e?{ok:!1}:{ok:!0,value:e}}(await n());return i.ok?(h.set(o,{value:i.value,expiry:Date.now()+t}),{data:i.value}):{data:null}},invalidate(e){h.delete(C(e))},async read(e,t){if(r.signal.aborted)return null;const n=x(e),o=O(e)&&t?.scope?le(a,t.scope)?.emitter??null:s;if(!o)return null;if(void 0===o.getCached(n))return null;const c=P(e),i="unknown"!==c?c[0].toLowerCase()+c.slice(1):null;if(i){const e=v.current.inspect[i];e?.pending?.()&&await new Promise((t,n)=>{if(r.signal.aborted)return void n(r.signal.reason);const o=()=>n(r.signal.reason);r.signal.addEventListener("abort",o,{once:!0}),e.settled().then(()=>{r.signal.removeEventListener("abort",o),t()})})}return o.getCached(n)??null},peek(e,t){if(r.signal.aborted)return null;const n=x(e),o=O(e)&&t?.scope?le(a,t.scope)?.emitter??null:s;return o?o.getCached(n)??null:null}}}},[g]);r.useLayoutEffect(()=>{function t(t,n,r){return async function(o,c){const i=r();if(e.isNotNullable(c)&&e.isNotNullable(i)&&!function(e,t){for(const n of Object.keys(e))if(t[n]!==e[n])return!1;return!0}(c,i))return;const s={processes:/* @__PURE__ */new Set},a=Promise.withResolvers(),u=$(t,o,s);try{await n(u,o)}catch(d){const e=R.current.handlers.has(l.Error),n={reason:M(d),error:k(d),action:P(t),handled:e,tasks:p};f?.(n),e&&A.emit(l.Error,n)}finally{for(const e of p)if(e===u.task){p.delete(e),L.current.delete(e);break}s.processes.forEach(e=>v.current.prune(e)),s.processes.size>0&&m(),a.resolve()}}}T.current++;const n=/* @__PURE__ */new Set;return R.current.handlers.forEach((e,r)=>{for(const{getChannel:o,handler:c}of e){const e=t(r,c,o);if(O(r)){if(a)for(const t of a.values()){const o=t.emitter;o.on(r,e),n.add(()=>o.off(r,e))}A.on(r,e),N.multicast.add(r),n.add(()=>A.off(r,e))}else S(r)?(s.on(r,e),A.on(r,e),N.broadcast.add(r),n.add(()=>{s.off(r,e),A.off(r,e)})):(A.on(r,e),n.add(()=>A.off(r,e)))}}),()=>{const e=++T.current,t=new Set(n);queueMicrotask(()=>{if(T.current===e){for(const e of L.current)e.controller.abort(),p.delete(e);L.current.clear(),U.current=d.Unmounting,A.emit(l.Unmount),U.current=d.Unmounted;for(const e of t)e()}else for(const e of t)e()})}},[A]),r.useLayoutEffect(()=>{for(const[e,t]of z.pending.current)z.emitted.current.get(e)!==t&&(z.emitted.current.set(e,t),A.emit(u.Node,t,{Name:e}));z.pending.current.clear()}),function({unicast:n,broadcast:o,dispatchers:c,scope:i,phase:s,data:a}){const u=r.useRef(null);r.useLayoutEffect(()=>{s.current===d.Mounting&&(n.emit(l.Mount),c.broadcast.forEach(t=>{const r=o.getCached(t);e.isNullable(r)||n.emit(t,r)}),i&&c.multicast.forEach(t=>{for(const r of i.values()){const o=r.emitter.getCached(t);e.isNullable(o)||n.emit(t,o)}}),s.current=d.Mounted)},[]),r.useLayoutEffect(()=>{if(e.isNotNullable(u.current)){const e=function(e,t){return Object.keys(t).reduce((n,r)=>e[r]!==t[r]?{...n,[r]:t[r]}:n,{})}(u.current,a);t.isNotEmpty(Object.keys(e))&&n.emit(l.Update,e)}u.current=a},[a,n])}({unicast:A,broadcast:s,dispatchers:N,scope:a,phase:U,data:i()});const B=r.useMemo(()=>[g,{dispatch(e,t,n){const r=x(e),o=E(e)?e.channel:void 0;if(O(e)&&n?.scope){const e=le(a,n.scope);return void(e&&e.emitter.emit(r,t,o))}(S(e)?s:A).emit(r,t,o)},get inspect(){return v.current.inspect},get nodes(){return z.refs.current},node(e,t){z.refs.current[e]=t,z.pending.current.set(e,t)},stream:(e,t)=>r.createElement(ye,{action:x(e),renderer:t})}],[g,A]);return B.useAction=(e,t)=>{!function(e,t,n){const o=r.useRef(n);r.useLayoutEffect(()=>{o.current=n});const c=r.useRef(t);r.useLayoutEffect(()=>{c.current=t});const i=r.useCallback(async(e,t)=>{const n=o.current;if("GeneratorFunction"===n.constructor.name||"AsyncGeneratorFunction"===n.constructor.name){const r=n(e,t);for await(const e of r);}else await n(e,t)},[]),s=r.useCallback(()=>E(c.current)?c.current.channel:void 0,[]),a=x(t),u=e.current.handlers.get(a)??/* @__PURE__ */new Set;0===u.size&&e.current.handlers.set(a,u),u.add({getChannel:s,handler:i})}(R,e,t)},B}export{j as Action,se as Boundary,f as Distribution,A as Entry,R as Error,l as Lifecycle,U as Op,U as Operation,p as Reason,fe as Scope,V as State,pe as With,J as annotate,be as useActions,g as utils,de as withScope};
1
+ import{G as e,A as t}from"@mobily/ts-belt";import{jsx as n}from"react/jsx-runtime";import*as r from"react";import{createContext as o,useContext as c}from"react";import{immerable as s,enablePatches as i,Immer as a}from"immer";class u{static Payload=/* @__PURE__ */Symbol("chizu.brand/Payload");static Broadcast=/* @__PURE__ */Symbol("chizu.brand/Broadcast");static Multicast=/* @__PURE__ */Symbol("chizu.brand/Multicast");static Action=/* @__PURE__ */Symbol("chizu.brand/Action");static Channel=/* @__PURE__ */Symbol("chizu.brand/Channel");static Node=/* @__PURE__ */Symbol("chizu.action.lifecycle/Node");static Cache=/* @__PURE__ */Symbol("chizu.brand/Cache")}function l(e){const t=/* @__PURE__ */Symbol(`chizu.action.lifecycle/${e}`),n=function(e){return{[u.Action]:t,[u.Payload]:void 0,[u.Channel]:e,channel:e}};return Object.defineProperty(n,u.Action,{value:t,enumerable:!1}),Object.defineProperty(n,u.Payload,{value:void 0,enumerable:!1}),n}class f{static Mount(){return l("Mount")}static Unmount(){return l("Unmount")}static Error(){return l("Error")}static Update(){return l("Update")}static Node(){return l("Node")}}var d=/* @__PURE__ */(e=>(e.Unicast="unicast",e.Broadcast="broadcast",e.Multicast="multicast",e))(d||{}),h=/* @__PURE__ */(e=>(e.Mounting="mounting",e.Mounted="mounted",e.Unmounting="unmounting",e.Unmounted="unmounted",e))(h||{}),p=/* @__PURE__ */(e=>(e.On="on",e.Off="off",e.Toggle="toggle",e))(p||{}),m=/* @__PURE__ */(e=>(e[e.Timedout=0]="Timedout",e[e.Supplanted=1]="Supplanted",e[e.Disallowed=2]="Disallowed",e[e.Errored=3]="Errored",e[e.Unmounted=4]="Unmounted",e))(m||{});class y extends Error{name="AbortError";constructor(e="Aborted"){super(e)}}class b extends Error{name="DisallowedError";constructor(e="Disallowed"){super(e)}}const v={actionPrefix:"chizu.action/",broadcastActionPrefix:"chizu.action/broadcast/",multicastActionPrefix:"chizu.action/multicast/",channelPrefix:"chizu.channel/",cachePrefix:"chizu.cache/",lifecyclePrefix:"chizu.action.lifecycle/"};function g(e,t){return new Promise((n,r)=>{if(t?.aborted)return void r(new y);const o=setTimeout(n,e);t?.addEventListener("abort",()=>{clearTimeout(o),r(new y)},{once:!0})})}async function w(e,t,n){if(t?.aborted)throw new y;for(;;){if(await n())return;await g(e,t)}}function P(e){return e?Boolean(e&&"symbol"!=typeof e):/* @__PURE__ */Symbol(`pk.${Date.now()}.${crypto.randomUUID()}`)}const x=/* @__PURE__ */Object.freeze(/* @__PURE__ */Object.defineProperty({__proto__:null,config:v,pk:P,poll:w,sleep:g,"ζ":g,"κ":P,"π":w},Symbol.toStringTag,{value:"Module"})),S=e=>"symbol"==typeof e;function E(t){return e.isString(t)||S(t)?t:(e.isObject(t)||e.isFunction(t))&&u.Action in t?t[u.Action]:t}function O(t){if(e.isString(t))return t.startsWith(v.broadcastActionPrefix);if(S(t))return t.description?.startsWith(v.broadcastActionPrefix)??!1;if(e.isObject(t)||e.isFunction(t)){if(u.Broadcast in t&&t[u.Broadcast])return!0;if(u.Action in t){const e=t[u.Action];return e.description?.startsWith(v.broadcastActionPrefix)??!1}}return!1}function j(t){const n=E(t),r=e.isString(n)?n:n.description??"";return r.startsWith(v.actionPrefix)&&r.slice(r.lastIndexOf("/")+1)||"unknown"}function C(t){return e.isObject(t)&&u.Channel in t&&"channel"in t}function A(e){const t=E(e),n=S(t)?t.description??"":t;return n.startsWith(v.lifecyclePrefix)&&n.slice(v.lifecyclePrefix.length)||null}function M(t){if(e.isString(t))return t.startsWith(v.multicastActionPrefix);if(S(t))return t.description?.startsWith(v.multicastActionPrefix)??!1;if(e.isObject(t)||e.isFunction(t)){if(u.Multicast in t&&t[u.Multicast])return!0;if(u.Action in t){const e=t[u.Action];return e.description?.startsWith(v.multicastActionPrefix)??!1}}return!1}const k=(e,t=d.Unicast)=>{const n=t===d.Broadcast?/* @__PURE__ */Symbol(`${v.broadcastActionPrefix}${e}`):t===d.Multicast?/* @__PURE__ */Symbol(`${v.multicastActionPrefix}${e}`):/* @__PURE__ */Symbol(`${v.actionPrefix}${e}`),r=function(e){return{[u.Action]:n,[u.Payload]:void 0,[u.Channel]:e,channel:e}};return Object.defineProperty(r,u.Action,{value:n,enumerable:!1}),Object.defineProperty(r,u.Payload,{value:void 0,enumerable:!1}),t===d.Broadcast&&Object.defineProperty(r,u.Broadcast,{value:!0,enumerable:!1}),t===d.Multicast&&Object.defineProperty(r,u.Multicast,{value:!0,enumerable:!1}),r};function _(){const e=/* @__PURE__ */Symbol("chizu.cache/Entry"),t=function(t){return{[u.Cache]:e,channel:t}};return Object.defineProperty(t,u.Cache,{value:e,enumerable:!1}),t}function R(e){const t=function(e){return e[u.Cache]}(e),n=function(e){return"channel"in e}(e)&&(r=e.channel)?[...Object.keys(r)].toSorted().map(e=>`${e}=${String(r[e])}`).join("&"):"";var r;return`${String(t)}:${n}`}function N(e){if(e instanceof Error){if("TimeoutError"===e.name)return m.Timedout;if("AbortError"===e.name)return m.Supplanted;if("DisallowedError"===e.name)return m.Disallowed}return m.Errored}function U(e){return e instanceof Error?e:new Error(String(e))}const L=o(void 0);function z({handler:e,children:t}){/* @__PURE__ */
2
+ return n(L.Provider,{value:e,children:t})}let T=(e=21)=>{let t="",n=crypto.getRandomValues(new Uint8Array(e|=0));for(;e--;)t+="useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict"[63&n[e]];return t};var $=/* @__PURE__ */(e=>(e[e.Add=1]="Add",e[e.Remove=2]="Remove",e[e.Update=4]="Update",e[e.Move=8]="Move",e[e.Replace=16]="Replace",e[e.Sort=32]="Sort",e[e.Create=64]="Create",e[e.Fetch=128]="Fetch",e[e.Clone=256]="Clone",e[e.Archive=512]="Archive",e[e.Restore=1024]="Restore",e[e.Merge=2048]="Merge",e[e.Reorder=4096]="Reorder",e[e.Sync=8192]="Sync",e[e.Publish=16384]="Publish",e[e.Link=32768]="Link",e[e.Unlink=65536]="Unlink",e[e.Lock=131072]="Lock",e[e.Unlock=262144]="Unlock",e[e.Import=524288]="Import",e[e.Export=1048576]="Export",e[e.Transfer=2097152]="Transfer",e))($||{}),D=/* @__PURE__ */(e=>(e[e.Produce=0]="Produce",e[e.Hydrate=1]="Hydrate",e))(D||{}),B=/* @__PURE__ */(e=>(e.Property="property",e.Process="process",e.Value="value",e.Operation="operation",e))(B||{});class W{[s]=!0;static keys=new Set(Object.values(B));property=null;process=null;value;operation;constructor(e,t){this.value=e,this.operation=t}assign(e,t){const n=new W(this.value,this.operation);return n.property=e,n.process=t,n}}class F{static immer=(()=>{i();const e=new a;return e.setAutoFreeze(!1),e})();static tag="κ";static id=T}function H(e,t){const n="string"==typeof t?""===t?[]:t.split("."):t;let r=e;for(const o of n){if(null==r)return;r=r[o]}return r}function G(t){if(e.isNullable(t)||q(t))return t;if(e.isArray(t))return t.map(e=>G(e));if(e.isObject(t)&&V(t)){const e=Object.entries(t).map(([e,t])=>[e,G(t)]);return{...Object.fromEntries(e),[F.tag]:t[F.tag]??F.id()}}return t}function I(e){if(Array.isArray(e))return e.filter(e=>F.tag in e).map(e=>e[F.tag]??"").join(",");const t=e[F.tag];if(t)return t;try{return JSON.stringify(e)}catch{return`[unserializable:${typeof e}]`}}function V(e){const t=Object.getPrototypeOf(e);return t===Object.prototype||null===t}function q(t){return e.isNullable(t)||e.isString(t)||e.isNumber(t)||e.isBoolean(t)||"symbol"==typeof t||"bigint"==typeof t}function J(t,n,r,o,c,s){return function i(a,u=n.path){if(a instanceof W){const n=H(r,u.join("."));if(Object.entries(a).filter(([e,t])=>!W.keys.has(e)&&t instanceof W).forEach(([e,t])=>i(t,u.concat(e))),q(a.value)){if(t===D.Hydrate)return a.value;const i=u.slice(0,-1),l=i.length>0?H(r,i.join(".")):r;return e.isNullable(l)||K(l,a,u.at(-1),o,c,s),n??a.value}if(t===D.Hydrate){const e=G(i(a.value,u));return K(e,a,null,o,c,s),e}const l=n??G(a.value);return K(l,a,null,o,c,s),e.isNullable(n)?l:(i(a.value,u),n)}if(e.isArray(a))return a.map((e,t)=>i(e,u.concat(t)));if(e.isObject(a)&&!V(a))return a;if(e.isObject(a)){const e=Object.entries(a).map(([e,t])=>[e,i(t,u.concat(e))]),n=Object.fromEntries(e);if(t===D.Hydrate){const e=G(n);return Object.entries(a).forEach(([t,n])=>{n instanceof W&&q(n.value)&&K(e,n,t,o,c,s)}),e}return n}return a}(n.value)}function K(e,t,n,r,o,c){const s=c(e),i=o.get(s)??[];o.set(s,[t.assign(n,r),...i])}class Q{#e={};#t;#n=/* @__PURE__ */new Map;#r=/* @__PURE__ */new Set;#o=!1;constructor(e=I){this.#t=e}static pk(){return T()}static"κ"=Q.pk;annotate(e,t){return new W(t,e)}"δ"=this.annotate;get model(){return this.#e}get inspect(){return function(n,r,o,c,s){function i(c){const s=c.at(-1),i=H(n(),c),a=c.slice(0,-1),u=t.isNotEmpty(a)?H(n(),a):n();return[...e.isObject(i)||e.isArray(i)?r.get(o(i))?.filter(t=>e.isNullable(t.property))??[]:[],...e.isObject(u)?r.get(o(u))?.filter(e=>e.property===s)??[]:[]]}return function e(r){return new Proxy(()=>{},{get:(o,a)=>"pending"===a?()=>!t.isEmpty(i(r)):"remaining"===a?()=>t.length(i(r)):"box"===a?()=>({value:H(n(),r),inspect:e(r)}):"is"===a?e=>i(r).some(t=>0!==(t.operation&e)):"draft"===a?()=>t.head(i(r))?.value??H(n(),r):"settled"===a?()=>new Promise(e=>{if(t.isEmpty(i(r)))return e(H(n(),r));const o=()=>{t.isEmpty(i(r))&&(s(o),e(H(n(),r)))};c(o)}):e([...r,String(a)])})}([])}(()=>this.#e,this.#n,this.#t,e=>this.#r.add(e),e=>this.#r.delete(e))}hydrate(e){return this.#o=!0,this.#c(D.Hydrate,()=>e)}produce(e){if(!this.#o)throw new Error("State must be hydrated using hydrate() before calling produce()");return this.#c(D.Produce,e)}#c(e,t){const n=/* @__PURE__ */Symbol("process"),[,r]=F.immer.produceWithPatches(this.#e,t);return this.#e=r.reduce((t,r)=>F.immer.applyPatches(t,[{...r,value:J(e,r,t,n,this.#n,this.#t)}]),this.#e),this.#e=G(this.#e),this.#s(),n}prune(e){this.#n.forEach((n,r)=>{const o=n.filter(t=>t.process!==e);t.isEmpty(o)?this.#n.delete(r):this.#n.set(r,o)}),this.#s()}#s(){this.#r.forEach(e=>e())}observe(e){const t=()=>e(this.#e);return this.#r.add(t),()=>this.#r.delete(t)}}const X=new Q;function Y(e,t){return X.annotate(e,t)}function Z(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var ee,te={exports:{}};const ne=/* @__PURE__ */Z((ee||(ee=1,function(e){var t=Object.prototype.hasOwnProperty,n="~";function r(){}function o(e,t,n){this.fn=e,this.context=t,this.once=n||!1}function c(e,t,r,c,s){if("function"!=typeof r)throw new TypeError("The listener must be a function");var i=new o(r,c||e,s),a=n?n+t:t;return e._events[a]?e._events[a].fn?e._events[a]=[e._events[a],i]:e._events[a].push(i):(e._events[a]=i,e._eventsCount++),e}function s(e,t){0===--e._eventsCount?e._events=new r:delete e._events[t]}function i(){this._events=new r,this._eventsCount=0}Object.create&&(r.prototype=/* @__PURE__ */Object.create(null),(new r).__proto__||(n=!1)),i.prototype.eventNames=function(){var e,r,o=[];if(0===this._eventsCount)return o;for(r in e=this._events)t.call(e,r)&&o.push(n?r.slice(1):r);return Object.getOwnPropertySymbols?o.concat(Object.getOwnPropertySymbols(e)):o},i.prototype.listeners=function(e){var t=this._events[n?n+e:e];if(!t)return[];if(t.fn)return[t.fn];for(var r=0,o=t.length,c=new Array(o);r<o;r++)c[r]=t[r].fn;return c},i.prototype.listenerCount=function(e){var t=this._events[n?n+e:e];return t?t.fn?1:t.length:0},i.prototype.emit=function(e,t,r,o,c,s){var i=n?n+e:e;if(!this._events[i])return!1;var a,u,l=this._events[i],f=arguments.length;if(l.fn){switch(l.once&&this.removeListener(e,l.fn,void 0,!0),f){case 1:return l.fn.call(l.context),!0;case 2:return l.fn.call(l.context,t),!0;case 3:return l.fn.call(l.context,t,r),!0;case 4:return l.fn.call(l.context,t,r,o),!0;case 5:return l.fn.call(l.context,t,r,o,c),!0;case 6:return l.fn.call(l.context,t,r,o,c,s),!0}for(u=1,a=new Array(f-1);u<f;u++)a[u-1]=arguments[u];l.fn.apply(l.context,a)}else{var d,h=l.length;for(u=0;u<h;u++)switch(l[u].once&&this.removeListener(e,l[u].fn,void 0,!0),f){case 1:l[u].fn.call(l[u].context);break;case 2:l[u].fn.call(l[u].context,t);break;case 3:l[u].fn.call(l[u].context,t,r);break;case 4:l[u].fn.call(l[u].context,t,r,o);break;default:if(!a)for(d=1,a=new Array(f-1);d<f;d++)a[d-1]=arguments[d];l[u].fn.apply(l[u].context,a)}}return!0},i.prototype.on=function(e,t,n){return c(this,e,t,n,!1)},i.prototype.once=function(e,t,n){return c(this,e,t,n,!0)},i.prototype.removeListener=function(e,t,r,o){var c=n?n+e:e;if(!this._events[c])return this;if(!t)return s(this,c),this;var i=this._events[c];if(i.fn)i.fn!==t||o&&!i.once||r&&i.context!==r||s(this,c);else{for(var a=0,u=[],l=i.length;a<l;a++)(i[a].fn!==t||o&&!i[a].once||r&&i[a].context!==r)&&u.push(i[a]);u.length?this._events[c]=1===u.length?u[0]:u:s(this,c)}return this},i.prototype.removeAllListeners=function(e){var t;return e?this._events[t=n?n+e:e]&&s(this,t):(this._events=new r,this._eventsCount=0),this},i.prototype.off=i.prototype.removeListener,i.prototype.addListener=i.prototype.on,i.prefixed=n,i.EventEmitter=i,e.exports=i}(te)),te.exports));class re extends ne{cache=/* @__PURE__ */new Map;emit(e,...t){return this.cache.set(e,t[0]),super.emit(e,...t)}setCache(e,t){this.cache.set(e,t)}getCached(e){return this.cache.get(e)}}const oe=r.createContext(new re);function ce(){return r.useContext(oe)}function se({children:e}){const t=r.useMemo(()=>new re,[]);/* @__PURE__ */
3
+ return n(oe.Provider,{value:t,children:e})}const ie=r.createContext(/* @__PURE__ */new Map);function ae({children:e}){const t=r.useMemo(()=>/* @__PURE__ */new Map,[]);/* @__PURE__ */
4
+ return n(ie.Provider,{value:t,children:e})}const ue=r.createContext(/* @__PURE__ */new Set);function le({children:e}){const t=r.useMemo(()=>/* @__PURE__ */new Set,[]);/* @__PURE__ */
5
+ return n(ue.Provider,{value:t,children:e})}const fe=r.createContext({mode:"allow-all",actions:/* @__PURE__ */new Set});function de({children:e}){const t=r.useMemo(()=>({mode:"allow-all",actions:/* @__PURE__ */new Set}),[]);/* @__PURE__ */
6
+ return n(fe.Provider,{value:t,children:e})}function he({children:e}){/* @__PURE__ */
7
+ return n(se,{children:/* @__PURE__ */n(ae,{children:/* @__PURE__ */n(de,{children:/* @__PURE__ */n(le,{children:e})})})})}const pe=r.createContext(null);function me(){return r.useContext(pe)}function ye(e,t){return e?.get(t)??null}function be({name:e,children:t}){const o=me(),c=r.useMemo(()=>({name:e,emitter:new re}),[]),s=r.useMemo(()=>{const t=new Map(o??[]);return t.set(e,c),t},[o,e,c]);/* @__PURE__ */
8
+ return n(pe.Provider,{value:s,children:t})}function ve(e,t){const r=`Scoped${t.displayName||t.name||"Component"}`;return{[r]:r=>/* @__PURE__ */n(be,{name:e,children:/* @__PURE__ */n(t,{...r})})}[r]}function ge(e,t,n){const r=e.features;switch(n){case p.On:r[t]=!0;break;case p.Off:r[t]=!1;break;case p.Toggle:r[t]=!r[t]}}function we(e,t,...n){e instanceof re&&e.setCache(t,n[0]);const r=e.listeners(t);return 0===r.length?Promise.resolve():Promise.all(r.map(e=>Promise.resolve(e(...n)))).then(()=>{})}function Pe(e){return(t,n)=>{t.actions.produce(t=>{t.model[e]=n})}}function xe(e,t){for(const n of e.keys())if(A(n)===t)return n;return null}function Se(){const[,e]=r.useReducer(e=>e+1,0);return e}const Ee=r.createContext(/* @__PURE__ */new Map);function Oe({action:t,renderer:n}){const o=ce(),c=r.useContext(Ee),s=Se(),i=r.useMemo(()=>{const e=c.get(t);if(e)return e;const n={state:new Q,listeners:/* @__PURE__ */new Set};return c.set(t,n),n},[t,c]);r.useLayoutEffect(()=>{function e(e){i.state.hydrate({value:e}),i.listeners.forEach(e=>e())}return i.listeners.add(s),o.on(t,e),()=>{i.listeners.delete(s),o.off(t,e)}},[t,o,i]);const a=i.state.model?.value;return e.isNullable(a)?null:n(a,i.state.inspect.value)}function je(...n){const o=e.isUndefined(n[0])||e.isFunction(n[0])?{}:n[0],s=e.isFunction(n[0])?n[0]:n[1]??(()=>({})),i=ce(),a=me(),u=c(L),l=r.useContext(ue),f=r.useContext(ie),d=r.useContext(fe),p=Se(),y=r.useRef(!1),v=r.useRef(null),g=r.useRef(new Q);y.current||(y.current=!0,v.current=g.current.hydrate(o));const[w,P]=r.useState(()=>g.current.model),x=function(e){const t=r.useRef(e);return r.useLayoutEffect(()=>{t.current=e},[e]),r.useMemo(()=>{return n=t,Object.keys(e).reduce((e,t)=>(Object.defineProperty(e,t,{get:()=>n.current[t],enumerable:!0}),e),{});var n},[e])}(s()),S=r.useMemo(()=>new ne,[]),A=r.useRef({handlers:/* @__PURE__ */new Map});A.current.handlers=/* @__PURE__ */new Map;const k=function(){const e=r.useRef(/* @__PURE__ */new Set),t=r.useRef(/* @__PURE__ */new Set);return r.useMemo(()=>({broadcast:e.current,multicast:t.current}),[])}(),_=r.useRef(h.Mounting),z=function(){const e=r.useRef({}),t=r.useRef(/* @__PURE__ */new Map),n=r.useRef(/* @__PURE__ */new Map);return r.useMemo(()=>({refs:e,pending:t,emitted:n}),[])}(),T=r.useRef(/* @__PURE__ */new Set),$=r.useRef(0),D=r.useCallback((e,t,n)=>{const r=new AbortController,o={controller:r,action:e,payload:t};return l.add(o),T.current.add(o),{model:g.current.model,get phase(){return _.current},task:o,data:x,tasks:l,nodes:z.refs.current,regulator:{disallow(...e){if(d.actions.clear(),0===e.length)d.mode="disallow-all";else{d.mode="disallow-matching";for(const t of e)d.actions.add(E(t))}},allow(...e){if(d.actions.clear(),0===e.length)d.mode="allow-all";else{d.mode="allow-matching";for(const t of e)d.actions.add(E(t))}}},actions:{produce(e){if(r.signal.aborted)return;const t=g.current.produce(t=>e({model:t,inspect:g.current.inspect}));P(g.current.model),n.processes.add(t),v.current&&(n.processes.add(v.current),v.current=null)},dispatch(e,t,n){if(r.signal.aborted)return Promise.resolve();const o=E(e),c=C(e)?e.channel:void 0;if(M(e)&&n?.scope){const e=ye(a,n.scope);return e?we(e.emitter,o,t,c):Promise.resolve()}return we(O(e)?i:S,o,t,c)},annotate:(e,t)=>g.current.annotate(e,t),async cacheable(e,t,n){if(r.signal.aborted)return{data:null};const o=R(e),c=f.get(o);if(c&&Date.now()<c.expiry)return{data:c.value};const s=function(e){return null!=e&&"object"==typeof e&&"TAG"in e?0===e.TAG?{ok:!0,value:e._0}:{ok:!1}:null==e?{ok:!1}:{ok:!0,value:e}}(await n());return s.ok?(f.set(o,{value:s.value,expiry:Date.now()+t}),{data:s.value}):{data:null}},invalidate(e){f.delete(R(e))},feature(e,t){if(r.signal.aborted)return;const o=g.current.produce(n=>ge(n,e,t));P(g.current.model),n.processes.add(o),v.current&&(n.processes.add(v.current),v.current=null)},async read(e,t){if(r.signal.aborted)return null;const n=E(e),o=M(e)&&t?.scope?ye(a,t.scope)?.emitter??null:i;if(!o)return null;if(void 0===o.getCached(n))return null;const c=j(e),s="unknown"!==c?c[0].toLowerCase()+c.slice(1):null;if(s){const e=g.current.inspect[s];e?.pending?.()&&await new Promise((t,n)=>{if(r.signal.aborted)return void n(r.signal.reason);const o=()=>n(r.signal.reason);r.signal.addEventListener("abort",o,{once:!0}),e.settled().then(()=>{r.signal.removeEventListener("abort",o),t()})})}return o.getCached(n)??null},peek(e,t){if(r.signal.aborted)return null;const n=E(e),o=M(e)&&t?.scope?ye(a,t.scope)?.emitter??null:i;return o?o.getCached(n)??null:null}}}},[w]);r.useLayoutEffect(()=>{function t(t,n,r){return function(o,c){if(!function(e,t){switch(t.mode){case"allow-all":return!0;case"disallow-all":return!1;case"disallow-matching":return!t.actions.has(e);case"allow-matching":return t.actions.has(e)}}(t,d)){const e=xe(A.current.handlers,"Error"),n=null!==e,r={reason:m.Disallowed,error:new b,action:j(t),handled:n,tasks:l};return u?.(r),void(n&&e&&S.emit(e,r))}const s=r();if(e.isNotNullable(c)&&e.isNotNullable(s)&&!function(e,t){for(const n of Object.keys(e))if(t[n]!==e[n])return!1;return!0}(c,s))return;const i={processes:/* @__PURE__ */new Set},a=Promise.withResolvers(),f=D(t,o,i);function h(e){const n=xe(A.current.handlers,"Error"),r=null!==n,o={reason:N(e),error:U(e),action:j(t),handled:r,tasks:l};u?.(o),r&&n&&S.emit(n,o)}function y(){for(const e of l)if(e===f.task){l.delete(e),T.current.delete(e);break}i.processes.forEach(e=>g.current.prune(e)),i.processes.size>0&&p(),a.resolve()}let v;try{v=n(f,o)}catch(w){return h(w),void y()}if(!function(e){if(!e||"object"!=typeof e)return!1;const t=Object.prototype.toString.call(e);return"[object Generator]"===t||"[object AsyncGenerator]"===t}(v))return Promise.resolve(v).catch(h).finally(y),a.promise;(async()=>{for await(const e of v);})().catch(h).finally(y)}}$.current++;const n=/* @__PURE__ */new Set;return A.current.handlers.forEach((e,r)=>{for(const{getChannel:o,handler:c}of e){const e=t(r,c,o);if(M(r)){if(a)for(const t of a.values()){const o=t.emitter;o.on(r,e),n.add(()=>o.off(r,e))}S.on(r,e),k.multicast.add(r),n.add(()=>S.off(r,e))}else O(r)?(i.on(r,e),S.on(r,e),k.broadcast.add(r),n.add(()=>{i.off(r,e),S.off(r,e)})):(S.on(r,e),n.add(()=>S.off(r,e)))}}),()=>{const e=++$.current,t=new Set(n);queueMicrotask(()=>{if($.current!==e){for(const e of t)e();return}for(const e of T.current)e.controller.abort(),l.delete(e);T.current.clear(),_.current=h.Unmounting;const n=xe(A.current.handlers,"Unmount");n&&S.emit(n),_.current=h.Unmounted;for(const e of t)e()})}},[S]),r.useLayoutEffect(()=>{const e=xe(A.current.handlers,"Node");for(const[t,n]of z.pending.current)z.emitted.current.get(t)!==n&&(z.emitted.current.set(t,n),e&&S.emit(e,n,{Name:t}));z.pending.current.clear()}),function({unicast:n,broadcast:o,dispatchers:c,scope:s,phase:i,data:a,handlers:u}){const l=r.useRef(null);r.useLayoutEffect(()=>{if(i.current!==h.Mounting)return;const t=xe(u,"Mount");t&&n.emit(t),c.broadcast.forEach(t=>{const r=o.getCached(t);e.isNullable(r)||n.emit(t,r)}),s&&c.multicast.forEach(t=>{for(const r of s.values()){const o=r.emitter.getCached(t);e.isNullable(o)||n.emit(t,o)}}),i.current=h.Mounted},[]),r.useLayoutEffect(()=>{if(e.isNotNullable(l.current)){const e=function(e,t){return Object.keys(t).reduce((n,r)=>e[r]!==t[r]?{...n,[r]:t[r]}:n,{})}(l.current,a);if(t.isNotEmpty(Object.keys(e))){const t=xe(u,"Update");t&&n.emit(t,e)}}l.current=a},[a,n])}({unicast:S,broadcast:i,dispatchers:k,scope:a,phase:_,data:s(),handlers:A.current.handlers});const B=r.useMemo(()=>[w,{dispatch(e,t,n){const r=E(e),o=C(e)?e.channel:void 0;if(M(e)&&n?.scope){const e=ye(a,n.scope);return e?we(e.emitter,r,t,o):Promise.resolve()}return we(O(e)?i:S,r,t,o)},get inspect(){return g.current.inspect},get nodes(){return z.refs.current},node(e,t){z.refs.current[e]=t,z.pending.current.set(e,t)},feature(e,t){const n=g.current.produce(n=>ge(n,e,t));P(g.current.model),g.current.prune(n)},stream:(e,t)=>r.createElement(Oe,{action:E(e),renderer:t})}],[w,S]);return B.useAction=(e,t)=>{!function(e,t,n){const o=r.useRef(n);r.useLayoutEffect(()=>{o.current=n});const c=r.useRef(t);r.useLayoutEffect(()=>{c.current=t});const s=r.useCallback((e,t)=>o.current(e,t),[]),i=r.useCallback(()=>C(c.current)?c.current.channel:void 0,[]),a=E(t),u=e.current.handlers.get(a)??/* @__PURE__ */new Set;0===u.size&&e.current.handlers.set(a,u),u.add({getChannel:i,handler:s})}(A,e,t)},B}export{k as Action,he as Boundary,b as DisallowedError,d as Distribution,_ as Entry,z as Error,p as Feature,f as Lifecycle,$ as Op,$ as Operation,m as Reason,de as Regulators,be as Scope,Q as State,Pe as With,Y as annotate,je as useActions,x as utils,ve as withScope};
@@ -1 +1 @@
1
- var global,factory;global=this,factory=function(e,t,n,r,o){"use strict";function c(e){const t=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(e)for(const n in e)if("default"!==n){const r=Object.getOwnPropertyDescriptor(e,n);Object.defineProperty(t,n,r.get?r:{enumerable:!0,get:()=>e[n]})}return t.default=e,Object.freeze(t)}const i=c(r);class s{static Payload=Symbol("chizu.brand/Payload");static Broadcast=Symbol("chizu.brand/Broadcast");static Multicast=Symbol("chizu.brand/Multicast");static Action=Symbol("chizu.brand/Action");static Channel=Symbol("chizu.brand/Channel");static Node=Symbol("chizu.action.lifecycle/Node");static Cache=Symbol("chizu.brand/Cache")}class a{static Mount=Symbol("chizu.action.lifecycle/Mount");static Unmount=Symbol("chizu.action.lifecycle/Unmount");static Error=Symbol("chizu.action.lifecycle/Error");static Update=Symbol("chizu.action.lifecycle/Update");static Node=(()=>{const e=s.Node,t=function(t){return{[s.Action]:e,[s.Payload]:void 0,[s.Channel]:t,channel:t}};return Object.defineProperty(t,s.Action,{value:e,enumerable:!1}),Object.defineProperty(t,s.Payload,{value:void 0,enumerable:!1}),t})()}var u=(e=>(e.Unicast="unicast",e.Broadcast="broadcast",e.Multicast="multicast",e))(u||{}),l=(e=>(e.Mounting="mounting",e.Mounted="mounted",e.Unmounting="unmounting",e.Unmounted="unmounted",e))(l||{}),f=(e=>(e[e.Timedout=0]="Timedout",e[e.Supplanted=1]="Supplanted",e[e.Disallowed=2]="Disallowed",e[e.Errored=3]="Errored",e[e.Unmounted=4]="Unmounted",e))(f||{});class d extends Error{name="AbortError";constructor(e="Aborted"){super(e)}}const p={actionPrefix:"chizu.action/",broadcastActionPrefix:"chizu.action/broadcast/",multicastActionPrefix:"chizu.action/multicast/",channelPrefix:"chizu.channel/",cachePrefix:"chizu.cache/"};function h(e,t){return new Promise((n,r)=>{if(t?.aborted)return void r(new d);const o=setTimeout(n,e);t?.addEventListener("abort",()=>{clearTimeout(o),r(new d)},{once:!0})})}async function m(e,t,n){if(t?.aborted)throw new d;for(;;){if(await n())return;await h(e,t)}}function y(e){return e?Boolean(e&&"symbol"!=typeof e):Symbol(`pk.${Date.now()}.${crypto.randomUUID()}`)}const b=Object.freeze(Object.defineProperty({__proto__:null,config:p,pk:y,poll:m,sleep:h,"ζ":h,"κ":y,"π":m},Symbol.toStringTag,{value:"Module"})),v=e=>"symbol"==typeof e;function g(e){return t.G.isString(e)||v(e)?e:(t.G.isObject(e)||t.G.isFunction(e))&&s.Action in e?e[s.Action]:e}function w(e){if(t.G.isString(e))return e.startsWith(p.broadcastActionPrefix);if(v(e))return e.description?.startsWith(p.broadcastActionPrefix)??!1;if(t.G.isObject(e)||t.G.isFunction(e)){if(s.Broadcast in e&&e[s.Broadcast])return!0;if(s.Action in e){const t=e[s.Action];return t.description?.startsWith(p.broadcastActionPrefix)??!1}}return!1}function x(e){const n=g(e),r=t.G.isString(n)?n:n.description??"";return r.startsWith(p.actionPrefix)&&r.slice(r.lastIndexOf("/")+1)||"unknown"}function j(e){return t.G.isObject(e)&&s.Channel in e&&"channel"in e}function S(e){if(t.G.isString(e))return e.startsWith(p.multicastActionPrefix);if(v(e))return e.description?.startsWith(p.multicastActionPrefix)??!1;if(t.G.isObject(e)||t.G.isFunction(e)){if(s.Multicast in e&&e[s.Multicast])return!0;if(s.Action in e){const t=e[s.Action];return t.description?.startsWith(p.multicastActionPrefix)??!1}}return!1}function P(e){const t=function(e){return e[s.Cache]}(e),n=function(e){return"channel"in e}(e)&&(r=e.channel)?[...Object.keys(r)].toSorted().map(e=>`${e}=${String(r[e])}`).join("&"):"";var r;return`${String(t)}:${n}`}function A(e){if(e instanceof Error){if("TimeoutError"===e.name)return f.Timedout;if("AbortError"===e.name)return f.Supplanted}return f.Errored}function O(e){return e instanceof Error?e:new Error(String(e))}const E=r.createContext(void 0);let C=(e=21)=>{let t="",n=crypto.getRandomValues(new Uint8Array(e|=0));for(;e--;)t+="useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict"[63&n[e]];return t};var M=(e=>(e[e.Add=1]="Add",e[e.Remove=2]="Remove",e[e.Update=4]="Update",e[e.Move=8]="Move",e[e.Replace=16]="Replace",e[e.Sort=32]="Sort",e[e.Create=64]="Create",e[e.Fetch=128]="Fetch",e[e.Clone=256]="Clone",e[e.Archive=512]="Archive",e[e.Restore=1024]="Restore",e[e.Merge=2048]="Merge",e[e.Reorder=4096]="Reorder",e[e.Sync=8192]="Sync",e[e.Publish=16384]="Publish",e[e.Link=32768]="Link",e[e.Unlink=65536]="Unlink",e[e.Lock=131072]="Lock",e[e.Unlock=262144]="Unlock",e[e.Import=524288]="Import",e[e.Export=1048576]="Export",e[e.Transfer=2097152]="Transfer",e))(M||{}),k=(e=>(e[e.Produce=0]="Produce",e[e.Hydrate=1]="Hydrate",e))(k||{}),G=(e=>(e.Property="property",e.Process="process",e.Value="value",e.Operation="operation",e))(G||{});class _{[o.immerable]=!0;static keys=new Set(Object.values(G));property=null;process=null;value;operation;constructor(e,t){this.value=e,this.operation=t}assign(e,t){const n=new _(this.value,this.operation);return n.property=e,n.process=t,n}}class R{static immer=(()=>{o.enablePatches();const e=new o.Immer;return e.setAutoFreeze(!1),e})();static tag="κ";static id=C}function N(e,t){const n="string"==typeof t?""===t?[]:t.split("."):t;let r=e;for(const o of n){if(null==r)return;r=r[o]}return r}function z(e){if(t.G.isNullable(e)||T(e))return e;if(t.G.isArray(e))return e.map(e=>z(e));if(t.G.isObject(e)&&L(e)){const t=Object.entries(e).map(([e,t])=>[e,z(t)]);return{...Object.fromEntries(t),[R.tag]:e[R.tag]??R.id()}}return e}function U(e){if(Array.isArray(e))return e.filter(e=>R.tag in e).map(e=>e[R.tag]??"").join(",");const t=e[R.tag];if(t)return t;try{return JSON.stringify(e)}catch{return`[unserializable:${typeof e}]`}}function L(e){const t=Object.getPrototypeOf(e);return t===Object.prototype||null===t}function T(e){return t.G.isNullable(e)||t.G.isString(e)||t.G.isNumber(e)||t.G.isBoolean(e)||"symbol"==typeof e||"bigint"==typeof e}function $(e,n,r,o,c,i){return function s(a,u=n.path){if(a instanceof _){const n=N(r,u.join("."));if(Object.entries(a).filter(([e,t])=>!_.keys.has(e)&&t instanceof _).forEach(([e,t])=>s(t,u.concat(e))),T(a.value)){if(e===k.Hydrate)return a.value;const s=u.slice(0,-1),l=s.length>0?N(r,s.join(".")):r;return t.G.isNullable(l)||B(l,a,u.at(-1),o,c,i),n??a.value}if(e===k.Hydrate){const e=z(s(a.value,u));return B(e,a,null,o,c,i),e}const l=n??z(a.value);return B(l,a,null,o,c,i),t.G.isNullable(n)?l:(s(a.value,u),n)}if(t.G.isArray(a))return a.map((e,t)=>s(e,u.concat(t)));if(t.G.isObject(a)&&!L(a))return a;if(t.G.isObject(a)){const t=Object.entries(a).map(([e,t])=>[e,s(t,u.concat(e))]),n=Object.fromEntries(t);if(e===k.Hydrate){const e=z(n);return Object.entries(a).forEach(([t,n])=>{n instanceof _&&T(n.value)&&B(e,n,t,o,c,i)}),e}return n}return a}(n.value)}function B(e,t,n,r,o,c){const i=c(e),s=o.get(i)??[];o.set(i,[t.assign(n,r),...s])}class F{#e={};#t;#n=new Map;#r=new Set;#o=!1;constructor(e=U){this.#t=e}static pk(){return C()}static"κ"=F.pk;annotate(e,t){return new _(t,e)}"δ"=this.annotate;get model(){return this.#e}get inspect(){return function(e,n,r,o,c){function i(o){const c=o.at(-1),i=N(e(),o),s=o.slice(0,-1),a=t.A.isNotEmpty(s)?N(e(),s):e();return[...t.G.isObject(i)||t.G.isArray(i)?n.get(r(i))?.filter(e=>t.G.isNullable(e.property))??[]:[],...t.G.isObject(a)?n.get(r(a))?.filter(e=>e.property===c)??[]:[]]}return function n(r){return new Proxy(()=>{},{get:(s,a)=>"pending"===a?()=>!t.A.isEmpty(i(r)):"remaining"===a?()=>t.A.length(i(r)):"box"===a?()=>({value:N(e(),r),inspect:n(r)}):"is"===a?e=>i(r).some(t=>0!==(t.operation&e)):"draft"===a?()=>t.A.head(i(r))?.value??N(e(),r):"settled"===a?()=>new Promise(n=>{if(t.A.isEmpty(i(r)))return n(N(e(),r));const s=()=>{t.A.isEmpty(i(r))&&(c(s),n(N(e(),r)))};o(s)}):n([...r,String(a)])})}([])}(()=>this.#e,this.#n,this.#t,e=>this.#r.add(e),e=>this.#r.delete(e))}hydrate(e){return this.#o=!0,this.#c(k.Hydrate,()=>e)}produce(e){if(!this.#o)throw new Error("State must be hydrated using hydrate() before calling produce()");return this.#c(k.Produce,e)}#c(e,t){const n=Symbol("process"),[,r]=R.immer.produceWithPatches(this.#e,t);return this.#e=r.reduce((t,r)=>R.immer.applyPatches(t,[{...r,value:$(e,r,t,n,this.#n,this.#t)}]),this.#e),this.#e=z(this.#e),this.#i(),n}prune(e){this.#n.forEach((n,r)=>{const o=n.filter(t=>t.process!==e);t.A.isEmpty(o)?this.#n.delete(r):this.#n.set(r,o)}),this.#i()}#i(){this.#r.forEach(e=>e())}observe(e){const t=()=>e(this.#e);return this.#r.add(t),()=>this.#r.delete(t)}}const W=new F;function D(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var H,I={exports:{}},q=(H||(H=1,function(e){var t=Object.prototype.hasOwnProperty,n="~";function r(){}function o(e,t,n){this.fn=e,this.context=t,this.once=n||!1}function c(e,t,r,c,i){if("function"!=typeof r)throw new TypeError("The listener must be a function");var s=new o(r,c||e,i),a=n?n+t:t;return e._events[a]?e._events[a].fn?e._events[a]=[e._events[a],s]:e._events[a].push(s):(e._events[a]=s,e._eventsCount++),e}function i(e,t){0===--e._eventsCount?e._events=new r:delete e._events[t]}function s(){this._events=new r,this._eventsCount=0}Object.create&&(r.prototype=Object.create(null),(new r).__proto__||(n=!1)),s.prototype.eventNames=function(){var e,r,o=[];if(0===this._eventsCount)return o;for(r in e=this._events)t.call(e,r)&&o.push(n?r.slice(1):r);return Object.getOwnPropertySymbols?o.concat(Object.getOwnPropertySymbols(e)):o},s.prototype.listeners=function(e){var t=this._events[n?n+e:e];if(!t)return[];if(t.fn)return[t.fn];for(var r=0,o=t.length,c=new Array(o);r<o;r++)c[r]=t[r].fn;return c},s.prototype.listenerCount=function(e){var t=this._events[n?n+e:e];return t?t.fn?1:t.length:0},s.prototype.emit=function(e,t,r,o,c,i){var s=n?n+e:e;if(!this._events[s])return!1;var a,u,l=this._events[s],f=arguments.length;if(l.fn){switch(l.once&&this.removeListener(e,l.fn,void 0,!0),f){case 1:return l.fn.call(l.context),!0;case 2:return l.fn.call(l.context,t),!0;case 3:return l.fn.call(l.context,t,r),!0;case 4:return l.fn.call(l.context,t,r,o),!0;case 5:return l.fn.call(l.context,t,r,o,c),!0;case 6:return l.fn.call(l.context,t,r,o,c,i),!0}for(u=1,a=new Array(f-1);u<f;u++)a[u-1]=arguments[u];l.fn.apply(l.context,a)}else{var d,p=l.length;for(u=0;u<p;u++)switch(l[u].once&&this.removeListener(e,l[u].fn,void 0,!0),f){case 1:l[u].fn.call(l[u].context);break;case 2:l[u].fn.call(l[u].context,t);break;case 3:l[u].fn.call(l[u].context,t,r);break;case 4:l[u].fn.call(l[u].context,t,r,o);break;default:if(!a)for(d=1,a=new Array(f-1);d<f;d++)a[d-1]=arguments[d];l[u].fn.apply(l[u].context,a)}}return!0},s.prototype.on=function(e,t,n){return c(this,e,t,n,!1)},s.prototype.once=function(e,t,n){return c(this,e,t,n,!0)},s.prototype.removeListener=function(e,t,r,o){var c=n?n+e:e;if(!this._events[c])return this;if(!t)return i(this,c),this;var s=this._events[c];if(s.fn)s.fn!==t||o&&!s.once||r&&s.context!==r||i(this,c);else{for(var a=0,u=[],l=s.length;a<l;a++)(s[a].fn!==t||o&&!s[a].once||r&&s[a].context!==r)&&u.push(s[a]);u.length?this._events[c]=1===u.length?u[0]:u:i(this,c)}return this},s.prototype.removeAllListeners=function(e){var t;return e?this._events[t=n?n+e:e]&&i(this,t):(this._events=new r,this._eventsCount=0),this},s.prototype.off=s.prototype.removeListener,s.prototype.addListener=s.prototype.on,s.prefixed=n,s.EventEmitter=s,e.exports=s}(I)),I.exports);const V=D(q);class J extends V{cache=new Map;emit(e,...t){return this.cache.set(e,t[0]),super.emit(e,...t)}getCached(e){return this.cache.get(e)}}const K=i.createContext(new J);function Q(){return i.useContext(K)}function X({children:e}){const t=i.useMemo(()=>new J,[]);return n.jsx(K.Provider,{value:t,children:e})}const Y=i.createContext(new Map);function Z({children:e}){const t=i.useMemo(()=>new Map,[]);return n.jsx(Y.Provider,{value:t,children:e})}const ee=i.createContext(new Set);function te({children:e}){const t=i.useMemo(()=>new Set,[]);return n.jsx(ee.Provider,{value:t,children:e})}const ne=i.createContext(null);function re(){return i.useContext(ne)}function oe(e,t){return e?.get(t)??null}function ce({name:e,children:t}){const r=re(),o=i.useMemo(()=>({name:e,emitter:new J}),[]),c=i.useMemo(()=>{const t=new Map(r??[]);return t.set(e,o),t},[r,e,o]);return n.jsx(ne.Provider,{value:c,children:t})}function ie(){const[,e]=i.useReducer(e=>e+1,0);return e}const se=i.createContext(new Map);function ae({action:e,renderer:n}){const r=Q(),o=i.useContext(se),c=ie(),s=i.useMemo(()=>{const t=o.get(e);if(t)return t;const n={state:new F,listeners:new Set};return o.set(e,n),n},[e,o]);i.useLayoutEffect(()=>{function t(e){s.state.hydrate({value:e}),s.listeners.forEach(e=>e())}return s.listeners.add(c),r.on(e,t),()=>{s.listeners.delete(c),r.off(e,t)}},[e,r,s]);const a=s.state.model?.value;return t.G.isNullable(a)?null:n(a,s.state.inspect.value)}e.Action=(e,t=u.Unicast)=>{const n=t===u.Broadcast?Symbol(`${p.broadcastActionPrefix}${e}`):t===u.Multicast?Symbol(`${p.multicastActionPrefix}${e}`):Symbol(`${p.actionPrefix}${e}`),r=function(e){return{[s.Action]:n,[s.Payload]:void 0,[s.Channel]:e,channel:e}};return Object.defineProperty(r,s.Action,{value:n,enumerable:!1}),Object.defineProperty(r,s.Payload,{value:void 0,enumerable:!1}),t===u.Broadcast&&Object.defineProperty(r,s.Broadcast,{value:!0,enumerable:!1}),t===u.Multicast&&Object.defineProperty(r,s.Multicast,{value:!0,enumerable:!1}),r},e.Boundary=function({children:e}){return n.jsx(X,{children:n.jsx(Z,{children:n.jsx(te,{children:e})})})},e.Distribution=u,e.Entry=function(){const e=Symbol("chizu.cache/Entry"),t=function(t){return{[s.Cache]:e,channel:t}};return Object.defineProperty(t,s.Cache,{value:e,enumerable:!1}),t},e.Error=function({handler:e,children:t}){return n.jsx(E.Provider,{value:e,children:t})},e.Lifecycle=a,e.Op=M,e.Operation=M,e.Reason=f,e.Scope=ce,e.State=F,e.With=function(e){return(t,n)=>{t.actions.produce(t=>{t.model[e]=n})}},e.annotate=function(e,t){return W.annotate(e,t)},e.useActions=function(...e){const n=t.G.isUndefined(e[0])||t.G.isFunction(e[0])?{}:e[0],o=t.G.isFunction(e[0])?e[0]:e[1]??(()=>({})),c=Q(),u=re(),f=r.useContext(E),d=i.useContext(ee),p=i.useContext(Y),h=ie(),m=i.useRef(!1),y=i.useRef(null),b=i.useRef(new F);m.current||(m.current=!0,y.current=b.current.hydrate(n));const[v,C]=i.useState(()=>b.current.model),M=function(e){const t=i.useRef(e);return i.useLayoutEffect(()=>{t.current=e},[e]),i.useMemo(()=>{return n=t,Object.keys(e).reduce((e,t)=>(Object.defineProperty(e,t,{get:()=>n.current[t],enumerable:!0}),e),{});var n},[e])}(o()),k=i.useMemo(()=>new V,[]),G=i.useRef({handlers:new Map});G.current.handlers=new Map;const _=function(){const e=i.useRef(new Set),t=i.useRef(new Set);return i.useMemo(()=>({broadcast:e.current,multicast:t.current}),[])}(),R=i.useRef(l.Mounting),N=function(){const e=i.useRef({}),t=i.useRef(new Map),n=i.useRef(new Map);return i.useMemo(()=>({refs:e,pending:t,emitted:n}),[])}(),z=i.useRef(new Set),U=i.useRef(0),L=i.useCallback((e,t,n)=>{const r=new AbortController,o={controller:r,action:e,payload:t};return d.add(o),z.current.add(o),{model:b.current.model,get phase(){return R.current},task:o,data:M,tasks:d,nodes:N.refs.current,actions:{produce(e){if(r.signal.aborted)return;const t=b.current.produce(t=>e({model:t,inspect:b.current.inspect}));C(b.current.model),n.processes.add(t),y.current&&(n.processes.add(y.current),y.current=null)},dispatch(e,t,n){if(r.signal.aborted)return;const o=g(e),i=j(e)?e.channel:void 0;if(S(e)&&n?.scope){const e=oe(u,n.scope);return void(e&&e.emitter.emit(o,t,i))}(w(e)?c:k).emit(o,t,i)},annotate:(e,t)=>b.current.annotate(e,t),async cacheable(e,t,n){if(r.signal.aborted)return{data:null};const o=P(e),c=p.get(o);if(c&&Date.now()<c.expiry)return{data:c.value};const i=function(e){return null!=e&&"object"==typeof e&&"TAG"in e?0===e.TAG?{ok:!0,value:e._0}:{ok:!1}:null==e?{ok:!1}:{ok:!0,value:e}}(await n());return i.ok?(p.set(o,{value:i.value,expiry:Date.now()+t}),{data:i.value}):{data:null}},invalidate(e){p.delete(P(e))},async read(e,t){if(r.signal.aborted)return null;const n=g(e),o=S(e)&&t?.scope?oe(u,t.scope)?.emitter??null:c;if(!o)return null;if(void 0===o.getCached(n))return null;const i=x(e),s="unknown"!==i?i[0].toLowerCase()+i.slice(1):null;if(s){const e=b.current.inspect[s];e?.pending?.()&&await new Promise((t,n)=>{if(r.signal.aborted)return void n(r.signal.reason);const o=()=>n(r.signal.reason);r.signal.addEventListener("abort",o,{once:!0}),e.settled().then(()=>{r.signal.removeEventListener("abort",o),t()})})}return o.getCached(n)??null},peek(e,t){if(r.signal.aborted)return null;const n=g(e),o=S(e)&&t?.scope?oe(u,t.scope)?.emitter??null:c;return o?o.getCached(n)??null:null}}}},[v]);i.useLayoutEffect(()=>{function e(e,n,r){return async function(o,c){const i=r();if(t.G.isNotNullable(c)&&t.G.isNotNullable(i)&&!function(e,t){for(const n of Object.keys(e))if(t[n]!==e[n])return!1;return!0}(c,i))return;const s={processes:new Set},u=Promise.withResolvers(),l=L(e,o,s);try{await n(l,o)}catch(p){const t=G.current.handlers.has(a.Error),n={reason:A(p),error:O(p),action:x(e),handled:t,tasks:d};f?.(n),t&&k.emit(a.Error,n)}finally{for(const e of d)if(e===l.task){d.delete(e),z.current.delete(e);break}s.processes.forEach(e=>b.current.prune(e)),s.processes.size>0&&h(),u.resolve()}}}U.current++;const n=new Set;return G.current.handlers.forEach((t,r)=>{for(const{getChannel:o,handler:i}of t){const t=e(r,i,o);if(S(r)){if(u)for(const e of u.values()){const o=e.emitter;o.on(r,t),n.add(()=>o.off(r,t))}k.on(r,t),_.multicast.add(r),n.add(()=>k.off(r,t))}else w(r)?(c.on(r,t),k.on(r,t),_.broadcast.add(r),n.add(()=>{c.off(r,t),k.off(r,t)})):(k.on(r,t),n.add(()=>k.off(r,t)))}}),()=>{const e=++U.current,t=new Set(n);queueMicrotask(()=>{if(U.current===e){for(const e of z.current)e.controller.abort(),d.delete(e);z.current.clear(),R.current=l.Unmounting,k.emit(a.Unmount),R.current=l.Unmounted;for(const e of t)e()}else for(const e of t)e()})}},[k]),i.useLayoutEffect(()=>{for(const[e,t]of N.pending.current)N.emitted.current.get(e)!==t&&(N.emitted.current.set(e,t),k.emit(s.Node,t,{Name:e}));N.pending.current.clear()}),function({unicast:e,broadcast:n,dispatchers:r,scope:o,phase:c,data:s}){const u=i.useRef(null);i.useLayoutEffect(()=>{c.current===l.Mounting&&(e.emit(a.Mount),r.broadcast.forEach(r=>{const o=n.getCached(r);t.G.isNullable(o)||e.emit(r,o)}),o&&r.multicast.forEach(n=>{for(const r of o.values()){const o=r.emitter.getCached(n);t.G.isNullable(o)||e.emit(n,o)}}),c.current=l.Mounted)},[]),i.useLayoutEffect(()=>{if(t.G.isNotNullable(u.current)){const n=function(e,t){return Object.keys(t).reduce((n,r)=>e[r]!==t[r]?{...n,[r]:t[r]}:n,{})}(u.current,s);t.A.isNotEmpty(Object.keys(n))&&e.emit(a.Update,n)}u.current=s},[s,e])}({unicast:k,broadcast:c,dispatchers:_,scope:u,phase:R,data:o()});const T=i.useMemo(()=>[v,{dispatch(e,t,n){const r=g(e),o=j(e)?e.channel:void 0;if(S(e)&&n?.scope){const e=oe(u,n.scope);return void(e&&e.emitter.emit(r,t,o))}(w(e)?c:k).emit(r,t,o)},get inspect(){return b.current.inspect},get nodes(){return N.refs.current},node(e,t){N.refs.current[e]=t,N.pending.current.set(e,t)},stream:(e,t)=>i.createElement(ae,{action:g(e),renderer:t})}],[v,k]);return T.useAction=(e,t)=>{!function(e,t,n){const r=i.useRef(n);i.useLayoutEffect(()=>{r.current=n});const o=i.useRef(t);i.useLayoutEffect(()=>{o.current=t});const c=i.useCallback(async(e,t)=>{const n=r.current;if("GeneratorFunction"===n.constructor.name||"AsyncGeneratorFunction"===n.constructor.name){const r=n(e,t);for await(const e of r);}else await n(e,t)},[]),s=i.useCallback(()=>j(o.current)?o.current.channel:void 0,[]),a=g(t),u=e.current.handlers.get(a)??new Set;0===u.size&&e.current.handlers.set(a,u),u.add({getChannel:s,handler:c})}(G,e,t)},T},e.utils=b,e.withScope=function(e,t){const r=`Scoped${t.displayName||t.name||"Component"}`;return{[r]:r=>n.jsx(ce,{name:e,children:n.jsx(t,{...r})})}[r]},Object.defineProperty(e,Symbol.toStringTag,{value:"Module"})},"object"==typeof exports&&"undefined"!=typeof module?factory(exports,require("@mobily/ts-belt"),require("react/jsx-runtime"),require("react"),require("immer")):"function"==typeof define&&define.amd?define(["exports","@mobily/ts-belt","react/jsx-runtime","react","immer"],factory):factory((global="undefined"!=typeof globalThis?globalThis:global||self).Chizu={},global.TsBelt,global.jsxRuntime,global.React,global.Immer);
1
+ var global,factory;global=this,factory=function(e,t,n,r,o){"use strict";function c(e){const t=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(e)for(const n in e)if("default"!==n){const r=Object.getOwnPropertyDescriptor(e,n);Object.defineProperty(t,n,r.get?r:{enumerable:!0,get:()=>e[n]})}return t.default=e,Object.freeze(t)}const s=c(r);class i{static Payload=Symbol("chizu.brand/Payload");static Broadcast=Symbol("chizu.brand/Broadcast");static Multicast=Symbol("chizu.brand/Multicast");static Action=Symbol("chizu.brand/Action");static Channel=Symbol("chizu.brand/Channel");static Node=Symbol("chizu.action.lifecycle/Node");static Cache=Symbol("chizu.brand/Cache")}function a(e){const t=Symbol(`chizu.action.lifecycle/${e}`),n=function(e){return{[i.Action]:t,[i.Payload]:void 0,[i.Channel]:e,channel:e}};return Object.defineProperty(n,i.Action,{value:t,enumerable:!1}),Object.defineProperty(n,i.Payload,{value:void 0,enumerable:!1}),n}var u=(e=>(e.Unicast="unicast",e.Broadcast="broadcast",e.Multicast="multicast",e))(u||{}),l=(e=>(e.Mounting="mounting",e.Mounted="mounted",e.Unmounting="unmounting",e.Unmounted="unmounted",e))(l||{}),f=(e=>(e.On="on",e.Off="off",e.Toggle="toggle",e))(f||{}),d=(e=>(e[e.Timedout=0]="Timedout",e[e.Supplanted=1]="Supplanted",e[e.Disallowed=2]="Disallowed",e[e.Errored=3]="Errored",e[e.Unmounted=4]="Unmounted",e))(d||{});class h extends Error{name="AbortError";constructor(e="Aborted"){super(e)}}class p extends Error{name="DisallowedError";constructor(e="Disallowed"){super(e)}}const m={actionPrefix:"chizu.action/",broadcastActionPrefix:"chizu.action/broadcast/",multicastActionPrefix:"chizu.action/multicast/",channelPrefix:"chizu.channel/",cachePrefix:"chizu.cache/",lifecyclePrefix:"chizu.action.lifecycle/"};function b(e,t){return new Promise((n,r)=>{if(t?.aborted)return void r(new h);const o=setTimeout(n,e);t?.addEventListener("abort",()=>{clearTimeout(o),r(new h)},{once:!0})})}async function y(e,t,n){if(t?.aborted)throw new h;for(;;){if(await n())return;await b(e,t)}}function v(e){return e?Boolean(e&&"symbol"!=typeof e):Symbol(`pk.${Date.now()}.${crypto.randomUUID()}`)}const g=Object.freeze(Object.defineProperty({__proto__:null,config:m,pk:v,poll:y,sleep:b,"ζ":b,"κ":v,"π":y},Symbol.toStringTag,{value:"Module"})),w=e=>"symbol"==typeof e;function x(e){return t.G.isString(e)||w(e)?e:(t.G.isObject(e)||t.G.isFunction(e))&&i.Action in e?e[i.Action]:e}function j(e){if(t.G.isString(e))return e.startsWith(m.broadcastActionPrefix);if(w(e))return e.description?.startsWith(m.broadcastActionPrefix)??!1;if(t.G.isObject(e)||t.G.isFunction(e)){if(i.Broadcast in e&&e[i.Broadcast])return!0;if(i.Action in e){const t=e[i.Action];return t.description?.startsWith(m.broadcastActionPrefix)??!1}}return!1}function P(e){const n=x(e),r=t.G.isString(n)?n:n.description??"";return r.startsWith(m.actionPrefix)&&r.slice(r.lastIndexOf("/")+1)||"unknown"}function S(e){return t.G.isObject(e)&&i.Channel in e&&"channel"in e}function O(e){const t=x(e),n=w(t)?t.description??"":t;return n.startsWith(m.lifecyclePrefix)&&n.slice(m.lifecyclePrefix.length)||null}function E(e){if(t.G.isString(e))return e.startsWith(m.multicastActionPrefix);if(w(e))return e.description?.startsWith(m.multicastActionPrefix)??!1;if(t.G.isObject(e)||t.G.isFunction(e)){if(i.Multicast in e&&e[i.Multicast])return!0;if(i.Action in e){const t=e[i.Action];return t.description?.startsWith(m.multicastActionPrefix)??!1}}return!1}function A(e){const t=function(e){return e[i.Cache]}(e),n=function(e){return"channel"in e}(e)&&(r=e.channel)?[...Object.keys(r)].toSorted().map(e=>`${e}=${String(r[e])}`).join("&"):"";var r;return`${String(t)}:${n}`}function C(e){if(e instanceof Error){if("TimeoutError"===e.name)return d.Timedout;if("AbortError"===e.name)return d.Supplanted;if("DisallowedError"===e.name)return d.Disallowed}return d.Errored}function M(e){return e instanceof Error?e:new Error(String(e))}const k=r.createContext(void 0);let G=(e=21)=>{let t="",n=crypto.getRandomValues(new Uint8Array(e|=0));for(;e--;)t+="useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict"[63&n[e]];return t};var _=(e=>(e[e.Add=1]="Add",e[e.Remove=2]="Remove",e[e.Update=4]="Update",e[e.Move=8]="Move",e[e.Replace=16]="Replace",e[e.Sort=32]="Sort",e[e.Create=64]="Create",e[e.Fetch=128]="Fetch",e[e.Clone=256]="Clone",e[e.Archive=512]="Archive",e[e.Restore=1024]="Restore",e[e.Merge=2048]="Merge",e[e.Reorder=4096]="Reorder",e[e.Sync=8192]="Sync",e[e.Publish=16384]="Publish",e[e.Link=32768]="Link",e[e.Unlink=65536]="Unlink",e[e.Lock=131072]="Lock",e[e.Unlock=262144]="Unlock",e[e.Import=524288]="Import",e[e.Export=1048576]="Export",e[e.Transfer=2097152]="Transfer",e))(_||{}),R=(e=>(e[e.Produce=0]="Produce",e[e.Hydrate=1]="Hydrate",e))(R||{}),N=(e=>(e.Property="property",e.Process="process",e.Value="value",e.Operation="operation",e))(N||{});class U{[o.immerable]=!0;static keys=new Set(Object.values(N));property=null;process=null;value;operation;constructor(e,t){this.value=e,this.operation=t}assign(e,t){const n=new U(this.value,this.operation);return n.property=e,n.process=t,n}}class L{static immer=(()=>{o.enablePatches();const e=new o.Immer;return e.setAutoFreeze(!1),e})();static tag="κ";static id=G}function z(e,t){const n="string"==typeof t?""===t?[]:t.split("."):t;let r=e;for(const o of n){if(null==r)return;r=r[o]}return r}function T(e){if(t.G.isNullable(e)||B(e))return e;if(t.G.isArray(e))return e.map(e=>T(e));if(t.G.isObject(e)&&$(e)){const t=Object.entries(e).map(([e,t])=>[e,T(t)]);return{...Object.fromEntries(t),[L.tag]:e[L.tag]??L.id()}}return e}function D(e){if(Array.isArray(e))return e.filter(e=>L.tag in e).map(e=>e[L.tag]??"").join(",");const t=e[L.tag];if(t)return t;try{return JSON.stringify(e)}catch{return`[unserializable:${typeof e}]`}}function $(e){const t=Object.getPrototypeOf(e);return t===Object.prototype||null===t}function B(e){return t.G.isNullable(e)||t.G.isString(e)||t.G.isNumber(e)||t.G.isBoolean(e)||"symbol"==typeof e||"bigint"==typeof e}function W(e,n,r,o,c,s){return function i(a,u=n.path){if(a instanceof U){const n=z(r,u.join("."));if(Object.entries(a).filter(([e,t])=>!U.keys.has(e)&&t instanceof U).forEach(([e,t])=>i(t,u.concat(e))),B(a.value)){if(e===R.Hydrate)return a.value;const i=u.slice(0,-1),l=i.length>0?z(r,i.join(".")):r;return t.G.isNullable(l)||F(l,a,u.at(-1),o,c,s),n??a.value}if(e===R.Hydrate){const e=T(i(a.value,u));return F(e,a,null,o,c,s),e}const l=n??T(a.value);return F(l,a,null,o,c,s),t.G.isNullable(n)?l:(i(a.value,u),n)}if(t.G.isArray(a))return a.map((e,t)=>i(e,u.concat(t)));if(t.G.isObject(a)&&!$(a))return a;if(t.G.isObject(a)){const t=Object.entries(a).map(([e,t])=>[e,i(t,u.concat(e))]),n=Object.fromEntries(t);if(e===R.Hydrate){const e=T(n);return Object.entries(a).forEach(([t,n])=>{n instanceof U&&B(n.value)&&F(e,n,t,o,c,s)}),e}return n}return a}(n.value)}function F(e,t,n,r,o,c){const s=c(e),i=o.get(s)??[];o.set(s,[t.assign(n,r),...i])}class H{#e={};#t;#n=new Map;#r=new Set;#o=!1;constructor(e=D){this.#t=e}static pk(){return G()}static"κ"=H.pk;annotate(e,t){return new U(t,e)}"δ"=this.annotate;get model(){return this.#e}get inspect(){return function(e,n,r,o,c){function s(o){const c=o.at(-1),s=z(e(),o),i=o.slice(0,-1),a=t.A.isNotEmpty(i)?z(e(),i):e();return[...t.G.isObject(s)||t.G.isArray(s)?n.get(r(s))?.filter(e=>t.G.isNullable(e.property))??[]:[],...t.G.isObject(a)?n.get(r(a))?.filter(e=>e.property===c)??[]:[]]}return function n(r){return new Proxy(()=>{},{get:(i,a)=>"pending"===a?()=>!t.A.isEmpty(s(r)):"remaining"===a?()=>t.A.length(s(r)):"box"===a?()=>({value:z(e(),r),inspect:n(r)}):"is"===a?e=>s(r).some(t=>0!==(t.operation&e)):"draft"===a?()=>t.A.head(s(r))?.value??z(e(),r):"settled"===a?()=>new Promise(n=>{if(t.A.isEmpty(s(r)))return n(z(e(),r));const i=()=>{t.A.isEmpty(s(r))&&(c(i),n(z(e(),r)))};o(i)}):n([...r,String(a)])})}([])}(()=>this.#e,this.#n,this.#t,e=>this.#r.add(e),e=>this.#r.delete(e))}hydrate(e){return this.#o=!0,this.#c(R.Hydrate,()=>e)}produce(e){if(!this.#o)throw new Error("State must be hydrated using hydrate() before calling produce()");return this.#c(R.Produce,e)}#c(e,t){const n=Symbol("process"),[,r]=L.immer.produceWithPatches(this.#e,t);return this.#e=r.reduce((t,r)=>L.immer.applyPatches(t,[{...r,value:W(e,r,t,n,this.#n,this.#t)}]),this.#e),this.#e=T(this.#e),this.#s(),n}prune(e){this.#n.forEach((n,r)=>{const o=n.filter(t=>t.process!==e);t.A.isEmpty(o)?this.#n.delete(r):this.#n.set(r,o)}),this.#s()}#s(){this.#r.forEach(e=>e())}observe(e){const t=()=>e(this.#e);return this.#r.add(t),()=>this.#r.delete(t)}}const I=new H;function q(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var V,J={exports:{}},K=(V||(V=1,function(e){var t=Object.prototype.hasOwnProperty,n="~";function r(){}function o(e,t,n){this.fn=e,this.context=t,this.once=n||!1}function c(e,t,r,c,s){if("function"!=typeof r)throw new TypeError("The listener must be a function");var i=new o(r,c||e,s),a=n?n+t:t;return e._events[a]?e._events[a].fn?e._events[a]=[e._events[a],i]:e._events[a].push(i):(e._events[a]=i,e._eventsCount++),e}function s(e,t){0===--e._eventsCount?e._events=new r:delete e._events[t]}function i(){this._events=new r,this._eventsCount=0}Object.create&&(r.prototype=Object.create(null),(new r).__proto__||(n=!1)),i.prototype.eventNames=function(){var e,r,o=[];if(0===this._eventsCount)return o;for(r in e=this._events)t.call(e,r)&&o.push(n?r.slice(1):r);return Object.getOwnPropertySymbols?o.concat(Object.getOwnPropertySymbols(e)):o},i.prototype.listeners=function(e){var t=this._events[n?n+e:e];if(!t)return[];if(t.fn)return[t.fn];for(var r=0,o=t.length,c=new Array(o);r<o;r++)c[r]=t[r].fn;return c},i.prototype.listenerCount=function(e){var t=this._events[n?n+e:e];return t?t.fn?1:t.length:0},i.prototype.emit=function(e,t,r,o,c,s){var i=n?n+e:e;if(!this._events[i])return!1;var a,u,l=this._events[i],f=arguments.length;if(l.fn){switch(l.once&&this.removeListener(e,l.fn,void 0,!0),f){case 1:return l.fn.call(l.context),!0;case 2:return l.fn.call(l.context,t),!0;case 3:return l.fn.call(l.context,t,r),!0;case 4:return l.fn.call(l.context,t,r,o),!0;case 5:return l.fn.call(l.context,t,r,o,c),!0;case 6:return l.fn.call(l.context,t,r,o,c,s),!0}for(u=1,a=new Array(f-1);u<f;u++)a[u-1]=arguments[u];l.fn.apply(l.context,a)}else{var d,h=l.length;for(u=0;u<h;u++)switch(l[u].once&&this.removeListener(e,l[u].fn,void 0,!0),f){case 1:l[u].fn.call(l[u].context);break;case 2:l[u].fn.call(l[u].context,t);break;case 3:l[u].fn.call(l[u].context,t,r);break;case 4:l[u].fn.call(l[u].context,t,r,o);break;default:if(!a)for(d=1,a=new Array(f-1);d<f;d++)a[d-1]=arguments[d];l[u].fn.apply(l[u].context,a)}}return!0},i.prototype.on=function(e,t,n){return c(this,e,t,n,!1)},i.prototype.once=function(e,t,n){return c(this,e,t,n,!0)},i.prototype.removeListener=function(e,t,r,o){var c=n?n+e:e;if(!this._events[c])return this;if(!t)return s(this,c),this;var i=this._events[c];if(i.fn)i.fn!==t||o&&!i.once||r&&i.context!==r||s(this,c);else{for(var a=0,u=[],l=i.length;a<l;a++)(i[a].fn!==t||o&&!i[a].once||r&&i[a].context!==r)&&u.push(i[a]);u.length?this._events[c]=1===u.length?u[0]:u:s(this,c)}return this},i.prototype.removeAllListeners=function(e){var t;return e?this._events[t=n?n+e:e]&&s(this,t):(this._events=new r,this._eventsCount=0),this},i.prototype.off=i.prototype.removeListener,i.prototype.addListener=i.prototype.on,i.prefixed=n,i.EventEmitter=i,e.exports=i}(J)),J.exports);const Q=q(K);class X extends Q{cache=new Map;emit(e,...t){return this.cache.set(e,t[0]),super.emit(e,...t)}setCache(e,t){this.cache.set(e,t)}getCached(e){return this.cache.get(e)}}const Y=s.createContext(new X);function Z(){return s.useContext(Y)}function ee({children:e}){const t=s.useMemo(()=>new X,[]);return n.jsx(Y.Provider,{value:t,children:e})}const te=s.createContext(new Map);function ne({children:e}){const t=s.useMemo(()=>new Map,[]);return n.jsx(te.Provider,{value:t,children:e})}const re=s.createContext(new Set);function oe({children:e}){const t=s.useMemo(()=>new Set,[]);return n.jsx(re.Provider,{value:t,children:e})}const ce=s.createContext({mode:"allow-all",actions:new Set});function se({children:e}){const t=s.useMemo(()=>({mode:"allow-all",actions:new Set}),[]);return n.jsx(ce.Provider,{value:t,children:e})}const ie=s.createContext(null);function ae(){return s.useContext(ie)}function ue(e,t){return e?.get(t)??null}function le({name:e,children:t}){const r=ae(),o=s.useMemo(()=>({name:e,emitter:new X}),[]),c=s.useMemo(()=>{const t=new Map(r??[]);return t.set(e,o),t},[r,e,o]);return n.jsx(ie.Provider,{value:c,children:t})}function fe(e,t,n){const r=e.features;switch(n){case f.On:r[t]=!0;break;case f.Off:r[t]=!1;break;case f.Toggle:r[t]=!r[t]}}function de(e,t,...n){e instanceof X&&e.setCache(t,n[0]);const r=e.listeners(t);return 0===r.length?Promise.resolve():Promise.all(r.map(e=>Promise.resolve(e(...n)))).then(()=>{})}function he(e,t){for(const n of e.keys())if(O(n)===t)return n;return null}function pe(){const[,e]=s.useReducer(e=>e+1,0);return e}const me=s.createContext(new Map);function be({action:e,renderer:n}){const r=Z(),o=s.useContext(me),c=pe(),i=s.useMemo(()=>{const t=o.get(e);if(t)return t;const n={state:new H,listeners:new Set};return o.set(e,n),n},[e,o]);s.useLayoutEffect(()=>{function t(e){i.state.hydrate({value:e}),i.listeners.forEach(e=>e())}return i.listeners.add(c),r.on(e,t),()=>{i.listeners.delete(c),r.off(e,t)}},[e,r,i]);const a=i.state.model?.value;return t.G.isNullable(a)?null:n(a,i.state.inspect.value)}e.Action=(e,t=u.Unicast)=>{const n=t===u.Broadcast?Symbol(`${m.broadcastActionPrefix}${e}`):t===u.Multicast?Symbol(`${m.multicastActionPrefix}${e}`):Symbol(`${m.actionPrefix}${e}`),r=function(e){return{[i.Action]:n,[i.Payload]:void 0,[i.Channel]:e,channel:e}};return Object.defineProperty(r,i.Action,{value:n,enumerable:!1}),Object.defineProperty(r,i.Payload,{value:void 0,enumerable:!1}),t===u.Broadcast&&Object.defineProperty(r,i.Broadcast,{value:!0,enumerable:!1}),t===u.Multicast&&Object.defineProperty(r,i.Multicast,{value:!0,enumerable:!1}),r},e.Boundary=function({children:e}){return n.jsx(ee,{children:n.jsx(ne,{children:n.jsx(se,{children:n.jsx(oe,{children:e})})})})},e.DisallowedError=p,e.Distribution=u,e.Entry=function(){const e=Symbol("chizu.cache/Entry"),t=function(t){return{[i.Cache]:e,channel:t}};return Object.defineProperty(t,i.Cache,{value:e,enumerable:!1}),t},e.Error=function({handler:e,children:t}){return n.jsx(k.Provider,{value:e,children:t})},e.Feature=f,e.Lifecycle=class{static Mount(){return a("Mount")}static Unmount(){return a("Unmount")}static Error(){return a("Error")}static Update(){return a("Update")}static Node(){return a("Node")}},e.Op=_,e.Operation=_,e.Reason=d,e.Regulators=se,e.Scope=le,e.State=H,e.With=function(e){return(t,n)=>{t.actions.produce(t=>{t.model[e]=n})}},e.annotate=function(e,t){return I.annotate(e,t)},e.useActions=function(...e){const n=t.G.isUndefined(e[0])||t.G.isFunction(e[0])?{}:e[0],o=t.G.isFunction(e[0])?e[0]:e[1]??(()=>({})),c=Z(),i=ae(),a=r.useContext(k),u=s.useContext(re),f=s.useContext(te),h=s.useContext(ce),m=pe(),b=s.useRef(!1),y=s.useRef(null),v=s.useRef(new H);b.current||(b.current=!0,y.current=v.current.hydrate(n));const[g,w]=s.useState(()=>v.current.model),O=function(e){const t=s.useRef(e);return s.useLayoutEffect(()=>{t.current=e},[e]),s.useMemo(()=>{return n=t,Object.keys(e).reduce((e,t)=>(Object.defineProperty(e,t,{get:()=>n.current[t],enumerable:!0}),e),{});var n},[e])}(o()),G=s.useMemo(()=>new Q,[]),_=s.useRef({handlers:new Map});_.current.handlers=new Map;const R=function(){const e=s.useRef(new Set),t=s.useRef(new Set);return s.useMemo(()=>({broadcast:e.current,multicast:t.current}),[])}(),N=s.useRef(l.Mounting),U=function(){const e=s.useRef({}),t=s.useRef(new Map),n=s.useRef(new Map);return s.useMemo(()=>({refs:e,pending:t,emitted:n}),[])}(),L=s.useRef(new Set),z=s.useRef(0),T=s.useCallback((e,t,n)=>{const r=new AbortController,o={controller:r,action:e,payload:t};return u.add(o),L.current.add(o),{model:v.current.model,get phase(){return N.current},task:o,data:O,tasks:u,nodes:U.refs.current,regulator:{disallow(...e){if(h.actions.clear(),0===e.length)h.mode="disallow-all";else{h.mode="disallow-matching";for(const t of e)h.actions.add(x(t))}},allow(...e){if(h.actions.clear(),0===e.length)h.mode="allow-all";else{h.mode="allow-matching";for(const t of e)h.actions.add(x(t))}}},actions:{produce(e){if(r.signal.aborted)return;const t=v.current.produce(t=>e({model:t,inspect:v.current.inspect}));w(v.current.model),n.processes.add(t),y.current&&(n.processes.add(y.current),y.current=null)},dispatch(e,t,n){if(r.signal.aborted)return Promise.resolve();const o=x(e),s=S(e)?e.channel:void 0;if(E(e)&&n?.scope){const e=ue(i,n.scope);return e?de(e.emitter,o,t,s):Promise.resolve()}return de(j(e)?c:G,o,t,s)},annotate:(e,t)=>v.current.annotate(e,t),async cacheable(e,t,n){if(r.signal.aborted)return{data:null};const o=A(e),c=f.get(o);if(c&&Date.now()<c.expiry)return{data:c.value};const s=function(e){return null!=e&&"object"==typeof e&&"TAG"in e?0===e.TAG?{ok:!0,value:e._0}:{ok:!1}:null==e?{ok:!1}:{ok:!0,value:e}}(await n());return s.ok?(f.set(o,{value:s.value,expiry:Date.now()+t}),{data:s.value}):{data:null}},invalidate(e){f.delete(A(e))},feature(e,t){if(r.signal.aborted)return;const o=v.current.produce(n=>fe(n,e,t));w(v.current.model),n.processes.add(o),y.current&&(n.processes.add(y.current),y.current=null)},async read(e,t){if(r.signal.aborted)return null;const n=x(e),o=E(e)&&t?.scope?ue(i,t.scope)?.emitter??null:c;if(!o)return null;if(void 0===o.getCached(n))return null;const s=P(e),a="unknown"!==s?s[0].toLowerCase()+s.slice(1):null;if(a){const e=v.current.inspect[a];e?.pending?.()&&await new Promise((t,n)=>{if(r.signal.aborted)return void n(r.signal.reason);const o=()=>n(r.signal.reason);r.signal.addEventListener("abort",o,{once:!0}),e.settled().then(()=>{r.signal.removeEventListener("abort",o),t()})})}return o.getCached(n)??null},peek(e,t){if(r.signal.aborted)return null;const n=x(e),o=E(e)&&t?.scope?ue(i,t.scope)?.emitter??null:c;return o?o.getCached(n)??null:null}}}},[g]);s.useLayoutEffect(()=>{function e(e,n,r){return function(o,c){if(!function(e,t){switch(t.mode){case"allow-all":return!0;case"disallow-all":return!1;case"disallow-matching":return!t.actions.has(e);case"allow-matching":return t.actions.has(e)}}(e,h)){const t=he(_.current.handlers,"Error"),n=null!==t,r={reason:d.Disallowed,error:new p,action:P(e),handled:n,tasks:u};return a?.(r),void(n&&t&&G.emit(t,r))}const s=r();if(t.G.isNotNullable(c)&&t.G.isNotNullable(s)&&!function(e,t){for(const n of Object.keys(e))if(t[n]!==e[n])return!1;return!0}(c,s))return;const i={processes:new Set},l=Promise.withResolvers(),f=T(e,o,i);function b(t){const n=he(_.current.handlers,"Error"),r=null!==n,o={reason:C(t),error:M(t),action:P(e),handled:r,tasks:u};a?.(o),r&&n&&G.emit(n,o)}function y(){for(const e of u)if(e===f.task){u.delete(e),L.current.delete(e);break}i.processes.forEach(e=>v.current.prune(e)),i.processes.size>0&&m(),l.resolve()}let g;try{g=n(f,o)}catch(w){return b(w),void y()}if(!function(e){if(!e||"object"!=typeof e)return!1;const t=Object.prototype.toString.call(e);return"[object Generator]"===t||"[object AsyncGenerator]"===t}(g))return Promise.resolve(g).catch(b).finally(y),l.promise;(async()=>{for await(const e of g);})().catch(b).finally(y)}}z.current++;const n=new Set;return _.current.handlers.forEach((t,r)=>{for(const{getChannel:o,handler:s}of t){const t=e(r,s,o);if(E(r)){if(i)for(const e of i.values()){const o=e.emitter;o.on(r,t),n.add(()=>o.off(r,t))}G.on(r,t),R.multicast.add(r),n.add(()=>G.off(r,t))}else j(r)?(c.on(r,t),G.on(r,t),R.broadcast.add(r),n.add(()=>{c.off(r,t),G.off(r,t)})):(G.on(r,t),n.add(()=>G.off(r,t)))}}),()=>{const e=++z.current,t=new Set(n);queueMicrotask(()=>{if(z.current!==e){for(const e of t)e();return}for(const e of L.current)e.controller.abort(),u.delete(e);L.current.clear(),N.current=l.Unmounting;const n=he(_.current.handlers,"Unmount");n&&G.emit(n),N.current=l.Unmounted;for(const e of t)e()})}},[G]),s.useLayoutEffect(()=>{const e=he(_.current.handlers,"Node");for(const[t,n]of U.pending.current)U.emitted.current.get(t)!==n&&(U.emitted.current.set(t,n),e&&G.emit(e,n,{Name:t}));U.pending.current.clear()}),function({unicast:e,broadcast:n,dispatchers:r,scope:o,phase:c,data:i,handlers:a}){const u=s.useRef(null);s.useLayoutEffect(()=>{if(c.current!==l.Mounting)return;const s=he(a,"Mount");s&&e.emit(s),r.broadcast.forEach(r=>{const o=n.getCached(r);t.G.isNullable(o)||e.emit(r,o)}),o&&r.multicast.forEach(n=>{for(const r of o.values()){const o=r.emitter.getCached(n);t.G.isNullable(o)||e.emit(n,o)}}),c.current=l.Mounted},[]),s.useLayoutEffect(()=>{if(t.G.isNotNullable(u.current)){const n=function(e,t){return Object.keys(t).reduce((n,r)=>e[r]!==t[r]?{...n,[r]:t[r]}:n,{})}(u.current,i);if(t.A.isNotEmpty(Object.keys(n))){const t=he(a,"Update");t&&e.emit(t,n)}}u.current=i},[i,e])}({unicast:G,broadcast:c,dispatchers:R,scope:i,phase:N,data:o(),handlers:_.current.handlers});const D=s.useMemo(()=>[g,{dispatch(e,t,n){const r=x(e),o=S(e)?e.channel:void 0;if(E(e)&&n?.scope){const e=ue(i,n.scope);return e?de(e.emitter,r,t,o):Promise.resolve()}return de(j(e)?c:G,r,t,o)},get inspect(){return v.current.inspect},get nodes(){return U.refs.current},node(e,t){U.refs.current[e]=t,U.pending.current.set(e,t)},feature(e,t){const n=v.current.produce(n=>fe(n,e,t));w(v.current.model),v.current.prune(n)},stream:(e,t)=>s.createElement(be,{action:x(e),renderer:t})}],[g,G]);return D.useAction=(e,t)=>{!function(e,t,n){const r=s.useRef(n);s.useLayoutEffect(()=>{r.current=n});const o=s.useRef(t);s.useLayoutEffect(()=>{o.current=t});const c=s.useCallback((e,t)=>r.current(e,t),[]),i=s.useCallback(()=>S(o.current)?o.current.channel:void 0,[]),a=x(t),u=e.current.handlers.get(a)??new Set;0===u.size&&e.current.handlers.set(a,u),u.add({getChannel:i,handler:c})}(_,e,t)},D},e.utils=g,e.withScope=function(e,t){const r=`Scoped${t.displayName||t.name||"Component"}`;return{[r]:r=>n.jsx(le,{name:e,children:n.jsx(t,{...r})})}[r]},Object.defineProperty(e,Symbol.toStringTag,{value:"Module"})},"object"==typeof exports&&"undefined"!=typeof module?factory(exports,require("@mobily/ts-belt"),require("react/jsx-runtime"),require("react"),require("immer")):"function"==typeof define&&define.amd?define(["exports","@mobily/ts-belt","react/jsx-runtime","react","immer"],factory):factory((global="undefined"!=typeof globalThis?globalThis:global||self).Chizu={},global.TsBelt,global.jsxRuntime,global.React,global.Immer);
@@ -1,6 +1,6 @@
1
1
  import { Props } from './types';
2
2
  export { useError } from './utils';
3
- export { Reason, AbortError, TimeoutError } from './types';
3
+ export { Reason, AbortError, TimeoutError, DisallowedError } from './types';
4
4
  export type { Fault, Catcher } from './types';
5
5
  /**
6
6
  * Error boundary component for catching and handling errors from actions.
@@ -42,6 +42,19 @@ export declare class TimeoutError extends Error {
42
42
  name: string;
43
43
  constructor(message?: string);
44
44
  }
45
+ /**
46
+ * Error thrown when an action is blocked by the regulator policy.
47
+ * Works across all platforms including React Native where `DOMException` is unavailable.
48
+ *
49
+ * @example
50
+ * ```ts
51
+ * throw new DisallowedError("Action blocked by regulator");
52
+ * ```
53
+ */
54
+ export declare class DisallowedError extends Error {
55
+ name: string;
56
+ constructor(message?: string);
57
+ }
45
58
  /**
46
59
  * Details about an error that occurred during action execution.
47
60
  * @template E Custom error types to include in the union with Error.
@@ -53,7 +66,7 @@ export type Fault<E extends Error = never> = {
53
66
  error: Error | E;
54
67
  /** The name of the action that caused the error (e.g., "Increment"). */
55
68
  action: string;
56
- /** Whether the component has a `Lifecycle.Error` handler registered. */
69
+ /** Whether the component has a `Lifecycle.Error()` handler registered. */
57
70
  handled: boolean;
58
71
  /**
59
72
  * All currently running tasks across the application.
@@ -83,4 +83,6 @@ export type LifecycleConfig = {
83
83
  phase: RefObject<Phase>;
84
84
  /** Current snapshot of reactive data props for change detection */
85
85
  data: Props;
86
+ /** Handler registry for lifecycle action discovery */
87
+ handlers: Map<ActionId, Set<unknown>>;
86
88
  };
@@ -1,5 +1,6 @@
1
1
  import { RefObject } from 'react';
2
- import { Props, Model, Actions, Filter, ActionId, HandlerPayload, ChanneledAction, HandlerContext } from '../types/index.ts';
2
+ import { Props, Model, Actions, Filter, ActionId, HandlerPayload, ChanneledAction, HandlerContext, Feature } from '../types/index.ts';
3
+ import { default as EventEmitter } from 'eventemitter3';
3
4
  import { Dispatchers, LifecycleConfig, References, Scope } from './types.ts';
4
5
  import { isChanneledAction, getActionSymbol } from '../action/index.ts';
5
6
  import * as React from "react";
@@ -9,9 +10,26 @@ import * as React from "react";
9
10
  */
10
11
  export declare function withGetters<P extends Props>(a: P, b: RefObject<P>): P;
11
12
  /**
12
- * Checks if the given result is a generator or async generator.
13
+ * Checks if the given result is a generator or async generator object.
14
+ * Uses `Object.prototype.toString` which reliably returns
15
+ * `"[object Generator]"` or `"[object AsyncGenerator]"` regardless of
16
+ * the generator function's name.
13
17
  */
14
18
  export declare function isGenerator(result: unknown): result is Generator | AsyncGenerator;
19
+ /**
20
+ * Applies a Feature operation to a boolean feature flag on an Immertation draft.
21
+ * @internal
22
+ */
23
+ export declare function applyFeature(draft: Record<string, unknown>, name: string, operation: Feature): void;
24
+ /**
25
+ * Invokes all listeners for an event and returns a promise that resolves
26
+ * when every handler has settled. For {@link BroadcastEmitter} instances the
27
+ * payload is cached before listeners fire so late-mounting components still
28
+ * see the latest value.
29
+ *
30
+ * @internal
31
+ */
32
+ export declare function emitAsync(emitter: EventEmitter, event: string | symbol, ...args: unknown[]): Promise<void>;
15
33
  /**
16
34
  * Emits lifecycle events for component mount and DOM attachment.
17
35
  * Also invokes broadcast action handlers with cached values on mount.
@@ -24,7 +42,7 @@ export declare function isGenerator(result: unknown): result is Generator | Asyn
24
42
  * - Mounting → (cached broadcast action values emitted here) → Mounted
25
43
  * - Mounted → Unmounting → Unmounted
26
44
  */
27
- export declare function useLifecycles({ unicast, broadcast, dispatchers, scope, phase, data, }: LifecycleConfig): void;
45
+ export declare function useLifecycles({ unicast, broadcast, dispatchers, scope, phase, data, handlers, }: LifecycleConfig): void;
28
46
  /**
29
47
  * Creates a data proxy for a given object, returning a memoized version.
30
48
  * The proxy provides stable access to the object's properties,
@@ -69,6 +87,23 @@ export declare function useData<P extends Props>(props: P): P;
69
87
  * ```
70
88
  */
71
89
  export declare function With<K extends string>(key: K): <M extends Model, A extends Actions | void, D extends Props, P extends K extends keyof M ? M[K] : never>(context: HandlerContext<M, A, D>, payload: P) => void;
90
+ /**
91
+ * Scans a handler registry for a lifecycle action of the given type.
92
+ *
93
+ * When lifecycle actions become per-class instances (via `Lifecycle.Mount()`),
94
+ * each Actions class has its own unique symbol. Emission sites can no longer
95
+ * emit to a shared singleton — they must discover the component's lifecycle
96
+ * action by scanning the registry keys for matching lifecycle prefixes.
97
+ *
98
+ * Handler maps typically contain 5–15 entries, so the O(n) scan is trivial.
99
+ *
100
+ * @param handlers The handler map from a component's scope.
101
+ * @param type The lifecycle type to find (e.g. `"Mount"`, `"Unmount"`, `"Error"`).
102
+ * @returns The matching ActionId, or `null` if no lifecycle action of that type is registered.
103
+ *
104
+ * @internal
105
+ */
106
+ export declare function findLifecycleAction(handlers: Map<ActionId, Set<unknown>>, type: string): ActionId | null;
72
107
  export { isChanneledAction, getActionSymbol };
73
108
  /**
74
109
  * Manages sets of broadcast and multicast action IDs.
package/dist/index.d.ts CHANGED
@@ -1,13 +1,15 @@
1
1
  export { Action } from './action/index.ts';
2
2
  export { Entry } from './cache/index.ts';
3
- export { Distribution, Lifecycle } from './types/index.ts';
4
- export { Error, Reason } from './error/index.tsx';
3
+ export { Distribution, Feature, Lifecycle } from './types/index.ts';
4
+ export { Error, Reason, DisallowedError } from './error/index.tsx';
5
5
  export { Operation, Op, State } from 'immertation';
6
6
  export { annotate } from './annotate/index.ts';
7
7
  export { Boundary } from './boundary/index.tsx';
8
+ export { Regulators } from './boundary/components/regulators/index.tsx';
8
9
  export { Scope, withScope } from './boundary/components/scope/index.tsx';
9
10
  export { useActions, With } from './hooks/index.ts';
10
11
  export * as utils from './utils/index.ts';
11
12
  export type { Box } from 'immertation';
12
13
  export type { Fault, Catcher } from './error/index.tsx';
13
14
  export type { Pk, Task, Tasks, Handlers } from './types/index.ts';
15
+ export type { Regulator } from './boundary/components/regulators/index.tsx';
@@ -2,6 +2,8 @@ import { Operation, Process, Inspect, Box } from 'immertation';
2
2
  import { ActionId, Task, Tasks } from '../boundary/components/tasks/types.ts';
3
3
  import { Option } from '@mobily/ts-belt/Option';
4
4
  import { Result as TsBeltResult } from '@mobily/ts-belt/Result';
5
+ import { Regulator } from '../boundary/components/regulators/types.ts';
6
+ import { Fault } from '../error/types.ts';
5
7
  import * as React from "react";
6
8
  export type { ActionId, Box, Task, Tasks };
7
9
  /**
@@ -94,49 +96,59 @@ export type ChanneledCacheId<T = unknown, C = unknown> = {
94
96
  readonly channel: C;
95
97
  };
96
98
  /**
97
- * Lifecycle actions that trigger at specific points in a component's lifecycle.
98
- * Define handlers for these in your actions class to respond to lifecycle events.
99
+ * Factory functions for lifecycle actions.
100
+ *
101
+ * Each call returns a **unique** action symbol, enabling per-component
102
+ * regulation. Assign the result as a static property in your Actions class:
99
103
  *
100
104
  * @example
101
105
  * ```ts
102
- * class {
103
- * [Lifecycle.Mount] = mountAction;
104
- * [Lifecycle.Error] = errorAction;
105
- * [Lifecycle.Unmount] = unmountAction;
106
+ * export class Actions {
107
+ * static Mount = Lifecycle.Mount();
108
+ * static Unmount = Lifecycle.Unmount();
109
+ * static Error = Lifecycle.Error();
110
+ * static Update = Lifecycle.Update();
111
+ * static Node = Lifecycle.Node();
112
+ *
113
+ * static Increment = Action("Increment");
106
114
  * }
115
+ *
116
+ * // Now regulating Lifecycle.Mount only blocks THIS component's mount:
117
+ * context.regulator.disallow(Actions.Mount);
107
118
  * ```
108
119
  */
109
120
  export declare class Lifecycle {
110
- /** Triggered once when the component mounts (`useLayoutEffect`). */
111
- static readonly Mount: unique symbol;
112
- /** Triggered when the component unmounts. */
113
- static readonly Unmount: unique symbol;
114
- /** Triggered when an action throws an error. Receives `Fault` as payload. */
115
- static readonly Error: unique symbol;
116
- /** Triggered when `context.data` has changed. Not fired on initial mount. Receives `Record<string, unknown>` payload with changed keys. */
117
- static readonly Update: unique symbol;
121
+ /** Creates a Mount lifecycle action. Triggered once on component mount (`useLayoutEffect`). */
122
+ static Mount(): HandlerPayload<never>;
123
+ /** Creates an Unmount lifecycle action. Triggered when the component unmounts. */
124
+ static Unmount(): HandlerPayload<never>;
125
+ /** Creates an Error lifecycle action. Triggered when an action throws. Receives `Fault` as payload. */
126
+ static Error(): HandlerPayload<Fault>;
127
+ /** Creates an Update lifecycle action. Triggered when `context.data` changes (not on initial mount). */
128
+ static Update(): HandlerPayload<Record<string, unknown>>;
118
129
  /**
119
- * Triggered when a node is captured or released via `actions.node()`.
120
- * Supports channeled subscriptions by node name.
121
- *
122
- * The payload is the captured node (or `null` when released).
130
+ * Creates a Node lifecycle action. Triggered when a DOM node is captured
131
+ * or released via `actions.node()`. Supports channeled subscriptions by
132
+ * node name.
123
133
  *
124
134
  * @example
125
135
  * ```ts
136
+ * export class Actions {
137
+ * static Node = Lifecycle.Node();
138
+ * }
139
+ *
126
140
  * // Subscribe to ALL node changes
127
- * actions.useAction(Lifecycle.Node, (context, node) => {
141
+ * actions.useAction(Actions.Node, (context, node) => {
128
142
  * console.log("Node changed:", node);
129
143
  * });
130
144
  *
131
145
  * // Subscribe to a specific node by name (channeled)
132
- * actions.useAction(Lifecycle.Node({ Name: "input" }), (context, node) => {
133
- * if (node) {
134
- * node.focus();
135
- * }
146
+ * actions.useAction(Actions.Node({ Name: "input" }), (context, node) => {
147
+ * if (node) node.focus();
136
148
  * });
137
149
  * ```
138
150
  */
139
- static Node: HandlerPayload<unknown, {
151
+ static Node(): HandlerPayload<unknown, {
140
152
  Name: string;
141
153
  }>;
142
154
  }
@@ -193,6 +205,24 @@ export declare enum Phase {
193
205
  /** Component has fully unmounted. */
194
206
  Unmounted = "unmounted"
195
207
  }
208
+ /**
209
+ * Operations for toggling boolean feature flags via `actions.feature()`.
210
+ *
211
+ * @example
212
+ * ```ts
213
+ * actions.feature("sidebar", Feature.Toggle);
214
+ * actions.feature("sidebar", Feature.On);
215
+ * actions.feature("sidebar", Feature.Off);
216
+ * ```
217
+ */
218
+ export declare enum Feature {
219
+ /** Sets the feature to `true`. */
220
+ On = "on",
221
+ /** Sets the feature to `false`. */
222
+ Off = "off",
223
+ /** Inverts the current boolean value. */
224
+ Toggle = "toggle"
225
+ }
196
226
  /**
197
227
  * Primary key type for identifying entities in collections.
198
228
  * Can be undefined (not yet assigned), a symbol (temporary/local), or a concrete value T.
@@ -424,7 +454,23 @@ export type Props = Record<string, unknown>;
424
454
  */
425
455
  export type Nodes<M> = M extends {
426
456
  nodes: infer N extends Record<string, unknown>;
427
- } ? N : Record<string, never>;
457
+ } ? N : Record<never, unknown>;
458
+ /**
459
+ * Extracts the `features` property from a Model type.
460
+ * If the model has a `features` property whose values are all booleans,
461
+ * returns its type. Otherwise returns an empty record, making the
462
+ * `feature()` method effectively uncallable.
463
+ *
464
+ * @example
465
+ * ```ts
466
+ * enum Feature { Sidebar = 'Sidebar', Modal = 'Modal' }
467
+ * type Model = { count: number; features: { [K in Feature]: boolean } };
468
+ * type F = Features<Model>; // { Sidebar: boolean; Modal: boolean }
469
+ * ```
470
+ */
471
+ export type FeatureFlags<M> = M extends {
472
+ features: infer F extends Record<string, boolean>;
473
+ } ? F : Record<never, boolean>;
428
474
  /**
429
475
  * Constraint type for action containers.
430
476
  * Actions are symbols grouped in an object (typically a class with static properties).
@@ -540,12 +586,32 @@ export type HandlerContext<M extends Model | void, _AC extends Actions | void, D
540
586
  readonly nodes: {
541
587
  [K in keyof Nodes<M>]: Nodes<M>[K] | null;
542
588
  };
589
+ /**
590
+ * The regulator API for controlling which actions may be dispatched.
591
+ *
592
+ * Each call replaces the previous policy entirely (last-write-wins).
593
+ * The policy is shared across all components within the same `<Boundary>`.
594
+ *
595
+ * @example
596
+ * ```ts
597
+ * actions.useAction(Actions.Mount, (context) => {
598
+ * // Block all actions except Critical
599
+ * context.regulator.allow(Actions.Critical);
600
+ * });
601
+ *
602
+ * actions.useAction(Actions.Unlock, (context) => {
603
+ * // Re-allow all actions
604
+ * context.regulator.allow();
605
+ * });
606
+ * ```
607
+ */
608
+ readonly regulator: Regulator;
543
609
  readonly actions: {
544
610
  produce<F extends (draft: {
545
611
  model: M;
546
612
  readonly inspect: Readonly<Inspect<M>>;
547
613
  }) => void>(ƒ: F & AssertSync<F>): void;
548
- dispatch(action: ActionOrChanneled, payload?: unknown, options?: MulticastOptions): void;
614
+ dispatch(action: ActionOrChanneled, payload?: unknown, options?: MulticastOptions): Promise<void>;
549
615
  annotate<T>(operation: Operation, value: T): T;
550
616
  /**
551
617
  * Fetches a value from the cache or executes the callback if not cached / expired.
@@ -586,6 +652,19 @@ export type HandlerContext<M extends Model | void, _AC extends Actions | void, D
586
652
  * ```
587
653
  */
588
654
  invalidate(entry: CacheId<unknown> | ChanneledCacheId<unknown>): void;
655
+ /**
656
+ * Mutates a boolean feature flag on the model and triggers a re-render.
657
+ *
658
+ * Requires the model to have a `features` property whose keys are the feature names.
659
+ * Read feature state from `model.features` directly.
660
+ *
661
+ * @example
662
+ * ```ts
663
+ * context.actions.feature(Feature.Sidebar, Feature.Toggle);
664
+ * context.actions.feature(Feature.Sidebar, Feature.Off);
665
+ * ```
666
+ */
667
+ feature<K extends keyof FeatureFlags<M>>(name: K, operation: Feature): void;
589
668
  /**
590
669
  * Reads the latest broadcast or multicast value, waiting for annotations to settle.
591
670
  *
@@ -730,10 +809,10 @@ export type UseActions<M extends Model | void, AC extends Actions | void, D exte
730
809
  * @param payload - The payload to send with the action
731
810
  * @param options - For multicast actions, must include `{ scope: "ScopeName" }`
732
811
  */
733
- dispatch<P>(action: HandlerPayload<P>, payload?: P, options?: MulticastOptions): void;
734
- dispatch<P>(action: BroadcastPayload<P>, payload?: P, options?: MulticastOptions): void;
735
- dispatch<P>(action: MulticastPayload<P>, payload: P, options: MulticastOptions): void;
736
- dispatch<P, C extends Filter>(action: ChanneledAction<P, C>, payload?: P, options?: MulticastOptions): void;
812
+ dispatch<P>(action: HandlerPayload<P>, payload?: P, options?: MulticastOptions): Promise<void>;
813
+ dispatch<P>(action: BroadcastPayload<P>, payload?: P, options?: MulticastOptions): Promise<void>;
814
+ dispatch<P>(action: MulticastPayload<P>, payload: P, options: MulticastOptions): Promise<void>;
815
+ dispatch<P, C extends Filter>(action: ChanneledAction<P, C>, payload?: P, options?: MulticastOptions): Promise<void>;
737
816
  inspect: Inspect<M>;
738
817
  /**
739
818
  * Captured DOM nodes registered via `node()`.
@@ -781,6 +860,19 @@ export type UseActions<M extends Model | void, AC extends Actions | void, D exte
781
860
  * ```
782
861
  */
783
862
  node<K extends keyof Nodes<M>>(name: K, node: Nodes<M>[K] | null): void;
863
+ /**
864
+ * Mutates a boolean feature flag on the model and triggers a re-render.
865
+ *
866
+ * Read feature state from `model.features` directly.
867
+ *
868
+ * @example
869
+ * ```tsx
870
+ * actions.feature(Feature.Sidebar, Feature.Toggle);
871
+ *
872
+ * {model.features.Sidebar && <Sidebar />}
873
+ * ```
874
+ */
875
+ feature<K extends keyof FeatureFlags<M>>(name: K, operation: Feature): void;
784
876
  /**
785
877
  * Streams broadcast values declaratively in JSX using a render-prop pattern.
786
878
  *
@@ -13,6 +13,8 @@ export declare const config: {
13
13
  channelPrefix: string;
14
14
  /** Prefix for cache operation symbols. */
15
15
  cachePrefix: string;
16
+ /** Prefix for lifecycle action symbols. */
17
+ lifecyclePrefix: string;
16
18
  };
17
19
  /**
18
20
  * Returns a promise that resolves after the specified number of milliseconds.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "chizu",
3
- "version": "0.2.67",
3
+ "version": "0.2.71",
4
4
  "type": "module",
5
5
  "license": "MIT",
6
6
  "packageManager": "yarn@1.22.22",