march-hare 0.7.5 → 0.8.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 +53 -32
- package/dist/hooks/index.d.ts +37 -1
- package/dist/index.d.ts +3 -2
- package/dist/march-hare.js +2 -2
- package/dist/march-hare.umd.cjs +1 -1
- package/dist/types/index.d.ts +42 -193
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -43,10 +43,10 @@ For advanced topics, see the [recipes directory](./recipes/).
|
|
|
43
43
|
|
|
44
44
|
## Getting started
|
|
45
45
|
|
|
46
|
-
We dispatch the `Actions.Name` event upon clicking the "Sign in" button and within the component we subscribe to that same event via `
|
|
46
|
+
We dispatch the `Actions.Name` event upon clicking the "Sign in" button and within the component we subscribe to that same event via `useContext` so that when it's triggered it updates the model with the payload – in the React component we render `model.name`. The `With.Update` helper binds the action's payload directly to a model property.
|
|
47
47
|
|
|
48
48
|
```tsx
|
|
49
|
-
import {
|
|
49
|
+
import { useContext, Action, With } from "march-hare";
|
|
50
50
|
|
|
51
51
|
type Model = {
|
|
52
52
|
name: string | null;
|
|
@@ -60,14 +60,21 @@ export class Actions {
|
|
|
60
60
|
static Name = Action<string>("Name");
|
|
61
61
|
}
|
|
62
62
|
|
|
63
|
-
|
|
64
|
-
const
|
|
63
|
+
function useActions() {
|
|
64
|
+
const context = useContext<Model, typeof Actions>();
|
|
65
|
+
const actions = context.useActions(model);
|
|
65
66
|
|
|
66
67
|
actions.useAction(Actions.Name, With.Update("name"));
|
|
67
68
|
|
|
69
|
+
return actions;
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
export default function Profile(): React.ReactElement {
|
|
73
|
+
const [model, actions] = useActions();
|
|
74
|
+
|
|
68
75
|
return (
|
|
69
76
|
<>
|
|
70
|
-
<p>Hey {
|
|
77
|
+
<p>Hey {model.name}</p>
|
|
71
78
|
|
|
72
79
|
<button onClick={() => actions.dispatch(Actions.Name, randomName())}>
|
|
73
80
|
Sign in
|
|
@@ -104,16 +111,16 @@ actions.useAction(Actions.Name, async (context) => {
|
|
|
104
111
|
|
|
105
112
|
Notice we're using `annotate` which you can read more about in the [Immertation documentation](https://github.com/Wildhoney/Immertation). Once the request is finished we update the model again with the name fetched from the response and re-render the React component. `Resource` caches the most recent successful payload and exposes typed params – the full API is covered [further down](#remote-data).
|
|
106
113
|
|
|
107
|
-
If you need to access external reactive values (like props or `useState` from parent components) that always reflect the latest value even after `await` operations, pass a data callback to `useActions`. The same snapshot is exposed as the third tuple element so JSX and handlers read from a single named source:
|
|
114
|
+
If you need to access external reactive values (like props or `useState` from parent components) that always reflect the latest value even after `await` operations, pass a data callback to `context.useActions`. The same snapshot is exposed as the third tuple element so JSX and handlers read from a single named source:
|
|
108
115
|
|
|
109
116
|
```tsx
|
|
110
|
-
const
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
+
const context = useContext<Model, typeof Actions, { query: string }>();
|
|
118
|
+
const actions = context.useActions(
|
|
119
|
+
model,
|
|
120
|
+
() => ({
|
|
121
|
+
query: props.query,
|
|
122
|
+
}),
|
|
123
|
+
);
|
|
117
124
|
|
|
118
125
|
actions.useAction(Actions.Search, async (context) => {
|
|
119
126
|
const results = await context.actions.resource(
|
|
@@ -128,33 +135,37 @@ return <input value={data.query} onChange={…} />;
|
|
|
128
135
|
|
|
129
136
|
`data` is read-only from the view side – handlers read fresh values via `context.data` (Proxy delegating to a ref kept current across `await`s), JSX reads via the third tuple element (the same Proxy, refreshed synchronously each render). If a handler needs to _react_ to a change in `data`, subscribe to `Lifecycle.Update()` — it fires whenever `getData`'s result differs from the previous render. For more details, see the [referential equality recipe](./recipes/referential-equality.md) and the [React context in handlers recipe](./recipes/react-context-in-handlers.md).
|
|
130
137
|
|
|
131
|
-
|
|
138
|
+
When an external library needs the dispatch callback at construction time (form libraries, animation engines) _and_ its return value must flow back into `context.useActions` via the data callback, there's a chicken-and-egg — each side wants the other to exist first. `useContext` resolves this by returning a stable handle up-front: `context.actions.dispatch` is callable from the first line, the external library closes over it, and `context.useActions(initialModel, getData?)` completes the binding once the external value is in scope. See the [`useContext` recipe](./recipes/use-context.md) for the full pattern.
|
|
139
|
+
|
|
140
|
+
The model defaults to `void`, so you can call `context.useActions()` with no generics or initial state when only handlers are needed:
|
|
132
141
|
|
|
133
142
|
```tsx
|
|
134
|
-
import {
|
|
143
|
+
import { useContext, Lifecycle } from "march-hare";
|
|
135
144
|
|
|
136
145
|
class Actions {
|
|
137
146
|
static Mount = Lifecycle.Mount();
|
|
138
147
|
}
|
|
139
148
|
|
|
140
|
-
const
|
|
149
|
+
const context = useContext<void, typeof Actions>();
|
|
150
|
+
const actions = context.useActions();
|
|
141
151
|
|
|
142
152
|
actions.useAction(Actions.Mount, () => {
|
|
143
153
|
console.log("Mounted!");
|
|
144
154
|
});
|
|
145
155
|
```
|
|
146
156
|
|
|
147
|
-
If your component doesn't need local state but still needs to dispatch or listen to typed actions,
|
|
157
|
+
If your component doesn't need local state but still needs to dispatch or listen to typed actions, call `context.useActions()` with no initial model. No state is allocated:
|
|
148
158
|
|
|
149
159
|
```tsx
|
|
150
|
-
import {
|
|
160
|
+
import { useContext, Action, Lifecycle } from "march-hare";
|
|
151
161
|
|
|
152
162
|
export class Actions {
|
|
153
163
|
static Ping = Action("Ping");
|
|
154
164
|
}
|
|
155
165
|
|
|
156
166
|
export default function Pinger(): React.ReactElement {
|
|
157
|
-
const
|
|
167
|
+
const context = useContext<void, typeof Actions>();
|
|
168
|
+
const actions = context.useActions();
|
|
158
169
|
|
|
159
170
|
actions.useAction(Actions.Ping, () => {
|
|
160
171
|
console.log("Pinged!");
|
|
@@ -243,7 +254,8 @@ You can also render broadcast values declaratively in JSX with `actions.stream`.
|
|
|
243
254
|
|
|
244
255
|
```tsx
|
|
245
256
|
function Dashboard() {
|
|
246
|
-
const
|
|
257
|
+
const context = useContext<Model, typeof Actions>();
|
|
258
|
+
const actions = context.useActions(initialModel);
|
|
247
259
|
|
|
248
260
|
return (
|
|
249
261
|
<div>
|
|
@@ -278,18 +290,22 @@ export const pay = Resource<Receipt, Body>(({ controller, params }) =>
|
|
|
278
290
|
|
|
279
291
|
```tsx
|
|
280
292
|
// actions.ts
|
|
281
|
-
import {
|
|
293
|
+
import { useContext } from "march-hare";
|
|
282
294
|
import { user, pay } from "./resources";
|
|
283
295
|
|
|
284
296
|
export function useActions() {
|
|
285
|
-
const
|
|
297
|
+
const context = useContext<Model, typeof Actions>();
|
|
298
|
+
|
|
299
|
+
const actions = context.useActions({
|
|
286
300
|
// Sync cache read at the model literal — returns null when nothing is cached.
|
|
287
301
|
user: user(),
|
|
288
302
|
receipt: null,
|
|
289
303
|
});
|
|
290
304
|
|
|
291
305
|
actions.useAction(Actions.Mount, async (context) => {
|
|
292
|
-
const data = await context.
|
|
306
|
+
const data = await context.controller
|
|
307
|
+
.resource(user())
|
|
308
|
+
.exceeds({ minutes: 5 });
|
|
293
309
|
context.actions.produce(({ model }) => void (model.user = data));
|
|
294
310
|
});
|
|
295
311
|
|
|
@@ -383,7 +399,8 @@ export const cat = Resource(
|
|
|
383
399
|
|
|
384
400
|
```ts
|
|
385
401
|
// actions.ts
|
|
386
|
-
const
|
|
402
|
+
const context = useContext<Model, typeof Actions>();
|
|
403
|
+
const actions = context.useActions({
|
|
387
404
|
// First render reads the Cache automatically.
|
|
388
405
|
cat: cat(),
|
|
389
406
|
});
|
|
@@ -391,7 +408,9 @@ const actions = useActions<Model, typeof Actions>({
|
|
|
391
408
|
actions.useAction(Actions.Mount, async (context) => {
|
|
392
409
|
// Short-circuits when the persisted payload is < 5 minutes old.
|
|
393
410
|
// The Cache writes through automatically on success.
|
|
394
|
-
const fresh = await context.
|
|
411
|
+
const fresh = await context.controller
|
|
412
|
+
.resource(cat())
|
|
413
|
+
.exceeds({ minutes: 5 });
|
|
395
414
|
context.actions.produce(({ model }) => void (model.cat = fresh));
|
|
396
415
|
});
|
|
397
416
|
```
|
|
@@ -400,11 +419,11 @@ actions.useAction(Actions.Mount, async (context) => {
|
|
|
400
419
|
|
|
401
420
|
See the [storage recipe](./recipes/storage.md) for backend adapters (React Native MMKV, browser extension `chrome.storage`), sign-out purge, and the `unset` sentinel that keeps "nothing stored" distinct from "a legitimately stored null".
|
|
402
421
|
|
|
403
|
-
For targeted event delivery, use channeled actions. Define a
|
|
422
|
+
For targeted event delivery, use channeled actions. Define a controller type as the second generic argument and call the action with a controller object – handlers fire when the dispatch controller matches:
|
|
404
423
|
|
|
405
424
|
```tsx
|
|
406
425
|
class Actions {
|
|
407
|
-
// Second generic arg defines the
|
|
426
|
+
// Second generic arg defines the controller type
|
|
408
427
|
static UserUpdated = Action<User, { UserId: number }>("UserUpdated");
|
|
409
428
|
}
|
|
410
429
|
|
|
@@ -434,7 +453,7 @@ actions.dispatch(Actions.UserUpdated({ Role: Role.Admin }), user);
|
|
|
434
453
|
actions.dispatch(Actions.UserUpdated, user);
|
|
435
454
|
```
|
|
436
455
|
|
|
437
|
-
Channel values support non-nullable primitives: `string`, `number`, `boolean`, or `symbol`. By convention, use uppercase keys like `{UserId: 4}` to distinguish
|
|
456
|
+
Channel values support non-nullable primitives: `string`, `number`, `boolean`, or `symbol`. By convention, use uppercase keys like `{UserId: 4}` to distinguish controller keys from payload properties.
|
|
438
457
|
|
|
439
458
|
For scoped communication between component groups, use multicast actions with the `withScope` HOC. Each multicast action defines its own scope – pass the same action to `withScope` and to `dispatch`, no separate scope name required:
|
|
440
459
|
|
|
@@ -473,7 +492,7 @@ See the [multicast recipe](./recipes/multicast-actions.md) for more details.
|
|
|
473
492
|
For coordinating between async handlers and threading ambient values (session tokens, locale, feature flags, current operational mode) without re-rendering the JSX tree on every dot read, use the per-`<Boundary>` `Store`. Declare your app's Store shape once via module augmentation, supply the initial value to `<Boundary store={...}>`, read via dot notation (`store.session`, `context.store.locale`), and write via `context.actions.produce(({ store }) => { ... })` — the same Immer-style recipe used for the model. Every `Resource` fetcher also receives a snapshot of the Store on its args object. When the view side needs to react to Store changes, subscribe to the global `Lifecycle.Store` broadcast — `actions.useAction(Lifecycle.Store, handler)` for handler-level work and `actions.stream(Lifecycle.Store, (store) => ...)` for JSX. Both seed from the initial Store on mount.
|
|
474
493
|
|
|
475
494
|
```ts
|
|
476
|
-
import {
|
|
495
|
+
import { useContext } from "march-hare";
|
|
477
496
|
|
|
478
497
|
// Declare your Store's shape once. Every read/write is typed against this.
|
|
479
498
|
declare module "march-hare" {
|
|
@@ -490,7 +509,8 @@ declare module "march-hare" {
|
|
|
490
509
|
</Boundary>;
|
|
491
510
|
|
|
492
511
|
export function useAuthActions() {
|
|
493
|
-
const
|
|
512
|
+
const context = useContext<void, typeof Actions>();
|
|
513
|
+
const actions = context.useActions();
|
|
494
514
|
|
|
495
515
|
actions.useAction(Actions.SignOut, async (context) => {
|
|
496
516
|
context.actions.produce(({ store }) => {
|
|
@@ -515,7 +535,7 @@ export function useAuthActions() {
|
|
|
515
535
|
Toggling boolean UI state – modals, sidebars, drawers – is one of the most common patterns. Bind a unicast action to a boolean field on the model with `With.Invert`:
|
|
516
536
|
|
|
517
537
|
```tsx
|
|
518
|
-
import {
|
|
538
|
+
import { useContext, Action, With } from "march-hare";
|
|
519
539
|
|
|
520
540
|
type Model = {
|
|
521
541
|
paymentDialog: boolean;
|
|
@@ -527,7 +547,8 @@ export class Actions {
|
|
|
527
547
|
static ToggleSidebar = Action("ToggleSidebar");
|
|
528
548
|
}
|
|
529
549
|
|
|
530
|
-
const
|
|
550
|
+
const context = useContext<Model, typeof Actions>();
|
|
551
|
+
const actions = context.useActions({
|
|
531
552
|
paymentDialog: false,
|
|
532
553
|
sidebar: false,
|
|
533
554
|
});
|
package/dist/hooks/index.d.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { Data } from './types';
|
|
2
|
-
import { Model, Props, Actions, UseActions } from '../types/index';
|
|
2
|
+
import { Model, Props, Actions, UseActions, Context as ContextHandle } from '../types/index';
|
|
3
3
|
export { With } from './utils';
|
|
4
4
|
/**
|
|
5
5
|
* A hook for managing state with actions.
|
|
@@ -45,3 +45,39 @@ export { With } from './utils';
|
|
|
45
45
|
*/
|
|
46
46
|
export declare function useActions<_M extends void = void, A extends Actions | void = void, D extends Props = Props>(getData?: Data<D>): UseActions<void, A, D>;
|
|
47
47
|
export declare function useActions<M extends Model, A extends Actions | void = void, D extends Props = Props>(initialModel: M, getData?: Data<D>): UseActions<M, A, D>;
|
|
48
|
+
/**
|
|
49
|
+
* Returns a stable, typed controller handle up-front — before a
|
|
50
|
+
* model is declared via `context.useActions(...)`. Use this when an
|
|
51
|
+
* external imperative library (form, animation, third-party SDK) needs a
|
|
52
|
+
* dispatch callback at construction time, while the value that library
|
|
53
|
+
* returns must flow back into the controller's data callback.
|
|
54
|
+
*
|
|
55
|
+
* The handle exposes `dispatch(action, payload?)` and a `useView(...)`
|
|
56
|
+
* method that materialises the component-local model and reactive data
|
|
57
|
+
* — the M and D pair of `useContext<M, AC, D>` — and
|
|
58
|
+
* returns the `[model, actions, data]` tuple with `useAction`, `dispatch`,
|
|
59
|
+
* `inspect`, and `stream` attached. The first invocation of
|
|
60
|
+
* `context.actions.dispatch(...)` must come from an event handler — not
|
|
61
|
+
* synchronously during render — because the underlying dispatch
|
|
62
|
+
* target is wired up when `context.useActions(...)` runs in the same
|
|
63
|
+
* render pass.
|
|
64
|
+
*
|
|
65
|
+
* @template M The model type representing the component's state.
|
|
66
|
+
* @template AC The actions class containing action definitions.
|
|
67
|
+
* @template D The data type for reactive external values.
|
|
68
|
+
*
|
|
69
|
+
* @example
|
|
70
|
+
* ```ts
|
|
71
|
+
* const context = useContext<Model, typeof Actions, Data>();
|
|
72
|
+
*
|
|
73
|
+
* const form = useForm({
|
|
74
|
+
* onSubmit: () => void context.actions.dispatch(Actions.Submit),
|
|
75
|
+
* });
|
|
76
|
+
*
|
|
77
|
+
* const actions = context.useActions(
|
|
78
|
+
* { user: user() },
|
|
79
|
+
* () => ({ form }),
|
|
80
|
+
* );
|
|
81
|
+
* ```
|
|
82
|
+
*/
|
|
83
|
+
export declare function useContext<M extends Model | void = void, AC extends Actions | void = void, D extends Props = Props>(): ContextHandle<M, AC, D>;
|
package/dist/index.d.ts
CHANGED
|
@@ -7,7 +7,8 @@ export { Boundary } from './boundary/index';
|
|
|
7
7
|
export { withScope } from './boundary/components/scope/index';
|
|
8
8
|
export { useStore } from './boundary/components/store/index';
|
|
9
9
|
export type { Store } from './boundary/components/store/index';
|
|
10
|
-
export {
|
|
10
|
+
export { useContext, With } from './hooks/index';
|
|
11
|
+
export type { Dispatch, Context } from './types/index';
|
|
11
12
|
export { Resource } from './resource/index';
|
|
12
13
|
export type { Fetcher } from './resource/index';
|
|
13
14
|
export { Cache } from './cache/index';
|
|
@@ -16,4 +17,4 @@ export * as utils from './utils/index';
|
|
|
16
17
|
export type { Stored, Unset } from './utils/index';
|
|
17
18
|
export type { Box } from 'immertation';
|
|
18
19
|
export type { Fault } from './error/index';
|
|
19
|
-
export type { Pk, Task, Tasks, Handlers, Handler, LeafActions, Dispatchable, Subscribable, } from './types/index';
|
|
20
|
+
export type { Pk, Reactive, Task, Tasks, Handlers, Handler, LeafActions, Dispatchable, Subscribable, } from './types/index';
|
package/dist/march-hare.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import{G as e,A as t}from"@mobily/ts-belt";import{immerable as n,enablePatches as r,Immer as o,produce as s}from"immer";import{jsx as c}from"react/jsx-runtime";import*as a from"react";const i=(e="")=>`march-hare.action/${e}`,u=(e="")=>`march-hare.action/broadcast/${e}`,l=(e="")=>`march-hare.action/multicast/${e}`,f=(e="")=>`march-hare.action.lifecycle/${e}`;class d{static Payload=/* @__PURE__ */Symbol("march-hare.brand/Payload");static Broadcast=/* @__PURE__ */Symbol("march-hare.brand/Broadcast");static Multicast=/* @__PURE__ */Symbol("march-hare.brand/Multicast");static Action=/* @__PURE__ */Symbol("march-hare.brand/Action");static Channel=/* @__PURE__ */Symbol("march-hare.brand/Channel");static Name=/* @__PURE__ */Symbol("march-hare.brand/Name")}function p(e){const t=/* @__PURE__ */Symbol(`march-hare.action.lifecycle/${e}`),n=function(n){return{[d.Action]:t,[d.Payload]:void 0,[d.Channel]:n,[d.Name]:e,channel:n}};return Object.defineProperty(n,d.Action,{value:t,enumerable:!1}),Object.defineProperty(n,d.Payload,{value:void 0,enumerable:!1}),Object.defineProperty(n,d.Name,{value:e,enumerable:!1}),n}const h=Symbol(u("Fault")),m=Symbol(u("Store"));class y{static Mount(){return p("Mount")}static Unmount(){return p("Unmount")}static Error(){return p("Error")}static Update(){return p("Update")}static Fault=(()=>{const e={};return Object.defineProperty(e,d.Action,{value:h,enumerable:!1}),Object.defineProperty(e,d.Payload,{value:void 0,enumerable:!1}),Object.defineProperty(e,d.Broadcast,{value:!0,enumerable:!1}),Object.defineProperty(e,d.Name,{value:"Fault",enumerable:!1}),e})();static Store=(()=>{const e={};return Object.defineProperty(e,d.Action,{value:m,enumerable:!1}),Object.defineProperty(e,d.Payload,{value:void 0,enumerable:!1}),Object.defineProperty(e,d.Broadcast,{value:!0,enumerable:!1}),Object.defineProperty(e,d.Name,{value:"Store",enumerable:!1}),e})()}var b=/* @__PURE__ */(e=>(e.Unicast="unicast",e.Broadcast="broadcast",e.Multicast="multicast",e))(b||{}),v=/* @__PURE__ */(e=>(e.Mounting="mounting",e.Mounted="mounted",e.Unmounting="unmounting",e.Unmounted="unmounted",e))(v||{});const g=e=>"symbol"==typeof e;function w(t){return e.isString(t)||g(t)?t:(e.isObject(t)||e.isFunction(t))&&d.Action in t?t[d.Action]:t}function O(t){if(e.isString(t))return t.startsWith(u());if(g(t))return t.description?.startsWith(u())??!1;if(e.isObject(t)||e.isFunction(t)){if(d.Broadcast in t&&t[d.Broadcast])return!0;if(d.Action in t){const e=t[d.Action];return e.description?.startsWith(u())??!1}}return!1}function P(t){const n=w(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)&&d.Channel in t&&"channel"in t}function j(e){const t=w(e),n=g(t)?t.description??"":t;return n.startsWith(f())&&n.slice(f().length)||null}function E(t){if(e.isString(t))return t.startsWith(l());if(g(t))return t.description?.startsWith(l())??!1;if(e.isObject(t)||e.isFunction(t)){if(d.Multicast in t&&t[d.Multicast])return!0;if(d.Action in t){const e=t[d.Action];return e.description?.startsWith(l())??!1}}return!1}const x=(e="",t=b.Unicast)=>{const n=t===b.Broadcast?Symbol(u(e)):t===b.Multicast?Symbol(l(e)):Symbol(i(e)),r=function(t){return{[d.Action]:n,[d.Payload]:void 0,[d.Channel]:t,[d.Name]:e,channel:t}};return Object.defineProperty(r,d.Action,{value:n,enumerable:!1}),Object.defineProperty(r,d.Payload,{value:void 0,enumerable:!1}),Object.defineProperty(r,d.Name,{value:e,enumerable:!1}),t===b.Broadcast&&Object.defineProperty(r,d.Broadcast,{value:!0,enumerable:!1}),t===b.Multicast&&Object.defineProperty(r,d.Multicast,{value:!0,enumerable:!1}),r};var M=/* @__PURE__ */(e=>(e[e.Timedout=0]="Timedout",e[e.Supplanted=1]="Supplanted",e[e.Errored=2]="Errored",e))(M||{});class C extends Error{name="AbortError";constructor(e="Aborted"){super(e)}}class k extends Error{name="TimeoutError";constructor(e="Timeout"){super(e)}}let N=(e=21)=>{let t="",n=crypto.getRandomValues(new Uint8Array(e|=0));for(;e--;)t+="useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict"[63&n[e]];return t};var 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))(_||{}),R=/* @__PURE__ */(e=>(e.Property="property",e.Process="process",e.Value="value",e.Operation="operation",e))(R||{});class U{[n]=!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 U(this.value,this.operation);return n.property=e,n.process=t,n}}class T{static immer=(()=>{r();const e=new o;return e.setAutoFreeze(!1),e})();static tag="κ";static id=N}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 B(t){if(e.isNullable(t)||$(t))return t;if(e.isArray(t))return t.map(e=>B(e));if(e.isObject(t)&&W(t)){const e=Object.entries(t).map(([e,t])=>[e,B(t)]);return{...Object.fromEntries(e),[T.tag]:t[T.tag]??T.id()}}return t}function F(e){if(Array.isArray(e))return e.filter(e=>T.tag in e).map(e=>e[T.tag]??"").join(",");const t=e[T.tag];if(t)return t;try{return JSON.stringify(e)}catch{return`[unserializable:${typeof e}]`}}function W(e){const t=Object.getPrototypeOf(e);return t===Object.prototype||null===t}function $(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 a(i,u=n.path){if(i instanceof U){const n=L(r,u.join("."));if(Object.entries(i).filter(([e,t])=>!U.keys.has(e)&&t instanceof U).forEach(([e,t])=>a(t,u.concat(e))),$(i.value)){if(t===_.Hydrate)return i.value;const a=u.slice(0,-1),l=a.length>0?L(r,a.join(".")):r;return e.isNullable(l)||H(l,i,u.at(-1),o,s,c),n??i.value}if(t===_.Hydrate){const e=B(a(i.value,u));return H(e,i,null,o,s,c),e}const l=n??B(i.value);return H(l,i,null,o,s,c),e.isNullable(n)?l:(a(i.value,u),n)}if(e.isArray(i))return i.map((e,t)=>a(e,u.concat(t)));if(e.isObject(i)&&!W(i))return i;if(e.isObject(i)){const e=Object.entries(i).map(([e,t])=>[e,a(t,u.concat(e))]),n=Object.fromEntries(e);if(t===_.Hydrate){const e=B(n);return Object.entries(i).forEach(([t,n])=>{n instanceof U&&$(n.value)&&H(e,n,t,o,s,c)}),e}return n}return i}(n.value)}function H(e,t,n,r,o,s){const c=s(e),a=o.get(c)??[];o.set(c,[t.assign(n,r),...a])}class I{#e={};#t;#n=/* @__PURE__ */new Map;#r=/* @__PURE__ */new Set;#o=!1;constructor(e=F){this.#t=e}static pk(){return N()}static"κ"=I.pk;annotate(e,t){return new U(t,e)}"δ"=this.annotate;get model(){return this.#e}get inspect(){return function(n,r,o,s,c){function a(s){const c=s.at(-1),a=L(n(),s),i=s.slice(0,-1),u=t.isNotEmpty(i)?L(n(),i):n();return[...e.isObject(a)||e.isArray(a)?r.get(o(a))?.filter(t=>e.isNullable(t.property))??[]:[],...e.isObject(u)?r.get(o(u))?.filter(e=>e.property===c)??[]:[]]}return function e(r){return new Proxy(()=>{},{get:(o,i)=>"pending"===i?()=>!t.isEmpty(a(r)):"remaining"===i?()=>t.length(a(r)):"box"===i?()=>({value:L(n(),r),inspect:e(r)}):"is"===i?e=>a(r).some(t=>0!==(t.operation&e)):"draft"===i?()=>t.head(a(r))?.value??L(n(),r):"settled"===i?()=>new Promise(e=>{if(t.isEmpty(a(r)))return e(L(n(),r));const o=()=>{t.isEmpty(a(r))&&(c(o),e(L(n(),r)))};s(o)}):e([...r,String(i)])})}([])}(()=>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]=T.immer.produceWithPatches(this.#e,t);return this.#e=r.reduce((t,r)=>T.immer.applyPatches(t,[{...r,value:D(e,r,t,n,this.#n,this.#t)}]),this.#e),this.#e=B(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 z=new I;function J(e,t=A.Update){return z.annotate(t,e)}function q(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var G,K={exports:{}};const V=/* @__PURE__ */q((G||(G=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 a=new o(r,s||e,c),i=n?n+t:t;return e._events[i]?e._events[i].fn?e._events[i]=[e._events[i],a]:e._events[i].push(a):(e._events[i]=a,e._eventsCount++),e}function c(e,t){0===--e._eventsCount?e._events=new r:delete e._events[t]}function a(){this._events=new r,this._eventsCount=0}Object.create&&(r.prototype=/* @__PURE__ */Object.create(null),(new r).__proto__||(n=!1)),a.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},a.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},a.prototype.listenerCount=function(e){var t=this._events[n?n+e:e];return t?t.fn?1:t.length:0},a.prototype.emit=function(e,t,r,o,s,c){var a=n?n+e:e;if(!this._events[a])return!1;var i,u,l=this._events[a],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(u=1,i=new Array(f-1);u<f;u++)i[u-1]=arguments[u];l.fn.apply(l.context,i)}else{var d,p=l.length;for(u=0;u<p;u++)switch(l[u].once&&this.removeListener(e,l[u].fn,void 0,!0),f){case 1:l[u].fn.call(l[u].context);break;case 2:l[u].fn.call(l[u].context,t);break;case 3:l[u].fn.call(l[u].context,t,r);break;case 4:l[u].fn.call(l[u].context,t,r,o);break;default:if(!i)for(d=1,i=new Array(f-1);d<f;d++)i[d-1]=arguments[d];l[u].fn.apply(l[u].context,i)}}return!0},a.prototype.on=function(e,t,n){return s(this,e,t,n,!1)},a.prototype.once=function(e,t,n){return s(this,e,t,n,!0)},a.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 a=this._events[s];if(a.fn)a.fn!==t||o&&!a.once||r&&a.context!==r||c(this,s);else{for(var i=0,u=[],l=a.length;i<l;i++)(a[i].fn!==t||o&&!a[i].once||r&&a[i].context!==r)&&u.push(a[i]);u.length?this._events[s]=1===u.length?u[0]:u:c(this,s)}return this},a.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},a.prototype.off=a.prototype.removeListener,a.prototype.addListener=a.prototype.on,a.prefixed=n,a.EventEmitter=a,e.exports=a}(K)),K.exports));class Q extends V{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 X=a.createContext(new Q);function Y(){return a.useContext(X)}function Z({children:e}){const t=a.useMemo(()=>new Q,[]);/* @__PURE__ */
|
|
1
|
+
import{G as e,A as t}from"@mobily/ts-belt";import{immerable as n,enablePatches as r,Immer as o,produce as s}from"immer";import{jsx as c}from"react/jsx-runtime";import*as a from"react";const i=(e="")=>`march-hare.action/${e}`,u=(e="")=>`march-hare.action/broadcast/${e}`,l=(e="")=>`march-hare.action/multicast/${e}`,f=(e="")=>`march-hare.action.lifecycle/${e}`;class d{static Payload=/* @__PURE__ */Symbol("march-hare.brand/Payload");static Broadcast=/* @__PURE__ */Symbol("march-hare.brand/Broadcast");static Multicast=/* @__PURE__ */Symbol("march-hare.brand/Multicast");static Action=/* @__PURE__ */Symbol("march-hare.brand/Action");static Channel=/* @__PURE__ */Symbol("march-hare.brand/Channel");static Name=/* @__PURE__ */Symbol("march-hare.brand/Name")}function p(e){const t=/* @__PURE__ */Symbol(`march-hare.action.lifecycle/${e}`),n=function(n){return{[d.Action]:t,[d.Payload]:void 0,[d.Channel]:n,[d.Name]:e,channel:n}};return Object.defineProperty(n,d.Action,{value:t,enumerable:!1}),Object.defineProperty(n,d.Payload,{value:void 0,enumerable:!1}),Object.defineProperty(n,d.Name,{value:e,enumerable:!1}),n}const h=Symbol(u("Fault")),m=Symbol(u("Store"));class y{static Mount(){return p("Mount")}static Unmount(){return p("Unmount")}static Error(){return p("Error")}static Update(){return p("Update")}static Fault=(()=>{const e={};return Object.defineProperty(e,d.Action,{value:h,enumerable:!1}),Object.defineProperty(e,d.Payload,{value:void 0,enumerable:!1}),Object.defineProperty(e,d.Broadcast,{value:!0,enumerable:!1}),Object.defineProperty(e,d.Name,{value:"Fault",enumerable:!1}),e})();static Store=(()=>{const e={};return Object.defineProperty(e,d.Action,{value:m,enumerable:!1}),Object.defineProperty(e,d.Payload,{value:void 0,enumerable:!1}),Object.defineProperty(e,d.Broadcast,{value:!0,enumerable:!1}),Object.defineProperty(e,d.Name,{value:"Store",enumerable:!1}),e})()}var b=/* @__PURE__ */(e=>(e.Unicast="unicast",e.Broadcast="broadcast",e.Multicast="multicast",e))(b||{}),v=/* @__PURE__ */(e=>(e.Mounting="mounting",e.Mounted="mounted",e.Unmounting="unmounting",e.Unmounted="unmounted",e))(v||{});const g=e=>"symbol"==typeof e;function w(t){return e.isString(t)||g(t)?t:(e.isObject(t)||e.isFunction(t))&&d.Action in t?t[d.Action]:t}function O(t){if(e.isString(t))return t.startsWith(u());if(g(t))return t.description?.startsWith(u())??!1;if(e.isObject(t)||e.isFunction(t)){if(d.Broadcast in t&&t[d.Broadcast])return!0;if(d.Action in t){const e=t[d.Action];return e.description?.startsWith(u())??!1}}return!1}function P(t){const n=w(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)&&d.Channel in t&&"channel"in t}function j(e){const t=w(e),n=g(t)?t.description??"":t;return n.startsWith(f())&&n.slice(f().length)||null}function E(t){if(e.isString(t))return t.startsWith(l());if(g(t))return t.description?.startsWith(l())??!1;if(e.isObject(t)||e.isFunction(t)){if(d.Multicast in t&&t[d.Multicast])return!0;if(d.Action in t){const e=t[d.Action];return e.description?.startsWith(l())??!1}}return!1}const x=(e="",t=b.Unicast)=>{const n=t===b.Broadcast?Symbol(u(e)):t===b.Multicast?Symbol(l(e)):Symbol(i(e)),r=function(t){return{[d.Action]:n,[d.Payload]:void 0,[d.Channel]:t,[d.Name]:e,channel:t}};return Object.defineProperty(r,d.Action,{value:n,enumerable:!1}),Object.defineProperty(r,d.Payload,{value:void 0,enumerable:!1}),Object.defineProperty(r,d.Name,{value:e,enumerable:!1}),t===b.Broadcast&&Object.defineProperty(r,d.Broadcast,{value:!0,enumerable:!1}),t===b.Multicast&&Object.defineProperty(r,d.Multicast,{value:!0,enumerable:!1}),r};var C=/* @__PURE__ */(e=>(e[e.Timedout=0]="Timedout",e[e.Supplanted=1]="Supplanted",e[e.Errored=2]="Errored",e))(C||{});class M extends Error{name="AbortError";constructor(e="Aborted"){super(e)}}class A extends Error{name="TimeoutError";constructor(e="Timeout"){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 N=/* @__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))(N||{}),_=/* @__PURE__ */(e=>(e[e.Produce=0]="Produce",e[e.Hydrate=1]="Hydrate",e))(_||{}),R=/* @__PURE__ */(e=>(e.Property="property",e.Process="process",e.Value="value",e.Operation="operation",e))(R||{});class U{[n]=!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 U(this.value,this.operation);return n.property=e,n.process=t,n}}class T{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 B(t){if(e.isNullable(t)||$(t))return t;if(e.isArray(t))return t.map(e=>B(e));if(e.isObject(t)&&W(t)){const e=Object.entries(t).map(([e,t])=>[e,B(t)]);return{...Object.fromEntries(e),[T.tag]:t[T.tag]??T.id()}}return t}function F(e){if(Array.isArray(e))return e.filter(e=>T.tag in e).map(e=>e[T.tag]??"").join(",");const t=e[T.tag];if(t)return t;try{return JSON.stringify(e)}catch{return`[unserializable:${typeof e}]`}}function W(e){const t=Object.getPrototypeOf(e);return t===Object.prototype||null===t}function $(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 a(i,u=n.path){if(i instanceof U){const n=L(r,u.join("."));if(Object.entries(i).filter(([e,t])=>!U.keys.has(e)&&t instanceof U).forEach(([e,t])=>a(t,u.concat(e))),$(i.value)){if(t===_.Hydrate)return i.value;const a=u.slice(0,-1),l=a.length>0?L(r,a.join(".")):r;return e.isNullable(l)||H(l,i,u.at(-1),o,s,c),n??i.value}if(t===_.Hydrate){const e=B(a(i.value,u));return H(e,i,null,o,s,c),e}const l=n??B(i.value);return H(l,i,null,o,s,c),e.isNullable(n)?l:(a(i.value,u),n)}if(e.isArray(i))return i.map((e,t)=>a(e,u.concat(t)));if(e.isObject(i)&&!W(i))return i;if(e.isObject(i)){const e=Object.entries(i).map(([e,t])=>[e,a(t,u.concat(e))]),n=Object.fromEntries(e);if(t===_.Hydrate){const e=B(n);return Object.entries(i).forEach(([t,n])=>{n instanceof U&&$(n.value)&&H(e,n,t,o,s,c)}),e}return n}return i}(n.value)}function H(e,t,n,r,o,s){const c=s(e),a=o.get(c)??[];o.set(c,[t.assign(n,r),...a])}class I{#e={};#t;#n=/* @__PURE__ */new Map;#r=/* @__PURE__ */new Set;#o=!1;constructor(e=F){this.#t=e}static pk(){return k()}static"κ"=I.pk;annotate(e,t){return new U(t,e)}"δ"=this.annotate;get model(){return this.#e}get inspect(){return function(n,r,o,s,c){function a(s){const c=s.at(-1),a=L(n(),s),i=s.slice(0,-1),u=t.isNotEmpty(i)?L(n(),i):n();return[...e.isObject(a)||e.isArray(a)?r.get(o(a))?.filter(t=>e.isNullable(t.property))??[]:[],...e.isObject(u)?r.get(o(u))?.filter(e=>e.property===c)??[]:[]]}return function e(r){return new Proxy(()=>{},{get:(o,i)=>"pending"===i?()=>!t.isEmpty(a(r)):"remaining"===i?()=>t.length(a(r)):"box"===i?()=>({value:L(n(),r),inspect:e(r)}):"is"===i?e=>a(r).some(t=>0!==(t.operation&e)):"draft"===i?()=>t.head(a(r))?.value??L(n(),r):"settled"===i?()=>new Promise(e=>{if(t.isEmpty(a(r)))return e(L(n(),r));const o=()=>{t.isEmpty(a(r))&&(c(o),e(L(n(),r)))};s(o)}):e([...r,String(i)])})}([])}(()=>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]=T.immer.produceWithPatches(this.#e,t);return this.#e=r.reduce((t,r)=>T.immer.applyPatches(t,[{...r,value:D(e,r,t,n,this.#n,this.#t)}]),this.#e),this.#e=B(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 z=new I;function J(e,t=N.Update){return z.annotate(t,e)}function q(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var G,K={exports:{}};const V=/* @__PURE__ */q((G||(G=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 a=new o(r,s||e,c),i=n?n+t:t;return e._events[i]?e._events[i].fn?e._events[i]=[e._events[i],a]:e._events[i].push(a):(e._events[i]=a,e._eventsCount++),e}function c(e,t){0===--e._eventsCount?e._events=new r:delete e._events[t]}function a(){this._events=new r,this._eventsCount=0}Object.create&&(r.prototype=/* @__PURE__ */Object.create(null),(new r).__proto__||(n=!1)),a.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},a.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},a.prototype.listenerCount=function(e){var t=this._events[n?n+e:e];return t?t.fn?1:t.length:0},a.prototype.emit=function(e,t,r,o,s,c){var a=n?n+e:e;if(!this._events[a])return!1;var i,u,l=this._events[a],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(u=1,i=new Array(f-1);u<f;u++)i[u-1]=arguments[u];l.fn.apply(l.context,i)}else{var d,p=l.length;for(u=0;u<p;u++)switch(l[u].once&&this.removeListener(e,l[u].fn,void 0,!0),f){case 1:l[u].fn.call(l[u].context);break;case 2:l[u].fn.call(l[u].context,t);break;case 3:l[u].fn.call(l[u].context,t,r);break;case 4:l[u].fn.call(l[u].context,t,r,o);break;default:if(!i)for(d=1,i=new Array(f-1);d<f;d++)i[d-1]=arguments[d];l[u].fn.apply(l[u].context,i)}}return!0},a.prototype.on=function(e,t,n){return s(this,e,t,n,!1)},a.prototype.once=function(e,t,n){return s(this,e,t,n,!0)},a.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 a=this._events[s];if(a.fn)a.fn!==t||o&&!a.once||r&&a.context!==r||c(this,s);else{for(var i=0,u=[],l=a.length;i<l;i++)(a[i].fn!==t||o&&!a[i].once||r&&a[i].context!==r)&&u.push(a[i]);u.length?this._events[s]=1===u.length?u[0]:u:c(this,s)}return this},a.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},a.prototype.off=a.prototype.removeListener,a.prototype.addListener=a.prototype.on,a.prefixed=n,a.EventEmitter=a,e.exports=a}(K)),K.exports));class Q extends V{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 X=a.createContext(new Q);function Y(){return a.useContext(X)}function Z({children:e}){const t=a.useMemo(()=>new Q,[]);/* @__PURE__ */
|
|
2
2
|
return c(X.Provider,{value:t,children:e})}const ee=a.createContext(/* @__PURE__ */new Set);function te({children:e}){const t=a.useMemo(()=>/* @__PURE__ */new Set,[]);/* @__PURE__ */
|
|
3
3
|
return c(ee.Provider,{value:t,children:e})}const ne=a.createContext({current:{}});function re(){const e=a.useContext(ne);return a.useMemo(()=>new Proxy({},{get:(t,n)=>Reflect.get(e.current,n),has:(t,n)=>n in e.current,ownKeys:()=>Reflect.ownKeys(e.current),getOwnPropertyDescriptor(t,n){const r=Object.getOwnPropertyDescriptor(e.current,n);if(void 0!==r)return{...r,configurable:!0}},set(){throw new TypeError("Store is read-only outside `context.actions.produce`. Mutate via produce(({ store }) => { store.x = ... }) instead.")}}),[e])}function oe({initial:e,children:t}){const n=a.useRef(e),r=Y();return void 0===r.getCached(m)&&r.setCache(m,n.current),/* @__PURE__ */c(ne.Provider,{value:n,children:t})}function se({store:e,children:t}){/* @__PURE__ */
|
|
4
4
|
return c(Z,{children:/* @__PURE__ */c(oe,{initial:e??{},children:/* @__PURE__ */c(te,{children:t})})})}const ce=a.createContext(null);function ae(){return a.useContext(ce)}function ie(e,t){return e?.get(t)??null}function ue(e,t){const n=`Scoped${t.displayName||t.name||"Component"}`,r=w(e);return{[n](e){const n=ae(),o=a.useMemo(()=>({action:r,emitter:new Q}),[]),s=a.useMemo(()=>{const e=new Map(n??[]);return e.set(r,o),e},[n,o]);/* @__PURE__ */
|
|
5
|
-
return c(ce.Provider,{value:s,children:/* @__PURE__ */c(t,{...e})})}}[n]}const le=Symbol(((e="")=>`march-hare/replay${e}`)());function fe(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(()=>{})}const de={Update:e=>(t,n)=>{t.actions.produce(t=>{t.model[e]=n})},Invert:e=>t=>{t.actions.produce(t=>{t.model[e]=!t.model[e]})}};function pe(e,t){for(const n of e.keys())if(j(n)===t)return n;return null}const he=/* @__PURE__ */Symbol("march-hare.unset");function me(){const[,e]=a.useReducer(e=>e+1,0);return e}function ye(){return{data:he,at:null,else:e=>e}}function be(e,t){return{data:e,at:t,else:t=>e}}function ve(e){if(e instanceof Error){if("TimeoutError"===e.name)return
|
|
5
|
+
return c(ce.Provider,{value:s,children:/* @__PURE__ */c(t,{...e})})}}[n]}const le=Symbol(((e="")=>`march-hare/replay${e}`)());function fe(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(()=>{})}const de={Update:e=>(t,n)=>{t.actions.produce(t=>{t.model[e]=n})},Invert:e=>t=>{t.actions.produce(t=>{t.model[e]=!t.model[e]})}};function pe(e,t){for(const n of e.keys())if(j(n)===t)return n;return null}const he=/* @__PURE__ */Symbol("march-hare.unset");function me(){const[,e]=a.useReducer(e=>e+1,0);return e}function ye(){return{data:he,at:null,else:e=>e}}function be(e,t){return{data:e,at:t,else:t=>e}}function ve(e){if(e instanceof Error){if("TimeoutError"===e.name)return C.Timedout;if("AbortError"===e.name)return C.Supplanted}return C.Errored}function ge(e){const t=/* @__PURE__ */new Map,n=e??{get:e=>t.get(e)??null,set:(e,n)=>{t.set(e,n)},remove:e=>{t.delete(e)},clear:()=>{t.clear()}};return{get(e){try{const t=n.get(e);if(null===t)return ye();const r=JSON.parse(t);return be(r.data,Temporal.Instant.from(r.at))}catch{return ye()}},set(e,t){if(t.data===he||null===t.at)return!1;try{return n.set(e,JSON.stringify({data:t.data,at:t.at.toString()})),!0}catch{return!1}},remove(e){n.remove(e)},clear(){n.clear()}}}function we(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 Oe(e,t,n){if(t?.aborted)throw new M;for(;;){if(await n())return;await we(e,t)}}function Pe(e){return e?Boolean(e&&"symbol"!=typeof e):/* @__PURE__ */Symbol(`pk.${Date.now()}.${crypto.randomUUID()}`)}const Se=/* @__PURE__ */Object.freeze(/* @__PURE__ */Object.defineProperty({__proto__:null,pk:Pe,poll:Oe,sleep:we,unset:he,"ζ":we,"κ":Pe,"π":Oe},Symbol.toStringTag,{value:"Module"})),je=/* @__PURE__ */new WeakMap;function Ee(e){return JSON.stringify(e)}let xe=null;function Ce(){if(null===xe)throw new Error("context.actions.resource(...) and context.actions.resource.set(...) must be called with a fresh resource invocation, e.g. context.actions.resource(cat({ id: 5 })).");const e=xe;return xe=null,e}function Me(e,t){const n=t??function(e){let t=je.get(e);return void 0===t&&(t=ge(),je.set(e,t)),t}(e),r=e=>{const t=n.get(Ee(e));return t.data===he||null===t.at?{data:he,at:null}:{data:t.data,at:t.at}},o=(t,r,o)=>e({store:t,controller:r,params:o}).then(e=>(n.set(Ee(o),be(e,Temporal.Now.instant())),e)),s=(e,t,r)=>{n.set(Ee(e),be(t,r))};return function(e){const t=e??{};xe={run:o,read:r,seed:s,params:t},queueMicrotask(()=>{null!==xe&&xe.params===t&&(xe=null)});const{data:n}=r(t);return n===he?null:n}}const Ae=a.createContext(/* @__PURE__ */new Map);function ke({action:t,renderer:n}){const r=Y(),o=a.useContext(Ae),s=me(),c=a.useMemo(()=>{const e=o.get(t);if(e)return e;const n=new I,s=r.getCached(t);void 0!==s&&n.hydrate({value:s});const c={state:n,listeners:/* @__PURE__ */new Set};return o.set(t,c),c},[t,r,o]);a.useLayoutEffect(()=>{function e(e){c.state.hydrate({value:e}),c.listeners.forEach(e=>e())}return c.listeners.add(s),r.on(t,e),()=>{c.listeners.delete(s),r.off(t,e)}},[t,r,c]);const i=c.state.model?.value;return e.isNullable(i)?null:n(i,c.state.inspect.value)}function Ne(){const n=a.useRef(null);return a.useMemo(()=>({actions:{dispatch:function(e,t){const r=n.current;if(!r)throw new Error("march-hare: useContext handle dispatched before its paired context.useActions(...) ran. Call context.actions.dispatch from event handlers, not synchronously during render.");return r(e,t)}},useActions:function(...r){const o=function(...n){const r=e.isUndefined(n[0])||e.isFunction(n[0])?{}:n[0],o=e.isFunction(n[0])?n[0]:n[1]??(()=>({})),c=Y(),i=ae(),u=a.useContext(ee),l=re(),f=a.useContext(ne),d=me(),p=a.useRef(!1),y=a.useRef(null),b=a.useRef(new I);p.current||(p.current=!0,y.current=b.current.hydrate(r));const[g,j]=a.useState(()=>b.current.model),x=function(e){const t=a.useRef(e);return t.current=e,a.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=a.useMemo(()=>new V,[]),M=a.useRef({handlers:/* @__PURE__ */new Map});M.current.handlers=/* @__PURE__ */new Map;const A=function(){const e=a.useRef(/* @__PURE__ */new Set),t=a.useRef(/* @__PURE__ */new Set);return a.useMemo(()=>({broadcast:e.current,multicast:t.current}),[])}(),k=a.useRef(v.Mounting),_=a.useRef(/* @__PURE__ */new Set),R=a.useRef(0),U=a.useCallback((e,t,n)=>{const r=new AbortController,o={controller:r,action:e,payload:t};return u.add(o),_.current.add(o),{model:b.current.model,get phase(){return k.current},task:o,data:x,tasks:u,store:l,actions:{produce(e){if(r.signal.aborted)return;const t=f.current,o=b.current.produce(t=>{f.current=s(f.current,n=>{e({model:t,inspect:b.current.inspect,store:n})})});j(b.current.model),f.current!==t&&c.emit(m,f.current),n.processes.add(o),y.current&&(n.processes.add(y.current),y.current=null)},dispatch(e,t){if(r.signal.aborted)return Promise.resolve();const n=w(e),o=S(e)?e.channel:void 0;if(E(e)){const e=ie(i,n);return e?fe(e.emitter,n,t,o):Promise.resolve()}return fe(O(e)?c:C,n,t,o)},annotate:(e,t=N.Update)=>b.current.annotate(t,e),get inspect(){return b.current.inspect},resource:Object.assign(function(e){const t=Ce(),n=()=>t.run(f.current,r,t.params);return{then:(e,t)=>n().then(e,t),exceeds:e=>{const{data:r,at:o}=t.read(t.params);if(r!==he&&null!==o){const t=Temporal.Now.instant().since(o),n=Temporal.Duration.from(e);if(Temporal.Duration.compare(t,n)<=0)return Promise.resolve(r)}return n()}}},{set:(e,t)=>{const n=Ce();n.seed(n.params,t,Temporal.Now.instant())}}),async resolution(e){if(r.signal.aborted)return null;const t=w(e),n=E(e)?ie(i,t)?.emitter??null:c;if(!n)return null;if(void 0===n.getCached(t))return null;const o=b.current.inspect;return o.pending()&&await new Promise((e,t)=>{if(r.signal.aborted)return void t(r.signal.reason);const n=()=>t(r.signal.reason);r.signal.addEventListener("abort",n,{once:!0}),o.settled().then(()=>{r.signal.removeEventListener("abort",n),e()})}),n.getCached(t)??null},peek(e){if(r.signal.aborted)return null;const t=w(e),n=E(e)?ie(i,t)?.emitter??null:c;return n?n.getCached(t)??null:null}}}},[g]);a.useLayoutEffect(()=>{function t(t,n,r){return function(o,s){const a=r();if(s===le&&e.isNotNullable(a))return;if(e.isNotNullable(s)&&s!==le&&e.isNotNullable(a)&&!function(e,t){for(const n of Object.keys(e))if(t[n]!==e[n])return!1;return!0}(s,a))return;const i={processes:/* @__PURE__ */new Set},l=Promise.withResolvers(),f=U(t,o,i);function p(e){const n=pe(M.current.handlers,"Error"),r=null!==n,o={reason:ve(e),error:(s=e,s instanceof Error?s:new Error(String(s))),action:P(t),handled:r,tasks:u};var s;c.fire(h,o),r&&n&&C.emit(n,o)}function m(){for(const e of u)if(e===f.task){u.delete(e),_.current.delete(e);break}i.processes.forEach(e=>b.current.prune(e)),i.processes.size>0&&d(),l.resolve()}let y;try{y=n(f,o)}catch(v){return p(v),void m()}if(!function(e){if(!e||"object"!=typeof e)return!1;const t=Object.prototype.toString.call(e);return"[object Generator]"===t||"[object AsyncGenerator]"===t}(y))return Promise.resolve(y).catch(p).finally(m),l.promise;(async()=>{for await(const e of y);})().catch(p).finally(m)}}R.current++;const n=/* @__PURE__ */new Set;return M.current.handlers.forEach((e,r)=>{for(const{getChannel:o,handler:s}of e){const e=t(r,s,o);if(E(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 O(r)?(c.on(r,e),C.on(r,e),A.broadcast.add(r),n.add(()=>{c.off(r,e),C.off(r,e)})):(C.on(r,e),n.add(()=>C.off(r,e)))}}),()=>{const e=++R.current,t=new Set(n);queueMicrotask(()=>{if(R.current!==e){for(const e of t)e();return}for(const e of _.current)e.controller.abort(),u.delete(e);_.current.clear(),k.current=v.Unmounting;const n=pe(M.current.handlers,"Unmount");n&&C.emit(n),k.current=v.Unmounted;for(const e of t)e()})}},[C]),function({unicast:n,broadcast:r,dispatchers:o,scope:s,phase:c,data:i,handlers:u}){const l=a.useRef(null);a.useLayoutEffect(()=>{if(c.current===v.Mounted)return;c.current=v.Mounting;const t=pe(u,"Mount");t&&n.emit(t),o.broadcast.forEach(t=>{const o=r.getCached(t);e.isNullable(o)||n.emit(t,o,le)}),s&&o.multicast.forEach(t=>{for(const r of s.values()){const o=r.emitter.getCached(t);e.isNullable(o)||n.emit(t,o,le)}}),c.current=v.Mounted},[]),a.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,i);if(t.isNotEmpty(Object.keys(e))){const t=pe(u,"Update");t&&n.emit(t,e)}}l.current=i},[i,n])}({unicast:C,broadcast:c,dispatchers:A,scope:i,phase:k,data:o(),handlers:M.current.handlers});const T=a.useMemo(()=>({dispatch(e,t){const n=w(e),r=S(e)?e.channel:void 0;if(E(e)){const e=ie(i,n);return e?fe(e.emitter,n,t,r):Promise.resolve()}return fe(O(e)?c:C,n,t,r)},get inspect(){return b.current.inspect},stream:(e,t)=>a.createElement(ke,{action:w(e),renderer:t})}),[g,C]),L=a.useMemo(()=>[g,T,x],[g,T,x]);return L.useAction=(e,t)=>{!function(e,t,n){const r=a.useRef(n);a.useLayoutEffect(()=>{r.current=n});const o=a.useRef(t);a.useLayoutEffect(()=>{o.current=t});const s=a.useCallback((e,t)=>r.current(e,t),[]),c=a.useCallback(()=>S(o.current)?o.current.channel:void 0,[]),i=w(t),u=e.current.handlers.get(i)??/* @__PURE__ */new Set;0===u.size&&e.current.handlers.set(i,u),u.add({getChannel:c,handler:s})}(M,e,t)},L.dispatch=L[1].dispatch,L}(...r);return n.current=o.dispatch,o}}),[])}export{M as AbortError,x as Action,se as Boundary,ge as Cache,b as Distribution,y as Lifecycle,N as Op,N as Operation,C as Reason,Me as Resource,I as State,A as TimeoutError,de as With,J as annotate,Ne as useContext,re as useStore,Se as utils,ue as withScope};
|
package/dist/march-hare.umd.cjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
var global,factory;global=this,factory=function(e,t,r,n,o){"use strict";function s(e){const t=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(e)for(const r in e)if("default"!==r){const n=Object.getOwnPropertyDescriptor(e,r);Object.defineProperty(t,r,n.get?n:{enumerable:!0,get:()=>e[r]})}return t.default=e,Object.freeze(t)}const c=s(o),a=(e="")=>`march-hare.action/${e}`,i=(e="")=>`march-hare.action/broadcast/${e}`,u=(e="")=>`march-hare.action/multicast/${e}`,l=(e="")=>`march-hare.action.lifecycle/${e}`;class f{static Payload=Symbol("march-hare.brand/Payload");static Broadcast=Symbol("march-hare.brand/Broadcast");static Multicast=Symbol("march-hare.brand/Multicast");static Action=Symbol("march-hare.brand/Action");static Channel=Symbol("march-hare.brand/Channel");static Name=Symbol("march-hare.brand/Name")}function d(e){const t=Symbol(`march-hare.action.lifecycle/${e}`),r=function(r){return{[f.Action]:t,[f.Payload]:void 0,[f.Channel]:r,[f.Name]:e,channel:r}};return Object.defineProperty(r,f.Action,{value:t,enumerable:!1}),Object.defineProperty(r,f.Payload,{value:void 0,enumerable:!1}),Object.defineProperty(r,f.Name,{value:e,enumerable:!1}),r}const p=Symbol(i("Fault")),h=Symbol(i("Store"));class m{static Mount(){return d("Mount")}static Unmount(){return d("Unmount")}static Error(){return d("Error")}static Update(){return d("Update")}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}),Object.defineProperty(e,f.Name,{value:"Fault",enumerable:!1}),e})();static Store=(()=>{const e={};return Object.defineProperty(e,f.Action,{value:h,enumerable:!1}),Object.defineProperty(e,f.Payload,{value:void 0,enumerable:!1}),Object.defineProperty(e,f.Broadcast,{value:!0,enumerable:!1}),Object.defineProperty(e,f.Name,{value:"Store",enumerable:!1}),e})()}var b=(e=>(e.Unicast="unicast",e.Broadcast="broadcast",e.Multicast="multicast",e))(b||{}),y=(e=>(e.Mounting="mounting",e.Mounted="mounted",e.Unmounting="unmounting",e.Unmounted="unmounted",e))(y||{});const v=e=>"symbol"==typeof e;function g(e){return t.G.isString(e)||v(e)?e:(t.G.isObject(e)||t.G.isFunction(e))&&f.Action in e?e[f.Action]:e}function w(e){if(t.G.isString(e))return e.startsWith(i());if(v(e))return e.description?.startsWith(i())??!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(i())??!1}}return!1}function j(e){const r=g(e),n=t.G.isString(r)?r:r.description??"";return n.startsWith(a())&&n.slice(n.lastIndexOf("/")+1)||"unknown"}function O(e){return t.G.isObject(e)&&f.Channel in e&&"channel"in e}function S(e){const t=g(e),r=v(t)?t.description??"":t;return r.startsWith(l())&&r.slice(l().length)||null}function P(e){if(t.G.isString(e))return e.startsWith(u());if(v(e))return e.description?.startsWith(u())??!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(u())??!1}}return!1}var x=(e=>(e[e.Timedout=0]="Timedout",e[e.Supplanted=1]="Supplanted",e[e.Errored=2]="Errored",e))(x||{});class E extends Error{name="AbortError";constructor(e="Aborted"){super(e)}}class M extends Error{name="TimeoutError";constructor(e="Timeout"){super(e)}}let A=(e=21)=>{let t="",r=crypto.getRandomValues(new Uint8Array(e|=0));for(;e--;)t+="useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict"[63&r[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 N{[r.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 r=new N(this.value,this.operation);return r.property=e,r.process=t,r}}class _{static immer=(()=>{r.enablePatches();const e=new r.Immer;return e.setAutoFreeze(!1),e})();static tag="κ";static id=A}function R(e,t){const r="string"==typeof t?""===t?[]:t.split("."):t;let n=e;for(const o of r){if(null==n)return;n=n[o]}return n}function T(e){if(t.G.isNullable(e)||B(e))return e;if(t.G.isArray(e))return e.map(e=>T(e));if(t.G.isObject(e)&&L(e)){const t=Object.entries(e).map(([e,t])=>[e,T(t)]);return{...Object.fromEntries(t),[_.tag]:e[_.tag]??_.id()}}return e}function U(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 L(e){const t=Object.getPrototypeOf(e);return t===Object.prototype||null===t}function B(e){return t.G.isNullable(e)||t.G.isString(e)||t.G.isNumber(e)||t.G.isBoolean(e)||"symbol"==typeof e||"bigint"==typeof e}function F(e,r,n,o,s,c){return function a(i,u=r.path){if(i instanceof N){const r=R(n,u.join("."));if(Object.entries(i).filter(([e,t])=>!N.keys.has(e)&&t instanceof N).forEach(([e,t])=>a(t,u.concat(e))),B(i.value)){if(e===G.Hydrate)return i.value;const a=u.slice(0,-1),l=a.length>0?R(n,a.join(".")):n;return t.G.isNullable(l)||W(l,i,u.at(-1),o,s,c),r??i.value}if(e===G.Hydrate){const e=T(a(i.value,u));return W(e,i,null,o,s,c),e}const l=r??T(i.value);return W(l,i,null,o,s,c),t.G.isNullable(r)?l:(a(i.value,u),r)}if(t.G.isArray(i))return i.map((e,t)=>a(e,u.concat(t)));if(t.G.isObject(i)&&!L(i))return i;if(t.G.isObject(i)){const t=Object.entries(i).map(([e,t])=>[e,a(t,u.concat(e))]),r=Object.fromEntries(t);if(e===G.Hydrate){const e=T(r);return Object.entries(i).forEach(([t,r])=>{r instanceof N&&B(r.value)&&W(e,r,t,o,s,c)}),e}return r}return i}(r.value)}function W(e,t,r,n,o,s){const c=s(e),a=o.get(c)??[];o.set(c,[t.assign(r,n),...a])}class ${#e={};#t;#r=new Map;#n=new Set;#o=!1;constructor(e=U){this.#t=e}static pk(){return A()}static"κ"=$.pk;annotate(e,t){return new N(t,e)}"δ"=this.annotate;get model(){return this.#e}get inspect(){return function(e,r,n,o,s){function c(o){const s=o.at(-1),c=R(e(),o),a=o.slice(0,-1),i=t.A.isNotEmpty(a)?R(e(),a):e();return[...t.G.isObject(c)||t.G.isArray(c)?r.get(n(c))?.filter(e=>t.G.isNullable(e.property))??[]:[],...t.G.isObject(i)?r.get(n(i))?.filter(e=>e.property===s)??[]:[]]}return function r(n){return new Proxy(()=>{},{get:(a,i)=>"pending"===i?()=>!t.A.isEmpty(c(n)):"remaining"===i?()=>t.A.length(c(n)):"box"===i?()=>({value:R(e(),n),inspect:r(n)}):"is"===i?e=>c(n).some(t=>0!==(t.operation&e)):"draft"===i?()=>t.A.head(c(n))?.value??R(e(),n):"settled"===i?()=>new Promise(r=>{if(t.A.isEmpty(c(n)))return r(R(e(),n));const a=()=>{t.A.isEmpty(c(n))&&(s(a),r(R(e(),n)))};o(a)}):r([...n,String(i)])})}([])}(()=>this.#e,this.#r,this.#t,e=>this.#n.add(e),e=>this.#n.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 r=Symbol("process"),[,n]=_.immer.produceWithPatches(this.#e,t);return this.#e=n.reduce((t,n)=>_.immer.applyPatches(t,[{...n,value:F(e,n,t,r,this.#r,this.#t)}]),this.#e),this.#e=T(this.#e),this.#c(),r}prune(e){this.#r.forEach((r,n)=>{const o=r.filter(t=>t.process!==e);t.A.isEmpty(o)?this.#r.delete(n):this.#r.set(n,o)}),this.#c()}#c(){this.#n.forEach(e=>e())}observe(e){const t=()=>e(this.#e);return this.#n.add(t),()=>this.#n.delete(t)}}const D=new $;function I(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var H,q={exports:{}},z=(H||(H=1,function(e){var t=Object.prototype.hasOwnProperty,r="~";function n(){}function o(e,t,r){this.fn=e,this.context=t,this.once=r||!1}function s(e,t,n,s,c){if("function"!=typeof n)throw new TypeError("The listener must be a function");var a=new o(n,s||e,c),i=r?r+t:t;return e._events[i]?e._events[i].fn?e._events[i]=[e._events[i],a]:e._events[i].push(a):(e._events[i]=a,e._eventsCount++),e}function c(e,t){0===--e._eventsCount?e._events=new n:delete e._events[t]}function a(){this._events=new n,this._eventsCount=0}Object.create&&(n.prototype=Object.create(null),(new n).__proto__||(r=!1)),a.prototype.eventNames=function(){var e,n,o=[];if(0===this._eventsCount)return o;for(n in e=this._events)t.call(e,n)&&o.push(r?n.slice(1):n);return Object.getOwnPropertySymbols?o.concat(Object.getOwnPropertySymbols(e)):o},a.prototype.listeners=function(e){var t=this._events[r?r+e:e];if(!t)return[];if(t.fn)return[t.fn];for(var n=0,o=t.length,s=new Array(o);n<o;n++)s[n]=t[n].fn;return s},a.prototype.listenerCount=function(e){var t=this._events[r?r+e:e];return t?t.fn?1:t.length:0},a.prototype.emit=function(e,t,n,o,s,c){var a=r?r+e:e;if(!this._events[a])return!1;var i,u,l=this._events[a],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,n),!0;case 4:return l.fn.call(l.context,t,n,o),!0;case 5:return l.fn.call(l.context,t,n,o,s),!0;case 6:return l.fn.call(l.context,t,n,o,s,c),!0}for(u=1,i=new Array(f-1);u<f;u++)i[u-1]=arguments[u];l.fn.apply(l.context,i)}else{var d,p=l.length;for(u=0;u<p;u++)switch(l[u].once&&this.removeListener(e,l[u].fn,void 0,!0),f){case 1:l[u].fn.call(l[u].context);break;case 2:l[u].fn.call(l[u].context,t);break;case 3:l[u].fn.call(l[u].context,t,n);break;case 4:l[u].fn.call(l[u].context,t,n,o);break;default:if(!i)for(d=1,i=new Array(f-1);d<f;d++)i[d-1]=arguments[d];l[u].fn.apply(l[u].context,i)}}return!0},a.prototype.on=function(e,t,r){return s(this,e,t,r,!1)},a.prototype.once=function(e,t,r){return s(this,e,t,r,!0)},a.prototype.removeListener=function(e,t,n,o){var s=r?r+e:e;if(!this._events[s])return this;if(!t)return c(this,s),this;var a=this._events[s];if(a.fn)a.fn!==t||o&&!a.once||n&&a.context!==n||c(this,s);else{for(var i=0,u=[],l=a.length;i<l;i++)(a[i].fn!==t||o&&!a[i].once||n&&a[i].context!==n)&&u.push(a[i]);u.length?this._events[s]=1===u.length?u[0]:u:c(this,s)}return this},a.prototype.removeAllListeners=function(e){var t;return e?this._events[t=r?r+e:e]&&c(this,t):(this._events=new n,this._eventsCount=0),this},a.prototype.off=a.prototype.removeListener,a.prototype.addListener=a.prototype.on,a.prefixed=r,a.EventEmitter=a,e.exports=a}(q)),q.exports);const J=I(z);class K 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 V=c.createContext(new K);function Q(){return c.useContext(V)}function X({children:e}){const t=c.useMemo(()=>new K,[]);return n.jsx(V.Provider,{value:t,children:e})}const Y=c.createContext(new Set);function Z({children:e}){const t=c.useMemo(()=>new Set,[]);return n.jsx(Y.Provider,{value:t,children:e})}const ee=c.createContext({current:{}});function te(){const e=c.useContext(ee);return c.useMemo(()=>new Proxy({},{get:(t,r)=>Reflect.get(e.current,r),has:(t,r)=>r in e.current,ownKeys:()=>Reflect.ownKeys(e.current),getOwnPropertyDescriptor(t,r){const n=Object.getOwnPropertyDescriptor(e.current,r);if(void 0!==n)return{...n,configurable:!0}},set(){throw new TypeError("Store is read-only outside `context.actions.produce`. Mutate via produce(({ store }) => { store.x = ... }) instead.")}}),[e])}function re({initial:e,children:t}){const r=c.useRef(e),o=Q();return void 0===o.getCached(h)&&o.setCache(h,r.current),n.jsx(ee.Provider,{value:r,children:t})}const ne=c.createContext(null);function oe(){return c.useContext(ne)}function se(e,t){return e?.get(t)??null}const ce=Symbol(((e="")=>`march-hare/replay${e}`)());function ae(e,t,...r){e instanceof K&&e.setCache(t,r[0]);const n=e.listeners(t);return 0===n.length?Promise.resolve():Promise.all(n.map(e=>Promise.resolve(e(...r)))).then(()=>{})}function ie(e,t){for(const r of e.keys())if(S(r)===t)return r;return null}const ue=Symbol("march-hare.unset");function le(){const[,e]=c.useReducer(e=>e+1,0);return e}function fe(){return{data:ue,at:null,else:e=>e}}function de(e,t){return{data:e,at:t,else:t=>e}}function pe(e){if(e instanceof Error){if("TimeoutError"===e.name)return x.Timedout;if("AbortError"===e.name)return x.Supplanted}return x.Errored}function he(e){const t=new Map,r=e??{get:e=>t.get(e)??null,set:(e,r)=>{t.set(e,r)},remove:e=>{t.delete(e)},clear:()=>{t.clear()}};return{get(e){try{const t=r.get(e);if(null===t)return fe();const n=JSON.parse(t);return de(n.data,Temporal.Instant.from(n.at))}catch{return fe()}},set(e,t){if(t.data===ue||null===t.at)return!1;try{return r.set(e,JSON.stringify({data:t.data,at:t.at.toString()})),!0}catch{return!1}},remove(e){r.remove(e)},clear(){r.clear()}}}function me(e,t){return new Promise((r,n)=>{if(t?.aborted)return void n(new E);const o=setTimeout(r,e);t?.addEventListener("abort",()=>{clearTimeout(o),n(new E)},{once:!0})})}async function be(e,t,r){if(t?.aborted)throw new E;for(;;){if(await r())return;await me(e,t)}}function ye(e){return e?Boolean(e&&"symbol"!=typeof e):Symbol(`pk.${Date.now()}.${crypto.randomUUID()}`)}const ve=Object.freeze(Object.defineProperty({__proto__:null,pk:ye,poll:be,sleep:me,unset:ue,"ζ":me,"κ":ye,"π":be},Symbol.toStringTag,{value:"Module"})),ge=new WeakMap;function we(e){return JSON.stringify(e)}let je=null;function Oe(){if(null===je)throw new Error("context.actions.resource(...) and context.actions.resource.set(...) must be called with a fresh resource invocation, e.g. context.actions.resource(cat({ id: 5 })).");const e=je;return je=null,e}const Se=c.createContext(new Map);function Pe({action:e,renderer:r}){const n=Q(),o=c.useContext(Se),s=le(),a=c.useMemo(()=>{const t=o.get(e);if(t)return t;const r=new $,s=n.getCached(e);void 0!==s&&r.hydrate({value:s});const c={state:r,listeners:new Set};return o.set(e,c),c},[e,n,o]);c.useLayoutEffect(()=>{function t(e){a.state.hydrate({value:e}),a.listeners.forEach(e=>e())}return a.listeners.add(s),n.on(e,t),()=>{a.listeners.delete(s),n.off(e,t)}},[e,n,a]);const i=a.state.model?.value;return t.G.isNullable(i)?null:r(i,a.state.inspect.value)}e.AbortError=E,e.Action=(e="",t=b.Unicast)=>{const r=t===b.Broadcast?Symbol(i(e)):t===b.Multicast?Symbol(u(e)):Symbol(a(e)),n=function(t){return{[f.Action]:r,[f.Payload]:void 0,[f.Channel]:t,[f.Name]:e,channel:t}};return Object.defineProperty(n,f.Action,{value:r,enumerable:!1}),Object.defineProperty(n,f.Payload,{value:void 0,enumerable:!1}),Object.defineProperty(n,f.Name,{value:e,enumerable:!1}),t===b.Broadcast&&Object.defineProperty(n,f.Broadcast,{value:!0,enumerable:!1}),t===b.Multicast&&Object.defineProperty(n,f.Multicast,{value:!0,enumerable:!1}),n},e.Boundary=function({store:e,children:t}){return n.jsx(X,{children:n.jsx(re,{initial:e??{},children:n.jsx(Z,{children:t})})})},e.Cache=he,e.Distribution=b,e.Lifecycle=m,e.Op=C,e.Operation=C,e.Reason=x,e.Resource=function(e,t){const r=t??function(e){let t=ge.get(e);return void 0===t&&(t=he(),ge.set(e,t)),t}(e),n=e=>{const t=r.get(we(e));return t.data===ue||null===t.at?{data:ue,at:null}:{data:t.data,at:t.at}},o=(t,n,o)=>e({store:t,controller:n,params:o}).then(e=>(r.set(we(o),de(e,Temporal.Now.instant())),e)),s=(e,t,n)=>{r.set(we(e),de(t,n))};return function(e){const t=e??{};je={run:o,read:n,seed:s,params:t},queueMicrotask(()=>{null!==je&&je.params===t&&(je=null)});const{data:r}=n(t);return r===ue?null:r}},e.State=$,e.TimeoutError=M,e.With={Update:e=>(t,r)=>{t.actions.produce(t=>{t.model[e]=r})},Invert:e=>t=>{t.actions.produce(t=>{t.model[e]=!t.model[e]})}},e.annotate=function(e,t=C.Update){return D.annotate(t,e)},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]??(()=>({})),s=Q(),a=oe(),i=c.useContext(Y),u=te(),l=c.useContext(ee),f=le(),d=c.useRef(!1),m=c.useRef(null),b=c.useRef(new $);d.current||(d.current=!0,m.current=b.current.hydrate(n));const[v,S]=c.useState(()=>b.current.model),x=function(e){const t=c.useRef(e);return t.current=e,c.useMemo(()=>{return r=t,Object.keys(e).reduce((e,t)=>(Object.defineProperty(e,t,{get:()=>r.current[t],enumerable:!0}),e),{});var r},[e])}(o()),E=c.useMemo(()=>new J,[]),M=c.useRef({handlers:new Map});M.current.handlers=new Map;const A=function(){const e=c.useRef(new Set),t=c.useRef(new Set);return c.useMemo(()=>({broadcast:e.current,multicast:t.current}),[])}(),G=c.useRef(y.Mounting),k=c.useRef(new Set),N=c.useRef(0),_=c.useCallback((e,t,n)=>{const o=new AbortController,c={controller:o,action:e,payload:t};return i.add(c),k.current.add(c),{model:b.current.model,get phase(){return G.current},task:c,data:x,tasks:i,store:u,actions:{produce(e){if(o.signal.aborted)return;const t=l.current,c=b.current.produce(t=>{l.current=r.produce(l.current,r=>{e({model:t,inspect:b.current.inspect,store:r})})});S(b.current.model),l.current!==t&&s.emit(h,l.current),n.processes.add(c),m.current&&(n.processes.add(m.current),m.current=null)},dispatch(e,t){if(o.signal.aborted)return Promise.resolve();const r=g(e),n=O(e)?e.channel:void 0;if(P(e)){const e=se(a,r);return e?ae(e.emitter,r,t,n):Promise.resolve()}return ae(w(e)?s:E,r,t,n)},annotate:(e,t=C.Update)=>b.current.annotate(t,e),resource:Object.assign(function(e){const t=Oe(),r=()=>t.run(l.current,o,t.params);return{then:(e,t)=>r().then(e,t),exceeds:e=>{const{data:n,at:o}=t.read(t.params);if(n!==ue&&null!==o){const t=Temporal.Now.instant().since(o),r=Temporal.Duration.from(e);if(Temporal.Duration.compare(t,r)<=0)return Promise.resolve(n)}return r()}}},{set:(e,t)=>{const r=Oe();r.seed(r.params,t,Temporal.Now.instant())}}),async resolution(e){if(o.signal.aborted)return null;const t=g(e),r=P(e)?se(a,t)?.emitter??null:s;if(!r)return null;if(void 0===r.getCached(t))return null;const n=b.current.inspect;return n.pending()&&await new Promise((e,t)=>{if(o.signal.aborted)return void t(o.signal.reason);const r=()=>t(o.signal.reason);o.signal.addEventListener("abort",r,{once:!0}),n.settled().then(()=>{o.signal.removeEventListener("abort",r),e()})}),r.getCached(t)??null},peek(e){if(o.signal.aborted)return null;const t=g(e),r=P(e)?se(a,t)?.emitter??null:s;return r?r.getCached(t)??null:null}}}},[v]);c.useLayoutEffect(()=>{function e(e,r,n){return function(o,c){const a=n();if(c===ce&&t.G.isNotNullable(a))return;if(t.G.isNotNullable(c)&&c!==ce&&t.G.isNotNullable(a)&&!function(e,t){for(const r of Object.keys(e))if(t[r]!==e[r])return!1;return!0}(c,a))return;const u={processes:new Set},l=Promise.withResolvers(),d=_(e,o,u);function h(t){const r=ie(M.current.handlers,"Error"),n=null!==r,o={reason:pe(t),error:(c=t,c instanceof Error?c:new Error(String(c))),action:j(e),handled:n,tasks:i};var c;s.fire(p,o),n&&r&&E.emit(r,o)}function m(){for(const e of i)if(e===d.task){i.delete(e),k.current.delete(e);break}u.processes.forEach(e=>b.current.prune(e)),u.processes.size>0&&f(),l.resolve()}let y;try{y=r(d,o)}catch(v){return h(v),void m()}if(!function(e){if(!e||"object"!=typeof e)return!1;const t=Object.prototype.toString.call(e);return"[object Generator]"===t||"[object AsyncGenerator]"===t}(y))return Promise.resolve(y).catch(h).finally(m),l.promise;(async()=>{for await(const e of y);})().catch(h).finally(m)}}N.current++;const r=new Set;return M.current.handlers.forEach((t,n)=>{for(const{getChannel:o,handler:c}of t){const t=e(n,c,o);if(P(n)){if(a)for(const e of a.values()){const o=e.emitter;o.on(n,t),r.add(()=>o.off(n,t))}E.on(n,t),A.multicast.add(n),r.add(()=>E.off(n,t))}else w(n)?(s.on(n,t),E.on(n,t),A.broadcast.add(n),r.add(()=>{s.off(n,t),E.off(n,t)})):(E.on(n,t),r.add(()=>E.off(n,t)))}}),()=>{const e=++N.current,t=new Set(r);queueMicrotask(()=>{if(N.current!==e){for(const e of t)e();return}for(const e of k.current)e.controller.abort(),i.delete(e);k.current.clear(),G.current=y.Unmounting;const r=ie(M.current.handlers,"Unmount");r&&E.emit(r),G.current=y.Unmounted;for(const e of t)e()})}},[E]),function({unicast:e,broadcast:r,dispatchers:n,scope:o,phase:s,data:a,handlers:i}){const u=c.useRef(null);c.useLayoutEffect(()=>{if(s.current===y.Mounted)return;s.current=y.Mounting;const c=ie(i,"Mount");c&&e.emit(c),n.broadcast.forEach(n=>{const o=r.getCached(n);t.G.isNullable(o)||e.emit(n,o,ce)}),o&&n.multicast.forEach(r=>{for(const n of o.values()){const o=n.emitter.getCached(r);t.G.isNullable(o)||e.emit(r,o,ce)}}),s.current=y.Mounted},[]),c.useLayoutEffect(()=>{if(t.G.isNotNullable(u.current)){const r=function(e,t){return Object.keys(t).reduce((r,n)=>e[n]!==t[n]?{...r,[n]:t[n]}:r,{})}(u.current,a);if(t.A.isNotEmpty(Object.keys(r))){const t=ie(i,"Update");t&&e.emit(t,r)}}u.current=a},[a,e])}({unicast:E,broadcast:s,dispatchers:A,scope:a,phase:G,data:o(),handlers:M.current.handlers});const R=c.useMemo(()=>({dispatch(e,t){const r=g(e),n=O(e)?e.channel:void 0;if(P(e)){const e=se(a,r);return e?ae(e.emitter,r,t,n):Promise.resolve()}return ae(w(e)?s:E,r,t,n)},get inspect(){return b.current.inspect},stream:(e,t)=>c.createElement(Pe,{action:g(e),renderer:t})}),[v,E]),T=c.useMemo(()=>[v,R,x],[v,R,x]);return T.useAction=(e,t)=>{!function(e,t,r){const n=c.useRef(r);c.useLayoutEffect(()=>{n.current=r});const o=c.useRef(t);c.useLayoutEffect(()=>{o.current=t});const s=c.useCallback((e,t)=>n.current(e,t),[]),a=c.useCallback(()=>O(o.current)?o.current.channel:void 0,[]),i=g(t),u=e.current.handlers.get(i)??new Set;0===u.size&&e.current.handlers.set(i,u),u.add({getChannel:a,handler:s})}(M,e,t)},T.dispatch=T[1].dispatch,T},e.useStore=te,e.utils=ve,e.withScope=function(e,t){const r=`Scoped${t.displayName||t.name||"Component"}`,o=g(e);return{[r](e){const r=oe(),s=c.useMemo(()=>({action:o,emitter:new K}),[]),a=c.useMemo(()=>{const e=new Map(r??[]);return e.set(o,s),e},[r,s]);return n.jsx(ne.Provider,{value:a,children:n.jsx(t,{...e})})}}[r]},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).MarchHare={},global.TsBelt,global.Immer,global.jsxRuntime,global.React);
|
|
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),a=(e="")=>`march-hare.action/${e}`,i=(e="")=>`march-hare.action/broadcast/${e}`,u=(e="")=>`march-hare.action/multicast/${e}`,l=(e="")=>`march-hare.action.lifecycle/${e}`;class f{static Payload=Symbol("march-hare.brand/Payload");static Broadcast=Symbol("march-hare.brand/Broadcast");static Multicast=Symbol("march-hare.brand/Multicast");static Action=Symbol("march-hare.brand/Action");static Channel=Symbol("march-hare.brand/Channel");static Name=Symbol("march-hare.brand/Name")}function d(e){const t=Symbol(`march-hare.action.lifecycle/${e}`),n=function(n){return{[f.Action]:t,[f.Payload]:void 0,[f.Channel]:n,[f.Name]:e,channel:n}};return Object.defineProperty(n,f.Action,{value:t,enumerable:!1}),Object.defineProperty(n,f.Payload,{value:void 0,enumerable:!1}),Object.defineProperty(n,f.Name,{value:e,enumerable:!1}),n}const p=Symbol(i("Fault")),h=Symbol(i("Store"));class m{static Mount(){return d("Mount")}static Unmount(){return d("Unmount")}static Error(){return d("Error")}static Update(){return d("Update")}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}),Object.defineProperty(e,f.Name,{value:"Fault",enumerable:!1}),e})();static Store=(()=>{const e={};return Object.defineProperty(e,f.Action,{value:h,enumerable:!1}),Object.defineProperty(e,f.Payload,{value:void 0,enumerable:!1}),Object.defineProperty(e,f.Broadcast,{value:!0,enumerable:!1}),Object.defineProperty(e,f.Name,{value:"Store",enumerable:!1}),e})()}var b=(e=>(e.Unicast="unicast",e.Broadcast="broadcast",e.Multicast="multicast",e))(b||{}),y=(e=>(e.Mounting="mounting",e.Mounted="mounted",e.Unmounting="unmounting",e.Unmounted="unmounted",e))(y||{});const v=e=>"symbol"==typeof e;function g(e){return t.G.isString(e)||v(e)?e:(t.G.isObject(e)||t.G.isFunction(e))&&f.Action in e?e[f.Action]:e}function w(e){if(t.G.isString(e))return e.startsWith(i());if(v(e))return e.description?.startsWith(i())??!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(i())??!1}}return!1}function j(e){const n=g(e),r=t.G.isString(n)?n:n.description??"";return r.startsWith(a())&&r.slice(r.lastIndexOf("/")+1)||"unknown"}function O(e){return t.G.isObject(e)&&f.Channel in e&&"channel"in e}function S(e){const t=g(e),n=v(t)?t.description??"":t;return n.startsWith(l())&&n.slice(l().length)||null}function P(e){if(t.G.isString(e))return e.startsWith(u());if(v(e))return e.description?.startsWith(u())??!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(u())??!1}}return!1}var x=(e=>(e[e.Timedout=0]="Timedout",e[e.Supplanted=1]="Supplanted",e[e.Errored=2]="Errored",e))(x||{});class E extends Error{name="AbortError";constructor(e="Aborted"){super(e)}}class M extends Error{name="TimeoutError";constructor(e="Timeout"){super(e)}}let C=(e=21)=>{let t="",n=crypto.getRandomValues(new Uint8Array(e|=0));for(;e--;)t+="useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict"[63&n[e]];return t};var A=(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||{}),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 N{[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 N(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=C}function R(e,t){const n="string"==typeof t?""===t?[]:t.split("."):t;let r=e;for(const o of n){if(null==r)return;r=r[o]}return r}function T(e){if(t.G.isNullable(e)||B(e))return e;if(t.G.isArray(e))return e.map(e=>T(e));if(t.G.isObject(e)&&L(e)){const t=Object.entries(e).map(([e,t])=>[e,T(t)]);return{...Object.fromEntries(t),[_.tag]:e[_.tag]??_.id()}}return e}function U(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 L(e){const t=Object.getPrototypeOf(e);return t===Object.prototype||null===t}function B(e){return t.G.isNullable(e)||t.G.isString(e)||t.G.isNumber(e)||t.G.isBoolean(e)||"symbol"==typeof e||"bigint"==typeof e}function F(e,n,r,o,s,c){return function a(i,u=n.path){if(i instanceof N){const n=R(r,u.join("."));if(Object.entries(i).filter(([e,t])=>!N.keys.has(e)&&t instanceof N).forEach(([e,t])=>a(t,u.concat(e))),B(i.value)){if(e===G.Hydrate)return i.value;const a=u.slice(0,-1),l=a.length>0?R(r,a.join(".")):r;return t.G.isNullable(l)||W(l,i,u.at(-1),o,s,c),n??i.value}if(e===G.Hydrate){const e=T(a(i.value,u));return W(e,i,null,o,s,c),e}const l=n??T(i.value);return W(l,i,null,o,s,c),t.G.isNullable(n)?l:(a(i.value,u),n)}if(t.G.isArray(i))return i.map((e,t)=>a(e,u.concat(t)));if(t.G.isObject(i)&&!L(i))return i;if(t.G.isObject(i)){const t=Object.entries(i).map(([e,t])=>[e,a(t,u.concat(e))]),n=Object.fromEntries(t);if(e===G.Hydrate){const e=T(n);return Object.entries(i).forEach(([t,n])=>{n instanceof N&&B(n.value)&&W(e,n,t,o,s,c)}),e}return n}return i}(n.value)}function W(e,t,n,r,o,s){const c=s(e),a=o.get(c)??[];o.set(c,[t.assign(n,r),...a])}class ${#e={};#t;#n=new Map;#r=new Set;#o=!1;constructor(e=U){this.#t=e}static pk(){return C()}static"κ"=$.pk;annotate(e,t){return new N(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=R(e(),o),a=o.slice(0,-1),i=t.A.isNotEmpty(a)?R(e(),a):e();return[...t.G.isObject(c)||t.G.isArray(c)?n.get(r(c))?.filter(e=>t.G.isNullable(e.property))??[]:[],...t.G.isObject(i)?n.get(r(i))?.filter(e=>e.property===s)??[]:[]]}return function n(r){return new Proxy(()=>{},{get:(a,i)=>"pending"===i?()=>!t.A.isEmpty(c(r)):"remaining"===i?()=>t.A.length(c(r)):"box"===i?()=>({value:R(e(),r),inspect:n(r)}):"is"===i?e=>c(r).some(t=>0!==(t.operation&e)):"draft"===i?()=>t.A.head(c(r))?.value??R(e(),r):"settled"===i?()=>new Promise(n=>{if(t.A.isEmpty(c(r)))return n(R(e(),r));const a=()=>{t.A.isEmpty(c(r))&&(s(a),n(R(e(),r)))};o(a)}):n([...r,String(i)])})}([])}(()=>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:F(e,r,t,n,this.#n,this.#t)}]),this.#e),this.#e=T(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 D=new $;function I(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var H,q={exports:{}},z=(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 a=new o(r,s||e,c),i=n?n+t:t;return e._events[i]?e._events[i].fn?e._events[i]=[e._events[i],a]:e._events[i].push(a):(e._events[i]=a,e._eventsCount++),e}function c(e,t){0===--e._eventsCount?e._events=new r:delete e._events[t]}function a(){this._events=new r,this._eventsCount=0}Object.create&&(r.prototype=Object.create(null),(new r).__proto__||(n=!1)),a.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},a.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},a.prototype.listenerCount=function(e){var t=this._events[n?n+e:e];return t?t.fn?1:t.length:0},a.prototype.emit=function(e,t,r,o,s,c){var a=n?n+e:e;if(!this._events[a])return!1;var i,u,l=this._events[a],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(u=1,i=new Array(f-1);u<f;u++)i[u-1]=arguments[u];l.fn.apply(l.context,i)}else{var d,p=l.length;for(u=0;u<p;u++)switch(l[u].once&&this.removeListener(e,l[u].fn,void 0,!0),f){case 1:l[u].fn.call(l[u].context);break;case 2:l[u].fn.call(l[u].context,t);break;case 3:l[u].fn.call(l[u].context,t,r);break;case 4:l[u].fn.call(l[u].context,t,r,o);break;default:if(!i)for(d=1,i=new Array(f-1);d<f;d++)i[d-1]=arguments[d];l[u].fn.apply(l[u].context,i)}}return!0},a.prototype.on=function(e,t,n){return s(this,e,t,n,!1)},a.prototype.once=function(e,t,n){return s(this,e,t,n,!0)},a.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 a=this._events[s];if(a.fn)a.fn!==t||o&&!a.once||r&&a.context!==r||c(this,s);else{for(var i=0,u=[],l=a.length;i<l;i++)(a[i].fn!==t||o&&!a[i].once||r&&a[i].context!==r)&&u.push(a[i]);u.length?this._events[s]=1===u.length?u[0]:u:c(this,s)}return this},a.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},a.prototype.off=a.prototype.removeListener,a.prototype.addListener=a.prototype.on,a.prefixed=n,a.EventEmitter=a,e.exports=a}(q)),q.exports);const J=I(z);class K 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 V=c.createContext(new K);function Q(){return c.useContext(V)}function X({children:e}){const t=c.useMemo(()=>new K,[]);return r.jsx(V.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({current:{}});function te(){const e=c.useContext(ee);return c.useMemo(()=>new Proxy({},{get:(t,n)=>Reflect.get(e.current,n),has:(t,n)=>n in e.current,ownKeys:()=>Reflect.ownKeys(e.current),getOwnPropertyDescriptor(t,n){const r=Object.getOwnPropertyDescriptor(e.current,n);if(void 0!==r)return{...r,configurable:!0}},set(){throw new TypeError("Store is read-only outside `context.actions.produce`. Mutate via produce(({ store }) => { store.x = ... }) instead.")}}),[e])}function ne({initial:e,children:t}){const n=c.useRef(e),o=Q();return void 0===o.getCached(h)&&o.setCache(h,n.current),r.jsx(ee.Provider,{value:n,children:t})}const re=c.createContext(null);function oe(){return c.useContext(re)}function se(e,t){return e?.get(t)??null}const ce=Symbol(((e="")=>`march-hare/replay${e}`)());function ae(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 ie(e,t){for(const n of e.keys())if(S(n)===t)return n;return null}const ue=Symbol("march-hare.unset");function le(){const[,e]=c.useReducer(e=>e+1,0);return e}function fe(){return{data:ue,at:null,else:e=>e}}function de(e,t){return{data:e,at:t,else:t=>e}}function pe(e){if(e instanceof Error){if("TimeoutError"===e.name)return x.Timedout;if("AbortError"===e.name)return x.Supplanted}return x.Errored}function he(e){const t=new Map,n=e??{get:e=>t.get(e)??null,set:(e,n)=>{t.set(e,n)},remove:e=>{t.delete(e)},clear:()=>{t.clear()}};return{get(e){try{const t=n.get(e);if(null===t)return fe();const r=JSON.parse(t);return de(r.data,Temporal.Instant.from(r.at))}catch{return fe()}},set(e,t){if(t.data===ue||null===t.at)return!1;try{return n.set(e,JSON.stringify({data:t.data,at:t.at.toString()})),!0}catch{return!1}},remove(e){n.remove(e)},clear(){n.clear()}}}function me(e,t){return new Promise((n,r)=>{if(t?.aborted)return void r(new E);const o=setTimeout(n,e);t?.addEventListener("abort",()=>{clearTimeout(o),r(new E)},{once:!0})})}async function be(e,t,n){if(t?.aborted)throw new E;for(;;){if(await n())return;await me(e,t)}}function ye(e){return e?Boolean(e&&"symbol"!=typeof e):Symbol(`pk.${Date.now()}.${crypto.randomUUID()}`)}const ve=Object.freeze(Object.defineProperty({__proto__:null,pk:ye,poll:be,sleep:me,unset:ue,"ζ":me,"κ":ye,"π":be},Symbol.toStringTag,{value:"Module"})),ge=new WeakMap;function we(e){return JSON.stringify(e)}let je=null;function Oe(){if(null===je)throw new Error("context.actions.resource(...) and context.actions.resource.set(...) must be called with a fresh resource invocation, e.g. context.actions.resource(cat({ id: 5 })).");const e=je;return je=null,e}const Se=c.createContext(new Map);function Pe({action:e,renderer:n}){const r=Q(),o=c.useContext(Se),s=le(),a=c.useMemo(()=>{const t=o.get(e);if(t)return t;const n=new $,s=r.getCached(e);void 0!==s&&n.hydrate({value:s});const c={state:n,listeners:new Set};return o.set(e,c),c},[e,r,o]);c.useLayoutEffect(()=>{function t(e){a.state.hydrate({value:e}),a.listeners.forEach(e=>e())}return a.listeners.add(s),r.on(e,t),()=>{a.listeners.delete(s),r.off(e,t)}},[e,r,a]);const i=a.state.model?.value;return t.G.isNullable(i)?null:n(i,a.state.inspect.value)}e.AbortError=E,e.Action=(e="",t=b.Unicast)=>{const n=t===b.Broadcast?Symbol(i(e)):t===b.Multicast?Symbol(u(e)):Symbol(a(e)),r=function(t){return{[f.Action]:n,[f.Payload]:void 0,[f.Channel]:t,[f.Name]:e,channel:t}};return Object.defineProperty(r,f.Action,{value:n,enumerable:!1}),Object.defineProperty(r,f.Payload,{value:void 0,enumerable:!1}),Object.defineProperty(r,f.Name,{value:e,enumerable:!1}),t===b.Broadcast&&Object.defineProperty(r,f.Broadcast,{value:!0,enumerable:!1}),t===b.Multicast&&Object.defineProperty(r,f.Multicast,{value:!0,enumerable:!1}),r},e.Boundary=function({store:e,children:t}){return r.jsx(X,{children:r.jsx(ne,{initial:e??{},children:r.jsx(Z,{children:t})})})},e.Cache=he,e.Distribution=b,e.Lifecycle=m,e.Op=A,e.Operation=A,e.Reason=x,e.Resource=function(e,t){const n=t??function(e){let t=ge.get(e);return void 0===t&&(t=he(),ge.set(e,t)),t}(e),r=e=>{const t=n.get(we(e));return t.data===ue||null===t.at?{data:ue,at:null}:{data:t.data,at:t.at}},o=(t,r,o)=>e({store:t,controller:r,params:o}).then(e=>(n.set(we(o),de(e,Temporal.Now.instant())),e)),s=(e,t,r)=>{n.set(we(e),de(t,r))};return function(e){const t=e??{};je={run:o,read:r,seed:s,params:t},queueMicrotask(()=>{null!==je&&je.params===t&&(je=null)});const{data:n}=r(t);return n===ue?null:n}},e.State=$,e.TimeoutError=M,e.With={Update:e=>(t,n)=>{t.actions.produce(t=>{t.model[e]=n})},Invert:e=>t=>{t.actions.produce(t=>{t.model[e]=!t.model[e]})}},e.annotate=function(e,t=A.Update){return D.annotate(t,e)},e.useContext=function(){const e=c.useRef(null);return c.useMemo(()=>({actions:{dispatch:function(t,n){const r=e.current;if(!r)throw new Error("march-hare: useContext handle dispatched before its paired context.useActions(...) ran. Call context.actions.dispatch from event handlers, not synchronously during render.");return r(t,n)}},useActions:function(...r){const o=function(...e){const r=t.G.isUndefined(e[0])||t.G.isFunction(e[0])?{}:e[0],o=t.G.isFunction(e[0])?e[0]:e[1]??(()=>({})),s=Q(),a=oe(),i=c.useContext(Y),u=te(),l=c.useContext(ee),f=le(),d=c.useRef(!1),m=c.useRef(null),b=c.useRef(new $);d.current||(d.current=!0,m.current=b.current.hydrate(r));const[v,S]=c.useState(()=>b.current.model),x=function(e){const t=c.useRef(e);return t.current=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()),E=c.useMemo(()=>new J,[]),M=c.useRef({handlers:new Map});M.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(y.Mounting),k=c.useRef(new Set),N=c.useRef(0),_=c.useCallback((e,t,r)=>{const o=new AbortController,c={controller:o,action:e,payload:t};return i.add(c),k.current.add(c),{model:b.current.model,get phase(){return G.current},task:c,data:x,tasks:i,store:u,actions:{produce(e){if(o.signal.aborted)return;const t=l.current,c=b.current.produce(t=>{l.current=n.produce(l.current,n=>{e({model:t,inspect:b.current.inspect,store:n})})});S(b.current.model),l.current!==t&&s.emit(h,l.current),r.processes.add(c),m.current&&(r.processes.add(m.current),m.current=null)},dispatch(e,t){if(o.signal.aborted)return Promise.resolve();const n=g(e),r=O(e)?e.channel:void 0;if(P(e)){const e=se(a,n);return e?ae(e.emitter,n,t,r):Promise.resolve()}return ae(w(e)?s:E,n,t,r)},annotate:(e,t=A.Update)=>b.current.annotate(t,e),get inspect(){return b.current.inspect},resource:Object.assign(function(e){const t=Oe(),n=()=>t.run(l.current,o,t.params);return{then:(e,t)=>n().then(e,t),exceeds:e=>{const{data:r,at:o}=t.read(t.params);if(r!==ue&&null!==o){const t=Temporal.Now.instant().since(o),n=Temporal.Duration.from(e);if(Temporal.Duration.compare(t,n)<=0)return Promise.resolve(r)}return n()}}},{set:(e,t)=>{const n=Oe();n.seed(n.params,t,Temporal.Now.instant())}}),async resolution(e){if(o.signal.aborted)return null;const t=g(e),n=P(e)?se(a,t)?.emitter??null:s;if(!n)return null;if(void 0===n.getCached(t))return null;const r=b.current.inspect;return r.pending()&&await new Promise((e,t)=>{if(o.signal.aborted)return void t(o.signal.reason);const n=()=>t(o.signal.reason);o.signal.addEventListener("abort",n,{once:!0}),r.settled().then(()=>{o.signal.removeEventListener("abort",n),e()})}),n.getCached(t)??null},peek(e){if(o.signal.aborted)return null;const t=g(e),n=P(e)?se(a,t)?.emitter??null:s;return n?n.getCached(t)??null:null}}}},[v]);c.useLayoutEffect(()=>{function e(e,n,r){return function(o,c){const a=r();if(c===ce&&t.G.isNotNullable(a))return;if(t.G.isNotNullable(c)&&c!==ce&&t.G.isNotNullable(a)&&!function(e,t){for(const n of Object.keys(e))if(t[n]!==e[n])return!1;return!0}(c,a))return;const u={processes:new Set},l=Promise.withResolvers(),d=_(e,o,u);function h(t){const n=ie(M.current.handlers,"Error"),r=null!==n,o={reason:pe(t),error:(c=t,c instanceof Error?c:new Error(String(c))),action:j(e),handled:r,tasks:i};var c;s.fire(p,o),r&&n&&E.emit(n,o)}function m(){for(const e of i)if(e===d.task){i.delete(e),k.current.delete(e);break}u.processes.forEach(e=>b.current.prune(e)),u.processes.size>0&&f(),l.resolve()}let y;try{y=n(d,o)}catch(v){return h(v),void m()}if(!function(e){if(!e||"object"!=typeof e)return!1;const t=Object.prototype.toString.call(e);return"[object Generator]"===t||"[object AsyncGenerator]"===t}(y))return Promise.resolve(y).catch(h).finally(m),l.promise;(async()=>{for await(const e of y);})().catch(h).finally(m)}}N.current++;const n=new Set;return M.current.handlers.forEach((t,r)=>{for(const{getChannel:o,handler:c}of t){const t=e(r,c,o);if(P(r)){if(a)for(const e of a.values()){const o=e.emitter;o.on(r,t),n.add(()=>o.off(r,t))}E.on(r,t),C.multicast.add(r),n.add(()=>E.off(r,t))}else w(r)?(s.on(r,t),E.on(r,t),C.broadcast.add(r),n.add(()=>{s.off(r,t),E.off(r,t)})):(E.on(r,t),n.add(()=>E.off(r,t)))}}),()=>{const e=++N.current,t=new Set(n);queueMicrotask(()=>{if(N.current!==e){for(const e of t)e();return}for(const e of k.current)e.controller.abort(),i.delete(e);k.current.clear(),G.current=y.Unmounting;const n=ie(M.current.handlers,"Unmount");n&&E.emit(n),G.current=y.Unmounted;for(const e of t)e()})}},[E]),function({unicast:e,broadcast:n,dispatchers:r,scope:o,phase:s,data:a,handlers:i}){const u=c.useRef(null);c.useLayoutEffect(()=>{if(s.current===y.Mounted)return;s.current=y.Mounting;const c=ie(i,"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=y.Mounted},[]),c.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,a);if(t.A.isNotEmpty(Object.keys(n))){const t=ie(i,"Update");t&&e.emit(t,n)}}u.current=a},[a,e])}({unicast:E,broadcast:s,dispatchers:C,scope:a,phase:G,data:o(),handlers:M.current.handlers});const R=c.useMemo(()=>({dispatch(e,t){const n=g(e),r=O(e)?e.channel:void 0;if(P(e)){const e=se(a,n);return e?ae(e.emitter,n,t,r):Promise.resolve()}return ae(w(e)?s:E,n,t,r)},get inspect(){return b.current.inspect},stream:(e,t)=>c.createElement(Pe,{action:g(e),renderer:t})}),[v,E]),T=c.useMemo(()=>[v,R,x],[v,R,x]);return T.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),[]),a=c.useCallback(()=>O(o.current)?o.current.channel:void 0,[]),i=g(t),u=e.current.handlers.get(i)??new Set;0===u.size&&e.current.handlers.set(i,u),u.add({getChannel:a,handler:s})}(M,e,t)},T.dispatch=T[1].dispatch,T}(...r);return e.current=o.dispatch,o}}),[])},e.useStore=te,e.utils=ve,e.withScope=function(e,t){const n=`Scoped${t.displayName||t.name||"Component"}`,o=g(e);return{[n](e){const n=oe(),s=c.useMemo(()=>({action:o,emitter:new K}),[]),a=c.useMemo(()=>{const e=new Map(n??[]);return e.set(o,s),e},[n,s]);return r.jsx(re.Provider,{value:a,children:r.jsx(t,{...e})})}}[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).MarchHare={},global.TsBelt,global.Immer,global.jsxRuntime,global.React);
|
package/dist/types/index.d.ts
CHANGED
|
@@ -237,6 +237,15 @@ export declare enum Phase {
|
|
|
237
237
|
* @template T - The concrete primary key type (e.g., string, number)
|
|
238
238
|
*/
|
|
239
239
|
export type Pk<T> = undefined | symbol | T;
|
|
240
|
+
/**
|
|
241
|
+
* Reactive field type — a value that may be a concrete `T`, or
|
|
242
|
+
* `null` / `undefined` while loading, awaiting a fetch, or before
|
|
243
|
+
* upstream data has arrived. Use this for model fields whose presence
|
|
244
|
+
* is determined by async or external state.
|
|
245
|
+
*
|
|
246
|
+
* @template T - The concrete value type
|
|
247
|
+
*/
|
|
248
|
+
export type Reactive<T> = T | null | undefined;
|
|
240
249
|
/**
|
|
241
250
|
* Base constraint type for model state objects.
|
|
242
251
|
* Models must be plain objects with string keys.
|
|
@@ -462,119 +471,10 @@ export type Result = {
|
|
|
462
471
|
};
|
|
463
472
|
export type HandlerContext<M extends Model | void, AC extends Actions | void, D extends Props = Props> = {
|
|
464
473
|
readonly model: DeepReadonly<M>;
|
|
465
|
-
/**
|
|
466
|
-
* The current lifecycle phase of the component.
|
|
467
|
-
* Useful for determining if the handler was called during mount (e.g., from a cached
|
|
468
|
-
* distributed action value) vs after the component is fully mounted.
|
|
469
|
-
*
|
|
470
|
-
* @example
|
|
471
|
-
* ```ts
|
|
472
|
-
* actions.useAction(Actions.Broadcast.Counter, (context, payload) => {
|
|
473
|
-
* if (context.phase === Phase.Mounting) {
|
|
474
|
-
* // Called with cached value during mount
|
|
475
|
-
* console.log("Received cached value:", payload);
|
|
476
|
-
* }
|
|
477
|
-
* });
|
|
478
|
-
* ```
|
|
479
|
-
*/
|
|
480
474
|
readonly phase: Phase;
|
|
481
|
-
/**
|
|
482
|
-
* The current task for the executing action handler.
|
|
483
|
-
* Contains the AbortController, action identifier, and payload for this specific invocation.
|
|
484
|
-
*
|
|
485
|
-
* Use `task.controller.signal` to check if the action was aborted, or `task.controller.abort()` to cancel it.
|
|
486
|
-
* The `task.action` and `task.payload` properties identify which action triggered this handler.
|
|
487
|
-
*
|
|
488
|
-
* @example
|
|
489
|
-
* ```ts
|
|
490
|
-
* actions.useAction(Actions.Fetch, async (context) => {
|
|
491
|
-
* const response = await fetch("/api", {
|
|
492
|
-
* signal: context.task.controller.signal,
|
|
493
|
-
* });
|
|
494
|
-
*
|
|
495
|
-
* if (context.task.controller.signal.aborted) return;
|
|
496
|
-
*
|
|
497
|
-
* context.actions.produce((draft) => {
|
|
498
|
-
* draft.model.data = response;
|
|
499
|
-
* });
|
|
500
|
-
* });
|
|
501
|
-
* ```
|
|
502
|
-
*/
|
|
503
475
|
readonly task: Task;
|
|
504
|
-
/**
|
|
505
|
-
* Reactive data values passed to useActions.
|
|
506
|
-
* Always returns the latest values, even after awaits in async handlers.
|
|
507
|
-
*
|
|
508
|
-
* @example
|
|
509
|
-
* ```ts
|
|
510
|
-
* const [name, setName] = useState("Adam");
|
|
511
|
-
* const actions = useActions<Model, typeof Actions>(model, () => ({ name }));
|
|
512
|
-
*
|
|
513
|
-
* actions.useAction(Actions.Fetch, async (context) => {
|
|
514
|
-
* await fetch("/api");
|
|
515
|
-
* // context.data.name is always the latest value
|
|
516
|
-
* console.log(context.data.name);
|
|
517
|
-
* });
|
|
518
|
-
* ```
|
|
519
|
-
*/
|
|
520
476
|
readonly data: DeepReadonly<D>;
|
|
521
|
-
/**
|
|
522
|
-
* Set of all running tasks across all components in the context.
|
|
523
|
-
* Tasks are ordered by creation time (oldest first).
|
|
524
|
-
*
|
|
525
|
-
* Each task contains:
|
|
526
|
-
* - `controller`: The AbortController to cancel this task
|
|
527
|
-
* - `action`: The action identifier that triggered this task
|
|
528
|
-
* - `payload`: The payload passed when the action was dispatched
|
|
529
|
-
*
|
|
530
|
-
* @example
|
|
531
|
-
* ```ts
|
|
532
|
-
* // Abort all tasks for a specific action
|
|
533
|
-
* for (const runningTask of context.tasks) {
|
|
534
|
-
* if (runningTask.action === Actions.Fetch) {
|
|
535
|
-
* runningTask.controller.abort();
|
|
536
|
-
* }
|
|
537
|
-
* }
|
|
538
|
-
*
|
|
539
|
-
* // Abort the oldest task
|
|
540
|
-
* const oldest = context.tasks.values().next().value;
|
|
541
|
-
* oldest?.controller.abort();
|
|
542
|
-
*
|
|
543
|
-
* // Abort all tasks except the current one
|
|
544
|
-
* for (const runningTask of context.tasks) {
|
|
545
|
-
* if (runningTask !== context.task) {
|
|
546
|
-
* runningTask.controller.abort();
|
|
547
|
-
* }
|
|
548
|
-
* }
|
|
549
|
-
* ```
|
|
550
|
-
*/
|
|
551
477
|
readonly tasks: ReadonlySet<Task>;
|
|
552
|
-
/**
|
|
553
|
-
* Read-only view of the per-`<Boundary>` Store — ambient,
|
|
554
|
-
* cross-cutting state (session, locale, feature flags, etc.) typed
|
|
555
|
-
* via module augmentation on the library's `Store` interface.
|
|
556
|
-
* Identical to the value returned by `useStore()` at the hook level.
|
|
557
|
-
*
|
|
558
|
-
* Reads use plain dot notation and always reflect the latest value,
|
|
559
|
-
* even after `await` boundaries. Writes go through
|
|
560
|
-
* `context.actions.produce(({ store }) => { store.x = ... })`
|
|
561
|
-
* — the same Immer-style recipe used for the model.
|
|
562
|
-
*
|
|
563
|
-
* @example
|
|
564
|
-
* ```ts
|
|
565
|
-
* actions.useAction(Actions.SignIn, async (context, credentials) => {
|
|
566
|
-
* const result = await context.actions.resource(signIn(credentials));
|
|
567
|
-
* context.actions.produce(({ store }) => {
|
|
568
|
-
* store.session = result;
|
|
569
|
-
* });
|
|
570
|
-
* });
|
|
571
|
-
*
|
|
572
|
-
* actions.useAction(Actions.Refresh, async (context) => {
|
|
573
|
-
* if (context.store.session === null) return;
|
|
574
|
-
* // ...
|
|
575
|
-
* });
|
|
576
|
-
* ```
|
|
577
|
-
*/
|
|
578
478
|
readonly store: DeepReadonly<Store>;
|
|
579
479
|
readonly actions: {
|
|
580
480
|
produce<F extends (draft: {
|
|
@@ -585,94 +485,13 @@ export type HandlerContext<M extends Model | void, AC extends Actions | void, D
|
|
|
585
485
|
dispatch(action: NoPayloadActions<Dispatchable<AC>>): Promise<void>;
|
|
586
486
|
dispatch<A extends WithPayloadActions<Dispatchable<AC>>>(action: A, payload: Payload<A>): Promise<void>;
|
|
587
487
|
annotate<T>(value: T, operation?: Operation): T;
|
|
588
|
-
|
|
589
|
-
* Fetches a {@link Resource} with the abort controller and Store
|
|
590
|
-
* snapshot auto-threaded from the current handler context. The
|
|
591
|
-
* argument is a resource invocation (`cat({ id: 5 })`) — the
|
|
592
|
-
* call primes a slot with the resource and params, and
|
|
593
|
-
* `.resource(...)` reads it. The return value is a thenable —
|
|
594
|
-
* `await` it to fire the fetch unconditionally, or use
|
|
595
|
-
* `.exceeds(duration)` to short-circuit when the per-params cache
|
|
596
|
-
* slot is still within the supplied freshness window (i.e. fetch
|
|
597
|
-
* only when the cache age *exceeds* the duration).
|
|
598
|
-
*
|
|
599
|
-
* @example
|
|
600
|
-
* ```ts
|
|
601
|
-
* actions.useAction(Actions.Mount, async (context) => {
|
|
602
|
-
* // Always fetch.
|
|
603
|
-
* const fresh = await context.actions.resource(user({ id: 5 }));
|
|
604
|
-
*
|
|
605
|
-
* // Reuse cache when < 5 minutes old.
|
|
606
|
-
* const maybe = await context.actions
|
|
607
|
-
* .resource(user({ id: 5 }))
|
|
608
|
-
* .exceeds({ minutes: 5 });
|
|
609
|
-
*
|
|
610
|
-
* context.actions.produce(({ model }) => void (model.user = fresh));
|
|
611
|
-
* });
|
|
612
|
-
* ```
|
|
613
|
-
*/
|
|
488
|
+
readonly inspect: Readonly<Inspect<M>>;
|
|
614
489
|
resource: (<T>(invocation: T | null) => PromiseLike<T> & {
|
|
615
490
|
readonly exceeds: (duration: Temporal.DurationLike) => Promise<T>;
|
|
616
491
|
}) & {
|
|
617
|
-
/**
|
|
618
|
-
* Writes `data` into the per-params cache slot of the resource
|
|
619
|
-
* invocation passed as the first argument, with a fresh timestamp.
|
|
620
|
-
* Use this when payloads arrive out-of-band (SSE, WebSocket,
|
|
621
|
-
* postMessage) and need to be reflected in the Resource cache
|
|
622
|
-
* without a fetcher round-trip.
|
|
623
|
-
*
|
|
624
|
-
* @example
|
|
625
|
-
* ```ts
|
|
626
|
-
* actions.useAction(Actions.Broadcast.UserSSE, (context, payload) => {
|
|
627
|
-
* context.actions.resource.set(user({ id: payload.id }), payload);
|
|
628
|
-
* });
|
|
629
|
-
* ```
|
|
630
|
-
*/
|
|
631
492
|
set<T>(invocation: T | null, data: T): void;
|
|
632
493
|
};
|
|
633
|
-
/**
|
|
634
|
-
* Returns the resolved broadcast or multicast value, waiting for any
|
|
635
|
-
* pending annotations to settle before resolving.
|
|
636
|
-
*
|
|
637
|
-
* If a value has already been dispatched it resolves immediately.
|
|
638
|
-
* Otherwise it waits until the next dispatch of the action.
|
|
639
|
-
* Resolves with `null` if the task is aborted before a value arrives.
|
|
640
|
-
*
|
|
641
|
-
* @param action - The broadcast or multicast action to resolve. Multicast
|
|
642
|
-
* actions read their scope from the action declaration.
|
|
643
|
-
* @returns The dispatched value, or `null` if aborted.
|
|
644
|
-
*
|
|
645
|
-
* @example
|
|
646
|
-
* ```ts
|
|
647
|
-
* actions.useAction(Actions.FetchPosts, async (context) => {
|
|
648
|
-
* const user = await context.actions.resolution(Actions.Broadcast.User);
|
|
649
|
-
* if (!user) return;
|
|
650
|
-
* const posts = await fetchPosts(user.id, {
|
|
651
|
-
* signal: context.task.controller.signal,
|
|
652
|
-
* });
|
|
653
|
-
* context.actions.produce(({ model }) => { model.posts = posts; });
|
|
654
|
-
* });
|
|
655
|
-
* ```
|
|
656
|
-
*/
|
|
657
494
|
resolution<T>(action: BroadcastPayload<T> | MulticastPayload<T>): Promise<T | null>;
|
|
658
|
-
/**
|
|
659
|
-
* Returns the latest broadcast or multicast value immediately without
|
|
660
|
-
* waiting for annotations to settle. Use this when you need the current
|
|
661
|
-
* cached value and do not need to wait for pending operations to complete.
|
|
662
|
-
*
|
|
663
|
-
* @param action - The broadcast or multicast action to peek at. Multicast
|
|
664
|
-
* actions read their scope from the action declaration.
|
|
665
|
-
* @returns The cached value, or `null` if no value has been dispatched.
|
|
666
|
-
*
|
|
667
|
-
* @example
|
|
668
|
-
* ```ts
|
|
669
|
-
* actions.useAction(Actions.Check, (context) => {
|
|
670
|
-
* const user = context.actions.peek(Actions.Broadcast.User);
|
|
671
|
-
* if (!user) return;
|
|
672
|
-
* console.log(user.name);
|
|
673
|
-
* });
|
|
674
|
-
* ```
|
|
675
|
-
*/
|
|
676
495
|
peek<T>(action: BroadcastPayload<T> | MulticastPayload<T>): T | null;
|
|
677
496
|
};
|
|
678
497
|
};
|
|
@@ -860,7 +679,8 @@ export type UseActions<M extends Model | void, AC extends Actions | void, D exte
|
|
|
860
679
|
dispatch<A extends WithPayloadActions<Dispatchable<AC>>>(action: A, payload: Payload<A>): Promise<void>;
|
|
861
680
|
/**
|
|
862
681
|
* Registers an action handler with the current scope.
|
|
863
|
-
* Types are pre-baked from the
|
|
682
|
+
* Types are pre-baked from the `channel.use(...)` call, so no type
|
|
683
|
+
* parameter is needed.
|
|
864
684
|
*
|
|
865
685
|
* Supports two subscription patterns:
|
|
866
686
|
* 1. **Plain action** - Receives ALL dispatches for that action (including channeled ones)
|
|
@@ -871,7 +691,8 @@ export type UseActions<M extends Model | void, AC extends Actions | void, D exte
|
|
|
871
691
|
*
|
|
872
692
|
* @example
|
|
873
693
|
* ```ts
|
|
874
|
-
* const
|
|
694
|
+
* const context = useContext<Model, typeof Actions>();
|
|
695
|
+
* const actions = context.useActions(model);
|
|
875
696
|
*
|
|
876
697
|
* // Subscribe to ALL UserUpdated events
|
|
877
698
|
* actions.useAction(Actions.UserUpdated, (context, user) => {
|
|
@@ -887,3 +708,31 @@ export type UseActions<M extends Model | void, AC extends Actions | void, D exte
|
|
|
887
708
|
useAction(action: NoPayloadActions<Subscribable<AC>>, handler: (context: HandlerContext<M, AC, D>) => void | Promise<void> | AsyncGenerator | Generator): void;
|
|
888
709
|
useAction<A extends WithPayloadActions<Subscribable<AC>>>(action: A, handler: (context: HandlerContext<M, AC, D>, payload: Payload<A>) => void | Promise<void> | AsyncGenerator | Generator): void;
|
|
889
710
|
};
|
|
711
|
+
/**
|
|
712
|
+
* Stable, typed dispatch function for the actions class `AC`. Same call
|
|
713
|
+
* signatures as `actions.dispatch` returned by `useActions`, available
|
|
714
|
+
* before the paired `useActions` has run via {@link Context}.
|
|
715
|
+
*/
|
|
716
|
+
export type Dispatch<AC extends Actions | void> = {
|
|
717
|
+
(action: NoPayloadActions<Dispatchable<AC>>): Promise<void>;
|
|
718
|
+
<A extends WithPayloadActions<Dispatchable<AC>>>(action: A, payload: Payload<A>): Promise<void>;
|
|
719
|
+
};
|
|
720
|
+
/**
|
|
721
|
+
* Handle returned by `useContext<M, AC, D>()`. Exposes
|
|
722
|
+
* `dispatch(action, payload?)` and a `useActions` method that materialises
|
|
723
|
+
* the component-local model and reactive data against the same dispatch
|
|
724
|
+
* target. Generics are declared on `useContext`; `useActions` inherits
|
|
725
|
+
* them — the call site does not re-state `Model` / `Actions` /
|
|
726
|
+
* `Data`.
|
|
727
|
+
*
|
|
728
|
+
* Note: this `Context` type is distinct from React's `useContext` /
|
|
729
|
+
* `React.Context` — it's the March Hare action surface returned by
|
|
730
|
+
* the `useContext` hook of this library.
|
|
731
|
+
*/
|
|
732
|
+
export type Context<M extends Model | void, AC extends Actions | void, D extends Props = Props> = {
|
|
733
|
+
readonly actions: {
|
|
734
|
+
dispatch: Dispatch<AC>;
|
|
735
|
+
};
|
|
736
|
+
useActions(getData?: () => D): UseActions<M, AC, D>;
|
|
737
|
+
useActions(initialModel: M extends void ? never : M, getData?: () => D): UseActions<M, AC, D>;
|
|
738
|
+
};
|