@kaena1/mm-ui-shared-utils 1.25.0-f-poc-EC-3301.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,117 @@
1
+ import { default as default_2 } from 'react';
2
+
3
+ export declare interface ComponentManifest {
4
+ bundleUrl: string;
5
+ styleUrl?: string;
6
+ }
7
+
8
+ export declare function fetchManifest(manifestUrl: string): Promise<RemoteManifest>;
9
+
10
+ /**
11
+ * Generates an import map JSON string for ES module dependency resolution
12
+ * This allows remote modules to use bare specifiers like 'react' instead of full CDN URLs
13
+ */
14
+ export declare function generateImportMapJson(): string;
15
+
16
+ export declare const ImportMapScripts: default_2.FC;
17
+
18
+ export declare class ModuleLoader {
19
+ private loadedModules;
20
+ private importMapInjected;
21
+ /**
22
+ * Ensure React and ReactDOM are available globally
23
+ * Remote components may expect these to be on window object.
24
+ */
25
+ /**
26
+ * Ensure import map is injected before loading any modules
27
+ * Import maps MUST be added before any module scripts
28
+ */
29
+ private ensureImportMap;
30
+ /**
31
+ * Load remote React component from ES module URL
32
+ *
33
+ * @param options - Configuration object with bundleUrl and componentName
34
+ * @returns Promise that resolves to the loaded React component
35
+ * @throws Error if component loading fails or times out (10s)
36
+ */
37
+ loadComponent(options: ModuleLoadOptions): Promise<any>;
38
+ /**
39
+ * Load ES module from external URL using dynamic script injection
40
+ * This bypasses Webpack's module resolution and works with import maps
41
+ */
42
+ private loadModuleViaScript;
43
+ /**
44
+ * Preload a module without extracting components
45
+ * Useful for warming up cache
46
+ *
47
+ * @param bundleUrl - URL of the module to preload
48
+ */
49
+ preloadModule(bundleUrl: string): Promise<void>;
50
+ /**
51
+ * Check if a module has already been loaded
52
+ *
53
+ * @param bundleUrl - URL of the module to check
54
+ * @returns true if module is already loaded, false otherwise
55
+ */
56
+ isLoaded(bundleUrl: string): boolean;
57
+ /**
58
+ * Clear all loaded modules from cache
59
+ * Useful for development/testing
60
+ */
61
+ clearCache(): void;
62
+ }
63
+
64
+ export declare const moduleLoader: ModuleLoader;
65
+
66
+ export declare interface ModuleLoadOptions {
67
+ bundleUrl: string;
68
+ componentName: string;
69
+ }
70
+
71
+ export declare interface RemoteComponentState {
72
+ component: any;
73
+ manifest: any;
74
+ loading: boolean;
75
+ error: string | null;
76
+ loaded: boolean;
77
+ }
78
+
79
+ export declare const RemoteLinks: default_2.FC<RemoteLinksProps>;
80
+
81
+ declare interface RemoteLinksProps {
82
+ manifest: ComponentManifest;
83
+ }
84
+
85
+ export declare interface RemoteManifest {
86
+ components: Record<string, ComponentManifest>;
87
+ version: string;
88
+ generatedAt: string;
89
+ }
90
+
91
+ export declare const RemoteRenderer: default_2.FC<RemoteRendererProps>;
92
+
93
+ declare interface RemoteRendererProps {
94
+ manifest: ComponentManifest;
95
+ componentName: string;
96
+ componentProps?: any;
97
+ autoLoad?: boolean;
98
+ placeholder?: default_2.ReactNode;
99
+ children?: default_2.ReactNode;
100
+ errorFallback?: (error: string) => default_2.ReactNode;
101
+ }
102
+
103
+ export declare function useRemoteComponent(options: UseRemoteComponentOptions): UseRemoteComponentReturn;
104
+
105
+ export declare interface UseRemoteComponentOptions {
106
+ manifest: any;
107
+ componentName: string;
108
+ autoLoad?: boolean;
109
+ }
110
+
111
+ export declare interface UseRemoteComponentReturn extends RemoteComponentState {
112
+ loadComponent: () => Promise<void>;
113
+ reload: () => Promise<void>;
114
+ clearError: () => void;
115
+ }
116
+
117
+ export { }
package/dist/index.js ADDED
@@ -0,0 +1,299 @@
1
+ var M = Object.defineProperty;
2
+ var y = (n, e, t) => e in n ? M(n, e, { enumerable: !0, configurable: !0, writable: !0, value: t }) : n[e] = t;
3
+ var u = (n, e, t) => y(n, typeof e != "symbol" ? e + "" : e, t);
4
+ import { useState as x, useEffect as w, useCallback as f } from "react";
5
+ import { jsx as l, Fragment as h, jsxs as g } from "react/jsx-runtime";
6
+ async function $(n) {
7
+ try {
8
+ const e = await fetch(n, {
9
+ headers: {
10
+ "Content-Type": "application/json"
11
+ }
12
+ });
13
+ if (!e.ok)
14
+ throw new Error(
15
+ `Failed to fetch manifest: ${e.status} ${e.statusText}`
16
+ );
17
+ const t = await e.json();
18
+ if (!t || typeof t != "object" || !t.components || typeof t.components != "object")
19
+ throw new Error("Invalid manifest: missing 'components' object");
20
+ return t;
21
+ } catch (e) {
22
+ throw e instanceof Error ? new Error(
23
+ `Manifest loading failed from ${n}: ${e.message}`
24
+ ) : new Error(
25
+ `Manifest loading failed from ${n}: Unknown error`
26
+ );
27
+ }
28
+ }
29
+ class R {
30
+ constructor() {
31
+ u(this, "loadedModules", /* @__PURE__ */ new Map());
32
+ u(this, "importMapInjected", !1);
33
+ }
34
+ /**
35
+ * Ensure React and ReactDOM are available globally
36
+ * Remote components may expect these to be on window object.
37
+ */
38
+ // private prepareGlobalDependencies(): void {
39
+ // if (typeof window === 'undefined') return;
40
+ // if (!(window as any).React) {
41
+ // (window as any).React = require('react');
42
+ // }
43
+ // if (!(window as any).ReactDOM) {
44
+ // (window as any).ReactDOM = require('react-dom');
45
+ // }
46
+ // }
47
+ /**
48
+ * Ensure import map is injected before loading any modules
49
+ * Import maps MUST be added before any module scripts
50
+ */
51
+ ensureImportMap() {
52
+ if (typeof window > "u" || this.importMapInjected) return;
53
+ if (document.querySelector(
54
+ 'script[type="importmap"], script[type="importmap-shim"]'
55
+ )) {
56
+ this.importMapInjected = !0;
57
+ return;
58
+ }
59
+ console.warn(
60
+ `Import map not found. Ensure an import map is included early in:
61
+
62
+ - pages router: the document head (e.g. in pages/_document.tsx).
63
+
64
+ - app router: the root layout head (e.g. in app/layout.tsx).`
65
+ ), this.importMapInjected = !0;
66
+ }
67
+ /**
68
+ * Load remote React component from ES module URL
69
+ *
70
+ * @param options - Configuration object with bundleUrl and componentName
71
+ * @returns Promise that resolves to the loaded React component
72
+ * @throws Error if component loading fails or times out (10s)
73
+ */
74
+ async loadComponent(e) {
75
+ const { bundleUrl: t, componentName: a } = e;
76
+ if (this.loadedModules.has(t)) {
77
+ console.log(
78
+ `%c📦 LOADER: Returning module from INTERNAL cache for ${t}`,
79
+ "color: green; font-weight: bold;"
80
+ );
81
+ const o = this.loadedModules.get(t), s = (o == null ? void 0 : o[a]) || (o == null ? void 0 : o.default);
82
+ if (s) return s;
83
+ }
84
+ this.ensureImportMap();
85
+ try {
86
+ const o = await this.loadModuleViaScript(t), s = o[a] || o.default;
87
+ if (!s)
88
+ throw new Error(`Component ${a} not found in module`);
89
+ return this.loadedModules.set(t, o), s;
90
+ } catch (o) {
91
+ throw console.error("🔍 LOADER: Failed to load component:", o), o;
92
+ }
93
+ }
94
+ /**
95
+ * Load ES module from external URL using dynamic script injection
96
+ * This bypasses Webpack's module resolution and works with import maps
97
+ */
98
+ loadModuleViaScript(e) {
99
+ return new Promise((t, a) => {
100
+ const o = `__moduleCallback_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`, s = 50, i = 200;
101
+ let c = 0;
102
+ const m = `
103
+ import * as loadedModule from '${e}';
104
+ window.${o} = loadedModule;
105
+ `, r = document.createElement("script");
106
+ r.type = "module-shim", r.textContent = m;
107
+ const d = setInterval(() => {
108
+ if (c++, window[o]) {
109
+ clearInterval(d);
110
+ const p = window[o];
111
+ delete window[o], r.parentNode && document.head.removeChild(r), t(p);
112
+ } else c >= i && (clearInterval(d), delete window[o], r.parentNode && document.head.removeChild(r), a(new Error(`Timeout loading module from ${e}`)));
113
+ }, s);
114
+ r.onerror = (p) => {
115
+ clearInterval(d), delete window[o], r.parentNode && document.head.removeChild(r), a(new Error(`Failed to load module from ${e}`));
116
+ }, document.head.appendChild(r);
117
+ });
118
+ }
119
+ /**
120
+ * Preload a module without extracting components
121
+ * Useful for warming up cache
122
+ *
123
+ * @param bundleUrl - URL of the module to preload
124
+ */
125
+ async preloadModule(e) {
126
+ if (!this.loadedModules.has(e)) {
127
+ this.ensureImportMap();
128
+ try {
129
+ const t = await this.loadModuleViaScript(e);
130
+ this.loadedModules.set(e, t);
131
+ } catch (t) {
132
+ console.error(`Failed to preload module ${e}:`, t);
133
+ }
134
+ }
135
+ }
136
+ /**
137
+ * Check if a module has already been loaded
138
+ *
139
+ * @param bundleUrl - URL of the module to check
140
+ * @returns true if module is already loaded, false otherwise
141
+ */
142
+ isLoaded(e) {
143
+ return this.loadedModules.has(e);
144
+ }
145
+ /**
146
+ * Clear all loaded modules from cache
147
+ * Useful for development/testing
148
+ */
149
+ clearCache() {
150
+ this.loadedModules.clear();
151
+ }
152
+ }
153
+ const j = new R();
154
+ function I() {
155
+ const n = `data:text/javascript;charset=utf-8,
156
+ const React = window.React;
157
+ export default React;
158
+ export const {
159
+ Component, PureComponent, createContext, useContext, useState, useEffect,
160
+ useCallback, useMemo, useRef, forwardRef, createElement, Fragment, memo, lazy, Suspense,
161
+ useLayoutEffect, useId, useReducer, useImperativeHandle
162
+ } = React;`, e = `data:text/javascript;charset=utf-8,
163
+ const React = window.React;
164
+ export const jsx = React.createElement;
165
+ export const jsxs = React.createElement;
166
+ export const Fragment = React.Fragment;`;
167
+ return JSON.stringify({
168
+ imports: {
169
+ react: n,
170
+ "react/jsx-runtime": e,
171
+ "react/jsx-dev-runtime": e,
172
+ "react/jsx-runtime.js": e,
173
+ "react/jsx-dev-runtime.js": e,
174
+ "react-dom": "https://esm.sh/react-dom@18.3.1",
175
+ "react-dom/client": "https://esm.sh/react-dom@18.3.1/client"
176
+ }
177
+ });
178
+ }
179
+ function C(n) {
180
+ const {
181
+ manifest: e,
182
+ componentName: t,
183
+ autoLoad: a = !0
184
+ } = n, [o, s] = x({
185
+ component: null,
186
+ manifest: null,
187
+ loading: !1,
188
+ error: null,
189
+ loaded: !1
190
+ });
191
+ w(() => {
192
+ var r;
193
+ typeof window < "u" && console.log("🧩 Remote sees React:", {
194
+ react: window.React,
195
+ useState: (r = window.React) == null ? void 0 : r.useState
196
+ });
197
+ }, []);
198
+ const i = f(async () => {
199
+ try {
200
+ s((p) => ({
201
+ ...p,
202
+ loading: !0,
203
+ error: null,
204
+ manifest: e
205
+ }));
206
+ const r = {
207
+ bundleUrl: e.bundleUrl,
208
+ componentName: t
209
+ }, d = await j.loadComponent(r);
210
+ s((p) => ({
211
+ ...p,
212
+ component: d,
213
+ loading: !1,
214
+ loaded: !0
215
+ }));
216
+ } catch (r) {
217
+ console.error("Error loading remote component:", r), s((d) => ({
218
+ ...d,
219
+ error: r.message,
220
+ loading: !1,
221
+ loaded: !1
222
+ }));
223
+ }
224
+ }, [e, t]), c = f(async () => {
225
+ await i();
226
+ }, [i]), m = f(() => {
227
+ s((r) => ({ ...r, error: null }));
228
+ }, []);
229
+ return w(() => {
230
+ a && i().then(() => {
231
+ s((r) => ({ ...r, loaded: !0 }));
232
+ });
233
+ }, [a, i]), {
234
+ ...o,
235
+ loadComponent: i,
236
+ reload: c,
237
+ clearError: m
238
+ };
239
+ }
240
+ const k = ({
241
+ manifest: n,
242
+ componentName: e,
243
+ componentProps: t,
244
+ autoLoad: a = !0,
245
+ placeholder: o = null,
246
+ children: s,
247
+ errorFallback: i
248
+ }) => {
249
+ const {
250
+ component: c,
251
+ error: m,
252
+ loaded: r
253
+ } = C({
254
+ manifest: n,
255
+ componentName: e,
256
+ autoLoad: a
257
+ });
258
+ return m ? i ? i(m) : null : !r || !c ? /* @__PURE__ */ l(h, { children: o }) : /* @__PURE__ */ l(c, { ...t, children: s });
259
+ }, b = ({ manifest: n }) => /* @__PURE__ */ g(h, { children: [
260
+ n.styleUrl && /* @__PURE__ */ l("link", { rel: "stylesheet", href: n.styleUrl }),
261
+ /* @__PURE__ */ l("link", { rel: "modulepreload", href: n.bundleUrl })
262
+ ] }), L = () => /* @__PURE__ */ g(h, { children: [
263
+ /* @__PURE__ */ l(
264
+ "script",
265
+ {
266
+ defer: !0,
267
+ src: "https://ga.jspm.io/npm:es-module-shims@1.10.0/dist/es-module-shims.js",
268
+ crossOrigin: "anonymous"
269
+ }
270
+ ),
271
+ /* @__PURE__ */ l(
272
+ "link",
273
+ {
274
+ rel: "preconnect",
275
+ href: "https://assets-qa.mintmobile.com",
276
+ crossOrigin: "anonymous"
277
+ }
278
+ ),
279
+ /* @__PURE__ */ l("link", { rel: "dns-prefetch", href: "https://assets-qa.mintmobile.com" }),
280
+ /* @__PURE__ */ l("link", { rel: "preconnect", href: "https://esm.sh", crossOrigin: "anonymous" }),
281
+ /* @__PURE__ */ l("link", { rel: "dns-prefetch", href: "https://esm.sh" }),
282
+ /* @__PURE__ */ l(
283
+ "script",
284
+ {
285
+ type: "importmap-shim",
286
+ dangerouslySetInnerHTML: { __html: I() }
287
+ }
288
+ )
289
+ ] });
290
+ export {
291
+ L as ImportMapScripts,
292
+ R as ModuleLoader,
293
+ b as RemoteLinks,
294
+ k as RemoteRenderer,
295
+ $ as fetchManifest,
296
+ I as generateImportMapJson,
297
+ j as moduleLoader,
298
+ C as useRemoteComponent
299
+ };
package/package.json ADDED
@@ -0,0 +1,65 @@
1
+ {
2
+ "name": "@kaena1/mm-ui-shared-utils",
3
+ "version": "1.25.0-f-poc-EC-3301.1",
4
+ "description": "Shared utilities for loading remote React components in Mint Mobile microfrontends",
5
+ "type": "module",
6
+ "main": "./dist/index.js",
7
+ "module": "./dist/index.js",
8
+ "types": "./dist/index.d.ts",
9
+ "exports": {
10
+ ".": {
11
+ "types": "./dist/index.d.ts",
12
+ "import": "./dist/index.js"
13
+ }
14
+ },
15
+ "files": [
16
+ "dist"
17
+ ],
18
+ "publishConfig": {
19
+ "access": "public"
20
+ },
21
+ "scripts": {
22
+ "dev": "vite build --watch",
23
+ "build": "vite build",
24
+ "build:debug": "vite build --debug",
25
+ "test": "echo \"Error: no test specified\" && exit 1",
26
+ "typecheck": "tsc --noEmit",
27
+ "lint": "eslint ./src",
28
+ "release": "semantic-release -e ./release.config.cjs"
29
+ },
30
+ "keywords": [
31
+ "mint",
32
+ "remote-components",
33
+ "microfrontends",
34
+ "shared-utils"
35
+ ],
36
+ "author": "",
37
+ "license": "ISC",
38
+ "peerDependencies": {
39
+ "react": "^18.3.1",
40
+ "react-dom": "^18.3.1"
41
+ },
42
+ "devDependencies": {
43
+ "@semantic-release/changelog": "^6.0.3",
44
+ "@semantic-release/commit-analyzer": "^11.0.0",
45
+ "@semantic-release/exec": "^6.0.3",
46
+ "@semantic-release/git": "^10.0.1",
47
+ "@semantic-release/npm": "^11.0.0",
48
+ "@semantic-release/release-notes-generator": "^12.0.0",
49
+ "@types/react": "^18.3.1",
50
+ "@types/react-dom": "^18.3.1",
51
+ "@typescript-eslint/eslint-plugin": "^8.53.0",
52
+ "@typescript-eslint/parser": "^8.53.0",
53
+ "conventional-changelog-conventionalcommits": "^7.0.2",
54
+ "eslint": "^9.39.2",
55
+ "react": "^18.3.1",
56
+ "react-dom": "^18.3.1",
57
+ "rollup-preserve-directives": "^1.1.3",
58
+ "semantic-release": "^23.0.0",
59
+ "semantic-release-slack-bot": "^4.0.2",
60
+ "typescript": "^5.0.0",
61
+ "vite": "^5.4.14",
62
+ "vite-plugin-dts": "^3.9.1",
63
+ "vite-plugin-externalize-deps": "^0.9.0"
64
+ }
65
+ }