UNPKG

impair

Version:

impair is a React framework bringing several programming concepts together in order to provide a foundation for a layered, scalable, performant and enterprise level react application.

3 lines (2 loc) 18.5 kB
import{pauseTracking as e,enableTracking as t,shallowReadonly as n,readonly as r,computed as o,stop as i,effectScope as c,effect as s,shallowReactive as a,reactive as u,shallowRef as f,ref as l,isProxy as d,toReadonly as p,toRaw as y}from"@vue/reactivity";export{enableTracking,pauseTracking,toReadonly}from"@vue/reactivity";import{container as m,Lifecycle as g,injectable as h}from"tsyringe";export{delay,inject}from"tsyringe";import{createContext as b,useContext as v,useMemo as w,useRef as R,useState as S,useEffect as O,memo as E,createElement as M,useCallback as j}from"react";import{jsx as C}from"react/jsx-runtime";const P={readonlyProxiesForView:!0,defaultStateReactiveLevel:"deep"};function I(e){Object.assign(P,e)}const k=Symbol.for("impair.symbols.isLifecycleHandled"),_=Symbol.for("impair.symbols.isInitialized"),A=Symbol.for("impair.symbols.state"),K=Symbol.for("impair.symbols.trigger"),V=Symbol.for("impair.symbols.derived"),N=Symbol.for("impair.symbols.injectable"),T=Symbol.for("impair.symbols.provide"),$=Symbol.for("impair.symbols.onMount"),D=Symbol.for("impair.symbols.onUnmount"),x=Symbol.for("impair.symbols.onInit"),z=Symbol.for("impair.symbols.onDestroy"),F=Symbol.for("impair.symbols.isContainerDisposed"),L=Symbol.for("impair.devtools.containerId");let q=0;const H=new Map,U=new Map;function W(e,t){return U.has(e)||U.set(e,new Set),U.get(e).add(t),()=>U.get(e)?.delete(t)}let B=!1;function G(n,r){const o=U.get(n);if(o?.size||B){e();try{if(o?.forEach(e=>e(r)),B&&"undefined"!=typeof window)try{window.postMessage({source:"impair-devtools-hook",event:n,data:J(r)},"*")}catch{}}finally{t()}}}function J(e,t=new WeakSet){if(null==e)return e;if("function"==typeof e)return`[Function: ${e.name||"anonymous"}]`;if("symbol"==typeof e)return e.description||e.toString();if("object"!=typeof e)return e;if(t.has(e))return"[Circular]";if(t.add(e),Array.isArray(e))return e.slice(0,100).map(e=>J(e,t));if(e instanceof Map){const n={};return e.forEach((e,r)=>{n[String(r)]=J(e,t)}),{__type:"Map",entries:n}}if(e instanceof Set)return{__type:"Set",values:[...e].slice(0,100).map(e=>J(e,t))};const n={},r=Object.keys(e);for(const o of r.slice(0,50))try{n[o]=J(e[o],t)}catch{n[o]="[Unserializable]"}return n}function Q(e,t){const n="impair-dt-"+q++;let r=null;t&&H.forEach(e=>{e.container===t&&(r=e.id)}),e[L]=n,H.set(n,{id:n,container:e,parentId:r,instances:new Map}),G("container-registered",{id:n,parentId:r})}function X(e){const t=e[L];t&&(H.forEach(e=>{e.parentId===t&&X(e.container)}),H.delete(t),G("container-unregistered",{id:t}))}function Y(e,t,n){const r=e[L];if(!r)return;const o=H.get(r);if(!o)return;const i=function(e){return"function"==typeof e?e.name||"Anonymous":"symbol"==typeof e?e.description||e.toString():String(e)}(t);o.instances.set(i,n),G("instance-registered",{containerId:r,tokenName:i})}function Z(){const e=[];return H.forEach(t=>{const n=[];t.instances.forEach((e,t)=>n.push(t)),e.push({id:t.id,parentId:t.parentId,services:n})}),e}function ee(e){const t=H.get(e);if(!t)return null;const n=[];return t.instances.forEach((e,t)=>{n.push({tokenName:t})}),{id:e,services:n}}function te(e,t){const n=H.get(e);if(!n)return null;const r=n.instances.get(t);if(!r)return null;const o={state:{},derived:{}},i=Reflect.getMetadata(A,r);if(i){const e=new Set;i.forEach(({propertyKey:t})=>{if(!e.has(t)){e.add(t);try{o.state[t]=J(r[t])}catch{o.state[t]="[Unreadable]"}}})}const c=Reflect.getMetadata(V,r);if(c){const e=new Set;c.forEach(({propertyKey:t})=>{if(!e.has(t)){e.add(t);try{o.derived[t]=J(r[t])}catch{o.derived[t]="[Unreadable]"}}})}return o}function ne(e,t,n,r){const o=H.get(e);if(!o)return!1;const i=o.instances.get(t);if(!i)return!1;try{return i[n]=r,G("state-changed",{containerId:e,tokenName:t,key:n,value:J(r)}),!0}catch{return!1}}function re(e){if("impair-devtools-content"!==e.data?.source)return;B=!0;const{command:t,args:n,requestId:r}=e.data;let o;switch(t){case"getTree":o=Z();break;case"getContainerDetails":o=ee(n.id);break;case"getInstanceState":o=te(n.containerId,n.tokenName);break;case"setStateValue":o=ne(n.containerId,n.tokenName,n.key,n.value)}window.postMessage({source:"impair-devtools-hook",event:"response",command:t,result:o,requestId:r},"*")}function oe(){return"undefined"==typeof window?null:window.__IMPAIR_DEVTOOLS_HOOK__}function ie(e){e[F]||(e[F]=!0,e.dispose())}"undefined"!=typeof window&&!1!==P.devtools&&function(){if("undefined"==typeof window)return;if(window.__IMPAIR_DEVTOOLS_HOOK__)return;window.addEventListener("message",re);const e={registerContainer:Q,unregisterContainer:X,registerInstance:Y,getTree:Z,getContainerDetails:ee,getInstanceState:te,setStateValue:ne,on:W,emit:G};window.__IMPAIR_DEVTOOLS_HOOK__=e}();const ce={ref:l,shallowRef:f,reactive:u,shallowReactive:a,effect:s,effectScope:c,stop:i,computed:o,readonly:r,shallowReadonly:n},se=Symbol("customDecoratorMetadata");function ae(e){return function(t,n){const r=Reflect.getMetadata(se,t)??[];r.push({propertyKey:n,initializer:e}),Reflect.metadata(se,r)(t)}}function ue(e,t){if("dispose"!==t){e.dispose||Object.defineProperty(e,"dispose",{value:function(){},writable:!0,configurable:!0});const n=Reflect.getMetadata(z,e)??[];n.push(t),Reflect.metadata(z,n)(e)}}function fe(e,t){const n=Reflect.getMetadata(x,e)??[];n.push(t),Reflect.metadata(x,n)(e)}function le(e,t,n){const r=Reflect.getMetadata(V,e)??[];return r.push({propertyKey:t,descriptor:n}),Reflect.metadata(V,r)(e)}function de(e,t){const n=Reflect.getMetadata(A,e)??[];return n.push(t),Reflect.metadata(A,n)(e)}function pe(e,t){return de(e,{propertyKey:t,type:"default"})}function ye({instance:e}){const t=new Map,n=Reflect.getMetadata(A,e);if(n){const r=new Map;n.forEach(e=>{r.set(e.propertyKey,e)}),r.forEach(({propertyKey:n,type:r})=>{const o=e[n],i="default"===r?P.defaultStateReactiveLevel:r,c=function(e,t){return"atom"===t?f(e):"deep"===t?l(e):"shallow"===t?f(null!=e&&"object"==typeof e?a(e):e):l(e)}(o,i);t.set(n,c),Object.defineProperty(e,n,{configurable:!0,get:()=>t.get(n)?.value,set(r){const o=t.get(n);o?(o.value="shallow"===i&&null!=r&&"object"==typeof r?a(r):r,oe()?.emit("state-changed",{instance:e,propertyKey:n,value:r})):console.error(`No ref value found for ${n}`)}})})}}function me(e){let t=!1;return()=>{t||(t=!0,queueMicrotask(()=>{t=!1,e()}))}}pe.shallow=function(e,t){return de(e,{propertyKey:t,type:"shallow"})},pe.atom=function(e,t){return de(e,{propertyKey:t,type:"atom"})},pe.deep=function(e,t){return de(e,{propertyKey:t,type:"deep"})};const ge=s;function he(e,t,n="sync",r){const o=Reflect.getMetadata(K,e)??[];return o.push({propertyKey:t,flush:n,ms:r}),Reflect.metadata(K,o)(e)}function be(e,t){if("number"!=typeof t||!Number.isFinite(t)||t<0)throw new Error(`@trigger.${e}(ms) requires a non-negative finite number, got ${String(t)}`)}function ve(e,t){return he(e,t)}function we({instance:e,disposers:t}){const n=Reflect.getMetadata(K,e);if(n){const r=new Map;n.forEach(e=>{r.set(e.propertyKey,e)}),r.forEach(({flush:n,propertyKey:r,ms:o})=>{const c=e[r];if("function"!=typeof c)throw new Error("@trigger decorator can only be used on methods with optional Cleanup param, not on "+typeof c);const s=c.bind(e);let a;const u=()=>(a?.(),a=void 0,s(e=>{a=e})),f="sync"===n?ge(u):"async"===n?function(e){const t=me(()=>{n()}),n=ge(e,{scheduler(){t()}});return n}(u):"debounce"===n?function(e,t){let n;const r=ge(e,{scheduler(){void 0!==n&&clearTimeout(n),n=setTimeout(()=>{n=void 0,r()},t)}});return r}(u,o):function(e,t){let n=!1,r=!1;const o=()=>{n=!1,r&&(r=!1,i(),c())},i=()=>{n=!0,setTimeout(o,t)},c=ge(e,{scheduler(){n?r=!0:(i(),c())}});return c}(u,o);t.push(()=>{a?.(),i(f)}),Object.defineProperty(e,r,{enumerable:!0,configurable:!0,writable:!0,value:s})})}}function Re(n){e();try{return n()}finally{t()}}function Se(e){return function(e){const t=new Set;let n=e;for(;null!==n&&n!==Object.prototype;)Object.getOwnPropertyNames(n).forEach(e=>{"constructor"!==e&&Object.getOwnPropertyDescriptor(n,e)?.value instanceof Function&&t.add(e)}),n=Object.getPrototypeOf(n);return[...t]}(e).forEach(t=>{e[t]=e[t].bind(e)}),e}function Oe(e){return null!=e&&"object"==typeof e&&Object.getPrototypeOf(e)===Object.prototype}function Ee(e){if(!je(e))try{const t=[];Me(e),function(e,t,n){const r=e[t];Object.defineProperty(e,t,{value:function(){r?.call(e),n()},configurable:!0,writable:!0})}(e,"dispose",function(){t.forEach(e=>{e()})});const n={instance:e,disposers:t};ye(n),function({disposers:e,instance:t}){const n=Reflect.getMetadata(V,t);if(n){const r=new Map;n.forEach(e=>{r.set(e.propertyKey,e)}),r.forEach(({propertyKey:n,descriptor:r})=>{const i=r.get;if("function"!=typeof i)throw new Error(`@derived property "${n}" must have a getter function.`);let s;const a=c();a.run(()=>{s=o(()=>i.call(t))}),e.push(()=>{a.stop()}),Object.defineProperty(t,n,{enumerable:!0,configurable:!0,get:()=>s.value})})}}(n),function(e,t){const n=Reflect.getMetadata(se,e);n?.forEach(({initializer:n,propertyKey:r})=>{const o=n(e,r,ce);o&&t.push(o)})}(e,t),we(n),Se(e),function(e,t){new Set(Reflect.getMetadata(x,e)??[]).forEach(n=>{let r;e[n].call(e,e=>{r=e}),t.push(()=>{r?.()})})}(e,t),function(e,t){new Set(Reflect.getMetadata(z,e)??[]).forEach(n=>{const r=e[n];t.push(()=>{r.call(e)})})}(e,t)}catch(t){console.error("Impair Error initializing instance",e,t),Me(e,!1)}return e}function Me(e,t=!0){e[_]=t}function je(e){return e[_]??!1}ve.async=function(e,t){return he(e,t,"async")},ve.debounce=function(e){return be("debounce",e),function(t,n){return he(t,n,"debounce",e)}},ve.throttle=function(e){return be("throttle",e),function(t,n){return he(t,n,"throttle",e)}};const Ce=Symbol.for("tsyringe.DependencyContainer.parentContainer");function Pe(e,t){if(e.isRegistered(t))return e;const n=e.getParentContainer?.();return n&&n!==m?Pe(n,t):void 0}function Ie(e){switch(e){case"singleton":return g.Singleton;case"transient":return g.Transient;case"container":return g.ContainerScoped;case"resolution":return g.ResolutionScoped;default:throw new Error("Invalid lifecycle")}}function ke(e,t,n){const r=[];t.forEach(t=>{const{provider:o,token:i,lifecycle:c}=function(e){if("function"==typeof e)return{token:e,provider:{useClass:e},lifecycle:"singleton"};if(Array.isArray(e)){if("string"==typeof e[1]){const[t,n]=e;return{token:t,provider:{useClass:t},lifecycle:n}}const[t,n,r="singleton"]=e;return{token:t,provider:{useClass:n},lifecycle:r}}if("object"==typeof e)return e;throw new Error("Invalid service provider registration")}(t);e.isRegistered(i)||(e.register(i,o,c?{lifecycle:Ie(c)}:void 0),n&&"singleton"===c&&r.push(i))}),n&&r.forEach(t=>{e.resolve(t)})}function _e(e){return function(t){Reflect.metadata(T,e)(t)}}function Ae(e,t){const n=function(e){return e.getParentContainer||(e.getParentContainer=function(){return e[Ce]}),e.setParentContainer||(e.setParentContainer=function(t){e[Ce]=t}),e}(e.createChildContainer());n.setParentContainer(e),oe()?.registerContainer(n,e);const r=n.resolve,o=new Map;return n.resolve=function(...e){const i=e[0];if(function(e){return"function"==typeof e||"symbol"==typeof e||"string"==typeof e}(i)){if(!n.isRegistered(i)){const t=Pe(n,i);if(t)return t.resolve.call(t,...e)}o.has(n)||o.set(n,new Set);const r=o.get(n);if(!r.has(i)){r.add(i);const e=function(e,t=!0){if("function"==typeof e){const n=Reflect.getMetadata(T,e)??[];return t?[...n,e]:n}return[]}(i,!1);ke(n,e),n.afterResolution(i,(e,r)=>{if(!je(r)&&function(e){const t=Object.getPrototypeOf(e).constructor;return"function"==typeof t&&Reflect.getMetadata(N,t)}(r)){const e=Ee(r);P.afterResolve?.({token:i,instance:e,container:n}),t?.(e),oe()?.registerInstance(n,i,e)}},{frequency:"Always"})}}return r.call(n,...e)},n}const Ke=Symbol("Props");class Ve{container;constructor(e){this.container=e,this.resolve=this.resolve.bind(this),this.resolveAll=this.container.resolveAll.bind(e),this.register=this.container.register.bind(e),this.isRegistered=this.container.isRegistered.bind(e)}resolve(e,t){if(null!=t&&"function"==typeof e){const n=Ae(this.container,Ee);return n.register(e,{useClass:e},{lifecycle:g.Transient}),n.registerInstance(Ke,t),n.resolve(e)}return this.container.resolve(e)}resolveAll;register;isRegistered}const Ne=Ae(m);Ne.register(Ke,{useValue:{}}),Ne.register(Ve,{useValue:new Ve(Ne)}),Ne.dispose=()=>{console.warn("Default container dispose called - operation ignored.")};const Te=b(Ne);function $e(){return v(Te)}function De(e,t){const n=Object.keys(e),r=Object.keys(t);for(const n of r)e[n]!==t[n]&&(e[n]=t[n]);for(const r of n)r in t||delete e[r]}function xe(e){const{state:t,next:r}=w(()=>{if(e&&!Oe(e))throw new Error("[useReactiveObject] props must be a plain js object");const t=e?a({...e}):void 0;return{state:t?n(t):void 0,next:e=>{if(!t)throw new Error("[useReactiveObject] argument was previously undefined");De(t,e)}}},[]);return e&&r(e),t}function ze(e){const t=R([]),n=R({}),r=function(e){const t=[];for(const n of e)if("function"==typeof n)t.push(n);else if(Array.isArray(n))t.push(...n.filter(e=>!Oe(e)));else if(t.push(n.token),n.provider){const e=n.provider;e.useClass&&t.push(e.useClass)}return t}(e);return(r.length!==t.current.length||r.some((e,n)=>e!==t.current[n]))&&(t.current=r,n.current={}),n.current}function Fe(e,t){const n=Reflect.getMetadata($,e)??[];n.push(t),Reflect.metadata($,n)(e)}function Le(e,t){const n=Reflect.getMetadata(D,e)??[];n.push(t),Reflect.metadata(D,n)(e)}function qe(e){if(!e[k]){e[k]=!0;const n=(t=e,[...new Set(Reflect.getMetadata($,t)??[])].map(e=>t[e].bind(t))).map(e=>{let t;return e(e=>{t=e}),()=>{t?.()}});return()=>{if(e[k]){e[k]=!1;const t=function(e){return[...new Set(Reflect.getMetadata(D,e)??[])].map(t=>e[t].bind(e))}(e);t.concat(n).forEach(e=>e())}}}var t}function He({services:e,sharedContainerRef:t,props:n,initializeSingletons:r}){const o=$e(),[i]=S(()=>new Set),[c]=S(()=>new Set),s=R(!1),u=R(void 0),f=xe(n),l=null!=n,d=function(e){const[t]=S([]),n=ze(e),r=w(()=>e.map((e,n)=>Array.isArray(e)&&Oe(e[1])?(t[n]=a(e[1]),{token:e[0],provider:{useValue:t[n]}}):e),[t,n]);return O(()=>{e.forEach((e,n)=>{if(Array.isArray(e)&&Oe(e[1])){const r=t[n];r&&De(r,e[1])}})},[t,e]),r}(e),p=function(){const[e,t]=S({}),n=R(!0);return n.current=!0,O(()=>(n.current||(n.current=!0,t({})),()=>{n.current=!1}),[]),e}(),{container:y}=w(()=>{const e=t?.current,n=void 0!==u.current&&u.current!==d;if(e&&!function(e){return!!e[F]}(e)){if(!n)return ke(e,d,r),u.current=d,{container:e,disposers:c};c.forEach(e=>{e?.()}),c.clear(),i.clear(),ie(e),oe()?.unregisterContainer(e),t.current=void 0}const a=Ae(o,e=>{i.add(e),s.current&&c.add(qe(e))});return a.isRegistered(Ve)||a.register(Ve,{useValue:new Ve(a)}),l&&!a.isRegistered(Ke)&&a.register(Ke,{useValue:f}),ke(a,d,r),t&&(t.current=a),u.current=d,{container:a,disposers:c}},[o,i,t?.current,d,p]);return O(()=>(s.current=!0,i.forEach(e=>{c.add(qe(e))}),()=>{c.forEach(e=>{e?.()}),y&&(ie(y),oe()?.unregisterContainer(y)),s.current=!1,i.clear(),c.clear()}),[c,i,y]),y}function Ue({provide:e,children:t,props:n,initializeSingletons:r}){const o=He({services:e,props:n,initializeSingletons:r});return C(Te.Provider,{value:o,children:t})}let We,Be,Ge=0;function Je(e,t,n){const r="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:"undefined"!=typeof window?window:void 0;if(!r)return;const o=r.$RefreshReg$;if("function"!=typeof o)return;const i=n||t?.displayName||t?.name||"ImpairComponent_"+ ++Ge;o(e,i);const c=r.$RefreshSig$;if("function"!=typeof c)return;c()(e,t?.toString?.()??`impair:${i}`,!1,void 0)}function Qe(e){Be=e}function Xe(e){We=e}function Ye(){return Be}function Ze(){return We}function et(e){const t={};return function(e){const t=new Set;let n=e;for(;null!==n&&n!==Object.prototype;)Object.getOwnPropertyNames(n).forEach(e=>{"constructor"!==e&&t.add(e)}),n=Object.getPrototypeOf(n);return[...t]}(e).forEach(n=>{let r;Object.defineProperty(t,n,{get(){if(!r){const t=e[n];if(d(t)){const t=o(()=>p(e[n]));r=()=>t.value}else r=()=>e[n]}return r()},configurable:!0,enumerable:!0})}),t}function tt(e){const t=Ye(),n=Ze();if(!t||!n)throw new Error("useViewModel must be used within a component");const r=He({services:[e],props:n.current,sharedContainerRef:t});return w(()=>{const t=r.resolve(e);return P.readonlyProxiesForView?et(t):t},[r,e])}function nt(e){const t=E(t=>{const n=function(){const[e,t]=S({});return j(()=>{t({})},[])}(),r=R(null),o=R(void 0),c=R(t),a=R(!1),u=R(void 0),f=R(!1);if(c.current=t,a.current=!1,o.current)o.current?.();else{const t=me(()=>{a.current&&f.current&&n()});o.current=s(()=>{Qe(u),Xe(c),r.current=e(c.current),Qe(void 0),Xe(void 0)},{scheduler(){a.current=!0,t()}})}return O(()=>(f.current=!0,n(),()=>{f.current=!1,o.current&&i(o.current),o.current=void 0,u.current&&(ie(u.current),u.current=void 0)}),[n]),u.current?M(Te.Provider,{value:u.current},r.current):r.current});return t.provide=(...e)=>{const n=n=>M(Ue,{provide:e},M(t,n));return n.displayName=`(ImpairServiceProvider) ${t.displayName||t.name||"Component"}`,Je(n,n,`${t.displayName||t.name||"Component"}.provide`),n},t.displayName=e.displayName||e.name||"Component",Je(t,e),t}function rt(e,t){const n=Ze();if(!n)throw new Error("useResolve must be used within a component");const r=He({services:"function"==typeof e?[[e,"transient"]]:[],props:t??n.current});return w(()=>{const t=r.resolve(e);return P.readonlyProxiesForView?et(t):t},[r,e])}function ot(e){const t=$e();return w(()=>{const n=t.resolve(e);return P.readonlyProxiesForView?et(n):n},[e,t])}function it(){return function(e){h()(e),e.prototype.dispose||Object.defineProperty(e.prototype,"dispose",{value:function(){},writable:!0,configurable:!0}),Reflect.metadata(N,!0)(e)}}function ct(e,t=!0){if(d(e)||!t)return y(e);if("object"==typeof e&&null!==e){if(Array.isArray(e))return e.map(e=>ct(e));if(Object.getPrototypeOf(e)===Object.prototype)return Object.fromEntries(Object.entries(e).map(([e,t])=>[e,ct(t)]));if(e instanceof Map)return new Map(e.entries().map(([e,t])=>[e,ct(t)]));if(e instanceof Set)return new Set([...e].map(e=>ct(e)))}return e}nt.fromViewModel=function(e){const t=()=>tt(e).render();t.displayName=e.name;const n=nt(t);return n.displayName=`(ImpairViewModel) ${e.name.replace("ViewModel","")}`,n};export{Ve as Container,Ke as Props,Ue as ServiceProvider,nt as component,I as configure,ae as createDecorator,le as derived,it as injectable,ue as onDispose,fe as onInit,Fe as onMount,Le as onUnmount,_e as provide,pe as state,ct as toRaw,ve as trigger,Re as untrack,xe as useReactiveObject,rt as useResolve,ot as useService,tt as useViewModel}; //# sourceMappingURL=index.js.map