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.).

797 lines (793 loc) 25.3 kB
import xe, { createContext as Rr, useContext as _r, useRef as Sr, useEffect as Oe } from "react"; var Q = { exports: {} }, H = {}; /** * @license React * react-jsx-runtime.production.min.js * * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ var Pe; function Cr() { if (Pe) return H; Pe = 1; var n = xe, a = Symbol.for("react.element"), p = Symbol.for("react.fragment"), d = Object.prototype.hasOwnProperty, l = n.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED.ReactCurrentOwner, S = { key: !0, ref: !0, __self: !0, __source: !0 }; function w(E, g, x) { var R, C = {}, O = null, W = null; x !== void 0 && (O = "" + x), g.key !== void 0 && (O = "" + g.key), g.ref !== void 0 && (W = g.ref); for (R in g) d.call(g, R) && !S.hasOwnProperty(R) && (C[R] = g[R]); if (E && E.defaultProps) for (R in g = E.defaultProps, g) C[R] === void 0 && (C[R] = g[R]); return { $$typeof: a, type: E, key: O, ref: W, props: C, _owner: l.current }; } return H.Fragment = p, H.jsx = w, H.jsxs = w, H; } var I = {}; /** * @license React * react-jsx-runtime.development.js * * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ var ke; function Tr() { return ke || (ke = 1, process.env.NODE_ENV !== "production" && function() { var n = xe, a = Symbol.for("react.element"), p = Symbol.for("react.portal"), d = Symbol.for("react.fragment"), l = Symbol.for("react.strict_mode"), S = Symbol.for("react.profiler"), w = Symbol.for("react.provider"), E = Symbol.for("react.context"), g = Symbol.for("react.forward_ref"), x = Symbol.for("react.suspense"), R = Symbol.for("react.suspense_list"), C = Symbol.for("react.memo"), O = Symbol.for("react.lazy"), W = Symbol.for("react.offscreen"), re = Symbol.iterator, Ie = "@@iterator"; function Le(e) { if (e === null || typeof e != "object") return null; var r = re && e[re] || e[Ie]; return typeof r == "function" ? r : null; } var j = n.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED; function y(e) { { for (var r = arguments.length, t = new Array(r > 1 ? r - 1 : 0), o = 1; o < r; o++) t[o - 1] = arguments[o]; We("error", e, t); } } function We(e, r, t) { { var o = j.ReactDebugCurrentFrame, s = o.getStackAddendum(); s !== "" && (r += "%s", t = t.concat([s])); var c = t.map(function(u) { return String(u); }); c.unshift("Warning: " + r), Function.prototype.apply.call(console[e], console, c); } } var Ye = !1, Ve = !1, Me = !1, Ue = !1, Je = !1, te; te = Symbol.for("react.module.reference"); function Be(e) { return !!(typeof e == "string" || typeof e == "function" || e === d || e === S || Je || e === l || e === x || e === R || Ue || e === W || Ye || Ve || Me || typeof e == "object" && e !== null && (e.$$typeof === O || e.$$typeof === C || e.$$typeof === w || e.$$typeof === E || e.$$typeof === g || // This needs to include all possible module reference object // types supported by any Flight configuration anywhere since // we don't know which Flight build this will end up being used // with. e.$$typeof === te || e.getModuleId !== void 0)); } function qe(e, r, t) { var o = e.displayName; if (o) return o; var s = r.displayName || r.name || ""; return s !== "" ? t + "(" + s + ")" : t; } function ne(e) { return e.displayName || "Context"; } function m(e) { if (e == null) return null; if (typeof e.tag == "number" && y("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 d: return "Fragment"; case p: return "Portal"; case S: return "Profiler"; case l: return "StrictMode"; case x: return "Suspense"; case R: return "SuspenseList"; } if (typeof e == "object") switch (e.$$typeof) { case E: var r = e; return ne(r) + ".Consumer"; case w: var t = e; return ne(t._context) + ".Provider"; case g: return qe(e, e.render, "ForwardRef"); case C: var o = e.displayName || null; return o !== null ? o : m(e.type) || "Memo"; case O: { var s = e, c = s._payload, u = s._init; try { return m(u(c)); } catch { return null; } } } return null; } var P = Object.assign, D = 0, oe, ae, ie, ue, se, ce, le; function fe() { } fe.__reactDisabledLog = !0; function Ke() { { if (D === 0) { oe = console.log, ae = console.info, ie = console.warn, ue = console.error, se = console.group, ce = console.groupCollapsed, le = console.groupEnd; var e = { configurable: !0, enumerable: !0, value: fe, writable: !0 }; Object.defineProperties(console, { info: e, log: e, warn: e, error: e, group: e, groupCollapsed: e, groupEnd: e }); } D++; } } function Ge() { { if (D--, D === 0) { var e = { configurable: !0, enumerable: !0, writable: !0 }; Object.defineProperties(console, { log: P({}, e, { value: oe }), info: P({}, e, { value: ae }), warn: P({}, e, { value: ie }), error: P({}, e, { value: ue }), group: P({}, e, { value: se }), groupCollapsed: P({}, e, { value: ce }), groupEnd: P({}, e, { value: le }) }); } D < 0 && y("disabledDepth fell below zero. This is a bug in React. Please file an issue."); } } var J = j.ReactCurrentDispatcher, B; function Y(e, r, t) { { if (B === void 0) try { throw Error(); } catch (s) { var o = s.stack.trim().match(/\n( *(at )?)/); B = o && o[1] || ""; } return ` ` + B + e; } } var q = !1, V; { var ze = typeof WeakMap == "function" ? WeakMap : Map; V = new ze(); } function de(e, r) { if (!e || q) return ""; { var t = V.get(e); if (t !== void 0) return t; } var o; q = !0; var s = Error.prepareStackTrace; Error.prepareStackTrace = void 0; var c; c = J.current, J.current = null, Ke(); 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 (b) { o = b; } Reflect.construct(e, [], u); } else { try { u.call(); } catch (b) { o = b; } e.call(u.prototype); } } else { try { throw Error(); } catch (b) { o = b; } e(); } } catch (b) { if (b && o && typeof b.stack == "string") { for (var i = b.stack.split(` `), h = o.stack.split(` `), f = i.length - 1, v = h.length - 1; f >= 1 && v >= 0 && i[f] !== h[v]; ) v--; for (; f >= 1 && v >= 0; f--, v--) if (i[f] !== h[v]) { if (f !== 1 || v !== 1) do if (f--, v--, v < 0 || i[f] !== h[v]) { var _ = ` ` + i[f].replace(" at new ", " at "); return e.displayName && _.includes("<anonymous>") && (_ = _.replace("<anonymous>", e.displayName)), typeof e == "function" && V.set(e, _), _; } while (f >= 1 && v >= 0); break; } } } finally { q = !1, J.current = c, Ge(), Error.prepareStackTrace = s; } var A = e ? e.displayName || e.name : "", k = A ? Y(A) : ""; return typeof e == "function" && V.set(e, k), k; } function Xe(e, r, t) { return de(e, !1); } function Ze(e) { var r = e.prototype; return !!(r && r.isReactComponent); } function M(e, r, t) { if (e == null) return ""; if (typeof e == "function") return de(e, Ze(e)); if (typeof e == "string") return Y(e); switch (e) { case x: return Y("Suspense"); case R: return Y("SuspenseList"); } if (typeof e == "object") switch (e.$$typeof) { case g: return Xe(e.render); case C: return M(e.type, r, t); case O: { var o = e, s = o._payload, c = o._init; try { return M(c(s), r, t); } catch { } } } return ""; } var F = Object.prototype.hasOwnProperty, ve = {}, pe = j.ReactDebugCurrentFrame; function U(e) { if (e) { var r = e._owner, t = M(e.type, e._source, r ? r.type : null); pe.setExtraStackFrame(t); } else pe.setExtraStackFrame(null); } function Qe(e, r, t, o, s) { { var c = Function.call.bind(F); for (var u in e) if (c(e, u)) { var i = void 0; try { if (typeof e[u] != "function") { var h = Error((o || "React class") + ": " + t + " 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 h.name = "Invariant Violation", h; } i = e[u](r, u, o, t, null, "SECRET_DO_NOT_PASS_THIS_OR_YOU_WILL_BE_FIRED"); } catch (f) { i = f; } i && !(i instanceof Error) && (U(s), y("%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).", o || "React class", t, u, typeof i), U(null)), i instanceof Error && !(i.message in ve) && (ve[i.message] = !0, U(s), y("Failed %s type: %s", t, i.message), U(null)); } } } var Ne = Array.isArray; function K(e) { return Ne(e); } function er(e) { { var r = typeof Symbol == "function" && Symbol.toStringTag, t = r && e[Symbol.toStringTag] || e.constructor.name || "Object"; return t; } } function rr(e) { try { return ge(e), !1; } catch { return !0; } } function ge(e) { return "" + e; } function ye(e) { if (rr(e)) return y("The provided key is an unsupported type %s. This value must be coerced to a string before before using it here.", er(e)), ge(e); } var he = j.ReactCurrentOwner, tr = { key: !0, ref: !0, __self: !0, __source: !0 }, Ee, be; function nr(e) { if (F.call(e, "ref")) { var r = Object.getOwnPropertyDescriptor(e, "ref").get; if (r && r.isReactWarning) return !1; } return e.ref !== void 0; } function or(e) { if (F.call(e, "key")) { var r = Object.getOwnPropertyDescriptor(e, "key").get; if (r && r.isReactWarning) return !1; } return e.key !== void 0; } function ar(e, r) { typeof e.ref == "string" && he.current; } function ir(e, r) { { var t = function() { Ee || (Ee = !0, y("%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)); }; t.isReactWarning = !0, Object.defineProperty(e, "key", { get: t, configurable: !0 }); } } function ur(e, r) { { var t = function() { be || (be = !0, y("%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)); }; t.isReactWarning = !0, Object.defineProperty(e, "ref", { get: t, configurable: !0 }); } } var sr = function(e, r, t, o, s, c, u) { var i = { // This tag allows us to uniquely identify this as a React Element $$typeof: a, // Built-in properties that belong on the element type: e, key: r, ref: t, props: u, // Record the component responsible for creating this element. _owner: c }; return i._store = {}, Object.defineProperty(i._store, "validated", { configurable: !1, enumerable: !1, writable: !0, value: !1 }), Object.defineProperty(i, "_self", { configurable: !1, enumerable: !1, writable: !1, value: o }), Object.defineProperty(i, "_source", { configurable: !1, enumerable: !1, writable: !1, value: s }), Object.freeze && (Object.freeze(i.props), Object.freeze(i)), i; }; function cr(e, r, t, o, s) { { var c, u = {}, i = null, h = null; t !== void 0 && (ye(t), i = "" + t), or(r) && (ye(r.key), i = "" + r.key), nr(r) && (h = r.ref, ar(r, s)); for (c in r) F.call(r, c) && !tr.hasOwnProperty(c) && (u[c] = r[c]); if (e && e.defaultProps) { var f = e.defaultProps; for (c in f) u[c] === void 0 && (u[c] = f[c]); } if (i || h) { var v = typeof e == "function" ? e.displayName || e.name || "Unknown" : e; i && ir(u, v), h && ur(u, v); } return sr(e, i, h, s, o, he.current, u); } } var G = j.ReactCurrentOwner, Re = j.ReactDebugCurrentFrame; function $(e) { if (e) { var r = e._owner, t = M(e.type, e._source, r ? r.type : null); Re.setExtraStackFrame(t); } else Re.setExtraStackFrame(null); } var z; z = !1; function X(e) { return typeof e == "object" && e !== null && e.$$typeof === a; } function _e() { { if (G.current) { var e = m(G.current.type); if (e) return ` Check the render method of \`` + e + "`."; } return ""; } } function lr(e) { return ""; } var Se = {}; function fr(e) { { var r = _e(); if (!r) { var t = typeof e == "string" ? e : e.displayName || e.name; t && (r = ` Check the top-level render call using <` + t + ">."); } return r; } } function Ce(e, r) { { if (!e._store || e._store.validated || e.key != null) return; e._store.validated = !0; var t = fr(r); if (Se[t]) return; Se[t] = !0; var o = ""; e && e._owner && e._owner !== G.current && (o = " It was passed a child from " + m(e._owner.type) + "."), $(e), y('Each child in a list should have a unique "key" prop.%s%s See https://reactjs.org/link/warning-keys for more information.', t, o), $(null); } } function Te(e, r) { { if (typeof e != "object") return; if (K(e)) for (var t = 0; t < e.length; t++) { var o = e[t]; X(o) && Ce(o, r); } else if (X(e)) e._store && (e._store.validated = !0); else if (e) { var s = Le(e); if (typeof s == "function" && s !== e.entries) for (var c = s.call(e), u; !(u = c.next()).done; ) X(u.value) && Ce(u.value, r); } } } function dr(e) { { var r = e.type; if (r == null || typeof r == "string") return; var t; if (typeof r == "function") t = r.propTypes; else if (typeof r == "object" && (r.$$typeof === g || // Note: Memo only checks outer props here. // Inner props are checked in the reconciler. r.$$typeof === C)) t = r.propTypes; else return; if (t) { var o = m(r); Qe(t, e.props, "prop", o, e); } else if (r.PropTypes !== void 0 && !z) { z = !0; var s = m(r); y("Component %s declared `PropTypes` instead of `propTypes`. Did you misspell the property assignment?", s || "Unknown"); } typeof r.getDefaultProps == "function" && !r.getDefaultProps.isReactClassApproved && y("getDefaultProps is only used on classic React.createClass definitions. Use a static property named `defaultProps` instead."); } } function vr(e) { { for (var r = Object.keys(e.props), t = 0; t < r.length; t++) { var o = r[t]; if (o !== "children" && o !== "key") { $(e), y("Invalid prop `%s` supplied to `React.Fragment`. React.Fragment can only have `key` and `children` props.", o), $(null); break; } } e.ref !== null && ($(e), y("Invalid attribute `ref` supplied to `React.Fragment`."), $(null)); } } var me = {}; function we(e, r, t, o, s, c) { { var u = Be(e); if (!u) { var i = ""; (e === void 0 || typeof e == "object" && e !== null && Object.keys(e).length === 0) && (i += " 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 h = lr(); h ? i += h : i += _e(); var f; e === null ? f = "null" : K(e) ? f = "array" : e !== void 0 && e.$$typeof === a ? (f = "<" + (m(e.type) || "Unknown") + " />", i = " Did you accidentally export a JSX literal instead of a component?") : f = typeof e, y("React.jsx: type is invalid -- expected a string (for built-in components) or a class/function (for composite components) but got: %s.%s", f, i); } var v = cr(e, r, t, s, c); if (v == null) return v; if (u) { var _ = r.children; if (_ !== void 0) if (o) if (K(_)) { for (var A = 0; A < _.length; A++) Te(_[A], e); Object.freeze && Object.freeze(_); } else y("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 Te(_, e); } if (F.call(r, "key")) { var k = m(e), b = Object.keys(r).filter(function(br) { return br !== "key"; }), Z = b.length > 0 ? "{key: someKey, " + b.join(": ..., ") + ": ...}" : "{key: someKey}"; if (!me[k + Z]) { var Er = b.length > 0 ? "{" + b.join(": ..., ") + ": ...}" : "{}"; y(`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} />`, Z, k, Er, k), me[k + Z] = !0; } } return e === d ? vr(v) : dr(v), v; } } function pr(e, r, t) { return we(e, r, t, !0); } function gr(e, r, t) { return we(e, r, t, !1); } var yr = gr, hr = pr; I.Fragment = d, I.jsx = yr, I.jsxs = hr; }()), I; } process.env.NODE_ENV === "production" ? Q.exports = Cr() : Q.exports = Tr(); var mr = Q.exports; const je = Rr(null); let N = {}; const wr = ({ children: n, hooks: a }) => { N = a; const p = {}; return Object.entries(a).forEach(([d, l]) => { try { p[d] = l(); } catch (S) { console.warn(`Failed to execute hook "${d}":`, S), p[d] = void 0; } }), /* @__PURE__ */ mr.jsx(je.Provider, { value: p, children: n }); }, kr = ({ children: n, hooks: a }) => wr({ children: n, hooks: a }), L = () => { const n = _r(je); if (n === null) throw new Error("useHookContext must be used within a HookProvider"); return n; }; function xr() { return L(); } const $e = (n) => n in N, Ae = () => Object.keys(N); function De(n, a) { const p = L(), d = Sr(); Oe(() => { if (!$e(a)) { const l = Ae(), S = l.filter( (E) => E.toLowerCase().includes(a.toLowerCase()) || a.toLowerCase().includes(E.toLowerCase()) ).slice(0, 3), w = S.length > 0 ? ` Did you mean one of these? ${S.map((E) => ` • "${E}"`).join(` `)}` : ""; console.error( `🚨 useHookService: Hook "${a}" is not registered in HookProvider. Available hooks: ${l.map((E) => `"${E}"`).join(", ")}${w}` ); } }, [a]), Oe(() => { const l = p[a]; l !== d.current && (l !== d.current && JSON.stringify(l) !== JSON.stringify(d.current) || l !== void 0) && (n._setValue(l), d.current = l); }, [p[a], n]); } function jr(n, a) { De(n, a); } function $r(n, a) { De(n, a); } function Ar(n) { return L()[n]; } function Dr(n) { return Or(n); } function Or(n) { const a = L(); return Object.prototype.hasOwnProperty.call(a, n) ? a[n] : void 0; } function Fr() { return L(); } function Fe() { let n = null, a = !1; return { // Internal method used by useHookService - don't call directly _setValue(p) { (p !== n && JSON.stringify(p) !== JSON.stringify(n) || !a) && (n = p, a = !0); }, // Get the current hook value get() { return n; }, // Check if the hook value is available isReady() { return a; }, // Use the hook value in a callback - this is the main way to use hooks in non-React files use(p) { if (!a) return console.warn( "Hook service not ready. Make sure you're using useHookService in a React component." ), null; try { return p(n); } catch (d) { return console.error("Error using hook service:", d), null; } }, // Reset the service (for testing) _reset() { n = null, a = !1; } }; } const T = /* @__PURE__ */ new Map(); function ee(n) { const a = Ae(); if (a.length === 0) { console.warn( `🚨 No hooks registered yet. Make sure to wrap your app with HookProvider first. Example: <HookProvider hooks={{ ${n}: your${n.charAt(0).toUpperCase() + n.slice(1)}Hook }}>` ); return; } if (!$e(n)) { const p = a.filter( (l) => l.toLowerCase().includes(n.toLowerCase()) || n.toLowerCase().includes(l.toLowerCase()) ).slice(0, 3), d = p.length > 0 ? ` Did you mean one of these? ${p.map((l) => ` • "${l}"`).join(` `)}` : ""; console.error( `🚨 Hook "${n}" is not registered in HookProvider. Available hooks: ${a.map((l) => `"${l}"`).join(", ")}${d} 💡 Make sure your HookProvider includes: <HookProvider hooks={{ ${n}: your${n.charAt(0).toUpperCase() + n.slice(1)}Hook, ...other hooks }}>` ); } } function He(n) { return ee(n), T.has(n) || T.set(n, Fe()), T.get(n); } function Hr(n) { ee(n); const a = T.get(n); return a || null; } function Ir() { T.forEach((n) => { n._reset(); }), T.clear(); } function Lr(n) { return He(n); } function Wr(n) { return ee(n), T.has(n) || T.set(n, Fe()), T.get(n); } function Yr(n) { return He(n); } export { wr as HookProvider, kr as TypedHookProvider, Fe as createHookService, Yr as createInferredSingletonService, He as createSingletonService, Wr as createStrictSingletonService, Lr as createTypedSingletonService, Hr as getSingletonService, Ir as resetAllServices, Fr as useAllHooks, Or as useHook, L as useHookContext, De as useHookService, Dr as useStrictHook, $r as useStrictHookService, Ar as useTypedHook, xr as useTypedHookContext, jr as useTypedHookService }; //# sourceMappingURL=index.js.map