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