chizu 0.2.56 → 0.2.58
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 +13 -0
- package/dist/chizu.js +2 -2
- package/dist/chizu.umd.cjs +1 -1
- package/dist/index.d.ts +0 -1
- package/dist/types/index.d.ts +67 -23
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -167,6 +167,19 @@ actions.useAction(Actions.Broadcast.Name, async (context, name) => {
|
|
|
167
167
|
});
|
|
168
168
|
```
|
|
169
169
|
|
|
170
|
+
Or read the latest broadcast value directly in a handler with `context.actions.consume`:
|
|
171
|
+
|
|
172
|
+
```tsx
|
|
173
|
+
actions.useAction(Actions.FetchFriends, async (context) => {
|
|
174
|
+
const name = await context.actions.consume(Actions.Broadcast.Name);
|
|
175
|
+
if (!name) return;
|
|
176
|
+
const friends = await fetch(api.friends(name));
|
|
177
|
+
context.actions.produce(({ model }) => {
|
|
178
|
+
model.friends = friends;
|
|
179
|
+
});
|
|
180
|
+
});
|
|
181
|
+
```
|
|
182
|
+
|
|
170
183
|
For targeted event delivery, use channeled actions. Define a channel type as the second generic argument and call the action with a channel object – handlers fire when the dispatch channel matches:
|
|
171
184
|
|
|
172
185
|
```tsx
|
package/dist/chizu.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{G as e,A as t}from"@mobily/ts-belt";import{jsx as n}from"react/jsx-runtime";import*as r from"react";import{createContext as o,useContext as c}from"react";import{immerable as i,enablePatches as s,Immer as a}from"immer";class u{static Payload=/* @__PURE__ */Symbol("chizu.brand/Payload");static Broadcast=/* @__PURE__ */Symbol("chizu.brand/Broadcast");static Multicast=/* @__PURE__ */Symbol("chizu.brand/Multicast");static Action=/* @__PURE__ */Symbol("chizu.brand/Action");static Channel=/* @__PURE__ */Symbol("chizu.brand/Channel");static Node=/* @__PURE__ */Symbol("chizu.action.lifecycle/Node");static Cache=/* @__PURE__ */Symbol("chizu.brand/Cache")}class l{static Mount=/* @__PURE__ */Symbol("chizu.action.lifecycle/Mount");static Unmount=/* @__PURE__ */Symbol("chizu.action.lifecycle/Unmount");static Error=/* @__PURE__ */Symbol("chizu.action.lifecycle/Error");static Update=/* @__PURE__ */Symbol("chizu.action.lifecycle/Update");static Node=(()=>{const e=u.Node,t=function(t){return{[u.Action]:e,[u.Payload]:void 0,[u.Channel]:t,channel:t}};return Object.defineProperty(t,u.Action,{value:e,enumerable:!1}),Object.defineProperty(t,u.Payload,{value:void 0,enumerable:!1}),t})()}var f=/* @__PURE__ */(e=>(e.Unicast="unicast",e.Broadcast="broadcast",e.Multicast="multicast",e))(f||{}),d=/* @__PURE__ */(e=>(e.Mounting="mounting",e.Mounted="mounted",e.Unmounting="unmounting",e.Unmounted="unmounted",e))(d||{}),p=/* @__PURE__ */(e=>(e[e.Timedout=0]="Timedout",e[e.Supplanted=1]="Supplanted",e[e.Disallowed=2]="Disallowed",e[e.Errored=3]="Errored",e[e.Unmounted=4]="Unmounted",e))(p||{});class h extends Error{name="AbortError";constructor(e="Aborted"){super(e)}}const m={actionPrefix:"chizu.action/",broadcastActionPrefix:"chizu.action/broadcast/",multicastActionPrefix:"chizu.action/multicast/",channelPrefix:"chizu.channel/",cachePrefix:"chizu.cache/"};function y(e,t){return new Promise((n,r)=>{if(t?.aborted)return void r(new h);const o=setTimeout(n,e);t?.addEventListener("abort",()=>{clearTimeout(o),r(new h)},{once:!0})})}function b(e){return e?Boolean(e&&"symbol"!=typeof e):/* @__PURE__ */Symbol(`pk.${Date.now()}.${crypto.randomUUID()}`)}const v=/* @__PURE__ */Object.freeze(/* @__PURE__ */Object.defineProperty({__proto__:null,config:m,pk:b,sleep:y,"ζ":y,"κ":b},Symbol.toStringTag,{value:"Module"})),g=e=>"symbol"==typeof e;function w(t){return e.isString(t)||g(t)?t:(e.isObject(t)||e.isFunction(t))&&u.Action in t?t[u.Action]:t}function
|
|
1
|
+
import{G as e,A as t}from"@mobily/ts-belt";import{jsx as n}from"react/jsx-runtime";import*as r from"react";import{createContext as o,useContext as c}from"react";import{immerable as i,enablePatches as s,Immer as a}from"immer";class u{static Payload=/* @__PURE__ */Symbol("chizu.brand/Payload");static Broadcast=/* @__PURE__ */Symbol("chizu.brand/Broadcast");static Multicast=/* @__PURE__ */Symbol("chizu.brand/Multicast");static Action=/* @__PURE__ */Symbol("chizu.brand/Action");static Channel=/* @__PURE__ */Symbol("chizu.brand/Channel");static Node=/* @__PURE__ */Symbol("chizu.action.lifecycle/Node");static Cache=/* @__PURE__ */Symbol("chizu.brand/Cache")}class l{static Mount=/* @__PURE__ */Symbol("chizu.action.lifecycle/Mount");static Unmount=/* @__PURE__ */Symbol("chizu.action.lifecycle/Unmount");static Error=/* @__PURE__ */Symbol("chizu.action.lifecycle/Error");static Update=/* @__PURE__ */Symbol("chizu.action.lifecycle/Update");static Node=(()=>{const e=u.Node,t=function(t){return{[u.Action]:e,[u.Payload]:void 0,[u.Channel]:t,channel:t}};return Object.defineProperty(t,u.Action,{value:e,enumerable:!1}),Object.defineProperty(t,u.Payload,{value:void 0,enumerable:!1}),t})()}var f=/* @__PURE__ */(e=>(e.Unicast="unicast",e.Broadcast="broadcast",e.Multicast="multicast",e))(f||{}),d=/* @__PURE__ */(e=>(e.Mounting="mounting",e.Mounted="mounted",e.Unmounting="unmounting",e.Unmounted="unmounted",e))(d||{}),p=/* @__PURE__ */(e=>(e[e.Timedout=0]="Timedout",e[e.Supplanted=1]="Supplanted",e[e.Disallowed=2]="Disallowed",e[e.Errored=3]="Errored",e[e.Unmounted=4]="Unmounted",e))(p||{});class h extends Error{name="AbortError";constructor(e="Aborted"){super(e)}}const m={actionPrefix:"chizu.action/",broadcastActionPrefix:"chizu.action/broadcast/",multicastActionPrefix:"chizu.action/multicast/",channelPrefix:"chizu.channel/",cachePrefix:"chizu.cache/"};function y(e,t){return new Promise((n,r)=>{if(t?.aborted)return void r(new h);const o=setTimeout(n,e);t?.addEventListener("abort",()=>{clearTimeout(o),r(new h)},{once:!0})})}function b(e){return e?Boolean(e&&"symbol"!=typeof e):/* @__PURE__ */Symbol(`pk.${Date.now()}.${crypto.randomUUID()}`)}const v=/* @__PURE__ */Object.freeze(/* @__PURE__ */Object.defineProperty({__proto__:null,config:m,pk:b,sleep:y,"ζ":y,"κ":b},Symbol.toStringTag,{value:"Module"})),g=e=>"symbol"==typeof e;function w(t){return e.isString(t)||g(t)?t:(e.isObject(t)||e.isFunction(t))&&u.Action in t?t[u.Action]:t}function P(t){if(e.isString(t))return t.startsWith(m.broadcastActionPrefix);if(g(t))return t.description?.startsWith(m.broadcastActionPrefix)??!1;if(e.isObject(t)||e.isFunction(t)){if(u.Broadcast in t&&t[u.Broadcast])return!0;if(u.Action in t){const e=t[u.Action];return e.description?.startsWith(m.broadcastActionPrefix)??!1}}return!1}function S(t){const n=w(t),r=e.isString(n)?n:n.description??"";return r.startsWith(m.actionPrefix)&&r.slice(r.lastIndexOf("/")+1)||"unknown"}function x(t){return e.isObject(t)&&u.Channel in t&&"channel"in t}function E(t){if(e.isString(t))return t.startsWith(m.multicastActionPrefix);if(g(t))return t.description?.startsWith(m.multicastActionPrefix)??!1;if(e.isObject(t)||e.isFunction(t)){if(u.Multicast in t&&t[u.Multicast])return!0;if(u.Action in t){const e=t[u.Action];return e.description?.startsWith(m.multicastActionPrefix)??!1}}return!1}const M=(e,t=f.Unicast)=>{const n=t===f.Broadcast?/* @__PURE__ */Symbol(`${m.broadcastActionPrefix}${e}`):t===f.Multicast?/* @__PURE__ */Symbol(`${m.multicastActionPrefix}${e}`):/* @__PURE__ */Symbol(`${m.actionPrefix}${e}`),r=function(e){return{[u.Action]:n,[u.Payload]:void 0,[u.Channel]:e,channel:e}};return Object.defineProperty(r,u.Action,{value:n,enumerable:!1}),Object.defineProperty(r,u.Payload,{value:void 0,enumerable:!1}),t===f.Broadcast&&Object.defineProperty(r,u.Broadcast,{value:!0,enumerable:!1}),t===f.Multicast&&Object.defineProperty(r,u.Multicast,{value:!0,enumerable:!1}),r};function O(){const e=/* @__PURE__ */Symbol("chizu.cache/Entry"),t=function(t){return{[u.Cache]:e,channel:t}};return Object.defineProperty(t,u.Cache,{value:e,enumerable:!1}),t}function A(e){const t=function(e){return e[u.Cache]}(e),n=function(e){return"channel"in e}(e)&&(r=e.channel)?[...Object.keys(r)].toSorted().map(e=>`${e}=${String(r[e])}`).join("&"):"";var r;return`${String(t)}:${n}`}function j(e){if(e instanceof Error){if("TimeoutError"===e.name)return p.Timedout;if("AbortError"===e.name)return p.Supplanted}return p.Errored}function k(e){return e instanceof Error?e:new Error(String(e))}const C=o(void 0);function _({handler:e,children:t}){/* @__PURE__ */
|
|
2
2
|
return n(C.Provider,{value:e,children:t})}let N=(e=21)=>{let t="",n=crypto.getRandomValues(new Uint8Array(e|=0));for(;e--;)t+="useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict"[63&n[e]];return t};var R=/* @__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))(R||{}),U=/* @__PURE__ */(e=>(e[e.Produce=0]="Produce",e[e.Hydrate=1]="Hydrate",e))(U||{}),z=/* @__PURE__ */(e=>(e.Property="property",e.Process="process",e.Value="value",e.Operation="operation",e))(z||{});class L{[i]=!0;static keys=new Set(Object.values(z));property=null;process=null;value;operation;constructor(e,t){this.value=e,this.operation=t}assign(e,t){const n=new L(this.value,this.operation);return n.property=e,n.process=t,n}}class T{static immer=(()=>{s();const e=new a;return e.setAutoFreeze(!1),e})();static tag="κ";static id=N}function $(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)||D(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 D(t){return e.isNullable(t)||e.isString(t)||e.isNumber(t)||e.isBoolean(t)||"symbol"==typeof t||"bigint"==typeof t}function H(t,n,r,o,c,i){return function s(a,u=n.path){if(a instanceof L){const n=$(r,u.join("."));if(Object.entries(a).filter(([e,t])=>!L.keys.has(e)&&t instanceof L).forEach(([e,t])=>s(t,u.concat(e))),D(a.value)){if(t===U.Hydrate)return a.value;const s=u.slice(0,-1),l=s.length>0?$(r,s.join(".")):r;return e.isNullable(l)||G(l,a,u.at(-1),o,c,i),n??a.value}if(t===U.Hydrate){const e=B(s(a.value,u));return G(e,a,null,o,c,i),e}const l=n??B(a.value);return G(l,a,null,o,c,i),e.isNullable(n)?l:(s(a.value,u),n)}if(e.isArray(a))return a.map((e,t)=>s(e,u.concat(t)));if(e.isObject(a)&&!W(a))return a;if(e.isObject(a)){const e=Object.entries(a).map(([e,t])=>[e,s(t,u.concat(e))]),n=Object.fromEntries(e);if(t===U.Hydrate){const e=B(n);return Object.entries(a).forEach(([t,n])=>{n instanceof L&&D(n.value)&&G(e,n,t,o,c,i)}),e}return n}return a}(n.value)}function G(e,t,n,r,o,c){const i=c(e),s=o.get(i)??[];o.set(i,[t.assign(n,r),...s])}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 L(t,e)}"δ"=this.annotate;get model(){return this.#e}get inspect(){return function(n,r,o,c,i){function s(c){const i=c.at(-1),s=$(n(),c),a=c.slice(0,-1),u=t.isNotEmpty(a)?$(n(),a):n();return[...e.isObject(s)||e.isArray(s)?r.get(o(s))?.filter(t=>e.isNullable(t.property))??[]:[],...e.isObject(u)?r.get(o(u))?.filter(e=>e.property===i)??[]:[]]}return function e(r){return new Proxy(()=>{},{get:(o,a)=>"pending"===a?()=>!t.isEmpty(s(r)):"remaining"===a?()=>t.length(s(r)):"box"===a?()=>({value:$(n(),r),inspect:e(r)}):"is"===a?e=>s(r).some(t=>0!==(t.operation&e)):"draft"===a?()=>t.head(s(r))?.value??$(n(),r):"settled"===a?()=>new Promise(e=>{if(t.isEmpty(s(r)))return e($(n(),r));const o=()=>{t.isEmpty(s(r))&&(i(o),e($(n(),r)))};c(o)}):e([...r,String(a)])})}([])}(()=>this.#e,this.#n,this.#t,e=>this.#r.add(e),e=>this.#r.delete(e))}hydrate(e){return this.#o=!0,this.#c(U.Hydrate,()=>e)}produce(e){if(!this.#o)throw new Error("State must be hydrated using hydrate() before calling produce()");return this.#c(U.Produce,e)}#c(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:H(e,r,t,n,this.#n,this.#t)}]),this.#e),this.#e=B(this.#e),this.#i(),n}prune(e){this.#n.forEach((n,r)=>{const o=n.filter(t=>t.process!==e);t.isEmpty(o)?this.#n.delete(r):this.#n.set(r,o)}),this.#i()}#i(){this.#r.forEach(e=>e())}observe(e){const t=()=>e(this.#e);return this.#r.add(t),()=>this.#r.delete(t)}}const V=new I;function q(e,t){return V.annotate(e,t)}function J(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var K,Q={exports:{}};const X=/* @__PURE__ */J((K||(K=1,function(e){var t=Object.prototype.hasOwnProperty,n="~";function r(){}function o(e,t,n){this.fn=e,this.context=t,this.once=n||!1}function c(e,t,r,c,i){if("function"!=typeof r)throw new TypeError("The listener must be a function");var s=new o(r,c||e,i),a=n?n+t:t;return e._events[a]?e._events[a].fn?e._events[a]=[e._events[a],s]:e._events[a].push(s):(e._events[a]=s,e._eventsCount++),e}function i(e,t){0===--e._eventsCount?e._events=new r:delete e._events[t]}function s(){this._events=new r,this._eventsCount=0}Object.create&&(r.prototype=/* @__PURE__ */Object.create(null),(new r).__proto__||(n=!1)),s.prototype.eventNames=function(){var e,r,o=[];if(0===this._eventsCount)return o;for(r in e=this._events)t.call(e,r)&&o.push(n?r.slice(1):r);return Object.getOwnPropertySymbols?o.concat(Object.getOwnPropertySymbols(e)):o},s.prototype.listeners=function(e){var t=this._events[n?n+e:e];if(!t)return[];if(t.fn)return[t.fn];for(var r=0,o=t.length,c=new Array(o);r<o;r++)c[r]=t[r].fn;return c},s.prototype.listenerCount=function(e){var t=this._events[n?n+e:e];return t?t.fn?1:t.length:0},s.prototype.emit=function(e,t,r,o,c,i){var s=n?n+e:e;if(!this._events[s])return!1;var a,u,l=this._events[s],f=arguments.length;if(l.fn){switch(l.once&&this.removeListener(e,l.fn,void 0,!0),f){case 1:return l.fn.call(l.context),!0;case 2:return l.fn.call(l.context,t),!0;case 3:return l.fn.call(l.context,t,r),!0;case 4:return l.fn.call(l.context,t,r,o),!0;case 5:return l.fn.call(l.context,t,r,o,c),!0;case 6:return l.fn.call(l.context,t,r,o,c,i),!0}for(u=1,a=new Array(f-1);u<f;u++)a[u-1]=arguments[u];l.fn.apply(l.context,a)}else{var d,p=l.length;for(u=0;u<p;u++)switch(l[u].once&&this.removeListener(e,l[u].fn,void 0,!0),f){case 1:l[u].fn.call(l[u].context);break;case 2:l[u].fn.call(l[u].context,t);break;case 3:l[u].fn.call(l[u].context,t,r);break;case 4:l[u].fn.call(l[u].context,t,r,o);break;default:if(!a)for(d=1,a=new Array(f-1);d<f;d++)a[d-1]=arguments[d];l[u].fn.apply(l[u].context,a)}}return!0},s.prototype.on=function(e,t,n){return c(this,e,t,n,!1)},s.prototype.once=function(e,t,n){return c(this,e,t,n,!0)},s.prototype.removeListener=function(e,t,r,o){var c=n?n+e:e;if(!this._events[c])return this;if(!t)return i(this,c),this;var s=this._events[c];if(s.fn)s.fn!==t||o&&!s.once||r&&s.context!==r||i(this,c);else{for(var a=0,u=[],l=s.length;a<l;a++)(s[a].fn!==t||o&&!s[a].once||r&&s[a].context!==r)&&u.push(s[a]);u.length?this._events[c]=1===u.length?u[0]:u:i(this,c)}return this},s.prototype.removeAllListeners=function(e){var t;return e?this._events[t=n?n+e:e]&&i(this,t):(this._events=new r,this._eventsCount=0),this},s.prototype.off=s.prototype.removeListener,s.prototype.addListener=s.prototype.on,s.prefixed=n,s.EventEmitter=s,e.exports=s}(Q)),Q.exports)),Y=r.createContext(new X);function Z(){return r.useContext(Y)}function ee({children:e}){const t=r.useMemo(()=>new X,[]);/* @__PURE__ */
|
|
3
3
|
return n(Y.Provider,{value:t,children:e})}const te=r.createContext(/* @__PURE__ */new Map);function ne(){return r.useContext(te)}function re(){const[,e]=r.useReducer(e=>e+1,0);return e}function oe({action:t,renderer:n}){const o=Z(),c=ne(),i=re(),s=r.useMemo(()=>{const e=c.get(t);if(e)return e;const n={state:new I,listeners:/* @__PURE__ */new Set};return c.set(t,n),n},[t,c]);r.useLayoutEffect(()=>{function e(e){s.state.hydrate({value:e}),s.listeners.forEach(e=>e())}return s.listeners.add(i),o.on(t,e),()=>{s.listeners.delete(i),o.off(t,e)}},[t,o,s]);const a=s.state.model?.value;return e.isNullable(a)?null:n({value:a,inspect:s.state.inspect.value})}function ce({children:e}){const t=r.useMemo(()=>/* @__PURE__ */new Map,[]);/* @__PURE__ */
|
|
4
4
|
return n(te.Provider,{value:t,children:e})}const ie=r.createContext(/* @__PURE__ */new Map);function se({children:e}){const t=r.useMemo(()=>/* @__PURE__ */new Map,[]);/* @__PURE__ */
|
|
@@ -6,4 +6,4 @@ return n(ie.Provider,{value:t,children:e})}const ae=r.createContext(/* @__PURE__
|
|
|
6
6
|
return n(ae.Provider,{value:t,children:e})}function le({children:e}){/* @__PURE__ */
|
|
7
7
|
return n(ee,{children:/* @__PURE__ */n(ce,{children:/* @__PURE__ */n(se,{children:/* @__PURE__ */n(ue,{children:e})})})})}const fe=r.createContext(null);function de(){return r.useContext(fe)}function pe(e,t){return e?.get(t)??null}function he({action:t,scopeName:n,renderer:o}){const c=de(),i=re(),s=r.useMemo(()=>pe(c,n),[c,n]),a=r.useMemo(()=>s?function(e,t){const n=e.store.get(t);if(n)return n;const r={state:new I,listeners:/* @__PURE__ */new Set};return e.store.set(t,r),r}(s,t):null,[t,s]);if(r.useLayoutEffect(()=>{if(s&&a)return a.listeners.add(i),s.emitter.on(t,e),()=>{a.listeners.delete(i),s.emitter.off(t,e)};function e(e){a&&(a.state.hydrate({value:e}),a.listeners.forEach(e=>e()))}},[t,s,a,i]),!a)return null;const u=a.state.model?.value;return e.isNullable(u)?null:o({value:u,inspect:a.state.inspect.value})}function me({name:e,children:t}){const o=de(),c=r.useMemo(()=>({name:e,emitter:new X,store:/* @__PURE__ */new Map,listeners:/* @__PURE__ */new Map}),[]),i=r.useMemo(()=>{const t=new Map(o??[]);return t.set(e,c),t},[o,e,c]);/* @__PURE__ */
|
|
8
8
|
return n(fe.Provider,{value:i,children:t})}function ye(e,t){return function(r){/* @__PURE__ */
|
|
9
|
-
return n(me,{name:e,children:/* @__PURE__ */n(t,{...r})})}}function be(e){return(t,n)=>{t.actions.produce(t=>{t.model[e]=n})}}function ve(n,o=()=>({})){const i=Z(),s=de(),a=c(C),
|
|
9
|
+
return n(me,{name:e,children:/* @__PURE__ */n(t,{...r})})}}function be(e){return(t,n)=>{t.actions.produce(t=>{t.model[e]=n})}}function ve(n,o=()=>({})){const i=Z(),s=de(),a=ne(),f=c(C),p=r.useContext(ae),m=r.useContext(ie),y=re(),b=r.useRef(!1),v=r.useRef(null),g=r.useRef(new I);b.current||(b.current=!0,v.current=g.current.hydrate(n));const[M,O]=r.useState(()=>g.current.model),_=function(e){const t=r.useRef(e);return r.useLayoutEffect(()=>{t.current=e},[e]),r.useMemo(()=>{return n=t,Object.keys(e).reduce((e,t)=>(Object.defineProperty(e,t,{get:()=>n.current[t],enumerable:!0}),e),{});var n},[e])}(o()),N=r.useMemo(()=>new X,[]),R=r.useRef({handlers:/* @__PURE__ */new Map});R.current.handlers=/* @__PURE__ */new Map;const U=function(){const e=r.useRef(/* @__PURE__ */new Set),t=r.useRef(/* @__PURE__ */new Set);return r.useMemo(()=>({broadcast:e.current,multicast:t.current}),[])}(),z=r.useRef(d.Mounting),L=function(){const e=r.useRef({}),t=r.useRef(/* @__PURE__ */new Map),n=r.useRef(/* @__PURE__ */new Map);return r.useMemo(()=>({refs:e,pending:t,emitted:n}),[])}(),T=r.useRef(/* @__PURE__ */new Set),$=r.useRef(0),B=r.useCallback((e,t,n)=>{const r=new AbortController,o={controller:r,action:e,payload:t};return p.add(o),T.current.add(o),{model:M,get phase(){return z.current},task:o,data:_,tasks:p,nodes:L.refs.current,actions:{produce(e){if(r.signal.aborted)return;const t=g.current.produce(t=>e({model:t,inspect:g.current.inspect}));O(g.current.model),n.processes.add(t),v.current&&(n.processes.add(v.current),v.current=null)},dispatch(e,t,n){if(r.signal.aborted)return;const o=w(e),c=x(e)?e.channel:void 0;if(E(e)&&n?.scope){const e=pe(s,n.scope);return void(e&&e.emitter.emit(o,t,c))}(P(e)?i:N).emit(o,t,c)},annotate:(e,t)=>g.current.annotate(e,t),async cacheable(e,t,n){if(r.signal.aborted)return{data:null};const o=A(e),c=m.get(o);if(c&&Date.now()<c.expiry)return{data:c.value};const i=function(e){return null!=e&&"object"==typeof e&&"TAG"in e?0===e.TAG?{ok:!0,value:e._0}:{ok:!1}:null==e?{ok:!1}:{ok:!0,value:e}}(await n());return i.ok?(m.set(o,{value:i.value,expiry:Date.now()+t}),{data:i.value}):{data:null}},invalidate(e){m.delete(A(e))},async consume(e,t){if(r.signal.aborted)return null;const n=w(e);let o;if(E(e)&&t?.scope){const e=pe(s,t.scope);if(!e)return null;o=e.store.get(n)}else o=a.get(n);if(!o?.state.model?.value)return null;const c=o.state.inspect;return c.value.pending()&&await new Promise((e,t)=>{if(r.signal.aborted)return void t(new h);const n=()=>t(new h);r.signal.addEventListener("abort",n,{once:!0}),c.value.settled().then(()=>{r.signal.removeEventListener("abort",n),e()})}),o.state.model.value}}}},[M]);r.useLayoutEffect(()=>{function t(t,n,r){return async function(o,c){const i=r();if(e.isNotNullable(c)&&e.isNotNullable(i)&&!function(e,t){for(const n of Object.keys(e))if(t[n]!==e[n])return!1;return!0}(c,i))return;const s={processes:/* @__PURE__ */new Set},a=Promise.withResolvers(),u=B(t,o,s);try{await n(u,o)}catch(d){const e=R.current.handlers.has(l.Error),n={reason:j(d),error:k(d),action:S(t),handled:e,tasks:p};f?.(n),e&&N.emit(l.Error,n)}finally{for(const e of p)if(e===u.task){p.delete(e),T.current.delete(e);break}s.processes.forEach(e=>g.current.prune(e)),s.processes.size>0&&y(),a.resolve()}}}$.current++;const n=/* @__PURE__ */new Set;return R.current.handlers.forEach((e,r)=>{for(const{getChannel:o,handler:c}of e){const e=t(r,c,o);if(E(r)){if(s)for(const t of s.values()){const o=t.emitter;o.on(r,e),n.add(()=>o.off(r,e))}N.on(r,e),U.multicast.add(r),n.add(()=>N.off(r,e))}else P(r)?(i.on(r,e),N.on(r,e),U.broadcast.add(r),n.add(()=>{i.off(r,e),N.off(r,e)})):(N.on(r,e),n.add(()=>N.off(r,e)))}}),()=>{const e=++$.current,t=new Set(n);queueMicrotask(()=>{if($.current===e){for(const e of T.current)e.controller.abort(),p.delete(e);T.current.clear(),z.current=d.Unmounting,N.emit(l.Unmount),z.current=d.Unmounted;for(const e of t)e()}else for(const e of t)e()})}},[N]),r.useLayoutEffect(()=>{for(const[e,t]of L.pending.current)L.emitted.current.get(e)!==t&&(L.emitted.current.set(e,t),N.emit(u.Node,t,{Name:e}));L.pending.current.clear()}),function({unicast:n,broadcastActions:o,phase:c,data:i}){const s=ne(),a=r.useRef(null);r.useLayoutEffect(()=>{c.current===d.Mounting&&(n.emit(l.Mount),o.forEach(t=>{const r=s.get(t),o=r?.state.model?.value;e.isNullable(o)||n.emit(t,o)}),c.current=d.Mounted)},[]),r.useLayoutEffect(()=>{if(e.isNotNullable(a.current)){const e=function(e,t){return Object.keys(t).reduce((n,r)=>e[r]!==t[r]?{...n,[r]:t[r]}:n,{})}(a.current,i);t.isNotEmpty(Object.keys(e))&&n.emit(l.Update,e)}a.current=i},[i,n])}({unicast:N,broadcastActions:U.broadcast,phase:z,data:o()});const F=r.useMemo(()=>[M,{dispatch(e,t,n){const r=w(e),o=x(e)?e.channel:void 0;if(E(e)&&n?.scope){const e=pe(s,n.scope);return void(e&&e.emitter.emit(r,t,o))}(P(e)?i:N).emit(r,t,o)},consume:(e,t,n)=>E(e)&&n?.scope?r.createElement(he,{action:w(e),scopeName:n.scope,renderer:t}):r.createElement(oe,{action:w(e),renderer:t}),get inspect(){return g.current.inspect},get nodes(){return L.refs.current},node(e,t){L.refs.current[e]=t,L.pending.current.set(e,t)}}],[M,N]);return F.useAction=(e,t)=>{!function(e,t,n){const o=r.useRef(n);r.useLayoutEffect(()=>{o.current=n});const c=r.useRef(t);r.useLayoutEffect(()=>{c.current=t});const i=r.useCallback(async(e,t)=>{const n=o.current;if("GeneratorFunction"===n.constructor.name||"AsyncGeneratorFunction"===n.constructor.name){const r=n(e,t);for await(const e of r);}else await n(e,t)},[]),s=r.useCallback(()=>x(c.current)?c.current.channel:void 0,[]),a=w(t),u=e.current.handlers.get(a)??/* @__PURE__ */new Set;0===u.size&&e.current.handlers.set(a,u),u.add({getChannel:s,handler:i})}(R,e,t)},F}export{M as Action,le as Boundary,f as Distribution,O as Entry,_ as Error,l as Lifecycle,R as Op,R as Operation,p as Reason,me as Scope,I as State,be as With,q as annotate,ve as useActions,v as utils,ye as withScope};
|
package/dist/chizu.umd.cjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
var global,factory;global=this,factory=function(e,t,n,r,o){"use strict";function c(e){const t=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(e)for(const n in e)if("default"!==n){const r=Object.getOwnPropertyDescriptor(e,n);Object.defineProperty(t,n,r.get?r:{enumerable:!0,get:()=>e[n]})}return t.default=e,Object.freeze(t)}const i=c(r);class s{static Payload=Symbol("chizu.brand/Payload");static Broadcast=Symbol("chizu.brand/Broadcast");static Multicast=Symbol("chizu.brand/Multicast");static Action=Symbol("chizu.brand/Action");static Channel=Symbol("chizu.brand/Channel");static Node=Symbol("chizu.action.lifecycle/Node");static Cache=Symbol("chizu.brand/Cache")}class a{static Mount=Symbol("chizu.action.lifecycle/Mount");static Unmount=Symbol("chizu.action.lifecycle/Unmount");static Error=Symbol("chizu.action.lifecycle/Error");static Update=Symbol("chizu.action.lifecycle/Update");static Node=(()=>{const e=s.Node,t=function(t){return{[s.Action]:e,[s.Payload]:void 0,[s.Channel]:t,channel:t}};return Object.defineProperty(t,s.Action,{value:e,enumerable:!1}),Object.defineProperty(t,s.Payload,{value:void 0,enumerable:!1}),t})()}var u=(e=>(e.Unicast="unicast",e.Broadcast="broadcast",e.Multicast="multicast",e))(u||{}),l=(e=>(e.Mounting="mounting",e.Mounted="mounted",e.Unmounting="unmounting",e.Unmounted="unmounted",e))(l||{}),f=(e=>(e[e.Timedout=0]="Timedout",e[e.Supplanted=1]="Supplanted",e[e.Disallowed=2]="Disallowed",e[e.Errored=3]="Errored",e[e.Unmounted=4]="Unmounted",e))(f||{});class d extends Error{name="AbortError";constructor(e="Aborted"){super(e)}}const p={actionPrefix:"chizu.action/",broadcastActionPrefix:"chizu.action/broadcast/",multicastActionPrefix:"chizu.action/multicast/",channelPrefix:"chizu.channel/",cachePrefix:"chizu.cache/"};function h(e,t){return new Promise((n,r)=>{if(t?.aborted)return void r(new d);const o=setTimeout(n,e);t?.addEventListener("abort",()=>{clearTimeout(o),r(new d)},{once:!0})})}function m(e){return e?Boolean(e&&"symbol"!=typeof e):Symbol(`pk.${Date.now()}.${crypto.randomUUID()}`)}const y=Object.freeze(Object.defineProperty({__proto__:null,config:p,pk:m,sleep:h,"ζ":h,"κ":m},Symbol.toStringTag,{value:"Module"})),b=e=>"symbol"==typeof e;function v(e){return t.G.isString(e)||b(e)?e:(t.G.isObject(e)||t.G.isFunction(e))&&s.Action in e?e[s.Action]:e}function g(e){if(t.G.isString(e))return e.startsWith(p.broadcastActionPrefix);if(b(e))return e.description?.startsWith(p.broadcastActionPrefix)??!1;if(t.G.isObject(e)||t.G.isFunction(e)){if(s.Broadcast in e&&e[s.Broadcast])return!0;if(s.Action in e){const t=e[s.Action];return t.description?.startsWith(p.broadcastActionPrefix)??!1}}return!1}function w(e){const n=v(e),r=t.G.isString(n)?n:n.description??"";return r.startsWith(p.actionPrefix)&&r.slice(r.lastIndexOf("/")+1)||"unknown"}function x(e){return t.G.isObject(e)&&s.Channel in e&&"channel"in e}function j(e){if(t.G.isString(e))return e.startsWith(p.multicastActionPrefix);if(b(e))return e.description?.startsWith(p.multicastActionPrefix)??!1;if(t.G.isObject(e)||t.G.isFunction(e)){if(s.Multicast in e&&e[s.Multicast])return!0;if(s.Action in e){const t=e[s.Action];return t.description?.startsWith(p.multicastActionPrefix)??!1}}return!1}function S(e){const t=function(e){return e[s.Cache]}(e),n=function(e){return"channel"in e}(e)&&(r=e.channel)?[...Object.keys(r)].toSorted().map(e=>`${e}=${String(r[e])}`).join("&"):"";var r;return`${String(t)}:${n}`}function P(e){if(e instanceof Error){if("TimeoutError"===e.name)return f.Timedout;if("AbortError"===e.name)return f.Supplanted}return f.Errored}function A(e){return e instanceof Error?e:new Error(String(e))}const O=r.createContext(void 0);let E=(e=21)=>{let t="",n=crypto.getRandomValues(new Uint8Array(e|=0));for(;e--;)t+="useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict"[63&n[e]];return t};var M=(e=>(e[e.Add=1]="Add",e[e.Remove=2]="Remove",e[e.Update=4]="Update",e[e.Move=8]="Move",e[e.Replace=16]="Replace",e[e.Sort=32]="Sort",e[e.Create=64]="Create",e[e.Fetch=128]="Fetch",e[e.Clone=256]="Clone",e[e.Archive=512]="Archive",e[e.Restore=1024]="Restore",e[e.Merge=2048]="Merge",e[e.Reorder=4096]="Reorder",e[e.Sync=8192]="Sync",e[e.Publish=16384]="Publish",e[e.Link=32768]="Link",e[e.Unlink=65536]="Unlink",e[e.Lock=131072]="Lock",e[e.Unlock=262144]="Unlock",e[e.Import=524288]="Import",e[e.Export=1048576]="Export",e[e.Transfer=2097152]="Transfer",e))(M||{}),C=(e=>(e[e.Produce=0]="Produce",e[e.Hydrate=1]="Hydrate",e))(C||{}),k=(e=>(e.Property="property",e.Process="process",e.Value="value",e.Operation="operation",e))(k||{});class G{[o.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 G(this.value,this.operation);return n.property=e,n.process=t,n}}class _{static immer=(()=>{o.enablePatches();const e=new o.Immer;return e.setAutoFreeze(!1),e})();static tag="κ";static id=E}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 N(e){if(t.G.isNullable(e)||L(e))return e;if(t.G.isArray(e))return e.map(e=>N(e));if(t.G.isObject(e)&&U(e)){const t=Object.entries(e).map(([e,t])=>[e,N(t)]);return{...Object.fromEntries(t),[_.tag]:e[_.tag]??_.id()}}return e}function z(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 U(e){const t=Object.getPrototypeOf(e);return t===Object.prototype||null===t}function L(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 T(e,n,r,o,c,i){return function s(a,u=n.path){if(a instanceof G){const n=R(r,u.join("."));if(Object.entries(a).filter(([e,t])=>!G.keys.has(e)&&t instanceof G).forEach(([e,t])=>s(t,u.concat(e))),L(a.value)){if(e===C.Hydrate)return a.value;const s=u.slice(0,-1),l=s.length>0?R(r,s.join(".")):r;return t.G.isNullable(l)||B(l,a,u.at(-1),o,c,i),n??a.value}if(e===C.Hydrate){const e=N(s(a.value,u));return B(e,a,null,o,c,i),e}const l=n??N(a.value);return B(l,a,null,o,c,i),t.G.isNullable(n)?l:(s(a.value,u),n)}if(t.G.isArray(a))return a.map((e,t)=>s(e,u.concat(t)));if(t.G.isObject(a)&&!U(a))return a;if(t.G.isObject(a)){const t=Object.entries(a).map(([e,t])=>[e,s(t,u.concat(e))]),n=Object.fromEntries(t);if(e===C.Hydrate){const e=N(n);return Object.entries(a).forEach(([t,n])=>{n instanceof G&&L(n.value)&&B(e,n,t,o,c,i)}),e}return n}return a}(n.value)}function B(e,t,n,r,o,c){const i=c(e),s=o.get(i)??[];o.set(i,[t.assign(n,r),...s])}class ${#e={};#t;#n=new Map;#r=new Set;#o=!1;constructor(e=z){this.#t=e}static pk(){return E()}static"κ"=$.pk;annotate(e,t){return new G(t,e)}"δ"=this.annotate;get model(){return this.#e}get inspect(){return function(e,n,r,o,c){function i(o){const c=o.at(-1),i=R(e(),o),s=o.slice(0,-1),a=t.A.isNotEmpty(s)?R(e(),s):e();return[...t.G.isObject(i)||t.G.isArray(i)?n.get(r(i))?.filter(e=>t.G.isNullable(e.property))??[]:[],...t.G.isObject(a)?n.get(r(a))?.filter(e=>e.property===c)??[]:[]]}return function n(r){return new Proxy(()=>{},{get:(s,a)=>"pending"===a?()=>!t.A.isEmpty(i(r)):"remaining"===a?()=>t.A.length(i(r)):"box"===a?()=>({value:R(e(),r),inspect:n(r)}):"is"===a?e=>i(r).some(t=>0!==(t.operation&e)):"draft"===a?()=>t.A.head(i(r))?.value??R(e(),r):"settled"===a?()=>new Promise(n=>{if(t.A.isEmpty(i(r)))return n(R(e(),r));const s=()=>{t.A.isEmpty(i(r))&&(c(s),n(R(e(),r)))};o(s)}):n([...r,String(a)])})}([])}(()=>this.#e,this.#n,this.#t,e=>this.#r.add(e),e=>this.#r.delete(e))}hydrate(e){return this.#o=!0,this.#c(C.Hydrate,()=>e)}produce(e){if(!this.#o)throw new Error("State must be hydrated using hydrate() before calling produce()");return this.#c(C.Produce,e)}#c(e,t){const n=Symbol("process"),[,r]=_.immer.produceWithPatches(this.#e,t);return this.#e=r.reduce((t,r)=>_.immer.applyPatches(t,[{...r,value:T(e,r,t,n,this.#n,this.#t)}]),this.#e),this.#e=N(this.#e),this.#i(),n}prune(e){this.#n.forEach((n,r)=>{const o=n.filter(t=>t.process!==e);t.A.isEmpty(o)?this.#n.delete(r):this.#n.set(r,o)}),this.#i()}#i(){this.#r.forEach(e=>e())}observe(e){const t=()=>e(this.#e);return this.#r.add(t),()=>this.#r.delete(t)}}const W=new $;function D(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var F,H={exports:{}},I=(F||(F=1,function(e){var t=Object.prototype.hasOwnProperty,n="~";function r(){}function o(e,t,n){this.fn=e,this.context=t,this.once=n||!1}function c(e,t,r,c,i){if("function"!=typeof r)throw new TypeError("The listener must be a function");var s=new o(r,c||e,i),a=n?n+t:t;return e._events[a]?e._events[a].fn?e._events[a]=[e._events[a],s]:e._events[a].push(s):(e._events[a]=s,e._eventsCount++),e}function i(e,t){0===--e._eventsCount?e._events=new r:delete e._events[t]}function s(){this._events=new r,this._eventsCount=0}Object.create&&(r.prototype=Object.create(null),(new r).__proto__||(n=!1)),s.prototype.eventNames=function(){var e,r,o=[];if(0===this._eventsCount)return o;for(r in e=this._events)t.call(e,r)&&o.push(n?r.slice(1):r);return Object.getOwnPropertySymbols?o.concat(Object.getOwnPropertySymbols(e)):o},s.prototype.listeners=function(e){var t=this._events[n?n+e:e];if(!t)return[];if(t.fn)return[t.fn];for(var r=0,o=t.length,c=new Array(o);r<o;r++)c[r]=t[r].fn;return c},s.prototype.listenerCount=function(e){var t=this._events[n?n+e:e];return t?t.fn?1:t.length:0},s.prototype.emit=function(e,t,r,o,c,i){var s=n?n+e:e;if(!this._events[s])return!1;var a,u,l=this._events[s],f=arguments.length;if(l.fn){switch(l.once&&this.removeListener(e,l.fn,void 0,!0),f){case 1:return l.fn.call(l.context),!0;case 2:return l.fn.call(l.context,t),!0;case 3:return l.fn.call(l.context,t,r),!0;case 4:return l.fn.call(l.context,t,r,o),!0;case 5:return l.fn.call(l.context,t,r,o,c),!0;case 6:return l.fn.call(l.context,t,r,o,c,i),!0}for(u=1,a=new Array(f-1);u<f;u++)a[u-1]=arguments[u];l.fn.apply(l.context,a)}else{var d,p=l.length;for(u=0;u<p;u++)switch(l[u].once&&this.removeListener(e,l[u].fn,void 0,!0),f){case 1:l[u].fn.call(l[u].context);break;case 2:l[u].fn.call(l[u].context,t);break;case 3:l[u].fn.call(l[u].context,t,r);break;case 4:l[u].fn.call(l[u].context,t,r,o);break;default:if(!a)for(d=1,a=new Array(f-1);d<f;d++)a[d-1]=arguments[d];l[u].fn.apply(l[u].context,a)}}return!0},s.prototype.on=function(e,t,n){return c(this,e,t,n,!1)},s.prototype.once=function(e,t,n){return c(this,e,t,n,!0)},s.prototype.removeListener=function(e,t,r,o){var c=n?n+e:e;if(!this._events[c])return this;if(!t)return i(this,c),this;var s=this._events[c];if(s.fn)s.fn!==t||o&&!s.once||r&&s.context!==r||i(this,c);else{for(var a=0,u=[],l=s.length;a<l;a++)(s[a].fn!==t||o&&!s[a].once||r&&s[a].context!==r)&&u.push(s[a]);u.length?this._events[c]=1===u.length?u[0]:u:i(this,c)}return this},s.prototype.removeAllListeners=function(e){var t;return e?this._events[t=n?n+e:e]&&i(this,t):(this._events=new r,this._eventsCount=0),this},s.prototype.off=s.prototype.removeListener,s.prototype.addListener=s.prototype.on,s.prefixed=n,s.EventEmitter=s,e.exports=s}(H)),H.exports);const q=D(I),V=i.createContext(new q);function J(){return i.useContext(V)}function K({children:e}){const t=i.useMemo(()=>new q,[]);return n.jsx(V.Provider,{value:t,children:e})}const Q=i.createContext(new Map);function X(){return i.useContext(Q)}function Y(){const[,e]=i.useReducer(e=>e+1,0);return e}function Z({action:e,renderer:n}){const r=J(),o=X(),c=Y(),s=i.useMemo(()=>{const t=o.get(e);if(t)return t;const n={state:new $,listeners:new Set};return o.set(e,n),n},[e,o]);i.useLayoutEffect(()=>{function t(e){s.state.hydrate({value:e}),s.listeners.forEach(e=>e())}return s.listeners.add(c),r.on(e,t),()=>{s.listeners.delete(c),r.off(e,t)}},[e,r,s]);const a=s.state.model?.value;return t.G.isNullable(a)?null:n({value:a,inspect:s.state.inspect.value})}function ee({children:e}){const t=i.useMemo(()=>new Map,[]);return n.jsx(Q.Provider,{value:t,children:e})}const te=i.createContext(new Map);function ne({children:e}){const t=i.useMemo(()=>new Map,[]);return n.jsx(te.Provider,{value:t,children:e})}const re=i.createContext(new Set);function oe({children:e}){const t=i.useMemo(()=>new Set,[]);return n.jsx(re.Provider,{value:t,children:e})}const ce=i.createContext(null);function ie(){return i.useContext(ce)}function se(e,t){return e?.get(t)??null}function ae({action:e,scopeName:n,renderer:r}){const o=ie(),c=Y(),s=i.useMemo(()=>se(o,n),[o,n]),a=i.useMemo(()=>s?function(e,t){const n=e.store.get(t);if(n)return n;const r={state:new $,listeners:new Set};return e.store.set(t,r),r}(s,e):null,[e,s]);if(i.useLayoutEffect(()=>{if(s&&a)return a.listeners.add(c),s.emitter.on(e,t),()=>{a.listeners.delete(c),s.emitter.off(e,t)};function t(e){a&&(a.state.hydrate({value:e}),a.listeners.forEach(e=>e()))}},[e,s,a,c]),!a)return null;const u=a.state.model?.value;return t.G.isNullable(u)?null:r({value:u,inspect:a.state.inspect.value})}function ue({name:e,children:t}){const r=ie(),o=i.useMemo(()=>({name:e,emitter:new q,store:new Map,listeners:new Map}),[]),c=i.useMemo(()=>{const t=new Map(r??[]);return t.set(e,o),t},[r,e,o]);return n.jsx(ce.Provider,{value:c,children:t})}e.Action=(e,t=u.Unicast)=>{const n=t===u.Broadcast?Symbol(`${p.broadcastActionPrefix}${e}`):t===u.Multicast?Symbol(`${p.multicastActionPrefix}${e}`):Symbol(`${p.actionPrefix}${e}`),r=function(e){return{[s.Action]:n,[s.Payload]:void 0,[s.Channel]:e,channel:e}};return Object.defineProperty(r,s.Action,{value:n,enumerable:!1}),Object.defineProperty(r,s.Payload,{value:void 0,enumerable:!1}),t===u.Broadcast&&Object.defineProperty(r,s.Broadcast,{value:!0,enumerable:!1}),t===u.Multicast&&Object.defineProperty(r,s.Multicast,{value:!0,enumerable:!1}),r},e.Boundary=function({children:e}){return n.jsx(K,{children:n.jsx(ee,{children:n.jsx(ne,{children:n.jsx(oe,{children:e})})})})},e.Distribution=u,e.Entry=function(){const e=Symbol("chizu.cache/Entry"),t=function(t){return{[s.Cache]:e,channel:t}};return Object.defineProperty(t,s.Cache,{value:e,enumerable:!1}),t},e.Error=function({handler:e,children:t}){return n.jsx(O.Provider,{value:e,children:t})},e.Lifecycle=a,e.Op=M,e.Operation=M,e.Reason=f,e.Scope=ue,e.State=$,e.With=function(e){return(t,n)=>{t.actions.produce(t=>{t.model[e]=n})}},e.annotate=function(e,t){return W.annotate(e,t)},e.useActions=function(e,n=()=>({})){const o=J(),c=ie(),u=r.useContext(O),f=i.useContext(re),d=i.useContext(te),p=Y(),h=i.useRef(!1),m=i.useRef(null),y=i.useRef(new $);h.current||(h.current=!0,m.current=y.current.hydrate(e));const[b,E]=i.useState(()=>y.current.model),M=function(e){const t=i.useRef(e);return i.useLayoutEffect(()=>{t.current=e},[e]),i.useMemo(()=>{return n=t,Object.keys(e).reduce((e,t)=>(Object.defineProperty(e,t,{get:()=>n.current[t],enumerable:!0}),e),{});var n},[e])}(n()),C=i.useMemo(()=>new q,[]),k=i.useRef({handlers:new Map});k.current.handlers=new Map;const G=function(){const e=i.useRef(new Set),t=i.useRef(new Set);return i.useMemo(()=>({broadcast:e.current,multicast:t.current}),[])}(),_=i.useRef(l.Mounting),R=function(){const e=i.useRef({}),t=i.useRef(new Map),n=i.useRef(new Map);return i.useMemo(()=>({refs:e,pending:t,emitted:n}),[])}(),N=i.useRef(new Set),z=i.useRef(0),U=i.useCallback((e,t,n)=>{const r=new AbortController,i={controller:r,action:e,payload:t};return f.add(i),N.current.add(i),{model:b,get phase(){return _.current},task:i,data:M,tasks:f,nodes:R.refs.current,actions:{produce(e){if(r.signal.aborted)return;const t=y.current.produce(t=>e({model:t,inspect:y.current.inspect}));E(y.current.model),n.processes.add(t),m.current&&(n.processes.add(m.current),m.current=null)},dispatch(e,t,n){if(r.signal.aborted)return;const i=v(e),s=x(e)?e.channel:void 0;if(j(e)&&n?.scope){const e=se(c,n.scope);return void(e&&e.emitter.emit(i,t,s))}(g(e)?o:C).emit(i,t,s)},annotate:(e,t)=>y.current.annotate(e,t),async cacheable(e,t,n){if(r.signal.aborted)return{data:null};const o=S(e),c=d.get(o);if(c&&Date.now()<c.expiry)return{data:c.value};const i=function(e){return null!=e&&"object"==typeof e&&"TAG"in e?0===e.TAG?{ok:!0,value:e._0}:{ok:!1}:null==e?{ok:!1}:{ok:!0,value:e}}(await n());return i.ok?(d.set(o,{value:i.value,expiry:Date.now()+t}),{data:i.value}):{data:null}},invalidate(e){d.delete(S(e))}}}},[b]);i.useLayoutEffect(()=>{function e(e,n,r){return async function(o,c){const i=r();if(t.G.isNotNullable(c)&&t.G.isNotNullable(i)&&!function(e,t){for(const n of Object.keys(e))if(t[n]!==e[n])return!1;return!0}(c,i))return;const s={processes:new Set},l=Promise.withResolvers(),d=U(e,o,s);try{await n(d,o)}catch(h){const t=k.current.handlers.has(a.Error),n={reason:P(h),error:A(h),action:w(e),handled:t,tasks:f};u?.(n),t&&C.emit(a.Error,n)}finally{for(const e of f)if(e===d.task){f.delete(e),N.current.delete(e);break}s.processes.forEach(e=>y.current.prune(e)),s.processes.size>0&&p(),l.resolve()}}}z.current++;const n=new Set;return k.current.handlers.forEach((t,r)=>{for(const{getChannel:i,handler:s}of t){const t=e(r,s,i);if(j(r)){if(c)for(const e of c.values()){const o=e.emitter;o.on(r,t),n.add(()=>o.off(r,t))}C.on(r,t),G.multicast.add(r),n.add(()=>C.off(r,t))}else g(r)?(o.on(r,t),C.on(r,t),G.broadcast.add(r),n.add(()=>{o.off(r,t),C.off(r,t)})):(C.on(r,t),n.add(()=>C.off(r,t)))}}),()=>{const e=++z.current,t=new Set(n);queueMicrotask(()=>{if(z.current===e){for(const e of N.current)e.controller.abort(),f.delete(e);N.current.clear(),_.current=l.Unmounting,C.emit(a.Unmount),_.current=l.Unmounted;for(const e of t)e()}else for(const e of t)e()})}},[C]),i.useLayoutEffect(()=>{for(const[e,t]of R.pending.current)R.emitted.current.get(e)!==t&&(R.emitted.current.set(e,t),C.emit(s.Node,t,{Name:e}));R.pending.current.clear()}),function({unicast:e,broadcastActions:n,phase:r,data:o}){const c=X(),s=i.useRef(null);i.useLayoutEffect(()=>{r.current===l.Mounting&&(e.emit(a.Mount),n.forEach(n=>{const r=c.get(n),o=r?.state.model?.value;t.G.isNullable(o)||e.emit(n,o)}),r.current=l.Mounted)},[]),i.useLayoutEffect(()=>{if(t.G.isNotNullable(s.current)){const n=function(e,t){return Object.keys(t).reduce((n,r)=>e[r]!==t[r]?{...n,[r]:t[r]}:n,{})}(s.current,o);t.A.isNotEmpty(Object.keys(n))&&e.emit(a.Update,n)}s.current=o},[o,e])}({unicast:C,broadcastActions:G.broadcast,phase:_,data:n()});const L=i.useMemo(()=>[b,{dispatch(e,t,n){const r=v(e),i=x(e)?e.channel:void 0;if(j(e)&&n?.scope){const e=se(c,n.scope);return void(e&&e.emitter.emit(r,t,i))}(g(e)?o:C).emit(r,t,i)},consume:(e,t,n)=>j(e)&&n?.scope?i.createElement(ae,{action:v(e),scopeName:n.scope,renderer:t}):i.createElement(Z,{action:v(e),renderer:t}),get inspect(){return y.current.inspect},get nodes(){return R.refs.current},node(e,t){R.refs.current[e]=t,R.pending.current.set(e,t)}}],[b,C]);return L.useAction=(e,t)=>{!function(e,t,n){const r=i.useRef(n);i.useLayoutEffect(()=>{r.current=n});const o=i.useRef(t);i.useLayoutEffect(()=>{o.current=t});const c=i.useCallback(async(e,t)=>{const n=r.current;if("GeneratorFunction"===n.constructor.name||"AsyncGeneratorFunction"===n.constructor.name){const r=n(e,t);for await(const e of r);}else await n(e,t)},[]),s=i.useCallback(()=>x(o.current)?o.current.channel:void 0,[]),a=v(t),u=e.current.handlers.get(a)??new Set;0===u.size&&e.current.handlers.set(a,u),u.add({getChannel:s,handler:c})}(k,e,t)},L},e.utils=y,e.withScope=function(e,t){return function(r){return n.jsx(ue,{name:e,children:n.jsx(t,{...r})})}},Object.defineProperty(e,Symbol.toStringTag,{value:"Module"})},"object"==typeof exports&&"undefined"!=typeof module?factory(exports,require("@mobily/ts-belt"),require("react/jsx-runtime"),require("react"),require("immer")):"function"==typeof define&&define.amd?define(["exports","@mobily/ts-belt","react/jsx-runtime","react","immer"],factory):factory((global="undefined"!=typeof globalThis?globalThis:global||self).Chizu={},global.TsBelt,global.jsxRuntime,global.React,global.Immer);
|
|
1
|
+
var global,factory;global=this,factory=function(e,t,n,r,o){"use strict";function c(e){const t=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(e)for(const n in e)if("default"!==n){const r=Object.getOwnPropertyDescriptor(e,n);Object.defineProperty(t,n,r.get?r:{enumerable:!0,get:()=>e[n]})}return t.default=e,Object.freeze(t)}const i=c(r);class s{static Payload=Symbol("chizu.brand/Payload");static Broadcast=Symbol("chizu.brand/Broadcast");static Multicast=Symbol("chizu.brand/Multicast");static Action=Symbol("chizu.brand/Action");static Channel=Symbol("chizu.brand/Channel");static Node=Symbol("chizu.action.lifecycle/Node");static Cache=Symbol("chizu.brand/Cache")}class a{static Mount=Symbol("chizu.action.lifecycle/Mount");static Unmount=Symbol("chizu.action.lifecycle/Unmount");static Error=Symbol("chizu.action.lifecycle/Error");static Update=Symbol("chizu.action.lifecycle/Update");static Node=(()=>{const e=s.Node,t=function(t){return{[s.Action]:e,[s.Payload]:void 0,[s.Channel]:t,channel:t}};return Object.defineProperty(t,s.Action,{value:e,enumerable:!1}),Object.defineProperty(t,s.Payload,{value:void 0,enumerable:!1}),t})()}var u=(e=>(e.Unicast="unicast",e.Broadcast="broadcast",e.Multicast="multicast",e))(u||{}),l=(e=>(e.Mounting="mounting",e.Mounted="mounted",e.Unmounting="unmounting",e.Unmounted="unmounted",e))(l||{}),f=(e=>(e[e.Timedout=0]="Timedout",e[e.Supplanted=1]="Supplanted",e[e.Disallowed=2]="Disallowed",e[e.Errored=3]="Errored",e[e.Unmounted=4]="Unmounted",e))(f||{});class d extends Error{name="AbortError";constructor(e="Aborted"){super(e)}}const p={actionPrefix:"chizu.action/",broadcastActionPrefix:"chizu.action/broadcast/",multicastActionPrefix:"chizu.action/multicast/",channelPrefix:"chizu.channel/",cachePrefix:"chizu.cache/"};function h(e,t){return new Promise((n,r)=>{if(t?.aborted)return void r(new d);const o=setTimeout(n,e);t?.addEventListener("abort",()=>{clearTimeout(o),r(new d)},{once:!0})})}function m(e){return e?Boolean(e&&"symbol"!=typeof e):Symbol(`pk.${Date.now()}.${crypto.randomUUID()}`)}const y=Object.freeze(Object.defineProperty({__proto__:null,config:p,pk:m,sleep:h,"ζ":h,"κ":m},Symbol.toStringTag,{value:"Module"})),b=e=>"symbol"==typeof e;function v(e){return t.G.isString(e)||b(e)?e:(t.G.isObject(e)||t.G.isFunction(e))&&s.Action in e?e[s.Action]:e}function g(e){if(t.G.isString(e))return e.startsWith(p.broadcastActionPrefix);if(b(e))return e.description?.startsWith(p.broadcastActionPrefix)??!1;if(t.G.isObject(e)||t.G.isFunction(e)){if(s.Broadcast in e&&e[s.Broadcast])return!0;if(s.Action in e){const t=e[s.Action];return t.description?.startsWith(p.broadcastActionPrefix)??!1}}return!1}function w(e){const n=v(e),r=t.G.isString(n)?n:n.description??"";return r.startsWith(p.actionPrefix)&&r.slice(r.lastIndexOf("/")+1)||"unknown"}function x(e){return t.G.isObject(e)&&s.Channel in e&&"channel"in e}function j(e){if(t.G.isString(e))return e.startsWith(p.multicastActionPrefix);if(b(e))return e.description?.startsWith(p.multicastActionPrefix)??!1;if(t.G.isObject(e)||t.G.isFunction(e)){if(s.Multicast in e&&e[s.Multicast])return!0;if(s.Action in e){const t=e[s.Action];return t.description?.startsWith(p.multicastActionPrefix)??!1}}return!1}function S(e){const t=function(e){return e[s.Cache]}(e),n=function(e){return"channel"in e}(e)&&(r=e.channel)?[...Object.keys(r)].toSorted().map(e=>`${e}=${String(r[e])}`).join("&"):"";var r;return`${String(t)}:${n}`}function P(e){if(e instanceof Error){if("TimeoutError"===e.name)return f.Timedout;if("AbortError"===e.name)return f.Supplanted}return f.Errored}function A(e){return e instanceof Error?e:new Error(String(e))}const O=r.createContext(void 0);let E=(e=21)=>{let t="",n=crypto.getRandomValues(new Uint8Array(e|=0));for(;e--;)t+="useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict"[63&n[e]];return t};var M=(e=>(e[e.Add=1]="Add",e[e.Remove=2]="Remove",e[e.Update=4]="Update",e[e.Move=8]="Move",e[e.Replace=16]="Replace",e[e.Sort=32]="Sort",e[e.Create=64]="Create",e[e.Fetch=128]="Fetch",e[e.Clone=256]="Clone",e[e.Archive=512]="Archive",e[e.Restore=1024]="Restore",e[e.Merge=2048]="Merge",e[e.Reorder=4096]="Reorder",e[e.Sync=8192]="Sync",e[e.Publish=16384]="Publish",e[e.Link=32768]="Link",e[e.Unlink=65536]="Unlink",e[e.Lock=131072]="Lock",e[e.Unlock=262144]="Unlock",e[e.Import=524288]="Import",e[e.Export=1048576]="Export",e[e.Transfer=2097152]="Transfer",e))(M||{}),C=(e=>(e[e.Produce=0]="Produce",e[e.Hydrate=1]="Hydrate",e))(C||{}),k=(e=>(e.Property="property",e.Process="process",e.Value="value",e.Operation="operation",e))(k||{});class G{[o.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 G(this.value,this.operation);return n.property=e,n.process=t,n}}class _{static immer=(()=>{o.enablePatches();const e=new o.Immer;return e.setAutoFreeze(!1),e})();static tag="κ";static id=E}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 N(e){if(t.G.isNullable(e)||U(e))return e;if(t.G.isArray(e))return e.map(e=>N(e));if(t.G.isObject(e)&&L(e)){const t=Object.entries(e).map(([e,t])=>[e,N(t)]);return{...Object.fromEntries(t),[_.tag]:e[_.tag]??_.id()}}return e}function z(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 U(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 T(e,n,r,o,c,i){return function s(a,u=n.path){if(a instanceof G){const n=R(r,u.join("."));if(Object.entries(a).filter(([e,t])=>!G.keys.has(e)&&t instanceof G).forEach(([e,t])=>s(t,u.concat(e))),U(a.value)){if(e===C.Hydrate)return a.value;const s=u.slice(0,-1),l=s.length>0?R(r,s.join(".")):r;return t.G.isNullable(l)||B(l,a,u.at(-1),o,c,i),n??a.value}if(e===C.Hydrate){const e=N(s(a.value,u));return B(e,a,null,o,c,i),e}const l=n??N(a.value);return B(l,a,null,o,c,i),t.G.isNullable(n)?l:(s(a.value,u),n)}if(t.G.isArray(a))return a.map((e,t)=>s(e,u.concat(t)));if(t.G.isObject(a)&&!L(a))return a;if(t.G.isObject(a)){const t=Object.entries(a).map(([e,t])=>[e,s(t,u.concat(e))]),n=Object.fromEntries(t);if(e===C.Hydrate){const e=N(n);return Object.entries(a).forEach(([t,n])=>{n instanceof G&&U(n.value)&&B(e,n,t,o,c,i)}),e}return n}return a}(n.value)}function B(e,t,n,r,o,c){const i=c(e),s=o.get(i)??[];o.set(i,[t.assign(n,r),...s])}class ${#e={};#t;#n=new Map;#r=new Set;#o=!1;constructor(e=z){this.#t=e}static pk(){return E()}static"κ"=$.pk;annotate(e,t){return new G(t,e)}"δ"=this.annotate;get model(){return this.#e}get inspect(){return function(e,n,r,o,c){function i(o){const c=o.at(-1),i=R(e(),o),s=o.slice(0,-1),a=t.A.isNotEmpty(s)?R(e(),s):e();return[...t.G.isObject(i)||t.G.isArray(i)?n.get(r(i))?.filter(e=>t.G.isNullable(e.property))??[]:[],...t.G.isObject(a)?n.get(r(a))?.filter(e=>e.property===c)??[]:[]]}return function n(r){return new Proxy(()=>{},{get:(s,a)=>"pending"===a?()=>!t.A.isEmpty(i(r)):"remaining"===a?()=>t.A.length(i(r)):"box"===a?()=>({value:R(e(),r),inspect:n(r)}):"is"===a?e=>i(r).some(t=>0!==(t.operation&e)):"draft"===a?()=>t.A.head(i(r))?.value??R(e(),r):"settled"===a?()=>new Promise(n=>{if(t.A.isEmpty(i(r)))return n(R(e(),r));const s=()=>{t.A.isEmpty(i(r))&&(c(s),n(R(e(),r)))};o(s)}):n([...r,String(a)])})}([])}(()=>this.#e,this.#n,this.#t,e=>this.#r.add(e),e=>this.#r.delete(e))}hydrate(e){return this.#o=!0,this.#c(C.Hydrate,()=>e)}produce(e){if(!this.#o)throw new Error("State must be hydrated using hydrate() before calling produce()");return this.#c(C.Produce,e)}#c(e,t){const n=Symbol("process"),[,r]=_.immer.produceWithPatches(this.#e,t);return this.#e=r.reduce((t,r)=>_.immer.applyPatches(t,[{...r,value:T(e,r,t,n,this.#n,this.#t)}]),this.#e),this.#e=N(this.#e),this.#i(),n}prune(e){this.#n.forEach((n,r)=>{const o=n.filter(t=>t.process!==e);t.A.isEmpty(o)?this.#n.delete(r):this.#n.set(r,o)}),this.#i()}#i(){this.#r.forEach(e=>e())}observe(e){const t=()=>e(this.#e);return this.#r.add(t),()=>this.#r.delete(t)}}const W=new $;function D(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var F,H={exports:{}},I=(F||(F=1,function(e){var t=Object.prototype.hasOwnProperty,n="~";function r(){}function o(e,t,n){this.fn=e,this.context=t,this.once=n||!1}function c(e,t,r,c,i){if("function"!=typeof r)throw new TypeError("The listener must be a function");var s=new o(r,c||e,i),a=n?n+t:t;return e._events[a]?e._events[a].fn?e._events[a]=[e._events[a],s]:e._events[a].push(s):(e._events[a]=s,e._eventsCount++),e}function i(e,t){0===--e._eventsCount?e._events=new r:delete e._events[t]}function s(){this._events=new r,this._eventsCount=0}Object.create&&(r.prototype=Object.create(null),(new r).__proto__||(n=!1)),s.prototype.eventNames=function(){var e,r,o=[];if(0===this._eventsCount)return o;for(r in e=this._events)t.call(e,r)&&o.push(n?r.slice(1):r);return Object.getOwnPropertySymbols?o.concat(Object.getOwnPropertySymbols(e)):o},s.prototype.listeners=function(e){var t=this._events[n?n+e:e];if(!t)return[];if(t.fn)return[t.fn];for(var r=0,o=t.length,c=new Array(o);r<o;r++)c[r]=t[r].fn;return c},s.prototype.listenerCount=function(e){var t=this._events[n?n+e:e];return t?t.fn?1:t.length:0},s.prototype.emit=function(e,t,r,o,c,i){var s=n?n+e:e;if(!this._events[s])return!1;var a,u,l=this._events[s],f=arguments.length;if(l.fn){switch(l.once&&this.removeListener(e,l.fn,void 0,!0),f){case 1:return l.fn.call(l.context),!0;case 2:return l.fn.call(l.context,t),!0;case 3:return l.fn.call(l.context,t,r),!0;case 4:return l.fn.call(l.context,t,r,o),!0;case 5:return l.fn.call(l.context,t,r,o,c),!0;case 6:return l.fn.call(l.context,t,r,o,c,i),!0}for(u=1,a=new Array(f-1);u<f;u++)a[u-1]=arguments[u];l.fn.apply(l.context,a)}else{var d,p=l.length;for(u=0;u<p;u++)switch(l[u].once&&this.removeListener(e,l[u].fn,void 0,!0),f){case 1:l[u].fn.call(l[u].context);break;case 2:l[u].fn.call(l[u].context,t);break;case 3:l[u].fn.call(l[u].context,t,r);break;case 4:l[u].fn.call(l[u].context,t,r,o);break;default:if(!a)for(d=1,a=new Array(f-1);d<f;d++)a[d-1]=arguments[d];l[u].fn.apply(l[u].context,a)}}return!0},s.prototype.on=function(e,t,n){return c(this,e,t,n,!1)},s.prototype.once=function(e,t,n){return c(this,e,t,n,!0)},s.prototype.removeListener=function(e,t,r,o){var c=n?n+e:e;if(!this._events[c])return this;if(!t)return i(this,c),this;var s=this._events[c];if(s.fn)s.fn!==t||o&&!s.once||r&&s.context!==r||i(this,c);else{for(var a=0,u=[],l=s.length;a<l;a++)(s[a].fn!==t||o&&!s[a].once||r&&s[a].context!==r)&&u.push(s[a]);u.length?this._events[c]=1===u.length?u[0]:u:i(this,c)}return this},s.prototype.removeAllListeners=function(e){var t;return e?this._events[t=n?n+e:e]&&i(this,t):(this._events=new r,this._eventsCount=0),this},s.prototype.off=s.prototype.removeListener,s.prototype.addListener=s.prototype.on,s.prefixed=n,s.EventEmitter=s,e.exports=s}(H)),H.exports);const q=D(I),V=i.createContext(new q);function J(){return i.useContext(V)}function K({children:e}){const t=i.useMemo(()=>new q,[]);return n.jsx(V.Provider,{value:t,children:e})}const Q=i.createContext(new Map);function X(){return i.useContext(Q)}function Y(){const[,e]=i.useReducer(e=>e+1,0);return e}function Z({action:e,renderer:n}){const r=J(),o=X(),c=Y(),s=i.useMemo(()=>{const t=o.get(e);if(t)return t;const n={state:new $,listeners:new Set};return o.set(e,n),n},[e,o]);i.useLayoutEffect(()=>{function t(e){s.state.hydrate({value:e}),s.listeners.forEach(e=>e())}return s.listeners.add(c),r.on(e,t),()=>{s.listeners.delete(c),r.off(e,t)}},[e,r,s]);const a=s.state.model?.value;return t.G.isNullable(a)?null:n({value:a,inspect:s.state.inspect.value})}function ee({children:e}){const t=i.useMemo(()=>new Map,[]);return n.jsx(Q.Provider,{value:t,children:e})}const te=i.createContext(new Map);function ne({children:e}){const t=i.useMemo(()=>new Map,[]);return n.jsx(te.Provider,{value:t,children:e})}const re=i.createContext(new Set);function oe({children:e}){const t=i.useMemo(()=>new Set,[]);return n.jsx(re.Provider,{value:t,children:e})}const ce=i.createContext(null);function ie(){return i.useContext(ce)}function se(e,t){return e?.get(t)??null}function ae({action:e,scopeName:n,renderer:r}){const o=ie(),c=Y(),s=i.useMemo(()=>se(o,n),[o,n]),a=i.useMemo(()=>s?function(e,t){const n=e.store.get(t);if(n)return n;const r={state:new $,listeners:new Set};return e.store.set(t,r),r}(s,e):null,[e,s]);if(i.useLayoutEffect(()=>{if(s&&a)return a.listeners.add(c),s.emitter.on(e,t),()=>{a.listeners.delete(c),s.emitter.off(e,t)};function t(e){a&&(a.state.hydrate({value:e}),a.listeners.forEach(e=>e()))}},[e,s,a,c]),!a)return null;const u=a.state.model?.value;return t.G.isNullable(u)?null:r({value:u,inspect:a.state.inspect.value})}function ue({name:e,children:t}){const r=ie(),o=i.useMemo(()=>({name:e,emitter:new q,store:new Map,listeners:new Map}),[]),c=i.useMemo(()=>{const t=new Map(r??[]);return t.set(e,o),t},[r,e,o]);return n.jsx(ce.Provider,{value:c,children:t})}e.Action=(e,t=u.Unicast)=>{const n=t===u.Broadcast?Symbol(`${p.broadcastActionPrefix}${e}`):t===u.Multicast?Symbol(`${p.multicastActionPrefix}${e}`):Symbol(`${p.actionPrefix}${e}`),r=function(e){return{[s.Action]:n,[s.Payload]:void 0,[s.Channel]:e,channel:e}};return Object.defineProperty(r,s.Action,{value:n,enumerable:!1}),Object.defineProperty(r,s.Payload,{value:void 0,enumerable:!1}),t===u.Broadcast&&Object.defineProperty(r,s.Broadcast,{value:!0,enumerable:!1}),t===u.Multicast&&Object.defineProperty(r,s.Multicast,{value:!0,enumerable:!1}),r},e.Boundary=function({children:e}){return n.jsx(K,{children:n.jsx(ee,{children:n.jsx(ne,{children:n.jsx(oe,{children:e})})})})},e.Distribution=u,e.Entry=function(){const e=Symbol("chizu.cache/Entry"),t=function(t){return{[s.Cache]:e,channel:t}};return Object.defineProperty(t,s.Cache,{value:e,enumerable:!1}),t},e.Error=function({handler:e,children:t}){return n.jsx(O.Provider,{value:e,children:t})},e.Lifecycle=a,e.Op=M,e.Operation=M,e.Reason=f,e.Scope=ue,e.State=$,e.With=function(e){return(t,n)=>{t.actions.produce(t=>{t.model[e]=n})}},e.annotate=function(e,t){return W.annotate(e,t)},e.useActions=function(e,n=()=>({})){const o=J(),c=ie(),u=X(),f=r.useContext(O),p=i.useContext(re),h=i.useContext(te),m=Y(),y=i.useRef(!1),b=i.useRef(null),E=i.useRef(new $);y.current||(y.current=!0,b.current=E.current.hydrate(e));const[M,C]=i.useState(()=>E.current.model),k=function(e){const t=i.useRef(e);return i.useLayoutEffect(()=>{t.current=e},[e]),i.useMemo(()=>{return n=t,Object.keys(e).reduce((e,t)=>(Object.defineProperty(e,t,{get:()=>n.current[t],enumerable:!0}),e),{});var n},[e])}(n()),G=i.useMemo(()=>new q,[]),_=i.useRef({handlers:new Map});_.current.handlers=new Map;const R=function(){const e=i.useRef(new Set),t=i.useRef(new Set);return i.useMemo(()=>({broadcast:e.current,multicast:t.current}),[])}(),N=i.useRef(l.Mounting),z=function(){const e=i.useRef({}),t=i.useRef(new Map),n=i.useRef(new Map);return i.useMemo(()=>({refs:e,pending:t,emitted:n}),[])}(),L=i.useRef(new Set),U=i.useRef(0),T=i.useCallback((e,t,n)=>{const r=new AbortController,i={controller:r,action:e,payload:t};return p.add(i),L.current.add(i),{model:M,get phase(){return N.current},task:i,data:k,tasks:p,nodes:z.refs.current,actions:{produce(e){if(r.signal.aborted)return;const t=E.current.produce(t=>e({model:t,inspect:E.current.inspect}));C(E.current.model),n.processes.add(t),b.current&&(n.processes.add(b.current),b.current=null)},dispatch(e,t,n){if(r.signal.aborted)return;const i=v(e),s=x(e)?e.channel:void 0;if(j(e)&&n?.scope){const e=se(c,n.scope);return void(e&&e.emitter.emit(i,t,s))}(g(e)?o:G).emit(i,t,s)},annotate:(e,t)=>E.current.annotate(e,t),async cacheable(e,t,n){if(r.signal.aborted)return{data:null};const o=S(e),c=h.get(o);if(c&&Date.now()<c.expiry)return{data:c.value};const i=function(e){return null!=e&&"object"==typeof e&&"TAG"in e?0===e.TAG?{ok:!0,value:e._0}:{ok:!1}:null==e?{ok:!1}:{ok:!0,value:e}}(await n());return i.ok?(h.set(o,{value:i.value,expiry:Date.now()+t}),{data:i.value}):{data:null}},invalidate(e){h.delete(S(e))},async consume(e,t){if(r.signal.aborted)return null;const n=v(e);let o;if(j(e)&&t?.scope){const e=se(c,t.scope);if(!e)return null;o=e.store.get(n)}else o=u.get(n);if(!o?.state.model?.value)return null;const i=o.state.inspect;return i.value.pending()&&await new Promise((e,t)=>{if(r.signal.aborted)return void t(new d);const n=()=>t(new d);r.signal.addEventListener("abort",n,{once:!0}),i.value.settled().then(()=>{r.signal.removeEventListener("abort",n),e()})}),o.state.model.value}}}},[M]);i.useLayoutEffect(()=>{function e(e,n,r){return async function(o,c){const i=r();if(t.G.isNotNullable(c)&&t.G.isNotNullable(i)&&!function(e,t){for(const n of Object.keys(e))if(t[n]!==e[n])return!1;return!0}(c,i))return;const s={processes:new Set},u=Promise.withResolvers(),l=T(e,o,s);try{await n(l,o)}catch(d){const t=_.current.handlers.has(a.Error),n={reason:P(d),error:A(d),action:w(e),handled:t,tasks:p};f?.(n),t&&G.emit(a.Error,n)}finally{for(const e of p)if(e===l.task){p.delete(e),L.current.delete(e);break}s.processes.forEach(e=>E.current.prune(e)),s.processes.size>0&&m(),u.resolve()}}}U.current++;const n=new Set;return _.current.handlers.forEach((t,r)=>{for(const{getChannel:i,handler:s}of t){const t=e(r,s,i);if(j(r)){if(c)for(const e of c.values()){const o=e.emitter;o.on(r,t),n.add(()=>o.off(r,t))}G.on(r,t),R.multicast.add(r),n.add(()=>G.off(r,t))}else g(r)?(o.on(r,t),G.on(r,t),R.broadcast.add(r),n.add(()=>{o.off(r,t),G.off(r,t)})):(G.on(r,t),n.add(()=>G.off(r,t)))}}),()=>{const e=++U.current,t=new Set(n);queueMicrotask(()=>{if(U.current===e){for(const e of L.current)e.controller.abort(),p.delete(e);L.current.clear(),N.current=l.Unmounting,G.emit(a.Unmount),N.current=l.Unmounted;for(const e of t)e()}else for(const e of t)e()})}},[G]),i.useLayoutEffect(()=>{for(const[e,t]of z.pending.current)z.emitted.current.get(e)!==t&&(z.emitted.current.set(e,t),G.emit(s.Node,t,{Name:e}));z.pending.current.clear()}),function({unicast:e,broadcastActions:n,phase:r,data:o}){const c=X(),s=i.useRef(null);i.useLayoutEffect(()=>{r.current===l.Mounting&&(e.emit(a.Mount),n.forEach(n=>{const r=c.get(n),o=r?.state.model?.value;t.G.isNullable(o)||e.emit(n,o)}),r.current=l.Mounted)},[]),i.useLayoutEffect(()=>{if(t.G.isNotNullable(s.current)){const n=function(e,t){return Object.keys(t).reduce((n,r)=>e[r]!==t[r]?{...n,[r]:t[r]}:n,{})}(s.current,o);t.A.isNotEmpty(Object.keys(n))&&e.emit(a.Update,n)}s.current=o},[o,e])}({unicast:G,broadcastActions:R.broadcast,phase:N,data:n()});const B=i.useMemo(()=>[M,{dispatch(e,t,n){const r=v(e),i=x(e)?e.channel:void 0;if(j(e)&&n?.scope){const e=se(c,n.scope);return void(e&&e.emitter.emit(r,t,i))}(g(e)?o:G).emit(r,t,i)},consume:(e,t,n)=>j(e)&&n?.scope?i.createElement(ae,{action:v(e),scopeName:n.scope,renderer:t}):i.createElement(Z,{action:v(e),renderer:t}),get inspect(){return E.current.inspect},get nodes(){return z.refs.current},node(e,t){z.refs.current[e]=t,z.pending.current.set(e,t)}}],[M,G]);return B.useAction=(e,t)=>{!function(e,t,n){const r=i.useRef(n);i.useLayoutEffect(()=>{r.current=n});const o=i.useRef(t);i.useLayoutEffect(()=>{o.current=t});const c=i.useCallback(async(e,t)=>{const n=r.current;if("GeneratorFunction"===n.constructor.name||"AsyncGeneratorFunction"===n.constructor.name){const r=n(e,t);for await(const e of r);}else await n(e,t)},[]),s=i.useCallback(()=>x(o.current)?o.current.channel:void 0,[]),a=v(t),u=e.current.handlers.get(a)??new Set;0===u.size&&e.current.handlers.set(a,u),u.add({getChannel:s,handler:c})}(_,e,t)},B},e.utils=y,e.withScope=function(e,t){return function(r){return n.jsx(ue,{name:e,children:n.jsx(t,{...r})})}},Object.defineProperty(e,Symbol.toStringTag,{value:"Module"})},"object"==typeof exports&&"undefined"!=typeof module?factory(exports,require("@mobily/ts-belt"),require("react/jsx-runtime"),require("react"),require("immer")):"function"==typeof define&&define.amd?define(["exports","@mobily/ts-belt","react/jsx-runtime","react","immer"],factory):factory((global="undefined"!=typeof globalThis?globalThis:global||self).Chizu={},global.TsBelt,global.jsxRuntime,global.React,global.Immer);
|
package/dist/index.d.ts
CHANGED
|
@@ -11,4 +11,3 @@ export * as utils from './utils/index.ts';
|
|
|
11
11
|
export type { Box } from 'immertation';
|
|
12
12
|
export type { Fault, Catcher } from './error/index.tsx';
|
|
13
13
|
export type { Pk, Task, Tasks, Handlers } from './types/index.ts';
|
|
14
|
-
export type { CacheId, ChanneledCacheId } from './cache/index.ts';
|
package/dist/types/index.d.ts
CHANGED
|
@@ -576,6 +576,35 @@ export type HandlerContext<M extends Model, _AC extends Actions, D extends Props
|
|
|
576
576
|
* ```
|
|
577
577
|
*/
|
|
578
578
|
invalidate(entry: CacheId<unknown> | ChanneledCacheId<unknown>): void;
|
|
579
|
+
/**
|
|
580
|
+
* Reads the latest broadcast or multicast value from the consumer store.
|
|
581
|
+
*
|
|
582
|
+
* Returns the raw value `T` or `null` if no value has been dispatched.
|
|
583
|
+
* If the value has pending annotations, awaits `settled()` before returning.
|
|
584
|
+
* Respects the task's abort signal — returns `null` if the task is aborted
|
|
585
|
+
* while waiting.
|
|
586
|
+
*
|
|
587
|
+
* **Important:** A JSX-side `consume()` or `<Partition>` must have populated
|
|
588
|
+
* the store for this value to be available.
|
|
589
|
+
*
|
|
590
|
+
* @param action - The broadcast or multicast action to read.
|
|
591
|
+
* @param options - For multicast actions, must include `{ scope: "ScopeName" }`.
|
|
592
|
+
* @returns The latest dispatched value, or `null`.
|
|
593
|
+
*
|
|
594
|
+
* @example
|
|
595
|
+
* ```ts
|
|
596
|
+
* actions.useAction(Actions.FetchPosts, async (context) => {
|
|
597
|
+
* const user = await context.actions.consume(Actions.Broadcast.User);
|
|
598
|
+
* if (!user) return;
|
|
599
|
+
* const posts = await fetchPosts(user.id, {
|
|
600
|
+
* signal: context.task.controller.signal,
|
|
601
|
+
* });
|
|
602
|
+
* context.actions.produce(({ model }) => { model.posts = posts; });
|
|
603
|
+
* });
|
|
604
|
+
* ```
|
|
605
|
+
*/
|
|
606
|
+
consume<T>(action: BroadcastPayload<T>): Promise<T | null>;
|
|
607
|
+
consume<T>(action: MulticastPayload<T>, options: MulticastOptions): Promise<T | null>;
|
|
579
608
|
};
|
|
580
609
|
};
|
|
581
610
|
/**
|
|
@@ -617,6 +646,30 @@ export type HandlerContext<M extends Model, _AC extends Actions, D extends Props
|
|
|
617
646
|
* @see {@link Handlers} for the recommended HKT pattern
|
|
618
647
|
*/
|
|
619
648
|
export type Handler<M extends Model, AC extends Actions, K extends keyof AC, D extends Props = Props> = (context: HandlerContext<M, AC, D>, payload: Payload<AC[K] & HandlerPayload<unknown>>) => void | Promise<void> | AsyncGenerator | Generator;
|
|
649
|
+
/**
|
|
650
|
+
* Resolves the action value at a (possibly dot-notated) path within an actions object.
|
|
651
|
+
* For a simple key like `"SetName"`, returns `AC["SetName"]`.
|
|
652
|
+
* For a dotted key like `"Broadcast.PaymentSent"`, recursively resolves to
|
|
653
|
+
* `AC["Broadcast"]["PaymentSent"]`.
|
|
654
|
+
*
|
|
655
|
+
* @template AC - The actions object to traverse
|
|
656
|
+
* @template K - The key path (may contain dots)
|
|
657
|
+
*/
|
|
658
|
+
type DeepAction<AC, K extends string> = K extends `${infer Head}.${infer Tail}` ? Head extends keyof AC ? DeepAction<AC[Head], Tail> : never : K extends keyof AC ? AC[K] : never;
|
|
659
|
+
/**
|
|
660
|
+
* Produces a union of all valid dot-notated key paths that resolve to leaf actions
|
|
661
|
+
* (i.e. values with `Brand.Action`) within an actions object.
|
|
662
|
+
*
|
|
663
|
+
* Flat actions like `SetName` produce `"SetName"`.
|
|
664
|
+
* Nested namespaces like `Broadcast = { PaymentSent, PaymentLink }` produce
|
|
665
|
+
* `"Broadcast.PaymentSent" | "Broadcast.PaymentLink"`.
|
|
666
|
+
*
|
|
667
|
+
* @template AC - The actions object to flatten
|
|
668
|
+
* @template Prefix - Accumulated prefix for recursion (defaults to never)
|
|
669
|
+
*/
|
|
670
|
+
type FlattenKeys<AC, Prefix extends string = never> = {
|
|
671
|
+
[K in keyof AC & string]: AC[K] extends HandlerPayload ? [Prefix] extends [never] ? K : `${Prefix}.${K}` : FlattenKeys<AC[K], [Prefix] extends [never] ? K : `${Prefix}.${K}`>;
|
|
672
|
+
}[keyof AC & string];
|
|
620
673
|
/**
|
|
621
674
|
* Higher-Kinded Type (HKT) emulation for action handlers.
|
|
622
675
|
* Creates a mapped type where each action key maps to its fully-typed handler.
|
|
@@ -624,46 +677,37 @@ export type Handler<M extends Model, AC extends Actions, K extends keyof AC, D e
|
|
|
624
677
|
* TypeScript doesn't natively support HKTs (types that return types), but this
|
|
625
678
|
* pattern emulates them using mapped types with indexed access.
|
|
626
679
|
*
|
|
680
|
+
* Supports both flat and nested action classes with dot notation:
|
|
681
|
+
*
|
|
627
682
|
* @template M - The model type
|
|
628
683
|
* @template AC - The actions class type
|
|
629
684
|
* @template D - Optional data/props type (defaults to Props)
|
|
630
685
|
*
|
|
631
686
|
* @example
|
|
632
687
|
* ```ts
|
|
633
|
-
* import { Action, Handlers } from "chizu";
|
|
688
|
+
* import { Action, Distribution, Handlers } from "chizu";
|
|
689
|
+
*
|
|
690
|
+
* class BroadcastActions {
|
|
691
|
+
* static PaymentSent = Action("PaymentSent", Distribution.Broadcast);
|
|
692
|
+
* static PaymentLink = Action<PaymentLinkData>("PaymentLink", Distribution.Broadcast);
|
|
693
|
+
* }
|
|
634
694
|
*
|
|
635
695
|
* class Actions {
|
|
636
696
|
* static SetName = Action<string>("SetName");
|
|
637
|
-
* static
|
|
697
|
+
* static Broadcast = BroadcastActions;
|
|
638
698
|
* }
|
|
639
699
|
*
|
|
640
|
-
* // Define the HKT once for this module
|
|
641
700
|
* type H = Handlers<Model, typeof Actions>;
|
|
642
701
|
*
|
|
643
|
-
* //
|
|
644
|
-
* export const handleSetName: H["SetName"] = (context, name) => {
|
|
645
|
-
* context.actions.produce((draft) => {
|
|
646
|
-
* draft.model.name = name;
|
|
647
|
-
* });
|
|
648
|
-
* };
|
|
649
|
-
*
|
|
650
|
-
* export const handleSetAge: H["SetAge"] = (context, age) => {
|
|
651
|
-
* context.actions.produce((draft) => {
|
|
652
|
-
* draft.model.age = age;
|
|
653
|
-
* });
|
|
654
|
-
* };
|
|
702
|
+
* // Flat actions work as before
|
|
703
|
+
* export const handleSetName: H["SetName"] = (context, name) => { ... };
|
|
655
704
|
*
|
|
656
|
-
* //
|
|
657
|
-
* export
|
|
658
|
-
* const actions = useActions<Model, typeof Actions>(model);
|
|
659
|
-
* actions.useAction(Actions.SetName, handleSetName);
|
|
660
|
-
* actions.useAction(Actions.SetAge, handleSetAge);
|
|
661
|
-
* return actions;
|
|
662
|
-
* }
|
|
705
|
+
* // Nested actions use dot notation
|
|
706
|
+
* export const handlePaymentSent: H["Broadcast.PaymentSent"] = (context) => { ... };
|
|
663
707
|
* ```
|
|
664
708
|
*/
|
|
665
709
|
export type Handlers<M extends Model, AC extends Actions, D extends Props = Props> = {
|
|
666
|
-
[K in
|
|
710
|
+
[K in FlattenKeys<AC>]: (context: HandlerContext<M, AC, D>, payload: Payload<DeepAction<AC, K> & HandlerPayload<unknown>>) => void | Promise<void> | AsyncGenerator | Generator;
|
|
667
711
|
};
|
|
668
712
|
export type UseActions<M extends Model, AC extends Actions, D extends Props = Props> = [
|
|
669
713
|
Readonly<M>,
|