UNPKG

@yz-dev/react-dynamic-module

Version:

A powerful React component for dynamically loading premium or optional modules from a script URL with dependency injection.

23 lines (22 loc) 9.01 kB
(function(_,i){typeof exports=="object"&&typeof module<"u"?i(exports,require("react"),require("react-dom")):typeof define=="function"&&define.amd?define(["exports","react","react-dom"],i):(_=typeof globalThis<"u"?globalThis:_||self,i(_.YzDevReactDynamicModule={},_.React,_.ReactDOM))})(this,function(_,i,g){"use strict";var C={exports:{}},S={};/** * @license React * react-jsx-runtime.production.js * * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */var U;function Z(){if(U)return S;U=1;var o=Symbol.for("react.transitional.element"),m=Symbol.for("react.fragment");function f(s,t,d){var p=null;if(d!==void 0&&(p=""+d),t.key!==void 0&&(p=""+t.key),"key"in t){d={};for(var E in t)E!=="key"&&(d[E]=t[E])}else d=t;return t=d.ref,{$$typeof:o,type:s,key:p,ref:t!==void 0?t:null,props:d}}return S.Fragment=m,S.jsx=f,S.jsxs=f,S}var P={};/** * @license React * react-jsx-runtime.development.js * * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */var L;function Q(){return L||(L=1,process.env.NODE_ENV!=="production"&&function(){function o(e){if(e==null)return null;if(typeof e=="function")return e.$$typeof===le?null:e.displayName||e.name||null;if(typeof e=="string")return e;switch(e){case A:return"Fragment";case N:return"Profiler";case k:return"StrictMode";case oe:return"Suspense";case ae:return"SuspenseList";case ue:return"Activity"}if(typeof e=="object")switch(typeof e.tag=="number"&&console.error("Received an unexpected object in getComponentNameFromType(). This is likely a bug in React. Please file an issue."),e.$$typeof){case b:return"Portal";case te:return(e.displayName||"Context")+".Provider";case j:return(e._context.displayName||"Context")+".Consumer";case ne:var r=e.render;return e=e.displayName,e||(e=r.displayName||r.name||"",e=e!==""?"ForwardRef("+e+")":"ForwardRef"),e;case se:return r=e.displayName||null,r!==null?r:o(e.type)||"Memo";case q:r=e._payload,e=e._init;try{return o(e(r))}catch{}}return null}function m(e){return""+e}function f(e){try{m(e);var r=!1}catch{r=!0}if(r){r=console;var n=r.error,l=typeof Symbol=="function"&&Symbol.toStringTag&&e[Symbol.toStringTag]||e.constructor.name||"Object";return n.call(r,"The provided key is an unsupported type %s. This value must be coerced to a string before using it here.",l),m(e)}}function s(e){if(e===A)return"<>";if(typeof e=="object"&&e!==null&&e.$$typeof===q)return"<...>";try{var r=o(e);return r?"<"+r+">":"<...>"}catch{return"<...>"}}function t(){var e=M.A;return e===null?null:e.getOwner()}function d(){return Error("react-stack-top-frame")}function p(e){if(z.call(e,"key")){var r=Object.getOwnPropertyDescriptor(e,"key").get;if(r&&r.isReactWarning)return!1}return e.key!==void 0}function E(e,r){function n(){J||(J=!0,console.error("%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://react.dev/link/special-props)",r))}n.isReactWarning=!0,Object.defineProperty(e,"key",{get:n,configurable:!0})}function a(){var e=o(this.type);return V[e]||(V[e]=!0,console.error("Accessing element.ref was removed in React 19. ref is now a regular prop. It will be removed from the JSX Element type in a future release.")),e=this.props.ref,e!==void 0?e:null}function y(e,r,n,l,R,w,F,I){return n=w.ref,e={$$typeof:T,type:e,key:r,props:w,_owner:R},(n!==void 0?n:null)!==null?Object.defineProperty(e,"ref",{enumerable:!1,get:a}):Object.defineProperty(e,"ref",{enumerable:!1,value:null}),e._store={},Object.defineProperty(e._store,"validated",{configurable:!1,enumerable:!1,writable:!0,value:0}),Object.defineProperty(e,"_debugInfo",{configurable:!1,enumerable:!1,writable:!0,value:null}),Object.defineProperty(e,"_debugStack",{configurable:!1,enumerable:!1,writable:!0,value:F}),Object.defineProperty(e,"_debugTask",{configurable:!1,enumerable:!1,writable:!0,value:I}),Object.freeze&&(Object.freeze(e.props),Object.freeze(e)),e}function h(e,r,n,l,R,w,F,I){var c=r.children;if(c!==void 0)if(l)if(ce(c)){for(l=0;l<c.length;l++)v(c[l]);Object.freeze&&Object.freeze(c)}else console.error("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 v(c);if(z.call(r,"key")){c=o(e);var O=Object.keys(r).filter(function(ie){return ie!=="key"});l=0<O.length?"{key: someKey, "+O.join(": ..., ")+": ...}":"{key: someKey}",H[c+l]||(O=0<O.length?"{"+O.join(": ..., ")+": ...}":"{}",console.error(`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} />`,l,c,O,c),H[c+l]=!0)}if(c=null,n!==void 0&&(f(n),c=""+n),p(r)&&(f(r.key),c=""+r.key),"key"in r){n={};for(var G in r)G!=="key"&&(n[G]=r[G])}else n=r;return c&&E(n,typeof e=="function"?e.displayName||e.name||"Unknown":e),y(e,c,w,R,t(),n,F,I)}function v(e){typeof e=="object"&&e!==null&&e.$$typeof===T&&e._store&&(e._store.validated=1)}var u=i,T=Symbol.for("react.transitional.element"),b=Symbol.for("react.portal"),A=Symbol.for("react.fragment"),k=Symbol.for("react.strict_mode"),N=Symbol.for("react.profiler"),j=Symbol.for("react.consumer"),te=Symbol.for("react.context"),ne=Symbol.for("react.forward_ref"),oe=Symbol.for("react.suspense"),ae=Symbol.for("react.suspense_list"),se=Symbol.for("react.memo"),q=Symbol.for("react.lazy"),ue=Symbol.for("react.activity"),le=Symbol.for("react.client.reference"),M=u.__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE,z=Object.prototype.hasOwnProperty,ce=Array.isArray,D=console.createTask?console.createTask:function(){return null};u={react_stack_bottom_frame:function(e){return e()}};var J,V={},X=u.react_stack_bottom_frame.bind(u,d)(),B=D(s(d)),H={};P.Fragment=A,P.jsx=function(e,r,n,l,R){var w=1e4>M.recentlyCreatedOwnerStacks++;return h(e,r,n,!1,l,R,w?Error("react-stack-top-frame"):X,w?D(s(e)):B)},P.jsxs=function(e,r,n,l,R){var w=1e4>M.recentlyCreatedOwnerStacks++;return h(e,r,n,!0,l,R,w?Error("react-stack-top-frame"):X,w?D(s(e)):B)}}()),P}var W;function K(){return W||(W=1,process.env.NODE_ENV==="production"?C.exports=Z():C.exports=Q()),C.exports}var x=K();const $=new Map,ee=o=>{const{import:m,from:f,src:s,loadingUi:t=null,errorUi:d=null,dependencies:p={},...E}=o;$.has(s)||$.set(s,{status:"pending",promise:null,Component:null});const a=$.get(s),[y,h]=i.useState(a.status);return i.useEffect(()=>{a.status==="pending"&&(a.status="loading",h("loading"),a.promise=(async()=>{try{const v=await fetch(s);if(!v.ok||v.headers.get("content-type")?.includes("text/html"))throw new Error(`Module not found at ${s}`);await new Promise((b,A)=>{const k=document.createElement("script");k.src=s,k.async=!0,k.onload=()=>b(),k.onerror=j=>A(j);const N={React:i,ReactDOM:g,...p};Object.keys(N).forEach(j=>{window[j]=N[j]}),document.body.appendChild(k)});const u=window[f],T={React:i,ReactDOM:g,...p};if(Object.keys(T).forEach(b=>{delete window[b]}),u&&typeof u[m]=="function")a.Component=u[m],a.status="success";else throw new Error(`Module loaded, but export '${m}' not found on 'window.${f}'.`)}catch(v){o.onError&&o.onError(v),a.status="failure";const u={React:i,ReactDOM:g,...p};Object.keys(u).forEach(T=>{delete window[T]})}})(),a.promise.finally(()=>{h(a.status)}))},[s,f,m,p]),y==="success"&&a.Component?x.jsx(a.Component,{...E}):y==="failure"?x.jsx(x.Fragment,{children:d}):x.jsx(x.Fragment,{children:t})},Y=new Map,re=({src:o,from:m,import:f,dependencies:s={}})=>{Y.has(o)||Y.set(o,{status:"checking",promise:null,Component:null});const t=Y.get(o),[d,p]=i.useState(t.status);return i.useEffect(()=>{t.status==="checking"&&(t.status="loading",p("loading"),t.promise=(async()=>{try{const E=await fetch(o);if(!E.ok||E.headers.get("content-type")?.includes("text/html"))throw new Error(`Module not found at ${o}`);await new Promise((h,v)=>{const u=document.createElement("script");u.src=o,u.async=!0,u.onload=()=>h(),u.onerror=b=>v(b);const T={React:i,ReactDOM:g,...s};Object.keys(T).forEach(b=>{window[b]=T[b]}),document.body.appendChild(u)});const a=window[m],y={React:i,ReactDOM:g,...s};if(Object.keys(y).forEach(h=>{delete window[h]}),a&&typeof a[f]=="function")t.Component=a[f],t.status="available";else throw new Error(`Module loaded, but export '${f}' not found on 'window.${m}'.`)}catch(E){console.warn(`[useDynamicModule] Could not load module from ${o}:`,E.message),t.status="unavailable";const a={React:i,ReactDOM:g,...s};Object.keys(a).forEach(y=>{delete window[y]})}})(),t.promise.finally(()=>{p(t.status)}))},[o,m,f,s]),{status:d,as:t.Component}};_.DynamicModule=ee,_.useDynamicModule=re,Object.defineProperty(_,Symbol.toStringTag,{value:"Module"})});