chizu 0.2.72 → 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 +86 -76
- package/dist/boundary/components/broadcast/utils.d.ts +7 -1
- package/dist/boundary/components/scope/index.d.ts +26 -21
- package/dist/boundary/components/scope/types.d.ts +3 -2
- package/dist/boundary/index.d.ts +1 -1
- package/dist/chizu.js +6 -8
- package/dist/chizu.umd.cjs +1 -1
- package/dist/error/index.d.ts +1 -23
- package/dist/error/types.d.ts +12 -28
- package/dist/error/utils.d.ts +1 -11
- package/dist/hooks/utils.d.ts +8 -0
- package/dist/index.d.ts +5 -4
- package/dist/resource/index.d.ts +78 -0
- package/dist/types/index.d.ts +97 -96
- package/dist/utils/index.d.ts +0 -17
- package/dist/utils.d.ts +26 -0
- package/package.json +4 -1
- package/dist/boundary/components/cache/index.d.ts +0 -13
- package/dist/boundary/components/cache/types.d.ts +0 -19
- package/dist/boundary/components/cache/utils.d.ts +0 -12
- package/dist/cache/index.d.ts +0 -77
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 `
|
|
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.
|
|
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 – 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 – 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/) – 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 – 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 – 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 – 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 – 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
|
-
//
|
|
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
|
-
<
|
|
308
|
-
|
|
309
|
-
|
|
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
|
|
321
|
-
actions.dispatch(Actions.Multicast.Update, 42, { scope:
|
|
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 – perfect for isolated widget groups, form sections, or distinct UI regions. Like broadcast, multicast caches dispatched values per scope – 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(
|
|
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 – 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 – 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
|
|
@@ -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.
|
|
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.
|
|
20
|
+
* late-mounted components can read it via `context.actions.resolution()`.
|
|
20
21
|
*
|
|
21
|
-
* @param props.
|
|
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
|
-
*
|
|
27
|
-
*
|
|
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
|
-
* //
|
|
33
|
-
* actions.dispatch(Actions.Multicast.FilterChanged, filter, { scope:
|
|
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
|
|
41
|
-
* <Scope
|
|
43
|
+
* // Nested scopes - each class carries its own scope name
|
|
44
|
+
* <Scope of={AppActions}>
|
|
42
45
|
* <Header />
|
|
43
|
-
* <Scope
|
|
46
|
+
* <Scope of={SidebarActions}>
|
|
44
47
|
* <SidebarItem />
|
|
45
48
|
* </Scope>
|
|
46
|
-
* <Scope
|
|
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({
|
|
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
|
|
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
|
|
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
|
-
*
|
|
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>(
|
|
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
|
|
8
|
-
|
|
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
|
};
|
package/dist/boundary/index.d.ts
CHANGED
|
@@ -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,
|
|
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[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 y extends Error{name="DisallowedError";constructor(e="Disallowed"){super(e)}}const b={actionPrefix:"chizu.action/",broadcastActionPrefix:"chizu.action/broadcast/",multicastActionPrefix:"chizu.action/multicast/",channelPrefix:"chizu.channel/",cachePrefix:"chizu.cache/",lifecyclePrefix:"chizu.action.lifecycle/"};function v(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 g(e,t,n){if(t?.aborted)throw new m;for(;;){if(await n())return;await v(e,t)}}function w(e){return e?Boolean(e&&"symbol"!=typeof e):/* @__PURE__ */Symbol(`pk.${Date.now()}.${crypto.randomUUID()}`)}const P=/* @__PURE__ */Object.freeze(/* @__PURE__ */Object.defineProperty({__proto__:null,config:b,pk:w,poll:g,sleep:v,"ζ":v,"κ":w,"π":g},Symbol.toStringTag,{value:"Module"})),x=e=>"symbol"==typeof e;function S(t){return e.isString(t)||x(t)?t:(e.isObject(t)||e.isFunction(t))&&u.Action in t?t[u.Action]:t}function E(t){if(e.isString(t))return t.startsWith(b.broadcastActionPrefix);if(x(t))return t.description?.startsWith(b.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(b.broadcastActionPrefix)??!1}}return!1}function O(t){const n=S(t),r=e.isString(n)?n:n.description??"";return r.startsWith(b.actionPrefix)&&r.slice(r.lastIndexOf("/")+1)||"unknown"}function j(t){return e.isObject(t)&&u.Channel in t&&"channel"in t}function C(e){const t=S(e),n=x(t)?t.description??"":t;return n.startsWith(b.lifecyclePrefix)&&n.slice(b.lifecyclePrefix.length)||null}function A(t){if(e.isString(t))return t.startsWith(b.multicastActionPrefix);if(x(t))return t.description?.startsWith(b.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(b.multicastActionPrefix)??!1}}return!1}const M=(e,t=d.Unicast)=>{const n=t===d.Broadcast?/* @__PURE__ */Symbol(`${b.broadcastActionPrefix}${e}`):t===d.Multicast?/* @__PURE__ */Symbol(`${b.multicastActionPrefix}${e}`):/* @__PURE__ */Symbol(`${b.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 k(){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 _(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 R(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}function N(e){return e instanceof Error?e:new Error(String(e))}const U=o(void 0);function L({handler:e,children:t}){/* @__PURE__ */
|
|
2
|
-
return
|
|
3
|
-
return
|
|
4
|
-
return
|
|
5
|
-
return
|
|
6
|
-
return n(le.Provider,{value:t,children:e})}function de({children:e}){/* @__PURE__ */
|
|
7
|
-
return n(ce,{children:/* @__PURE__ */n(ie,{children:/* @__PURE__ */n(fe,{children:/* @__PURE__ */n(ue,{children:e})})})})}const he=r.createContext(null);function pe(){return r.useContext(he)}function me(e,t){return e?.get(t)??null}function ye({name:e,children:t}){const o=pe(),c=r.useMemo(()=>({name:e,emitter:new ne}),[]),s=r.useMemo(()=>{const t=new Map(o??[]);return t.set(e,c),t},[o,e,c]);/* @__PURE__ */
|
|
8
|
-
return n(he.Provider,{value:s,children:t})}function be(e,t){const r=`Scoped${t.displayName||t.name||"Component"}`;return{[r]:r=>/* @__PURE__ */n(ye,{name:e,children:/* @__PURE__ */n(t,{...r})})}[r]}function ve(e,t,...n){e instanceof ne&&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 ge(e){return(t,n)=>{t.actions.produce(t=>{t.model[e]=n})}}function we(e,t){for(const n of e.keys())if(C(n)===t)return n;return null}function Pe(){const[,e]=r.useReducer(e=>e+1,0);return e}const xe=r.createContext(/* @__PURE__ */new Map);function Se({action:t,renderer:n}){const o=oe(),c=r.useContext(xe),s=Pe(),i=r.useMemo(()=>{const e=c.get(t);if(e)return e;const n={state:new K,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 Ee(...n){const o=e.isUndefined(n[0])||e.isFunction(n[0])?{}:n[0],s=e.isFunction(n[0])?n[0]:n[1]??(()=>({})),i=oe(),a=pe(),u=c(U),l=r.useContext(ae),f=r.useContext(se),d=r.useContext(le),m=Pe(),b=r.useRef(!1),v=r.useRef(null),g=r.useRef(new K),w=r.useRef({features:null,nodes:null});function P(){null===w.current.features&&null===w.current.nodes||(g.current.model.meta={...null!==w.current.features?{features:w.current.features}:{},...null!==w.current.nodes?{nodes:w.current.nodes}:{}})}if(!b.current){b.current=!0;const e=o,t=e.meta;t?.features&&(w.current.features=t.features),t?.nodes&&(w.current.nodes=t.nodes);const{meta:n,...r}=e;v.current=g.current.hydrate(r),P()}const[x,C]=r.useState(()=>g.current.model),M=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()),k=r.useMemo(()=>new te,[]),L=r.useRef({handlers:/* @__PURE__ */new Map});L.current.handlers=/* @__PURE__ */new Map;const z=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),T=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}),[])}(),D=r.useRef(/* @__PURE__ */new Set),B=r.useRef(0),W=r.useCallback((e,t,n)=>{const r=new AbortController,o={controller:r,action:e,payload:t};return l.add(o),D.current.add(o),{model:g.current.model,get phase(){return $.current},task:o,data:M,tasks:l,get meta(){return{nodes:T.refs.current,features:w.current.features??{}}},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(S(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(S(t))}}},actions:{produce(e){if(r.signal.aborted)return;const t=g.current.produce(t=>{e({model:t,inspect:g.current.inspect})});P(),C(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=S(e),c=j(e)?e.channel:void 0;if(A(e)&&n?.scope){const e=me(a,n.scope);return e?ve(e.emitter,o,t,c):Promise.resolve()}return ve(E(e)?i:k,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=_(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(_(e))},features:{on(e){r.signal.aborted||(w.current.features={...w.current.features,[e]:!0},P(),C(g.current.model),v.current&&(n.processes.add(v.current),v.current=null))},off(e){r.signal.aborted||(w.current.features={...w.current.features,[e]:!1},P(),C(g.current.model),v.current&&(n.processes.add(v.current),v.current=null))},invert(e){if(r.signal.aborted)return;const t=w.current.features?.[e]??!1;w.current.features={...w.current.features,[e]:!t},P(),C(g.current.model),v.current&&(n.processes.add(v.current),v.current=null)}},async read(e,t){if(r.signal.aborted)return null;const n=S(e),o=A(e)&&t?.scope?me(a,t.scope)?.emitter??null:i;if(!o)return null;if(void 0===o.getCached(n))return null;const c=O(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=S(e),o=A(e)&&t?.scope?me(a,t.scope)?.emitter??null:i;return o?o.getCached(n)??null:null}}}},[x]);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=we(L.current.handlers,"Error"),n=null!==e,r={reason:p.Disallowed,error:new y,action:O(t),handled:n,tasks:l};return u?.(r),void(n&&e&&k.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=W(t,o,i);function h(e){const n=we(L.current.handlers,"Error"),r=null!==n,o={reason:R(e),error:N(e),action:O(t),handled:r,tasks:l};u?.(o),r&&n&&k.emit(n,o)}function b(){for(const e of l)if(e===f.task){l.delete(e),D.current.delete(e);break}i.processes.forEach(e=>g.current.prune(e)),i.processes.size>0&&m(),a.resolve()}let v;try{v=n(f,o)}catch(w){return h(w),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(h).finally(b),a.promise;(async()=>{for await(const e of v);})().catch(h).finally(b)}}B.current++;const n=/* @__PURE__ */new Set;return L.current.handlers.forEach((e,r)=>{for(const{getChannel:o,handler:c}of e){const e=t(r,c,o);if(A(r)){if(a)for(const t of a.values()){const o=t.emitter;o.on(r,e),n.add(()=>o.off(r,e))}k.on(r,e),z.multicast.add(r),n.add(()=>k.off(r,e))}else E(r)?(i.on(r,e),k.on(r,e),z.broadcast.add(r),n.add(()=>{i.off(r,e),k.off(r,e)})):(k.on(r,e),n.add(()=>k.off(r,e)))}}),()=>{const e=++B.current,t=new Set(n);queueMicrotask(()=>{if(B.current!==e){for(const e of t)e();return}for(const e of D.current)e.controller.abort(),l.delete(e);D.current.clear(),$.current=h.Unmounting;const n=we(L.current.handlers,"Unmount");n&&k.emit(n),$.current=h.Unmounted;for(const e of t)e()})}},[k]),r.useLayoutEffect(()=>{const e=we(L.current.handlers,"Node");let t=!1;for(const[n,r]of T.pending.current)if(T.emitted.current.get(n)!==r){if(T.emitted.current.set(n,r),null!==w.current.nodes){const e={...w.current.nodes};e[n]=r,w.current.nodes=e,t=!0}e&&k.emit(e,r,{Name:n})}t&&(P(),C(g.current.model)),T.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=we(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=we(u,"Update");t&&n.emit(t,e)}}l.current=a},[a,n])}({unicast:k,broadcast:i,dispatchers:z,scope:a,phase:$,data:s(),handlers:L.current.handlers});const F=r.useMemo(()=>[x,{dispatch(e,t,n){const r=S(e),o=j(e)?e.channel:void 0;if(A(e)&&n?.scope){const e=me(a,n.scope);return e?ve(e.emitter,r,t,o):Promise.resolve()}return ve(E(e)?i:k,r,t,o)},get inspect(){return g.current.inspect},get meta(){return{nodes:T.refs.current,features:w.current.features??{}}},node(e,t){T.refs.current[e]=t,T.pending.current.set(e,t)},features:{on(e){w.current.features={...w.current.features,[e]:!0},P(),C(g.current.model)},off(e){w.current.features={...w.current.features,[e]:!1},P(),C(g.current.model)},invert(e){const t=w.current.features?.[e]??!1;w.current.features={...w.current.features,[e]:!t},P(),C(g.current.model)}},stream:(e,t)=>r.createElement(Se,{action:S(e),renderer:t})}],[x,k]);return F.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(()=>j(c.current)?c.current.channel:void 0,[]),a=S(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})}(L,e,t)},F}export{M as Action,de as Boundary,y as DisallowedError,d as Distribution,k as Entry,L as Error,f as Lifecycle,$ as Op,$ as Operation,p as Reason,fe as Regulators,ye as Scope,K as State,ge as With,X as annotate,Ee as useActions,P as utils,be 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};
|
package/dist/chizu.umd.cjs
CHANGED
|
@@ -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 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[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)}}class h extends Error{name="DisallowedError";constructor(e="Disallowed"){super(e)}}const p={actionPrefix:"chizu.action/",broadcastActionPrefix:"chizu.action/broadcast/",multicastActionPrefix:"chizu.action/multicast/",channelPrefix:"chizu.channel/",cachePrefix:"chizu.cache/",lifecyclePrefix:"chizu.action.lifecycle/"};function m(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 b(e,t,n){if(t?.aborted)throw new d;for(;;){if(await n())return;await m(e,t)}}function y(e){return e?Boolean(e&&"symbol"!=typeof e):Symbol(`pk.${Date.now()}.${crypto.randomUUID()}`)}const v=Object.freeze(Object.defineProperty({__proto__:null,config:p,pk:y,poll:b,sleep:m,"ζ":m,"κ":y,"π":b},Symbol.toStringTag,{value:"Module"})),g=e=>"symbol"==typeof e;function w(e){return t.G.isString(e)||g(e)?e:(t.G.isObject(e)||t.G.isFunction(e))&&i.Action in e?e[i.Action]:e}function x(e){if(t.G.isString(e))return e.startsWith(p.broadcastActionPrefix);if(g(e))return e.description?.startsWith(p.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(p.broadcastActionPrefix)??!1}}return!1}function j(e){const n=w(e),r=t.G.isString(n)?n:n.description??"";return r.startsWith(p.actionPrefix)&&r.slice(r.lastIndexOf("/")+1)||"unknown"}function P(e){return t.G.isObject(e)&&i.Channel in e&&"channel"in e}function S(e){const t=w(e),n=g(t)?t.description??"":t;return n.startsWith(p.lifecyclePrefix)&&n.slice(p.lifecyclePrefix.length)||null}function E(e){if(t.G.isString(e))return e.startsWith(p.multicastActionPrefix);if(g(e))return e.description?.startsWith(p.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(p.multicastActionPrefix)??!1}}return!1}function O(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 A(e){if(e instanceof Error){if("TimeoutError"===e.name)return f.Timedout;if("AbortError"===e.name)return f.Supplanted;if("DisallowedError"===e.name)return f.Disallowed}return f.Errored}function C(e){return e instanceof Error?e:new Error(String(e))}const M=r.createContext(void 0);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 G=(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))(G||{}),_=(e=>(e[e.Produce=0]="Produce",e[e.Hydrate=1]="Hydrate",e))(_||{}),R=(e=>(e.Property="property",e.Process="process",e.Value="value",e.Operation="operation",e))(R||{});class N{[o.immerable]=!0;static keys=new Set(Object.values(R));property=null;process=null;value;operation;constructor(e,t){this.value=e,this.operation=t}assign(e,t){const n=new N(this.value,this.operation);return n.property=e,n.process=t,n}}class U{static immer=(()=>{o.enablePatches();const e=new o.Immer;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(e){if(t.G.isNullable(e)||$(e))return e;if(t.G.isArray(e))return e.map(e=>z(e));if(t.G.isObject(e)&&D(e)){const t=Object.entries(e).map(([e,t])=>[e,z(t)]);return{...Object.fromEntries(t),[U.tag]:e[U.tag]??U.id()}}return e}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 D(e){const t=Object.getPrototypeOf(e);return t===Object.prototype||null===t}function $(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 B(e,n,r,o,c,s){return function i(a,u=n.path){if(a instanceof N){const n=L(r,u.join("."));if(Object.entries(a).filter(([e,t])=>!N.keys.has(e)&&t instanceof N).forEach(([e,t])=>i(t,u.concat(e))),$(a.value)){if(e===_.Hydrate)return a.value;const i=u.slice(0,-1),l=i.length>0?L(r,i.join(".")):r;return t.G.isNullable(l)||W(l,a,u.at(-1),o,c,s),n??a.value}if(e===_.Hydrate){const e=z(i(a.value,u));return W(e,a,null,o,c,s),e}const l=n??z(a.value);return W(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)&&!D(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===_.Hydrate){const e=z(n);return Object.entries(a).forEach(([t,n])=>{n instanceof N&&$(n.value)&&W(e,n,t,o,c,s)}),e}return n}return a}(n.value)}function W(e,t,n,r,o,c){const s=c(e),i=o.get(s)??[];o.set(s,[t.assign(n,r),...i])}class F{#e={};#t;#n=new Map;#r=new Set;#o=!1;constructor(e=T){this.#t=e}static pk(){return k()}static"κ"=F.pk;annotate(e,t){return new N(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=L(e(),o),i=o.slice(0,-1),a=t.A.isNotEmpty(i)?L(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:L(e(),r),inspect:n(r)}):"is"===a?e=>s(r).some(t=>0!==(t.operation&e)):"draft"===a?()=>t.A.head(s(r))?.value??L(e(),r):"settled"===a?()=>new Promise(n=>{if(t.A.isEmpty(s(r)))return n(L(e(),r));const i=()=>{t.A.isEmpty(s(r))&&(c(i),n(L(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(_.Hydrate,()=>e)}produce(e){if(!this.#o)throw new Error("State must be hydrated using hydrate() before calling produce()");return this.#c(_.Produce,e)}#c(e,t){const n=Symbol("process"),[,r]=U.immer.produceWithPatches(this.#e,t);return this.#e=r.reduce((t,r)=>U.immer.applyPatches(t,[{...r,value:B(e,r,t,n,this.#n,this.#t)}]),this.#e),this.#e=z(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 H=new F;function I(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var q,V={exports:{}},J=(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,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}(V)),V.exports);const K=I(J);class Q extends K{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 X=s.createContext(new Q);function Y(){return s.useContext(X)}function Z({children:e}){const t=s.useMemo(()=>new Q,[]);return n.jsx(X.Provider,{value:t,children:e})}const ee=s.createContext(new Map);function te({children:e}){const t=s.useMemo(()=>new Map,[]);return n.jsx(ee.Provider,{value:t,children:e})}const ne=s.createContext(new Set);function re({children:e}){const t=s.useMemo(()=>new Set,[]);return n.jsx(ne.Provider,{value:t,children:e})}const oe=s.createContext({mode:"allow-all",actions:new Set});function ce({children:e}){const t=s.useMemo(()=>({mode:"allow-all",actions:new Set}),[]);return n.jsx(oe.Provider,{value:t,children:e})}const se=s.createContext(null);function ie(){return s.useContext(se)}function ae(e,t){return e?.get(t)??null}function ue({name:e,children:t}){const r=ie(),o=s.useMemo(()=>({name:e,emitter:new Q}),[]),c=s.useMemo(()=>{const t=new Map(r??[]);return t.set(e,o),t},[r,e,o]);return n.jsx(se.Provider,{value:c,children:t})}function le(e,t,...n){e instanceof Q&&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,t){for(const n of e.keys())if(S(n)===t)return n;return null}function de(){const[,e]=s.useReducer(e=>e+1,0);return e}const he=s.createContext(new Map);function pe({action:e,renderer:n}){const r=Y(),o=s.useContext(he),c=de(),i=s.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]);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(`${p.broadcastActionPrefix}${e}`):t===u.Multicast?Symbol(`${p.multicastActionPrefix}${e}`):Symbol(`${p.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(Z,{children:n.jsx(te,{children:n.jsx(ce,{children:n.jsx(re,{children:e})})})})},e.DisallowedError=h,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(M.Provider,{value:e,children:t})},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=G,e.Operation=G,e.Reason=f,e.Regulators=ce,e.Scope=ue,e.State=F,e.With=function(e){return(t,n)=>{t.actions.produce(t=>{t.model[e]=n})}},e.annotate=function(e,t){return H.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=Y(),i=ie(),a=r.useContext(M),u=s.useContext(ne),d=s.useContext(ee),p=s.useContext(oe),m=de(),b=s.useRef(!1),y=s.useRef(null),v=s.useRef(new F),g=s.useRef({features:null,nodes:null});function S(){null===g.current.features&&null===g.current.nodes||(v.current.model.meta={...null!==g.current.features?{features:g.current.features}:{},...null!==g.current.nodes?{nodes:g.current.nodes}:{}})}if(!b.current){b.current=!0;const e=n,t=e.meta;t?.features&&(g.current.features=t.features),t?.nodes&&(g.current.nodes=t.nodes);const{meta:r,...o}=e;y.current=v.current.hydrate(o),S()}const[k,G]=s.useState(()=>v.current.model),_=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()),R=s.useMemo(()=>new K,[]),N=s.useRef({handlers:new Map});N.current.handlers=new Map;const U=function(){const e=s.useRef(new Set),t=s.useRef(new Set);return s.useMemo(()=>({broadcast:e.current,multicast:t.current}),[])}(),L=s.useRef(l.Mounting),z=function(){const e=s.useRef({}),t=s.useRef(new Map),n=s.useRef(new Map);return s.useMemo(()=>({refs:e,pending:t,emitted:n}),[])}(),T=s.useRef(new Set),D=s.useRef(0),$=s.useCallback((e,t,n)=>{const r=new AbortController,o={controller:r,action:e,payload:t};return u.add(o),T.current.add(o),{model:v.current.model,get phase(){return L.current},task:o,data:_,tasks:u,get meta(){return{nodes:z.refs.current,features:g.current.features??{}}},regulator:{disallow(...e){if(p.actions.clear(),0===e.length)p.mode="disallow-all";else{p.mode="disallow-matching";for(const t of e)p.actions.add(w(t))}},allow(...e){if(p.actions.clear(),0===e.length)p.mode="allow-all";else{p.mode="allow-matching";for(const t of e)p.actions.add(w(t))}}},actions:{produce(e){if(r.signal.aborted)return;const t=v.current.produce(t=>{e({model:t,inspect:v.current.inspect})});S(),G(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=w(e),s=P(e)?e.channel:void 0;if(E(e)&&n?.scope){const e=ae(i,n.scope);return e?le(e.emitter,o,t,s):Promise.resolve()}return le(x(e)?c:R,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=O(e),c=d.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?(d.set(o,{value:s.value,expiry:Date.now()+t}),{data:s.value}):{data:null}},invalidate(e){d.delete(O(e))},features:{on(e){r.signal.aborted||(g.current.features={...g.current.features,[e]:!0},S(),G(v.current.model),y.current&&(n.processes.add(y.current),y.current=null))},off(e){r.signal.aborted||(g.current.features={...g.current.features,[e]:!1},S(),G(v.current.model),y.current&&(n.processes.add(y.current),y.current=null))},invert(e){if(r.signal.aborted)return;const t=g.current.features?.[e]??!1;g.current.features={...g.current.features,[e]:!t},S(),G(v.current.model),y.current&&(n.processes.add(y.current),y.current=null)}},async read(e,t){if(r.signal.aborted)return null;const n=w(e),o=E(e)&&t?.scope?ae(i,t.scope)?.emitter??null:c;if(!o)return null;if(void 0===o.getCached(n))return null;const s=j(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=w(e),o=E(e)&&t?.scope?ae(i,t.scope)?.emitter??null:c;return o?o.getCached(n)??null:null}}}},[k]);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,p)){const t=fe(N.current.handlers,"Error"),n=null!==t,r={reason:f.Disallowed,error:new h,action:j(e),handled:n,tasks:u};return a?.(r),void(n&&t&&R.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(),d=$(e,o,i);function b(t){const n=fe(N.current.handlers,"Error"),r=null!==n,o={reason:A(t),error:C(t),action:j(e),handled:r,tasks:u};a?.(o),r&&n&&R.emit(n,o)}function y(){for(const e of u)if(e===d.task){u.delete(e),T.current.delete(e);break}i.processes.forEach(e=>v.current.prune(e)),i.processes.size>0&&m(),l.resolve()}let g;try{g=n(d,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)}}D.current++;const n=new Set;return N.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))}R.on(r,t),U.multicast.add(r),n.add(()=>R.off(r,t))}else x(r)?(c.on(r,t),R.on(r,t),U.broadcast.add(r),n.add(()=>{c.off(r,t),R.off(r,t)})):(R.on(r,t),n.add(()=>R.off(r,t)))}}),()=>{const e=++D.current,t=new Set(n);queueMicrotask(()=>{if(D.current!==e){for(const e of t)e();return}for(const e of T.current)e.controller.abort(),u.delete(e);T.current.clear(),L.current=l.Unmounting;const n=fe(N.current.handlers,"Unmount");n&&R.emit(n),L.current=l.Unmounted;for(const e of t)e()})}},[R]),s.useLayoutEffect(()=>{const e=fe(N.current.handlers,"Node");let t=!1;for(const[n,r]of z.pending.current)if(z.emitted.current.get(n)!==r){if(z.emitted.current.set(n,r),null!==g.current.nodes){const e={...g.current.nodes};e[n]=r,g.current.nodes=e,t=!0}e&&R.emit(e,r,{Name:n})}t&&(S(),G(v.current.model)),z.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=fe(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=fe(a,"Update");t&&e.emit(t,n)}}u.current=i},[i,e])}({unicast:R,broadcast:c,dispatchers:U,scope:i,phase:L,data:o(),handlers:N.current.handlers});const B=s.useMemo(()=>[k,{dispatch(e,t,n){const r=w(e),o=P(e)?e.channel:void 0;if(E(e)&&n?.scope){const e=ae(i,n.scope);return e?le(e.emitter,r,t,o):Promise.resolve()}return le(x(e)?c:R,r,t,o)},get inspect(){return v.current.inspect},get meta(){return{nodes:z.refs.current,features:g.current.features??{}}},node(e,t){z.refs.current[e]=t,z.pending.current.set(e,t)},features:{on(e){g.current.features={...g.current.features,[e]:!0},S(),G(v.current.model)},off(e){g.current.features={...g.current.features,[e]:!1},S(),G(v.current.model)},invert(e){const t=g.current.features?.[e]??!1;g.current.features={...g.current.features,[e]:!t},S(),G(v.current.model)}},stream:(e,t)=>s.createElement(pe,{action:w(e),renderer:t})}],[k,R]);return B.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(()=>P(o.current)?o.current.channel:void 0,[]),a=w(t),u=e.current.handlers.get(a)??new Set;0===u.size&&e.current.handlers.set(a,u),u.add({getChannel:i,handler:c})}(N,e,t)},B},e.utils=v,e.withScope=function(e,t){const r=`Scoped${t.displayName||t.name||"Component"}`;return{[r]:r=>n.jsx(ue,{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 s(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 c=s(o),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=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")}function d(e){const t=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=(e=>(e.Unicast="unicast",e.Broadcast="broadcast",e.Multicast="multicast",e))(m||{}),b=(e=>(e.Mounting="mounting",e.Mounted="mounted",e.Unmounting="unmounting",e.Unmounted="unmounted",e))(b||{});const y=e=>"symbol"==typeof e;function v(e){return t.G.isString(e)||y(e)?e:(t.G.isObject(e)||t.G.isFunction(e))&&f.Action in e?e[f.Action]:e}function g(e){if(t.G.isString(e))return e.startsWith(u());if(y(e))return e.description?.startsWith(u())??!1;if(t.G.isObject(e)||t.G.isFunction(e)){if(f.Broadcast in e&&e[f.Broadcast])return!0;if(f.Action in e){const t=e[f.Action];return t.description?.startsWith(u())??!1}}return!1}function w(e){const n=v(e),r=t.G.isString(n)?n:n.description??"";return r.startsWith(i())&&r.slice(r.lastIndexOf("/")+1)||"unknown"}function j(e){return t.G.isObject(e)&&f.Channel in e&&"channel"in e}function S(e){const t=v(e),n=y(t)?t.description??"":t;return n.startsWith(l())&&n.slice(l().length)||null}function O(e){if(t.G.isString(e))return e.startsWith(a());if(y(e))return e.description?.startsWith(a())??!1;if(t.G.isObject(e)||t.G.isFunction(e)){if(f.Multicast in e&&e[f.Multicast])return!0;if(f.Action in e){const t=e[f.Action];return t.description?.startsWith(a())??!1}}return!1}var E=(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))(E||{});class x extends Error{name="AbortError";constructor(e="Aborted"){super(e)}}class P extends Error{name="TimeoutError";constructor(e="Timeout"){super(e)}}class M extends Error{name="DisallowedError";constructor(e="Disallowed"){super(e)}}let A=(e=21)=>{let t="",n=crypto.getRandomValues(new Uint8Array(e|=0));for(;e--;)t+="useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict"[63&n[e]];return t};var C=(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))(C||{}),G=(e=>(e[e.Produce=0]="Produce",e[e.Hydrate=1]="Hydrate",e))(G||{}),k=(e=>(e.Property="property",e.Process="process",e.Value="value",e.Operation="operation",e))(k||{});class R{[n.immerable]=!0;static keys=new Set(Object.values(k));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 _{static immer=(()=>{n.enablePatches();const e=new n.Immer;return e.setAutoFreeze(!1),e})();static tag="κ";static id=A}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 U(e){if(t.G.isNullable(e)||T(e))return e;if(t.G.isArray(e))return e.map(e=>U(e));if(t.G.isObject(e)&&z(e)){const t=Object.entries(e).map(([e,t])=>[e,U(t)]);return{...Object.fromEntries(t),[_.tag]:e[_.tag]??_.id()}}return e}function L(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 z(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 B(e,n,r,o,s,c){return function i(u,a=n.path){if(u instanceof R){const n=N(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))),T(u.value)){if(e===G.Hydrate)return u.value;const i=a.slice(0,-1),l=i.length>0?N(r,i.join(".")):r;return t.G.isNullable(l)||D(l,u,a.at(-1),o,s,c),n??u.value}if(e===G.Hydrate){const e=U(i(u.value,a));return D(e,u,null,o,s,c),e}const l=n??U(u.value);return D(l,u,null,o,s,c),t.G.isNullable(n)?l:(i(u.value,a),n)}if(t.G.isArray(u))return u.map((e,t)=>i(e,a.concat(t)));if(t.G.isObject(u)&&!z(u))return u;if(t.G.isObject(u)){const t=Object.entries(u).map(([e,t])=>[e,i(t,a.concat(e))]),n=Object.fromEntries(t);if(e===G.Hydrate){const e=U(n);return Object.entries(u).forEach(([t,n])=>{n instanceof R&&T(n.value)&&D(e,n,t,o,s,c)}),e}return n}return u}(n.value)}function D(e,t,n,r,o,s){const c=s(e),i=o.get(c)??[];o.set(c,[t.assign(n,r),...i])}class F{#e={};#t;#n=new Map;#r=new Set;#o=!1;constructor(e=L){this.#t=e}static pk(){return A()}static"κ"=F.pk;annotate(e,t){return new R(t,e)}"δ"=this.annotate;get model(){return this.#e}get inspect(){return function(e,n,r,o,s){function c(o){const s=o.at(-1),c=N(e(),o),i=o.slice(0,-1),u=t.A.isNotEmpty(i)?N(e(),i):e();return[...t.G.isObject(c)||t.G.isArray(c)?n.get(r(c))?.filter(e=>t.G.isNullable(e.property))??[]:[],...t.G.isObject(u)?n.get(r(u))?.filter(e=>e.property===s)??[]:[]]}return function n(r){return new Proxy(()=>{},{get:(i,u)=>"pending"===u?()=>!t.A.isEmpty(c(r)):"remaining"===u?()=>t.A.length(c(r)):"box"===u?()=>({value:N(e(),r),inspect:n(r)}):"is"===u?e=>c(r).some(t=>0!==(t.operation&e)):"draft"===u?()=>t.A.head(c(r))?.value??N(e(),r):"settled"===u?()=>new Promise(n=>{if(t.A.isEmpty(c(r)))return n(N(e(),r));const i=()=>{t.A.isEmpty(c(r))&&(s(i),n(N(e(),r)))};o(i)}):n([...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(G.Hydrate,()=>e)}produce(e){if(!this.#o)throw new Error("State must be hydrated using hydrate() before calling produce()");return this.#s(G.Produce,e)}#s(e,t){const n=Symbol("process"),[,r]=_.immer.produceWithPatches(this.#e,t);return this.#e=r.reduce((t,r)=>_.immer.applyPatches(t,[{...r,value:B(e,r,t,n,this.#n,this.#t)}]),this.#e),this.#e=U(this.#e),this.#c(),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.#c()}#c(){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 $(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 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=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}(I)),I.exports);const J=$(q);class V extends J{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)}fire(e,...t){return super.emit(e,...t)}}const K=c.createContext(new V);function Q(){return c.useContext(K)}function X({children:e}){const t=c.useMemo(()=>new V,[]);return r.jsx(K.Provider,{value:t,children:e})}const Y=c.createContext(new Set);function Z({children:e}){const t=c.useMemo(()=>new Set,[]);return r.jsx(Y.Provider,{value:t,children:e})}const ee=c.createContext({mode:"allow-all",actions:new Set});function te({children:e}){const t=c.useMemo(()=>({mode:"allow-all",actions:new Set}),[]);return r.jsx(ee.Provider,{value:t,children:e})}const ne=c.createContext(null);function re(){return c.useContext(ne)}function oe(e,t){return e?.get(t)??null}function se({of:e,children:t}){const n=re(),o=e.Scope,s=c.useMemo(()=>({name:o,emitter:new V}),[]),i=c.useMemo(()=>{const e=new Map(n??[]);return e.set(o,s),e},[n,o,s]);return r.jsx(ne.Provider,{value:i,children:t})}const ce=Symbol(((e="")=>`chizu/replay${e}`)());function ie(e,t,...n){e instanceof V&&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 ue(e,t){for(const n of e.keys())if(S(n)===t)return n;return null}function ae(){const[,e]=c.useReducer(e=>e+1,0);return e}function le(e){if(e instanceof Error){if("TimeoutError"===e.name)return E.Timedout;if("AbortError"===e.name)return E.Supplanted;if("DisallowedError"===e.name)return E.Disallowed}return E.Errored}const fe=c.createContext(new Map);function de({action:e,renderer:n}){const r=Q(),o=c.useContext(fe),s=ae(),i=c.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]);c.useLayoutEffect(()=>{function t(e){i.state.hydrate({value:e}),i.listeners.forEach(e=>e())}return i.listeners.add(s),r.on(e,t),()=>{i.listeners.delete(s),r.off(e,t)}},[e,r,i]);const u=i.state.model?.value;return t.G.isNullable(u)?null:n(u,i.state.inspect.value)}function pe(e,t){return new Promise((n,r)=>{if(t?.aborted)return void r(new x);const o=setTimeout(n,e);t?.addEventListener("abort",()=>{clearTimeout(o),r(new x)},{once:!0})})}async function he(e,t,n){if(t?.aborted)throw new x;for(;;){if(await n())return;await pe(e,t)}}function me(e){return e?Boolean(e&&"symbol"!=typeof e):Symbol(`pk.${Date.now()}.${crypto.randomUUID()}`)}const be=Object.freeze(Object.defineProperty({__proto__:null,pk:me,poll:he,sleep:pe,"ζ":pe,"κ":me,"π":he},Symbol.toStringTag,{value:"Module"}));e.AbortError=x,e.Action=(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},e.Boundary=function({children:e}){return r.jsx(X,{children:r.jsx(te,{children:r.jsx(Z,{children:e})})})},e.DisallowedError=M,e.Distribution=m,e.Lifecycle=h,e.Op=C,e.Operation=C,e.Reason=E,e.Regulators=te,e.Resource=function(e,t,n,r){const o=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}}},e.Scope=se,e.State=F,e.TimeoutError=P,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],r=t.G.isFunction(e[0])?e[0]:e[1]??(()=>({})),o=Q(),s=re(),i=c.useContext(Y),u=c.useContext(ee),a=ae(),l=c.useRef(!1),f=c.useRef(null),d=c.useRef(new F),h=c.useRef({features:null,nodes:null});function m(){null===h.current.features&&null===h.current.nodes||(d.current.model.meta={...null!==h.current.features?{features:h.current.features}:{},...null!==h.current.nodes?{nodes:h.current.nodes}:{}})}if(!l.current){l.current=!0;const e=n,t=e.meta;t?.features&&(h.current.features=t.features),t?.nodes&&(h.current.nodes=t.nodes);const{meta:r,...o}=e;f.current=d.current.hydrate(o),m()}const[y,S]=c.useState(()=>d.current.model),x=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])}(r()),P=c.useMemo(()=>new J,[]),A=c.useRef({handlers:new Map});A.current.handlers=new Map;const C=function(){const e=c.useRef(new Set),t=c.useRef(new Set);return c.useMemo(()=>({broadcast:e.current,multicast:t.current}),[])}(),G=c.useRef(b.Mounting),k=function(){const e=c.useRef({}),t=c.useRef(new Map),n=c.useRef(new Map);return c.useMemo(()=>({refs:e,pending:t,emitted:n}),[])}(),R=c.useRef(new Set),_=c.useRef(0),N=c.useCallback((e,t,n)=>{const r=new AbortController,c={controller:r,action:e,payload:t};return i.add(c),R.current.add(c),{model:d.current.model,get phase(){return G.current},task:c,data:x,tasks:i,get meta(){return{nodes:k.refs.current,features:h.current.features??{}}},regulator:{disallow(...e){if(u.actions.clear(),0===e.length)u.mode="disallow-all";else{u.mode="disallow-matching";for(const t of e)u.actions.add(v(t))}},allow(...e){if(u.actions.clear(),0===e.length)u.mode="allow-all";else{u.mode="allow-matching";for(const t of e)u.actions.add(v(t))}}},actions:{produce(e){if(r.signal.aborted)return;const t=d.current.produce(t=>{e({model:t,inspect:d.current.inspect})});m(),S(d.current.model),n.processes.add(t),f.current&&(n.processes.add(f.current),f.current=null)},dispatch(e,t,n){if(r.signal.aborted)return Promise.resolve();const c=v(e),i=j(e)?e.channel:void 0;if(O(e)&&n?.scope){const e=oe(s,n.scope.Scope);return e?ie(e.emitter,c,t,i):Promise.resolve()}return ie(g(e)?o:P,c,t,i)},annotate:(e,t)=>d.current.annotate(e,t),features:{on(e){r.signal.aborted||(h.current.features={...h.current.features,[e]:!0},m(),S(d.current.model),f.current&&(n.processes.add(f.current),f.current=null))},off(e){r.signal.aborted||(h.current.features={...h.current.features,[e]:!1},m(),S(d.current.model),f.current&&(n.processes.add(f.current),f.current=null))},invert(e){if(r.signal.aborted)return;const t=h.current.features?.[e]??!1;h.current.features={...h.current.features,[e]:!t},m(),S(d.current.model),f.current&&(n.processes.add(f.current),f.current=null)}},async resolution(e,t){if(r.signal.aborted)return null;const n=v(e),c=O(e)&&t?.scope?oe(s,t.scope.Scope)?.emitter??null:o;if(!c)return null;if(void 0===c.getCached(n))return null;const i=w(e),u="unknown"!==i?i[0].toLowerCase()+i.slice(1):null;if(u){const e=d.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 c.getCached(n)??null},peek(e,t){if(r.signal.aborted)return null;const n=v(e),c=O(e)&&t?.scope?oe(s,t.scope.Scope)?.emitter??null:o;return c?c.getCached(n)??null:null}}}},[y]);c.useLayoutEffect(()=>{function e(e,n,r){return function(s,c){if(e!==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)}}(e,u)){const t=ue(A.current.handlers,"Error"),n=null!==t,r={reason:E.Disallowed,error:new M,action:w(e),handled:n,tasks:i};return o.fire(p,r),void(n&&t&&P.emit(t,r))}const l=r();if(c===ce&&t.G.isNotNullable(l))return;if(t.G.isNotNullable(c)&&c!==ce&&t.G.isNotNullable(l)&&!function(e,t){for(const n of Object.keys(e))if(t[n]!==e[n])return!1;return!0}(c,l))return;const f={processes:new Set},h=Promise.withResolvers(),m=N(e,s,f);function b(t){const n=ue(A.current.handlers,"Error"),r=null!==n,s={reason:le(t),error:(c=t,c instanceof Error?c:new Error(String(c))),action:w(e),handled:r,tasks:i};var c;o.fire(p,s),r&&n&&P.emit(n,s)}function y(){for(const e of i)if(e===m.task){i.delete(e),R.current.delete(e);break}f.processes.forEach(e=>d.current.prune(e)),f.processes.size>0&&a(),h.resolve()}let v;try{v=n(m,s)}catch(g){return b(g),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(b).finally(y),h.promise;(async()=>{for await(const e of v);})().catch(b).finally(y)}}_.current++;const n=new Set;return A.current.handlers.forEach((t,r)=>{for(const{getChannel:c,handler:i}of t){const t=e(r,i,c);if(O(r)){if(s)for(const e of s.values()){const o=e.emitter;o.on(r,t),n.add(()=>o.off(r,t))}P.on(r,t),C.multicast.add(r),n.add(()=>P.off(r,t))}else g(r)?(o.on(r,t),P.on(r,t),C.broadcast.add(r),n.add(()=>{o.off(r,t),P.off(r,t)})):(P.on(r,t),n.add(()=>P.off(r,t)))}}),()=>{const e=++_.current,t=new Set(n);queueMicrotask(()=>{if(_.current!==e){for(const e of t)e();return}for(const e of R.current)e.controller.abort(),i.delete(e);R.current.clear(),G.current=b.Unmounting;const n=ue(A.current.handlers,"Unmount");n&&P.emit(n),G.current=b.Unmounted;for(const e of t)e()})}},[P]),c.useLayoutEffect(()=>{const e=ue(A.current.handlers,"Node");let t=!1;for(const[n,r]of k.pending.current)if(k.emitted.current.get(n)!==r){if(k.emitted.current.set(n,r),null!==h.current.nodes){const e={...h.current.nodes};e[n]=r,h.current.nodes=e,t=!0}e&&P.emit(e,r,{Name:n})}t&&(m(),S(d.current.model)),k.pending.current.clear()}),function({unicast:e,broadcast:n,dispatchers:r,scope:o,phase:s,data:i,handlers:u}){const a=c.useRef(null);c.useLayoutEffect(()=>{if(s.current!==b.Mounting)return;const c=ue(u,"Mount");c&&e.emit(c),r.broadcast.forEach(r=>{const o=n.getCached(r);t.G.isNullable(o)||e.emit(r,o,ce)}),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,ce)}}),s.current=b.Mounted},[]),c.useLayoutEffect(()=>{if(t.G.isNotNullable(a.current)){const n=function(e,t){return Object.keys(t).reduce((n,r)=>e[r]!==t[r]?{...n,[r]:t[r]}:n,{})}(a.current,i);if(t.A.isNotEmpty(Object.keys(n))){const t=ue(u,"Update");t&&e.emit(t,n)}}a.current=i},[i,e])}({unicast:P,broadcast:o,dispatchers:C,scope:s,phase:G,data:r(),handlers:A.current.handlers});const U=c.useMemo(()=>[y,{dispatch(e,t,n){const r=v(e),c=j(e)?e.channel:void 0;if(O(e)&&n?.scope){const e=oe(s,n.scope.Scope);return e?ie(e.emitter,r,t,c):Promise.resolve()}return ie(g(e)?o:P,r,t,c)},get inspect(){return d.current.inspect},get meta(){return{nodes:k.refs.current,features:h.current.features??{}}},node(e,t){k.refs.current[e]=t,k.pending.current.set(e,t)},features:{on(e){h.current.features={...h.current.features,[e]:!0},m(),S(d.current.model)},off(e){h.current.features={...h.current.features,[e]:!1},m(),S(d.current.model)},invert(e){const t=h.current.features?.[e]??!1;h.current.features={...h.current.features,[e]:!t},m(),S(d.current.model)}},stream:(e,t)=>c.createElement(de,{action:v(e),renderer:t})}],[y,P]);return U.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(()=>j(o.current)?o.current.channel:void 0,[]),u=v(t),a=e.current.handlers.get(u)??new Set;0===a.size&&e.current.handlers.set(u,a),a.add({getChannel:i,handler:s})}(A,e,t)},U.useResource=e=>{const t=c.useMemo(()=>(e,t)=>{const n=j(e)?e.channel:void 0;return ie(o,v(e),t,n)},[o]);return c.useCallback((...n)=>e.fetch(t,x,...n),[e,t,x])},U},e.utils=be,e.withScope=function(e,t){const n=`Scoped${t.displayName||t.name||"Component"}`;return{[n]:n=>r.jsx(se,{of:e,children:r.jsx(t,{...n})})}[n]},Object.defineProperty(e,Symbol.toStringTag,{value:"Module"})},"object"==typeof exports&&"undefined"!=typeof module?factory(exports,require("@mobily/ts-belt"),require("immer"),require("react/jsx-runtime"),require("react")):"function"==typeof define&&define.amd?define(["exports","@mobily/ts-belt","immer","react/jsx-runtime","react"],factory):factory((global="undefined"!=typeof globalThis?globalThis:global||self).Chizu={},global.TsBelt,global.Immer,global.jsxRuntime,global.React);
|