chizu 0.2.71 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -31,7 +31,7 @@ For advanced topics, see the [recipes directory](./recipes/).
31
31
  - Built-in request cancellation with `AbortController`.
32
32
  - Granular async state tracking per model field.
33
33
  - Declarative lifecycle hooks without `useEffect`.
34
- - Centralised error handling via the `Error` component.
34
+ - Centralised error handling via the global `Lifecycle.Fault` broadcast.
35
35
  - React Native compatible – uses [eventemitter3](https://github.com/primus/eventemitter3) for cross-platform pub/sub.
36
36
 
37
37
  ## Getting started
@@ -196,7 +196,7 @@ Both `read` and `peek` access the latest cached broadcast value without subscrib
196
196
 
197
197
  ```tsx
198
198
  actions.useAction(Actions.FetchFriends, async (context) => {
199
- const name = await context.actions.read(Actions.Broadcast.Name);
199
+ const name = await context.actions.resolution(Actions.Broadcast.Name);
200
200
  if (!name) return;
201
201
  const friends = await fetch(api.friends(name));
202
202
  context.actions.produce(({ model }) => {
@@ -249,6 +249,78 @@ function Dashboard() {
249
249
 
250
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.
251
251
 
252
+ For remote data, declare a `Resource` at module scope – same shape as `Action` – and consume it via `actions.useResource` inside a component. Convention is to keep all resources in `resources.ts` and import them as a namespace:
253
+
254
+ ```ts
255
+ // resources.ts
256
+ import { Resource } from "chizu";
257
+
258
+ export const user = Resource("user", () => ky.get("/api/user").json<User>());
259
+ ```
260
+
261
+ ```tsx
262
+ // actions.ts
263
+ import * as resource from "./resources";
264
+
265
+ function useUserActions() {
266
+ const actions = useActions<Model, typeof Actions>(initialModel);
267
+ const fetchUser = actions.useResource(resource.user);
268
+
269
+ actions.useAction(Actions.Mount, async (context) => {
270
+ const data = await fetchUser();
271
+ context.actions.produce(({ model }) => {
272
+ model.user = data;
273
+ });
274
+ });
275
+
276
+ return actions;
277
+ }
278
+ ```
279
+
280
+ Every call to the thunk fetches fresh &ndash; concurrent calls share one in-flight request, but there is no stale cache. Coordination across components happens at the broadcast layer.
281
+
282
+ The fetcher may take arguments &ndash; the thunk forwards them, and in-flight dedup keys per arg-tuple. This is how you build pagination, search, and other dynamic-param fetches:
283
+
284
+ ```ts
285
+ export const feed = Resource("feed", (cursor: string | null) =>
286
+ http
287
+ .get("feed", { searchParams: { cursor: cursor ?? "" } })
288
+ .json<Page<Item>>(),
289
+ );
290
+
291
+ const fetchFeed = actions.useResource(resource.feed);
292
+ const page = await fetchFeed(context.model.cursor);
293
+ ```
294
+
295
+ A complete IntersectionObserver-driven infinite-scroll demo lives at [`src/example/transactions/`](./src/example/transactions/) &ndash; mock paginated API, scroll-triggered `LoadMore`, `pending()` guard, broadcast on success.
296
+
297
+ Pass an `onSuccess` callback to fan a fresh fetch out as a broadcast event &ndash; the callback receives a `context` with `response`, `data` (the consuming component's reactive proxy), and `dispatch` (pre-bound to the surrounding `<Boundary>`'s broadcaster):
298
+
299
+ ```ts
300
+ export const user = Resource(
301
+ "user",
302
+ () => ky.get("/api/user").json<User>(),
303
+ ({ response, dispatch }) => dispatch(Actions.Broadcast.UserUpdated, response),
304
+ );
305
+ ```
306
+
307
+ For typed error handling, supply the second generic and an `onError` callback &ndash; the parameter narrows to your error union, so `instanceof` discrimination on a typed `HttpError` hierarchy is clean:
308
+
309
+ ```ts
310
+ export const user = Resource<User, ApiError>(
311
+ "user",
312
+ () => http.get("user").json<User>(),
313
+ ({ response, dispatch }) => dispatch(Actions.Broadcast.UserUpdated, response),
314
+ ({ error, dispatch }) => {
315
+ if (error instanceof RateLimitedError) {
316
+ dispatch(Actions.Broadcast.RateLimited, error.retryAfter);
317
+ }
318
+ },
319
+ );
320
+ ```
321
+
322
+ See the [Resource recipe](./recipes/use-resource.md) for the three-tier error handling model, parameterised resources, and limitations.
323
+
252
324
  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:
253
325
 
254
326
  ```tsx
@@ -285,17 +357,18 @@ actions.dispatch(Actions.UserUpdated, user);
285
357
 
286
358
  Channel values support non-nullable primitives: `string`, `number`, `boolean`, or `symbol`. By convention, use uppercase keys like `{UserId: 4}` to distinguish channel keys from payload properties.
287
359
 
288
- For scoped communication between component groups, use multicast actions with the `<Scope>` component:
360
+ For scoped communication between component groups, use multicast actions with the `<Scope>` component. The scope name lives as a `static Scope` literal on the same class as the multicast actions &ndash; passing the class as a carrier prevents typos and keeps a single source of truth:
289
361
 
290
362
  ```tsx
291
363
  import { Action, Distribution, Scope } from "chizu";
292
364
 
293
- // Shared multicast actions
365
+ // Scope name and multicast actions live on the same class
294
366
  class MulticastActions {
367
+ static Scope = "scoreboard" as const;
295
368
  static Update = Action<number>("Update", Distribution.Multicast);
296
369
  }
297
370
 
298
- // Component-level actions reference shared multicast
371
+ // Component-level actions reference the shared multicast
299
372
  class Actions {
300
373
  static Multicast = MulticastActions;
301
374
  static Increment = Action("Increment");
@@ -303,22 +376,15 @@ class Actions {
303
376
 
304
377
  function App() {
305
378
  return (
306
- <>
307
- <Scope name="TeamA">
308
- <ScoreBoard />
309
- <PlayerList />
310
- </Scope>
311
-
312
- <Scope name="TeamB">
313
- <ScoreBoard />
314
- <PlayerList />
315
- </Scope>
316
- </>
379
+ <Scope of={MulticastActions}>
380
+ <ScoreBoard />
381
+ <PlayerList />
382
+ </Scope>
317
383
  );
318
384
  }
319
385
 
320
- // Dispatch to all components within "TeamA" scope
321
- actions.dispatch(Actions.Multicast.Update, 42, { scope: "TeamA" });
386
+ // Dispatch to every component inside the scope
387
+ actions.dispatch(Actions.Multicast.Update, 42, { scope: Actions.Multicast });
322
388
  ```
323
389
 
324
390
  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()`.
@@ -327,8 +393,9 @@ For components that always render inside a scope, use the `withScope` HOC to eli
327
393
 
328
394
  ```tsx
329
395
  import { withScope } from "chizu";
396
+ import { MulticastActions } from "./types";
330
397
 
331
- export default withScope("payment-link", function Layout(): ReactElement {
398
+ export default withScope(MulticastActions, function Layout(): ReactElement {
332
399
  return (
333
400
  <div>
334
401
  <PaymentLink />
@@ -340,63 +407,6 @@ export default withScope("payment-link", function Layout(): ReactElement {
340
407
 
341
408
  See the [multicast recipe](./recipes/multicast-actions.md) for more details.
342
409
 
343
- For data that is expensive to fetch, use `cacheable` to cache values with a TTL. Define typed cache entries with `Entry` and call `context.actions.cacheable` inside a handler &ndash; the callback only runs when the cache is empty or expired:
344
-
345
- ```ts
346
- import { Entry, useActions, Action } from "chizu";
347
- import { O } from "@mobily/ts-belt";
348
-
349
- class CacheStore {
350
- static Pairs = Entry<CryptoPair[]>();
351
- static User = Entry<User, { UserId: number }>();
352
- }
353
-
354
- class Actions {
355
- static FetchPairs = Action("FetchPairs");
356
- static FetchUser = Action("FetchUser");
357
- }
358
- ```
359
-
360
- ```ts
361
- actions.useAction(Actions.FetchPairs, async (context) => {
362
- const { data } = await context.actions.cacheable(
363
- CacheStore.Pairs,
364
- 30_000,
365
- async () => O.Some(await api.fetchPairs()),
366
- );
367
-
368
- if (data) {
369
- context.actions.produce(({ model }) => {
370
- model.pairs = data;
371
- });
372
- }
373
- });
374
-
375
- // Channeled &ndash; independent cache per user
376
- actions.useAction(Actions.FetchUser, async (context) => {
377
- const { data } = await context.actions.cacheable(
378
- CacheStore.User({ UserId: context.data.userId }),
379
- 60_000,
380
- async () => O.Some(await api.fetchUser(context.data.userId)),
381
- );
382
-
383
- if (data) {
384
- context.actions.produce(({ model }) => {
385
- model.user = data;
386
- });
387
- }
388
- });
389
- ```
390
-
391
- Only `Some` / `Ok` values are stored in the cache. `None` and `Error` results are skipped. Use `context.actions.invalidate` to clear a specific entry so the next `cacheable` call fetches fresh data:
392
-
393
- ```ts
394
- context.actions.invalidate(CacheStore.Pairs);
395
- context.actions.invalidate(CacheStore.User({ UserId: 5 }));
396
- ```
397
-
398
- The cache is scoped to the nearest `<Boundary>`. See the [caching recipe](./recipes/caching.md) for more details.
399
-
400
410
  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
411
 
402
412
  ```ts
@@ -414,27 +424,33 @@ actions.useAction(Actions.Checkout, async (context) => {
414
424
 
415
425
  `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
426
 
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:
427
+ Toggling boolean UI state &ndash; modals, sidebars, drawers &ndash; is one of the most common patterns. Instead of defining actions and handlers, use the `actions.features` methods:
418
428
 
419
429
  ```tsx
420
- import { Feature, useActions } from "chizu";
430
+ import { useActions } from "chizu";
431
+ import type { Meta } from "chizu";
432
+
433
+ type F = {
434
+ paymentDialog: boolean;
435
+ sidebar: boolean;
436
+ };
421
437
 
422
438
  type Model = {
423
439
  name: string;
424
- features: { paymentDialog: boolean; sidebar: boolean };
440
+ meta: Meta.Features<F>;
425
441
  };
426
442
 
427
443
  const [model, actions] = useFeatureActions();
428
444
 
429
- // Mutate via actions.feature()
430
- actions.feature("paymentDialog", Feature.Toggle);
431
- actions.feature("paymentDialog", Feature.On);
432
- actions.feature("paymentDialog", Feature.Off);
445
+ // Mutate via actions.features
446
+ actions.features.invert("paymentDialog");
447
+ actions.features.on("paymentDialog");
448
+ actions.features.off("paymentDialog");
433
449
 
434
450
  // Read from model
435
451
  {
436
- model.features.paymentDialog && <PaymentDialog />;
452
+ model.meta.features.paymentDialog && <PaymentDialog />;
437
453
  }
438
454
  ```
439
455
 
440
- The method also works inside action handlers via `context.actions.feature()`. See the [feature toggles recipe](./recipes/feature-toggles.md) for more details.
456
+ The methods also work inside action handlers via `context.actions.features`. See the [feature toggles recipe](./recipes/feature-toggles.md) for more details.
@@ -6,7 +6,7 @@ import * as React from "react";
6
6
  * When a broadcast or multicast action is dispatched, the payload is
7
7
  * stored so that late-mounting components can replay it via
8
8
  * {@link useLifecycles} and handlers can read it via
9
- * `context.actions.read()`.
9
+ * `context.actions.resolution()`.
10
10
  */
11
11
  export declare class BroadcastEmitter extends EventEmitter {
12
12
  private cache;
@@ -20,6 +20,12 @@ export declare class BroadcastEmitter extends EventEmitter {
20
20
  * Retrieve the last emitted payload for a given event.
21
21
  */
22
22
  getCached(event: string | symbol): unknown;
23
+ /**
24
+ * Emit without caching the payload. Used by the framework to publish
25
+ * fire-and-forget events (such as `Lifecycle.Fault`) where late-mounting
26
+ * subscribers must not replay a stale value.
27
+ */
28
+ fire(event: string | symbol, ...args: unknown[]): boolean;
23
29
  }
24
30
  /**
25
31
  * React context for broadcasting distributed actions across components.
@@ -1,4 +1,5 @@
1
1
  import { Props } from './types.ts';
2
+ import { ScopeCarrier } from '../../../types/index.ts';
2
3
  import { ComponentType, ReactNode } from 'react';
3
4
  import * as React from "react";
4
5
  export { useScope, getScope } from './utils.ts';
@@ -16,56 +17,60 @@ export type { ScopeEntry, ScopeContext } from './types.ts';
16
17
  * with the matching name receives the event.
17
18
  *
18
19
  * Like Broadcast, multicast caches the most recent dispatched value so that
19
- * late-mounted components can read it via `context.actions.read()`.
20
+ * late-mounted components can read it via `context.actions.resolution()`.
20
21
  *
21
- * @param props.name - The unique name for this scope
22
- * @param props.children - Components within the scope boundary
22
+ * @param props.of - The carrier object (typically a `MulticastActions` class) exposing the scope name via `.Scope`.
23
+ * @param props.children - Components within the scope boundary.
23
24
  *
24
25
  * @example
25
26
  * ```tsx
26
- * // Create a scoped boundary
27
- * <Scope name="UserList">
27
+ * class UserListActions {
28
+ * static Scope = "UserList" as const;
29
+ * static FilterChanged = Action<Filter>("FilterChanged", Distribution.Multicast);
30
+ * }
31
+ *
32
+ * <Scope of={UserListActions}>
28
33
  * <UserFilter />
29
34
  * <UserTable />
30
35
  * </Scope>
31
36
  *
32
- * // In UserFilter - dispatch to all components in "UserList" scope
33
- * actions.dispatch(Actions.Multicast.FilterChanged, filter, { scope: "UserList" });
34
- *
35
- * // UserTable receives the event, other components outside don't
37
+ * // Dispatch reaches every component in the UserList scope:
38
+ * actions.dispatch(Actions.Multicast.FilterChanged, filter, { scope: Actions.Multicast });
36
39
  * ```
37
40
  *
38
41
  * @example
39
42
  * ```tsx
40
- * // Nested scopes - each creates its own boundary
41
- * <Scope name="App">
43
+ * // Nested scopes - each class carries its own scope name
44
+ * <Scope of={AppActions}>
42
45
  * <Header />
43
- * <Scope name="Sidebar">
46
+ * <Scope of={SidebarActions}>
44
47
  * <SidebarItem />
45
48
  * </Scope>
46
- * <Scope name="Content">
49
+ * <Scope of={ContentActions}>
47
50
  * <ContentItem />
48
51
  * </Scope>
49
52
  * </Scope>
50
- *
51
- * // Dispatch to "Sidebar" only reaches SidebarItem
52
- * // Dispatch to "App" reaches all components
53
53
  * ```
54
54
  */
55
- export declare function Scope({ name, children }: Props): React.ReactNode;
55
+ export declare function Scope({ of, children }: Props): React.ReactNode;
56
56
  /**
57
57
  * Higher-order component that wraps a component in a multicast `<Scope>`.
58
58
  *
59
- * Eliminates the need to manually wrap component output in `<Scope name={...}>`,
59
+ * Eliminates the need to manually wrap component output in `<Scope of={...}>`,
60
60
  * keeping the component body focused on its own rendering logic.
61
61
  *
62
- * @param name - The scope name for multicast action delivery.
62
+ * @param carrier - Scope carrier (typically a `MulticastActions` class) exposing the scope name via `.Scope`.
63
63
  * @param Component - The component to wrap.
64
64
  * @returns A new component that renders the original within a `<Scope>`.
65
65
  *
66
66
  * @example
67
67
  * ```tsx
68
- * export default withScope(SCOPE_NAME, function Layout(): ReactElement {
68
+ * class MulticastActions {
69
+ * static Scope = "payment-link" as const;
70
+ * static Update = Action<User>("Update", Distribution.Multicast);
71
+ * }
72
+ *
73
+ * export default withScope(MulticastActions, function Layout(): ReactElement {
69
74
  * return (
70
75
  * <div>
71
76
  * <Sidebar />
@@ -75,4 +80,4 @@ export declare function Scope({ name, children }: Props): React.ReactNode;
75
80
  * });
76
81
  * ```
77
82
  */
78
- export declare function withScope<P extends object>(name: string, Component: ComponentType<P>): (props: P) => ReactNode;
83
+ export declare function withScope<S extends string, P extends object>(carrier: ScopeCarrier<S>, Component: ComponentType<P>): (props: P) => ReactNode;
@@ -1,11 +1,12 @@
1
1
  import { BroadcastEmitter } from '../broadcast/utils.ts';
2
+ import { ScopeCarrier } from '../../../types/index.ts';
2
3
  import type * as React from "react";
3
4
  /**
4
5
  * Props for the Scope component.
5
6
  */
6
7
  export type Props = {
7
- /** The unique name for this scope. Used when dispatching multicast actions. */
8
- name: string;
8
+ /** The carrier object exposing the scope name via `.Scope`. Typically the feature's `MulticastActions` class. */
9
+ of: ScopeCarrier;
9
10
  /** Children to render within the scope boundary. */
10
11
  children: React.ReactNode;
11
12
  };
@@ -2,7 +2,7 @@ import { Props } from './types.ts';
2
2
  import * as React from "react";
3
3
  /**
4
4
  * Creates a unified context boundary for all Chizu features.
5
- * Wraps children with Broadcaster, Cache, and Tasks providers.
5
+ * Wraps children with Broadcaster, Regulators, and Tasks providers.
6
6
  *
7
7
  * Use this at the root of your application or to create isolated context boundaries
8
8
  * for libraries that need their own Chizu context.
package/dist/chizu.js CHANGED
@@ -1,8 +1,6 @@
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
+ import{G as e,A as t}from"@mobily/ts-belt";import{immerable as n,enablePatches as r,Immer as o}from"immer";import{jsx as s}from"react/jsx-runtime";import*as c from"react";const i=(e="")=>`chizu.action/${e}`,u=(e="")=>`chizu.action/broadcast/${e}`,a=(e="")=>`chizu.action/multicast/${e}`,l=(e="")=>`chizu.action.lifecycle/${e}`;class f{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")}function d(e){const t=/* @__PURE__ */Symbol(`chizu.action.lifecycle/${e}`),n=function(e){return{[f.Action]:t,[f.Payload]:void 0,[f.Channel]:e,channel:e}};return Object.defineProperty(n,f.Action,{value:t,enumerable:!1}),Object.defineProperty(n,f.Payload,{value:void 0,enumerable:!1}),n}const p=Symbol(u("Fault"));class h{static Mount(){return d("Mount")}static Unmount(){return d("Unmount")}static Error(){return d("Error")}static Update(){return d("Update")}static Node(){return d("Node")}static Fault=(()=>{const e={};return Object.defineProperty(e,f.Action,{value:p,enumerable:!1}),Object.defineProperty(e,f.Payload,{value:void 0,enumerable:!1}),Object.defineProperty(e,f.Broadcast,{value:!0,enumerable:!1}),e})()}var m=/* @__PURE__ */(e=>(e.Unicast="unicast",e.Broadcast="broadcast",e.Multicast="multicast",e))(m||{}),y=/* @__PURE__ */(e=>(e.Mounting="mounting",e.Mounted="mounted",e.Unmounting="unmounting",e.Unmounted="unmounted",e))(y||{});const b=e=>"symbol"==typeof e;function v(t){return e.isString(t)||b(t)?t:(e.isObject(t)||e.isFunction(t))&&f.Action in t?t[f.Action]:t}function g(t){if(e.isString(t))return t.startsWith(u());if(b(t))return t.description?.startsWith(u())??!1;if(e.isObject(t)||e.isFunction(t)){if(f.Broadcast in t&&t[f.Broadcast])return!0;if(f.Action in t){const e=t[f.Action];return e.description?.startsWith(u())??!1}}return!1}function w(t){const n=v(t),r=e.isString(n)?n:n.description??"";return r.startsWith(i())&&r.slice(r.lastIndexOf("/")+1)||"unknown"}function S(t){return e.isObject(t)&&f.Channel in t&&"channel"in t}function E(e){const t=v(e),n=b(t)?t.description??"":t;return n.startsWith(l())&&n.slice(l().length)||null}function O(t){if(e.isString(t))return t.startsWith(a());if(b(t))return t.description?.startsWith(a())??!1;if(e.isObject(t)||e.isFunction(t)){if(f.Multicast in t&&t[f.Multicast])return!0;if(f.Action in t){const e=t[f.Action];return e.description?.startsWith(a())??!1}}return!1}const j=(e,t=m.Unicast)=>{const n=t===m.Broadcast?Symbol(u(e)):t===m.Multicast?Symbol(a(e)):Symbol(i(e)),r=function(e){return{[f.Action]:n,[f.Payload]:void 0,[f.Channel]:e,channel:e}};return Object.defineProperty(r,f.Action,{value:n,enumerable:!1}),Object.defineProperty(r,f.Payload,{value:void 0,enumerable:!1}),t===m.Broadcast&&Object.defineProperty(r,f.Broadcast,{value:!0,enumerable:!1}),t===m.Multicast&&Object.defineProperty(r,f.Multicast,{value:!0,enumerable:!1}),r};var 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 M extends Error{name="AbortError";constructor(e="Aborted"){super(e)}}class C extends Error{name="TimeoutError";constructor(e="Timeout"){super(e)}}class x extends Error{name="DisallowedError";constructor(e="Disallowed"){super(e)}}let k=(e=21)=>{let t="",n=crypto.getRandomValues(new Uint8Array(e|=0));for(;e--;)t+="useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict"[63&n[e]];return t};var A=/* @__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))(A||{}),_=/* @__PURE__ */(e=>(e[e.Produce=0]="Produce",e[e.Hydrate=1]="Hydrate",e))(_||{}),N=/* @__PURE__ */(e=>(e.Property="property",e.Process="process",e.Value="value",e.Operation="operation",e))(N||{});class R{[n]=!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 R(this.value,this.operation);return n.property=e,n.process=t,n}}class U{static immer=(()=>{r();const e=new o;return e.setAutoFreeze(!1),e})();static tag="κ";static id=k}function L(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(t){if(e.isNullable(t)||F(t))return t;if(e.isArray(t))return t.map(e=>z(e));if(e.isObject(t)&&B(t)){const e=Object.entries(t).map(([e,t])=>[e,z(t)]);return{...Object.fromEntries(e),[U.tag]:t[U.tag]??U.id()}}return t}function T(e){if(Array.isArray(e))return e.filter(e=>U.tag in e).map(e=>e[U.tag]??"").join(",");const t=e[U.tag];if(t)return t;try{return JSON.stringify(e)}catch{return`[unserializable:${typeof e}]`}}function B(e){const t=Object.getPrototypeOf(e);return t===Object.prototype||null===t}function F(t){return e.isNullable(t)||e.isString(t)||e.isNumber(t)||e.isBoolean(t)||"symbol"==typeof t||"bigint"==typeof t}function D(t,n,r,o,s,c){return function i(u,a=n.path){if(u instanceof R){const n=L(r,a.join("."));if(Object.entries(u).filter(([e,t])=>!R.keys.has(e)&&t instanceof R).forEach(([e,t])=>i(t,a.concat(e))),F(u.value)){if(t===_.Hydrate)return u.value;const i=a.slice(0,-1),l=i.length>0?L(r,i.join(".")):r;return e.isNullable(l)||W(l,u,a.at(-1),o,s,c),n??u.value}if(t===_.Hydrate){const e=z(i(u.value,a));return W(e,u,null,o,s,c),e}const l=n??z(u.value);return W(l,u,null,o,s,c),e.isNullable(n)?l:(i(u.value,a),n)}if(e.isArray(u))return u.map((e,t)=>i(e,a.concat(t)));if(e.isObject(u)&&!B(u))return u;if(e.isObject(u)){const e=Object.entries(u).map(([e,t])=>[e,i(t,a.concat(e))]),n=Object.fromEntries(e);if(t===_.Hydrate){const e=z(n);return Object.entries(u).forEach(([t,n])=>{n instanceof R&&F(n.value)&&W(e,n,t,o,s,c)}),e}return n}return u}(n.value)}function W(e,t,n,r,o,s){const c=s(e),i=o.get(c)??[];o.set(c,[t.assign(n,r),...i])}class ${#e={};#t;#n=/* @__PURE__ */new Map;#r=/* @__PURE__ */new Set;#o=!1;constructor(e=T){this.#t=e}static pk(){return k()}static"κ"=$.pk;annotate(e,t){return new R(t,e)}"δ"=this.annotate;get model(){return this.#e}get inspect(){return function(n,r,o,s,c){function i(s){const c=s.at(-1),i=L(n(),s),u=s.slice(0,-1),a=t.isNotEmpty(u)?L(n(),u):n();return[...e.isObject(i)||e.isArray(i)?r.get(o(i))?.filter(t=>e.isNullable(t.property))??[]:[],...e.isObject(a)?r.get(o(a))?.filter(e=>e.property===c)??[]:[]]}return function e(r){return new Proxy(()=>{},{get:(o,u)=>"pending"===u?()=>!t.isEmpty(i(r)):"remaining"===u?()=>t.length(i(r)):"box"===u?()=>({value:L(n(),r),inspect:e(r)}):"is"===u?e=>i(r).some(t=>0!==(t.operation&e)):"draft"===u?()=>t.head(i(r))?.value??L(n(),r):"settled"===u?()=>new Promise(e=>{if(t.isEmpty(i(r)))return e(L(n(),r));const o=()=>{t.isEmpty(i(r))&&(c(o),e(L(n(),r)))};s(o)}):e([...r,String(u)])})}([])}(()=>this.#e,this.#n,this.#t,e=>this.#r.add(e),e=>this.#r.delete(e))}hydrate(e){return this.#o=!0,this.#s(_.Hydrate,()=>e)}produce(e){if(!this.#o)throw new Error("State must be hydrated using hydrate() before calling produce()");return this.#s(_.Produce,e)}#s(e,t){const n=/* @__PURE__ */Symbol("process"),[,r]=U.immer.produceWithPatches(this.#e,t);return this.#e=r.reduce((t,r)=>U.immer.applyPatches(t,[{...r,value:D(e,r,t,n,this.#n,this.#t)}]),this.#e),this.#e=z(this.#e),this.#c(),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.#c()}#c(){this.#r.forEach(e=>e())}observe(e){const t=()=>e(this.#e);return this.#r.add(t),()=>this.#r.delete(t)}}const H=new $;function I(e,t){return H.annotate(e,t)}function G(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var J,V={exports:{}};const q=/* @__PURE__ */G((J||(J=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 s(e,t,r,s,c){if("function"!=typeof r)throw new TypeError("The listener must be a function");var i=new o(r,s||e,c),u=n?n+t:t;return e._events[u]?e._events[u].fn?e._events[u]=[e._events[u],i]:e._events[u].push(i):(e._events[u]=i,e._eventsCount++),e}function c(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,s=new Array(o);r<o;r++)s[r]=t[r].fn;return s},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,s,c){var i=n?n+e:e;if(!this._events[i])return!1;var u,a,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,s),!0;case 6:return l.fn.call(l.context,t,r,o,s,c),!0}for(a=1,u=new Array(f-1);a<f;a++)u[a-1]=arguments[a];l.fn.apply(l.context,u)}else{var d,p=l.length;for(a=0;a<p;a++)switch(l[a].once&&this.removeListener(e,l[a].fn,void 0,!0),f){case 1:l[a].fn.call(l[a].context);break;case 2:l[a].fn.call(l[a].context,t);break;case 3:l[a].fn.call(l[a].context,t,r);break;case 4:l[a].fn.call(l[a].context,t,r,o);break;default:if(!u)for(d=1,u=new Array(f-1);d<f;d++)u[d-1]=arguments[d];l[a].fn.apply(l[a].context,u)}}return!0},i.prototype.on=function(e,t,n){return s(this,e,t,n,!1)},i.prototype.once=function(e,t,n){return s(this,e,t,n,!0)},i.prototype.removeListener=function(e,t,r,o){var s=n?n+e:e;if(!this._events[s])return this;if(!t)return c(this,s),this;var i=this._events[s];if(i.fn)i.fn!==t||o&&!i.once||r&&i.context!==r||c(this,s);else{for(var u=0,a=[],l=i.length;u<l;u++)(i[u].fn!==t||o&&!i[u].once||r&&i[u].context!==r)&&a.push(i[u]);a.length?this._events[s]=1===a.length?a[0]:a:c(this,s)}return this},i.prototype.removeAllListeners=function(e){var t;return e?this._events[t=n?n+e:e]&&c(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}(V)),V.exports));class K extends q{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)}fire(e,...t){return super.emit(e,...t)}}const Q=c.createContext(new K);function X(){return c.useContext(Q)}function Y({children:e}){const t=c.useMemo(()=>new K,[]);/* @__PURE__ */
2
+ return s(Q.Provider,{value:t,children:e})}const Z=c.createContext(/* @__PURE__ */new Set);function ee({children:e}){const t=c.useMemo(()=>/* @__PURE__ */new Set,[]);/* @__PURE__ */
3
+ return s(Z.Provider,{value:t,children:e})}const te=c.createContext({mode:"allow-all",actions:/* @__PURE__ */new Set});function ne({children:e}){const t=c.useMemo(()=>({mode:"allow-all",actions:/* @__PURE__ */new Set}),[]);/* @__PURE__ */
4
+ return s(te.Provider,{value:t,children:e})}function re({children:e}){/* @__PURE__ */
5
+ return s(Y,{children:/* @__PURE__ */s(ne,{children:/* @__PURE__ */s(ee,{children:e})})})}const oe=c.createContext(null);function se(){return c.useContext(oe)}function ce(e,t){return e?.get(t)??null}function ie({of:e,children:t}){const n=se(),r=e.Scope,o=c.useMemo(()=>({name:r,emitter:new K}),[]),i=c.useMemo(()=>{const e=new Map(n??[]);return e.set(r,o),e},[n,r,o]);/* @__PURE__ */
6
+ return s(oe.Provider,{value:i,children:t})}function ue(e,t){const n=`Scoped${t.displayName||t.name||"Component"}`;return{[n]:n=>/* @__PURE__ */s(ie,{of:e,children:/* @__PURE__ */s(t,{...n})})}[n]}const ae=Symbol(((e="")=>`chizu/replay${e}`)());function le(e,t,...n){e instanceof K&&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 fe(e){return(t,n)=>{t.actions.produce(t=>{t.model[e]=n})}}function de(e,t){for(const n of e.keys())if(E(n)===t)return n;return null}function pe(){const[,e]=c.useReducer(e=>e+1,0);return e}function he(e){if(e instanceof Error){if("TimeoutError"===e.name)return P.Timedout;if("AbortError"===e.name)return P.Supplanted;if("DisallowedError"===e.name)return P.Disallowed}return P.Errored}const me=c.createContext(/* @__PURE__ */new Map);function ye({action:t,renderer:n}){const r=X(),o=c.useContext(me),s=pe(),i=c.useMemo(()=>{const e=o.get(t);if(e)return e;const n={state:new $,listeners:/* @__PURE__ */new Set};return o.set(t,n),n},[t,o]);c.useLayoutEffect(()=>{function e(e){i.state.hydrate({value:e}),i.listeners.forEach(e=>e())}return i.listeners.add(s),r.on(t,e),()=>{i.listeners.delete(s),r.off(t,e)}},[t,r,i]);const u=i.state.model?.value;return e.isNullable(u)?null:n(u,i.state.inspect.value)}function be(...n){const r=e.isUndefined(n[0])||e.isFunction(n[0])?{}:n[0],o=e.isFunction(n[0])?n[0]:n[1]??(()=>({})),s=X(),i=se(),u=c.useContext(Z),a=c.useContext(te),l=pe(),f=c.useRef(!1),d=c.useRef(null),h=c.useRef(new $),m=c.useRef({features:null,nodes:null});function b(){null===m.current.features&&null===m.current.nodes||(h.current.model.meta={...null!==m.current.features?{features:m.current.features}:{},...null!==m.current.nodes?{nodes:m.current.nodes}:{}})}if(!f.current){f.current=!0;const e=r,t=e.meta;t?.features&&(m.current.features=t.features),t?.nodes&&(m.current.nodes=t.nodes);const{meta:n,...o}=e;d.current=h.current.hydrate(o),b()}const[E,j]=c.useState(()=>h.current.model),M=function(e){const t=c.useRef(e);return c.useLayoutEffect(()=>{t.current=e},[e]),c.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()),C=c.useMemo(()=>new q,[]),k=c.useRef({handlers:/* @__PURE__ */new Map});k.current.handlers=/* @__PURE__ */new Map;const A=function(){const e=c.useRef(/* @__PURE__ */new Set),t=c.useRef(/* @__PURE__ */new Set);return c.useMemo(()=>({broadcast:e.current,multicast:t.current}),[])}(),_=c.useRef(y.Mounting),N=function(){const e=c.useRef({}),t=c.useRef(/* @__PURE__ */new Map),n=c.useRef(/* @__PURE__ */new Map);return c.useMemo(()=>({refs:e,pending:t,emitted:n}),[])}(),R=c.useRef(/* @__PURE__ */new Set),U=c.useRef(0),L=c.useCallback((e,t,n)=>{const r=new AbortController,o={controller:r,action:e,payload:t};return u.add(o),R.current.add(o),{model:h.current.model,get phase(){return _.current},task:o,data:M,tasks:u,get meta(){return{nodes:N.refs.current,features:m.current.features??{}}},regulator:{disallow(...e){if(a.actions.clear(),0===e.length)a.mode="disallow-all";else{a.mode="disallow-matching";for(const t of e)a.actions.add(v(t))}},allow(...e){if(a.actions.clear(),0===e.length)a.mode="allow-all";else{a.mode="allow-matching";for(const t of e)a.actions.add(v(t))}}},actions:{produce(e){if(r.signal.aborted)return;const t=h.current.produce(t=>{e({model:t,inspect:h.current.inspect})});b(),j(h.current.model),n.processes.add(t),d.current&&(n.processes.add(d.current),d.current=null)},dispatch(e,t,n){if(r.signal.aborted)return Promise.resolve();const o=v(e),c=S(e)?e.channel:void 0;if(O(e)&&n?.scope){const e=ce(i,n.scope.Scope);return e?le(e.emitter,o,t,c):Promise.resolve()}return le(g(e)?s:C,o,t,c)},annotate:(e,t)=>h.current.annotate(e,t),features:{on(e){r.signal.aborted||(m.current.features={...m.current.features,[e]:!0},b(),j(h.current.model),d.current&&(n.processes.add(d.current),d.current=null))},off(e){r.signal.aborted||(m.current.features={...m.current.features,[e]:!1},b(),j(h.current.model),d.current&&(n.processes.add(d.current),d.current=null))},invert(e){if(r.signal.aborted)return;const t=m.current.features?.[e]??!1;m.current.features={...m.current.features,[e]:!t},b(),j(h.current.model),d.current&&(n.processes.add(d.current),d.current=null)}},async resolution(e,t){if(r.signal.aborted)return null;const n=v(e),o=O(e)&&t?.scope?ce(i,t.scope.Scope)?.emitter??null:s;if(!o)return null;if(void 0===o.getCached(n))return null;const c=w(e),u="unknown"!==c?c[0].toLowerCase()+c.slice(1):null;if(u){const e=h.current.inspect[u];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=v(e),o=O(e)&&t?.scope?ce(i,t.scope.Scope)?.emitter??null:s;return o?o.getCached(n)??null:null}}}},[E]);c.useLayoutEffect(()=>{function t(t,n,r){return function(o,c){if(t!==p&&!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,a)){const e=de(k.current.handlers,"Error"),n=null!==e,r={reason:P.Disallowed,error:new x,action:w(t),handled:n,tasks:u};return s.fire(p,r),void(n&&e&&C.emit(e,r))}const i=r();if(c===ae&&e.isNotNullable(i))return;if(e.isNotNullable(c)&&c!==ae&&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 f={processes:/* @__PURE__ */new Set},d=Promise.withResolvers(),m=L(t,o,f);function y(e){const n=de(k.current.handlers,"Error"),r=null!==n,o={reason:he(e),error:(c=e,c instanceof Error?c:new Error(String(c))),action:w(t),handled:r,tasks:u};var c;s.fire(p,o),r&&n&&C.emit(n,o)}function b(){for(const e of u)if(e===m.task){u.delete(e),R.current.delete(e);break}f.processes.forEach(e=>h.current.prune(e)),f.processes.size>0&&l(),d.resolve()}let v;try{v=n(m,o)}catch(g){return y(g),void b()}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(y).finally(b),d.promise;(async()=>{for await(const e of v);})().catch(y).finally(b)}}U.current++;const n=/* @__PURE__ */new Set;return k.current.handlers.forEach((e,r)=>{for(const{getChannel:o,handler:c}of e){const e=t(r,c,o);if(O(r)){if(i)for(const t of i.values()){const o=t.emitter;o.on(r,e),n.add(()=>o.off(r,e))}C.on(r,e),A.multicast.add(r),n.add(()=>C.off(r,e))}else g(r)?(s.on(r,e),C.on(r,e),A.broadcast.add(r),n.add(()=>{s.off(r,e),C.off(r,e)})):(C.on(r,e),n.add(()=>C.off(r,e)))}}),()=>{const e=++U.current,t=new Set(n);queueMicrotask(()=>{if(U.current!==e){for(const e of t)e();return}for(const e of R.current)e.controller.abort(),u.delete(e);R.current.clear(),_.current=y.Unmounting;const n=de(k.current.handlers,"Unmount");n&&C.emit(n),_.current=y.Unmounted;for(const e of t)e()})}},[C]),c.useLayoutEffect(()=>{const e=de(k.current.handlers,"Node");let t=!1;for(const[n,r]of N.pending.current)if(N.emitted.current.get(n)!==r){if(N.emitted.current.set(n,r),null!==m.current.nodes){const e={...m.current.nodes};e[n]=r,m.current.nodes=e,t=!0}e&&C.emit(e,r,{Name:n})}t&&(b(),j(h.current.model)),N.pending.current.clear()}),function({unicast:n,broadcast:r,dispatchers:o,scope:s,phase:i,data:u,handlers:a}){const l=c.useRef(null);c.useLayoutEffect(()=>{if(i.current!==y.Mounting)return;const t=de(a,"Mount");t&&n.emit(t),o.broadcast.forEach(t=>{const o=r.getCached(t);e.isNullable(o)||n.emit(t,o,ae)}),s&&o.multicast.forEach(t=>{for(const r of s.values()){const o=r.emitter.getCached(t);e.isNullable(o)||n.emit(t,o,ae)}}),i.current=y.Mounted},[]),c.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,u);if(t.isNotEmpty(Object.keys(e))){const t=de(a,"Update");t&&n.emit(t,e)}}l.current=u},[u,n])}({unicast:C,broadcast:s,dispatchers:A,scope:i,phase:_,data:o(),handlers:k.current.handlers});const z=c.useMemo(()=>[E,{dispatch(e,t,n){const r=v(e),o=S(e)?e.channel:void 0;if(O(e)&&n?.scope){const e=ce(i,n.scope.Scope);return e?le(e.emitter,r,t,o):Promise.resolve()}return le(g(e)?s:C,r,t,o)},get inspect(){return h.current.inspect},get meta(){return{nodes:N.refs.current,features:m.current.features??{}}},node(e,t){N.refs.current[e]=t,N.pending.current.set(e,t)},features:{on(e){m.current.features={...m.current.features,[e]:!0},b(),j(h.current.model)},off(e){m.current.features={...m.current.features,[e]:!1},b(),j(h.current.model)},invert(e){const t=m.current.features?.[e]??!1;m.current.features={...m.current.features,[e]:!t},b(),j(h.current.model)}},stream:(e,t)=>c.createElement(ye,{action:v(e),renderer:t})}],[E,C]);return z.useAction=(e,t)=>{!function(e,t,n){const r=c.useRef(n);c.useLayoutEffect(()=>{r.current=n});const o=c.useRef(t);c.useLayoutEffect(()=>{o.current=t});const s=c.useCallback((e,t)=>r.current(e,t),[]),i=c.useCallback(()=>S(o.current)?o.current.channel:void 0,[]),u=v(t),a=e.current.handlers.get(u)??/* @__PURE__ */new Set;0===a.size&&e.current.handlers.set(u,a),a.add({getChannel:i,handler:s})}(k,e,t)},z.useResource=e=>{const t=c.useMemo(()=>(e,t)=>{const n=S(e)?e.channel:void 0;return le(s,v(e),t,n)},[s]);return c.useCallback((...n)=>e.fetch(t,M,...n),[e,t,M])},z}function ve(e,t,n,r){const o=/* @__PURE__ */new Map;return{key:e,fetch:(e,s,...c)=>{const i=JSON.stringify(c),u=o.get(i);if(u)return u;const a=t(...c).then(t=>(o.get(i)===a&&o.delete(i),n?.({response:t,data:s,dispatch:e}),t),t=>{throw o.get(i)===a&&o.delete(i),r?.({error:t,data:s,dispatch:e}),t});return o.set(i,a),a}}}function ge(e,t){return new Promise((n,r)=>{if(t?.aborted)return void r(new M);const o=setTimeout(n,e);t?.addEventListener("abort",()=>{clearTimeout(o),r(new M)},{once:!0})})}async function we(e,t,n){if(t?.aborted)throw new M;for(;;){if(await n())return;await ge(e,t)}}function Se(e){return e?Boolean(e&&"symbol"!=typeof e):/* @__PURE__ */Symbol(`pk.${Date.now()}.${crypto.randomUUID()}`)}const Ee=/* @__PURE__ */Object.freeze(/* @__PURE__ */Object.defineProperty({__proto__:null,pk:Se,poll:we,sleep:ge,"ζ":ge,"κ":Se,"π":we},Symbol.toStringTag,{value:"Module"}));export{M as AbortError,j as Action,re as Boundary,x as DisallowedError,m as Distribution,h as Lifecycle,A as Op,A as Operation,P as Reason,ne as Regulators,ve as Resource,ie as Scope,$ as State,C as TimeoutError,fe as With,I as annotate,be as useActions,Ee as utils,ue as withScope};