UNPKG

react-use-anywhere

Version:

Use React hooks anywhere in your codebase - in services, utilities, and business logic. Router-agnostic, hook-agnostic, and works with any React hooks (auth, navigation, state, custom hooks, etc.).

28 lines (24 loc) 17.4 kB
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const w=require("react");function kr(t){const o=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(t){for(const l in t)if(l!=="default"){const f=Object.getOwnPropertyDescriptor(t,l);Object.defineProperty(o,l,f.get?f:{enumerable:!0,get:()=>t[l]})}}return o.default=t,Object.freeze(o)}const Tr=kr(w);var K={exports:{}},W={};var He;function Cr(){if(He)return W;He=1;var t=w,o=Symbol.for("react.element"),l=Symbol.for("react.fragment"),f=Object.prototype.hasOwnProperty,g=t.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED.ReactCurrentOwner,_={key:!0,ref:!0,__self:!0,__source:!0};function p(k,y,h){var S,O={},x=null,M=null;h!==void 0&&(x=""+h),y.key!==void 0&&(x=""+y.key),y.ref!==void 0&&(M=y.ref);for(S in y)f.call(y,S)&&!_.hasOwnProperty(S)&&(O[S]=y[S]);if(k&&k.defaultProps)for(S in y=k.defaultProps,y)O[S]===void 0&&(O[S]=y[S]);return{$$typeof:o,type:k,key:x,ref:M,props:O,_owner:g.current}}return W.Fragment=l,W.jsx=p,W.jsxs=p,W}var Y={};var $e;function Or(){return $e||($e=1,process.env.NODE_ENV!=="production"&&(function(){var t=w,o=Symbol.for("react.element"),l=Symbol.for("react.portal"),f=Symbol.for("react.fragment"),g=Symbol.for("react.strict_mode"),_=Symbol.for("react.profiler"),p=Symbol.for("react.provider"),k=Symbol.for("react.context"),y=Symbol.for("react.forward_ref"),h=Symbol.for("react.suspense"),S=Symbol.for("react.suspense_list"),O=Symbol.for("react.memo"),x=Symbol.for("react.lazy"),M=Symbol.for("react.offscreen"),ae=Symbol.iterator,We="@@iterator";function Ye(e){if(e===null||typeof e!="object")return null;var r=ae&&e[ae]||e[We];return typeof r=="function"?r:null}var $=t.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED;function b(e){{for(var r=arguments.length,n=new Array(r>1?r-1:0),i=1;i<r;i++)n[i-1]=arguments[i];Me("error",e,n)}}function Me(e,r,n){{var i=$.ReactDebugCurrentFrame,s=i.getStackAddendum();s!==""&&(r+="%s",n=n.concat([s]));var c=n.map(function(u){return String(u)});c.unshift("Warning: "+r),Function.prototype.apply.call(console[e],console,c)}}var Ue=!1,qe=!1,Je=!1,Be=!1,Ke=!1,ue;ue=Symbol.for("react.module.reference");function ze(e){return!!(typeof e=="string"||typeof e=="function"||e===f||e===_||Ke||e===g||e===h||e===S||Be||e===M||Ue||qe||Je||typeof e=="object"&&e!==null&&(e.$$typeof===x||e.$$typeof===O||e.$$typeof===p||e.$$typeof===k||e.$$typeof===y||e.$$typeof===ue||e.getModuleId!==void 0))}function Ge(e,r,n){var i=e.displayName;if(i)return i;var s=r.displayName||r.name||"";return s!==""?n+"("+s+")":n}function se(e){return e.displayName||"Context"}function m(e){if(e==null)return null;if(typeof e.tag=="number"&&b("Received an unexpected object in getComponentNameFromType(). This is likely a bug in React. Please file an issue."),typeof e=="function")return e.displayName||e.name||null;if(typeof e=="string")return e;switch(e){case f:return"Fragment";case l:return"Portal";case _:return"Profiler";case g:return"StrictMode";case h:return"Suspense";case S:return"SuspenseList"}if(typeof e=="object")switch(e.$$typeof){case k:var r=e;return se(r)+".Consumer";case p:var n=e;return se(n._context)+".Provider";case y:return Ge(e,e.render,"ForwardRef");case O:var i=e.displayName||null;return i!==null?i:m(e.type)||"Memo";case x:{var s=e,c=s._payload,u=s._init;try{return m(u(c))}catch{return null}}}return null}var j=Object.assign,L=0,ce,le,fe,de,ve,ge,pe;function ye(){}ye.__reactDisabledLog=!0;function Xe(){{if(L===0){ce=console.log,le=console.info,fe=console.warn,de=console.error,ve=console.group,ge=console.groupCollapsed,pe=console.groupEnd;var e={configurable:!0,enumerable:!0,value:ye,writable:!0};Object.defineProperties(console,{info:e,log:e,warn:e,error:e,group:e,groupCollapsed:e,groupEnd:e})}L++}}function Ze(){{if(L--,L===0){var e={configurable:!0,enumerable:!0,writable:!0};Object.defineProperties(console,{log:j({},e,{value:ce}),info:j({},e,{value:le}),warn:j({},e,{value:fe}),error:j({},e,{value:de}),group:j({},e,{value:ve}),groupCollapsed:j({},e,{value:ge}),groupEnd:j({},e,{value:pe})})}L<0&&b("disabledDepth fell below zero. This is a bug in React. Please file an issue.")}}var z=$.ReactCurrentDispatcher,G;function U(e,r,n){{if(G===void 0)try{throw Error()}catch(s){var i=s.stack.trim().match(/\n( *(at )?)/);G=i&&i[1]||""}return` `+G+e}}var X=!1,q;{var Qe=typeof WeakMap=="function"?WeakMap:Map;q=new Qe}function be(e,r){if(!e||X)return"";{var n=q.get(e);if(n!==void 0)return n}var i;X=!0;var s=Error.prepareStackTrace;Error.prepareStackTrace=void 0;var c;c=z.current,z.current=null,Xe();try{if(r){var u=function(){throw Error()};if(Object.defineProperty(u.prototype,"props",{set:function(){throw Error()}}),typeof Reflect=="object"&&Reflect.construct){try{Reflect.construct(u,[])}catch(R){i=R}Reflect.construct(e,[],u)}else{try{u.call()}catch(R){i=R}e.call(u.prototype)}}else{try{throw Error()}catch(R){i=R}e()}}catch(R){if(R&&i&&typeof R.stack=="string"){for(var a=R.stack.split(` `),E=i.stack.split(` `),d=a.length-1,v=E.length-1;d>=1&&v>=0&&a[d]!==E[v];)v--;for(;d>=1&&v>=0;d--,v--)if(a[d]!==E[v]){if(d!==1||v!==1)do if(d--,v--,v<0||a[d]!==E[v]){var T=` `+a[d].replace(" at new "," at ");return e.displayName&&T.includes("<anonymous>")&&(T=T.replace("<anonymous>",e.displayName)),typeof e=="function"&&q.set(e,T),T}while(d>=1&&v>=0);break}}}finally{X=!1,z.current=c,Ze(),Error.prepareStackTrace=s}var A=e?e.displayName||e.name:"",H=A?U(A):"";return typeof e=="function"&&q.set(e,H),H}function Ne(e,r,n){return be(e,!1)}function er(e){var r=e.prototype;return!!(r&&r.isReactComponent)}function J(e,r,n){if(e==null)return"";if(typeof e=="function")return be(e,er(e));if(typeof e=="string")return U(e);switch(e){case h:return U("Suspense");case S:return U("SuspenseList")}if(typeof e=="object")switch(e.$$typeof){case y:return Ne(e.render);case O:return J(e.type,r,n);case x:{var i=e,s=i._payload,c=i._init;try{return J(c(s),r,n)}catch{}}}return""}var V=Object.prototype.hasOwnProperty,Ee={},_e=$.ReactDebugCurrentFrame;function B(e){if(e){var r=e._owner,n=J(e.type,e._source,r?r.type:null);_e.setExtraStackFrame(n)}else _e.setExtraStackFrame(null)}function rr(e,r,n,i,s){{var c=Function.call.bind(V);for(var u in e)if(c(e,u)){var a=void 0;try{if(typeof e[u]!="function"){var E=Error((i||"React class")+": "+n+" type `"+u+"` is invalid; it must be a function, usually from the `prop-types` package, but received `"+typeof e[u]+"`.This often happens because of typos such as `PropTypes.function` instead of `PropTypes.func`.");throw E.name="Invariant Violation",E}a=e[u](r,u,i,n,null,"SECRET_DO_NOT_PASS_THIS_OR_YOU_WILL_BE_FIRED")}catch(d){a=d}a&&!(a instanceof Error)&&(B(s),b("%s: type specification of %s `%s` is invalid; the type checker function must return `null` or an `Error` but returned a %s. You may have forgotten to pass an argument to the type checker creator (arrayOf, instanceOf, objectOf, oneOf, oneOfType, and shape all require an argument).",i||"React class",n,u,typeof a),B(null)),a instanceof Error&&!(a.message in Ee)&&(Ee[a.message]=!0,B(s),b("Failed %s type: %s",n,a.message),B(null))}}}var tr=Array.isArray;function Z(e){return tr(e)}function nr(e){{var r=typeof Symbol=="function"&&Symbol.toStringTag,n=r&&e[Symbol.toStringTag]||e.constructor.name||"Object";return n}}function or(e){try{return Re(e),!1}catch{return!0}}function Re(e){return""+e}function he(e){if(or(e))return b("The provided key is an unsupported type %s. This value must be coerced to a string before before using it here.",nr(e)),Re(e)}var Se=$.ReactCurrentOwner,ir={key:!0,ref:!0,__self:!0,__source:!0},ke,Te;function ar(e){if(V.call(e,"ref")){var r=Object.getOwnPropertyDescriptor(e,"ref").get;if(r&&r.isReactWarning)return!1}return e.ref!==void 0}function ur(e){if(V.call(e,"key")){var r=Object.getOwnPropertyDescriptor(e,"key").get;if(r&&r.isReactWarning)return!1}return e.key!==void 0}function sr(e,r){typeof e.ref=="string"&&Se.current}function cr(e,r){{var n=function(){ke||(ke=!0,b("%s: `key` is not a prop. Trying to access it will result in `undefined` being returned. If you need to access the same value within the child component, you should pass it as a different prop. (https://reactjs.org/link/special-props)",r))};n.isReactWarning=!0,Object.defineProperty(e,"key",{get:n,configurable:!0})}}function lr(e,r){{var n=function(){Te||(Te=!0,b("%s: `ref` is not a prop. Trying to access it will result in `undefined` being returned. If you need to access the same value within the child component, you should pass it as a different prop. (https://reactjs.org/link/special-props)",r))};n.isReactWarning=!0,Object.defineProperty(e,"ref",{get:n,configurable:!0})}}var fr=function(e,r,n,i,s,c,u){var a={$$typeof:o,type:e,key:r,ref:n,props:u,_owner:c};return a._store={},Object.defineProperty(a._store,"validated",{configurable:!1,enumerable:!1,writable:!0,value:!1}),Object.defineProperty(a,"_self",{configurable:!1,enumerable:!1,writable:!1,value:i}),Object.defineProperty(a,"_source",{configurable:!1,enumerable:!1,writable:!1,value:s}),Object.freeze&&(Object.freeze(a.props),Object.freeze(a)),a};function dr(e,r,n,i,s){{var c,u={},a=null,E=null;n!==void 0&&(he(n),a=""+n),ur(r)&&(he(r.key),a=""+r.key),ar(r)&&(E=r.ref,sr(r,s));for(c in r)V.call(r,c)&&!ir.hasOwnProperty(c)&&(u[c]=r[c]);if(e&&e.defaultProps){var d=e.defaultProps;for(c in d)u[c]===void 0&&(u[c]=d[c])}if(a||E){var v=typeof e=="function"?e.displayName||e.name||"Unknown":e;a&&cr(u,v),E&&lr(u,v)}return fr(e,a,E,s,i,Se.current,u)}}var Q=$.ReactCurrentOwner,Ce=$.ReactDebugCurrentFrame;function D(e){if(e){var r=e._owner,n=J(e.type,e._source,r?r.type:null);Ce.setExtraStackFrame(n)}else Ce.setExtraStackFrame(null)}var N;N=!1;function ee(e){return typeof e=="object"&&e!==null&&e.$$typeof===o}function Oe(){{if(Q.current){var e=m(Q.current.type);if(e)return` Check the render method of \``+e+"`."}return""}}function vr(e){return""}var me={};function gr(e){{var r=Oe();if(!r){var n=typeof e=="string"?e:e.displayName||e.name;n&&(r=` Check the top-level render call using <`+n+">.")}return r}}function we(e,r){{if(!e._store||e._store.validated||e.key!=null)return;e._store.validated=!0;var n=gr(r);if(me[n])return;me[n]=!0;var i="";e&&e._owner&&e._owner!==Q.current&&(i=" It was passed a child from "+m(e._owner.type)+"."),D(e),b('Each child in a list should have a unique "key" prop.%s%s See https://reactjs.org/link/warning-keys for more information.',n,i),D(null)}}function Pe(e,r){{if(typeof e!="object")return;if(Z(e))for(var n=0;n<e.length;n++){var i=e[n];ee(i)&&we(i,r)}else if(ee(e))e._store&&(e._store.validated=!0);else if(e){var s=Ye(e);if(typeof s=="function"&&s!==e.entries)for(var c=s.call(e),u;!(u=c.next()).done;)ee(u.value)&&we(u.value,r)}}}function pr(e){{var r=e.type;if(r==null||typeof r=="string")return;var n;if(typeof r=="function")n=r.propTypes;else if(typeof r=="object"&&(r.$$typeof===y||r.$$typeof===O))n=r.propTypes;else return;if(n){var i=m(r);rr(n,e.props,"prop",i,e)}else if(r.PropTypes!==void 0&&!N){N=!0;var s=m(r);b("Component %s declared `PropTypes` instead of `propTypes`. Did you misspell the property assignment?",s||"Unknown")}typeof r.getDefaultProps=="function"&&!r.getDefaultProps.isReactClassApproved&&b("getDefaultProps is only used on classic React.createClass definitions. Use a static property named `defaultProps` instead.")}}function yr(e){{for(var r=Object.keys(e.props),n=0;n<r.length;n++){var i=r[n];if(i!=="children"&&i!=="key"){D(e),b("Invalid prop `%s` supplied to `React.Fragment`. React.Fragment can only have `key` and `children` props.",i),D(null);break}}e.ref!==null&&(D(e),b("Invalid attribute `ref` supplied to `React.Fragment`."),D(null))}}var xe={};function je(e,r,n,i,s,c){{var u=ze(e);if(!u){var a="";(e===void 0||typeof e=="object"&&e!==null&&Object.keys(e).length===0)&&(a+=" You likely forgot to export your component from the file it's defined in, or you might have mixed up default and named imports.");var E=vr();E?a+=E:a+=Oe();var d;e===null?d="null":Z(e)?d="array":e!==void 0&&e.$$typeof===o?(d="<"+(m(e.type)||"Unknown")+" />",a=" Did you accidentally export a JSX literal instead of a component?"):d=typeof e,b("React.jsx: type is invalid -- expected a string (for built-in components) or a class/function (for composite components) but got: %s.%s",d,a)}var v=dr(e,r,n,s,c);if(v==null)return v;if(u){var T=r.children;if(T!==void 0)if(i)if(Z(T)){for(var A=0;A<T.length;A++)Pe(T[A],e);Object.freeze&&Object.freeze(T)}else b("React.jsx: Static children should always be an array. You are likely explicitly calling React.jsxs or React.jsxDEV. Use the Babel transform instead.");else Pe(T,e)}if(V.call(r,"key")){var H=m(e),R=Object.keys(r).filter(function(Sr){return Sr!=="key"}),re=R.length>0?"{key: someKey, "+R.join(": ..., ")+": ...}":"{key: someKey}";if(!xe[H+re]){var hr=R.length>0?"{"+R.join(": ..., ")+": ...}":"{}";b(`A props object containing a "key" prop is being spread into JSX: let props = %s; <%s {...props} /> React keys must be passed directly to JSX without using spread: let props = %s; <%s key={someKey} {...props} />`,re,H,hr,H),xe[H+re]=!0}}return e===f?yr(v):pr(v),v}}function br(e,r,n){return je(e,r,n,!0)}function Er(e,r,n){return je(e,r,n,!1)}var _r=Er,Rr=br;Y.Fragment=f,Y.jsx=_r,Y.jsxs=Rr})()),Y}var De;function mr(){return De||(De=1,process.env.NODE_ENV==="production"?K.exports=Cr():K.exports=Or()),K.exports}var wr=mr();let F={enabled:!1};function Pr(t){F={...F,...t}}function xr(){return{...F}}const C={log(...t){F.enabled&&process.env.NODE_ENV!=="production"&&console.log(...t)},warn(...t){F.enabled&&process.env.NODE_ENV!=="production"&&console.warn(...t)},error(...t){F.enabled&&process.env.NODE_ENV!=="production"&&console.error(...t)}},Ae=w.createContext(null);let te={};const Fe=({children:t,hooks:o})=>{te=o;const l=Object.entries(o),f={};for(let g=0;g<l.length;g++){const[_,p]=l[g];try{f[_]=p(),C.log(`✅ HookProvider: Executed hook "${_}"`,f[_])}catch(k){C.warn(`Failed to execute hook "${_}":`,k),f[_]=void 0}}return C.log("🎯 HookProvider: Providing context with hooks:",Object.keys(f)),wr.jsx(Ae.Provider,{value:f,children:t})},jr=({children:t,hooks:o})=>Fe({children:t,hooks:o}),I=()=>{const t=w.useContext(Ae);if(t===null)throw new Error("useHookContext must be used within a HookProvider");return t};function Hr(){return I()}const Ie=t=>Object.prototype.hasOwnProperty.call(te,t),Le=()=>Object.keys(te);function ne(t,o){const l=I(),f=w.useRef(void 0),[,g]=Tr.useReducer(p=>p+1,0);C.log(`🔌 useHookService: Connecting service to hook "${o}"`,l[o]),w.useEffect(()=>{if(!Ie(o)){const p=Le(),k=p.filter(h=>h.toLowerCase().includes(o.toLowerCase())||o.toLowerCase().includes(h.toLowerCase())).slice(0,3),y=k.length>0?` Did you mean one of these? ${k.map(h=>` • "${h}"`).join(` `)}`:"";C.error(`🚨 useHookService: Hook "${o}" is not registered in HookProvider. Available hooks: ${p.map(h=>`"${h}"`).join(", ")}${y}`)}},[o]);const _=l[o];_!==f.current&&(t._setValue(_),f.current=_,C.log(`✅ useHookService: Value set for "${o}" during render. Service ready:`,t.isReady())),w.useEffect(()=>{const p=l[o];C.log(`📝 useHookService: Effect running for "${o}"`,p),p!==f.current&&(t._setValue(p),f.current=p,C.log(`✅ useHookService: Value updated for "${o}" in effect`),g())},[l,t,o,g])}function $r(t,o){ne(t,o)}function Dr(t,o){ne(t,o)}function Ar(t){return I()[t]}function Fr(t){return Ve(t)}function Ve(t){const o=I();return Object.prototype.hasOwnProperty.call(o,t)?o[t]:void 0}function Ir(){return I()}function oe(){let t=null,o=!1;return{_setValue(l){(l!==t||!o)&&(t=l,o=!0)},get(){return t},isReady(){return o},use(l){if(!o)return C.warn("Hook service not ready. Make sure you're using useHookService in a React component."),null;try{return l(t)}catch(f){return C.error("Error using hook service:",f),null}},_reset(){t=null,o=!1}}}const P=new Map;function Lr(t){const o=Le();if(o.length===0){C.warn(`🚨 No hooks registered yet. Make sure to wrap your app with HookProvider first. Example: <HookProvider hooks={{ ${t}: your${t.charAt(0).toUpperCase()+t.slice(1)}Hook }}>`);return}if(!Ie(t)){const l=o.filter(g=>g.toLowerCase().includes(t.toLowerCase())||t.toLowerCase().includes(g.toLowerCase())).slice(0,3),f=l.length>0?` Did you mean one of these? ${l.map(g=>` • "${g}"`).join(` `)}`:"";C.error(`🚨 Hook "${t}" is not registered in HookProvider. Available hooks: ${o.map(g=>`"${g}"`).join(", ")}${f} 💡 Make sure your HookProvider includes: <HookProvider hooks={{ ${t}: your${t.charAt(0).toUpperCase()+t.slice(1)}Hook, ...other hooks }}>`)}}function ie(t){return P.has(t)||P.set(t,oe()),P.get(t)}function Vr(t){const o=P.get(t);return o||null}function Wr(){P.forEach(t=>{t._reset()})}function Yr(t){return ie(t)}function Mr(t){return Lr(t),P.has(t)||P.set(t,oe()),P.get(t)}function Ur(t){return ie(t)}exports.HookProvider=Fe;exports.TypedHookProvider=jr;exports.configureLogging=Pr;exports.createHookService=oe;exports.createInferredSingletonService=Ur;exports.createSingletonService=ie;exports.createStrictSingletonService=Mr;exports.createTypedSingletonService=Yr;exports.getLoggerConfig=xr;exports.getSingletonService=Vr;exports.resetAllServices=Wr;exports.useAllHooks=Ir;exports.useHook=Ve;exports.useHookContext=I;exports.useHookService=ne;exports.useStrictHook=Fr;exports.useStrictHookService=Dr;exports.useTypedHook=Ar;exports.useTypedHookContext=Hr;exports.useTypedHookService=$r; //# sourceMappingURL=index.cjs.map