@withl5e/l5e 1.1.0-alpha.2 → 1.1.0-alpha.4
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.
- package/README.md +9 -1
- package/dist/entry-server.js +2 -2
- package/dist/index.js +4 -4
- package/dist/{middleware-CnDqZobD.js → middleware-B8m9wPBe.js} +2 -2
- package/dist/{middleware-CnDqZobD.js.map → middleware-B8m9wPBe.js.map} +1 -1
- package/dist/middleware.js +1 -1
- package/dist/{render-hUQUreah.js → render-Z3_uiPMp.js} +2 -2
- package/dist/{render-hUQUreah.js.map → render-Z3_uiPMp.js.map} +1 -1
- package/dist/{rolldown-runtime-B0aSnxlc.js → rolldown-runtime-DtPi1Y-2.js} +3 -10
- package/dist/{server-C35BtVu8.js → server-D7amTQoo.js} +4 -4
- package/dist/{server-C35BtVu8.js.map → server-D7amTQoo.js.map} +1 -1
- package/dist/server.js +1 -1
- package/dist/tooltip-config-vyMazu8C.js +24 -0
- package/dist/tooltip-config-vyMazu8C.js.map +1 -0
- package/dist/tooltip-runtime-CEzyDvmX.js +89 -0
- package/dist/tooltip-runtime-CEzyDvmX.js.map +1 -0
- package/dist/tooltip.js +15 -115
- package/dist/tooltip.js.map +1 -1
- package/dist/{vite-plugin-BOuzxmb2.js → vite-plugin-Bln1di66.js} +15 -13
- package/dist/vite-plugin-Bln1di66.js.map +1 -0
- package/dist/vite-plugin.js +1 -1
- package/package.json +1 -1
- package/src/core/chunking.ts +21 -5
- package/src/core/vite-plugin.ts +3 -1
- package/src/tooltip/index.ts +15 -2
- package/src/tooltip/tooltip-config.ts +82 -0
- package/src/tooltip/tooltip-runtime.ts +3 -78
- package/dist/vite-plugin-BOuzxmb2.js.map +0 -1
package/dist/tooltip.js
CHANGED
|
@@ -1,30 +1,29 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import { autoUpdate as t, computePosition as n, flip as r, hide as i, offset as a, shift as o } from "@floating-ui/dom";
|
|
1
|
+
import { t as e } from "./tooltip-config-vyMazu8C.js";
|
|
3
2
|
//#region src/tooltip/tooltip-loader.ts
|
|
4
|
-
function
|
|
3
|
+
function t() {
|
|
5
4
|
let e = navigator.userAgent.toLowerCase(), t = /android|webos|iphone|ipad|ipod|blackberry|iemobile|opera mini|mobile|tablet/i.test(e), n = window.matchMedia("(max-width: 768px)").matches;
|
|
6
5
|
return t || n;
|
|
7
6
|
}
|
|
8
|
-
function
|
|
7
|
+
function n() {
|
|
9
8
|
let e = document.querySelectorAll("[data-tooltip-id]");
|
|
10
9
|
if (e.length === 0) return;
|
|
11
|
-
let
|
|
10
|
+
let n = t();
|
|
12
11
|
e.forEach((e) => {
|
|
13
|
-
e.hasAttribute("data-tooltip-initialized") || (e.setAttribute("data-tooltip-initialized", "true"),
|
|
12
|
+
e.hasAttribute("data-tooltip-initialized") || (e.setAttribute("data-tooltip-initialized", "true"), n ? e.addEventListener("click", async (t) => {
|
|
14
13
|
t.preventDefault();
|
|
15
|
-
let { showTooltipMobile: n } = await
|
|
14
|
+
let { showTooltipMobile: n } = await import("./tooltip-runtime-CEzyDvmX.js");
|
|
16
15
|
n(e);
|
|
17
16
|
}) : (e.addEventListener("pointerenter", () => {
|
|
18
17
|
e.setAttribute("data-tooltip-active", "true");
|
|
19
18
|
}), e.addEventListener("pointerleave", () => {
|
|
20
19
|
e.removeAttribute("data-tooltip-active");
|
|
21
20
|
}), e.addEventListener("pointerenter", async () => {
|
|
22
|
-
let { showTooltip: t } = await
|
|
21
|
+
let { showTooltip: t } = await import("./tooltip-runtime-CEzyDvmX.js");
|
|
23
22
|
t(e);
|
|
24
23
|
}, { passive: !0 })));
|
|
25
24
|
});
|
|
26
25
|
}
|
|
27
|
-
function
|
|
26
|
+
function r() {
|
|
28
27
|
if (window.__tooltipObserver) return;
|
|
29
28
|
let e = new MutationObserver((e) => {
|
|
30
29
|
let t = !1;
|
|
@@ -35,7 +34,7 @@ function l() {
|
|
|
35
34
|
(n.hasAttribute("data-tooltip-id") || n.querySelector("[data-tooltip-id]")) && (t = !0);
|
|
36
35
|
}
|
|
37
36
|
});
|
|
38
|
-
}), t &&
|
|
37
|
+
}), t && n();
|
|
39
38
|
});
|
|
40
39
|
e.observe(document.body, {
|
|
41
40
|
childList: !0,
|
|
@@ -43,113 +42,14 @@ function l() {
|
|
|
43
42
|
}), window.__tooltipObserver = e;
|
|
44
43
|
}
|
|
45
44
|
//#endregion
|
|
46
|
-
//#region src/tooltip/
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
showTooltip: () => h,
|
|
50
|
-
showTooltipMobile: () => g
|
|
51
|
-
}), d = ({ type: e, id: t }) => `/tooltip/${e}/${t}`, f = ({ type: e, id: t }) => {
|
|
52
|
-
let n = document.documentElement.lang, r = "";
|
|
53
|
-
if (n) {
|
|
54
|
-
let e = n.split("-")[0].toLowerCase(), t = location.pathname.match(/^\/([a-zA-Z-]+)(?:\/|$)/)?.[1];
|
|
55
|
-
t && (t.toLowerCase() === e || t.toLowerCase() === n.toLowerCase()) && (r = `/${t}`);
|
|
56
|
-
}
|
|
57
|
-
return `${r}/tooltip/${e}/${t}`;
|
|
58
|
-
};
|
|
59
|
-
function p(e) {
|
|
60
|
-
window.__l5eTooltipUrl = e === "auto-locale" ? f : e;
|
|
45
|
+
//#region src/tooltip/index.ts
|
|
46
|
+
async function i(e) {
|
|
47
|
+
return (await import("./tooltip-runtime-CEzyDvmX.js")).showTooltip(e);
|
|
61
48
|
}
|
|
62
|
-
function
|
|
63
|
-
|
|
64
|
-
return (window.__l5eTooltipUrl ?? d)({
|
|
65
|
-
type: n ?? "",
|
|
66
|
-
id: t ?? "",
|
|
67
|
-
host: e
|
|
68
|
-
});
|
|
69
|
-
}
|
|
70
|
-
async function h(e) {
|
|
71
|
-
if (!e.hasAttribute("data-tooltip-active")) return;
|
|
72
|
-
let n = document.createElement("div");
|
|
73
|
-
n.className = "tp", n.innerHTML = "<div class=\"tp-loading\">Loading...</div>", document.body.append(n);
|
|
74
|
-
let r = null, i = () => {
|
|
75
|
-
r &&= (r(), null), document.body.contains(n) && n.remove();
|
|
76
|
-
};
|
|
77
|
-
if (e.addEventListener("pointerleave", i), !e.hasAttribute("data-tooltip-active")) {
|
|
78
|
-
e.removeEventListener("pointerleave", i), n.remove();
|
|
79
|
-
return;
|
|
80
|
-
}
|
|
81
|
-
r = t(e, n, () => v(e, n));
|
|
82
|
-
try {
|
|
83
|
-
let t = await fetch(m(e), { headers: { Accept: "text/html" } }).then((e) => e.text());
|
|
84
|
-
if (!document.body.contains(n)) return;
|
|
85
|
-
n.innerHTML = t, await v(e, n);
|
|
86
|
-
} catch {
|
|
87
|
-
document.body.contains(n) && (n.innerHTML = "<div class=\"tp-error\">Không thể tải tooltip</div>");
|
|
88
|
-
}
|
|
89
|
-
}
|
|
90
|
-
async function g(e) {
|
|
91
|
-
let t = document.createElement("div");
|
|
92
|
-
t.className = "tp-overlay";
|
|
93
|
-
let n = document.createElement("div");
|
|
94
|
-
n.className = "tp-mobile", n.innerHTML = "<div class=\"tp-loading\">Loading...</div>", t.append(n), document.body.append(t), document.body.style.overflow = "hidden";
|
|
95
|
-
let r = () => {
|
|
96
|
-
t.remove(), document.body.style.overflow = "";
|
|
97
|
-
};
|
|
98
|
-
t.addEventListener("click", (e) => {
|
|
99
|
-
e.target === t && r();
|
|
100
|
-
});
|
|
101
|
-
try {
|
|
102
|
-
let t = await fetch(m(e), { headers: { Accept: "text/html" } }).then((e) => e.text());
|
|
103
|
-
n.innerHTML = "";
|
|
104
|
-
let i = document.createElement("button");
|
|
105
|
-
i.className = "tp-mobile-close", i.innerHTML = "✕", i.addEventListener("click", r), n.append(i);
|
|
106
|
-
let a = document.createElement("div");
|
|
107
|
-
a.className = "tp-mobile-content", a.innerHTML = t, n.append(a);
|
|
108
|
-
let o = e.dataset.href;
|
|
109
|
-
if (o) {
|
|
110
|
-
let e = document.createElement("a");
|
|
111
|
-
e.className = "tp-mobile-link", e.href = o, e.textContent = "Xem chi tiết", n.append(e);
|
|
112
|
-
}
|
|
113
|
-
} catch {
|
|
114
|
-
n.innerHTML = "<div class=\"tp-error\">Không thể tải tooltip</div>";
|
|
115
|
-
}
|
|
116
|
-
}
|
|
117
|
-
function _() {
|
|
118
|
-
return {
|
|
119
|
-
name: "centerFallback",
|
|
120
|
-
fn({ rects: e }) {
|
|
121
|
-
let t = window.innerHeight;
|
|
122
|
-
return e.floating.height <= t * .6 ? {} : {
|
|
123
|
-
y: window.scrollY + Math.max(8, (t - e.floating.height) / 2),
|
|
124
|
-
data: {
|
|
125
|
-
centered: !0,
|
|
126
|
-
maxHeight: t - 16
|
|
127
|
-
}
|
|
128
|
-
};
|
|
129
|
-
}
|
|
130
|
-
};
|
|
131
|
-
}
|
|
132
|
-
function v(e, t) {
|
|
133
|
-
let s = e.dataset.tooltipPlacement ?? "left";
|
|
134
|
-
return n(e, t, {
|
|
135
|
-
placement: s,
|
|
136
|
-
middleware: [
|
|
137
|
-
a(6),
|
|
138
|
-
r(),
|
|
139
|
-
o({ padding: 5 }),
|
|
140
|
-
_(),
|
|
141
|
-
i()
|
|
142
|
-
]
|
|
143
|
-
}).then(({ x: e, y: n, middlewareData: r }) => {
|
|
144
|
-
Object.assign(t.style, {
|
|
145
|
-
left: `${e}px`,
|
|
146
|
-
top: `${n}px`
|
|
147
|
-
}), t.style.visibility = r.hide?.referenceHidden ? "hidden" : "visible";
|
|
148
|
-
let i = r.centerFallback;
|
|
149
|
-
i?.centered ? (t.style.maxHeight = `${i.maxHeight}px`, t.style.overflowY = "auto") : (t.style.maxHeight = "", t.style.overflowY = "");
|
|
150
|
-
});
|
|
49
|
+
async function a(e) {
|
|
50
|
+
return (await import("./tooltip-runtime-CEzyDvmX.js")).showTooltipMobile(e);
|
|
151
51
|
}
|
|
152
52
|
//#endregion
|
|
153
|
-
export {
|
|
53
|
+
export { e as configureTooltip, n as initTooltips, r as setupTooltipObserver, i as showTooltip, a as showTooltipMobile };
|
|
154
54
|
|
|
155
55
|
//# sourceMappingURL=tooltip.js.map
|
package/dist/tooltip.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"tooltip.js","names":[],"sources":["../src/tooltip/tooltip-loader.ts","../src/tooltip/tooltip-runtime.ts"],"sourcesContent":["// tooltip-loader.ts\n// File này chỉ làm nhiệm vụ wake up tooltip khi cần thiết\n\n// Định nghĩa kiểu cho tooltip host element\ntype TooltipHost = HTMLElement & {\n dataset: {\n tooltipId: string;\n tooltipType?: string;\n };\n};\n\n/**\n * Kiểm tra xem thiết bị hiện tại có phải là thiết bị di động hay không\n * @returns true nếu là thiết bị di động\n */\nfunction isMobileDevice(): boolean {\n // Kiểm tra User Agent\n const userAgent = navigator.userAgent.toLowerCase();\n const isMobile =\n /android|webos|iphone|ipad|ipod|blackberry|iemobile|opera mini|mobile|tablet/i.test(userAgent);\n\n // Kiểm tra thêm kích thước màn hình (dưới 768px thường được coi là thiết bị di động)\n const isTouchScreen = window.matchMedia('(max-width: 768px)').matches;\n\n return isMobile || isTouchScreen;\n}\n\n/**\n * Hàm khởi tạo tooltip, chỉ load runtime khi cần thiết\n */\nexport function initTooltips(): void {\n const tooltipTriggers = document.querySelectorAll<TooltipHost>('[data-tooltip-id]');\n if (tooltipTriggers.length === 0) return;\n\n const mobile = isMobileDevice();\n\n tooltipTriggers.forEach((trigger) => {\n if (trigger.hasAttribute('data-tooltip-initialized')) return;\n trigger.setAttribute('data-tooltip-initialized', 'true');\n\n if (mobile) {\n trigger.addEventListener('click', async (e) => {\n e.preventDefault();\n const { showTooltipMobile } = await import('./tooltip-runtime');\n showTooltipMobile(trigger);\n });\n } else {\n // Keep the interaction state explicitly. Firefox can lose the\n // `:hover` match while the lazily-loaded runtime is being evaluated,\n // even though the pointer is still over the trigger.\n trigger.addEventListener('pointerenter', () => {\n trigger.setAttribute('data-tooltip-active', 'true');\n });\n trigger.addEventListener('pointerleave', () => {\n trigger.removeAttribute('data-tooltip-active');\n });\n trigger.addEventListener(\n 'pointerenter',\n async () => {\n const { showTooltip } = await import('./tooltip-runtime');\n showTooltip(trigger);\n },\n { passive: true },\n );\n }\n });\n}\n\n// Thêm một MutationObserver để theo dõi các phần tử DOM mới (cho React components)\nexport function setupTooltipObserver(): void {\n // Kiểm tra xem đã có observer chưa\n if (window.__tooltipObserver) return;\n\n // Observer theo dõi khi có phần tử mới được thêm vào DOM\n const observer = new MutationObserver((mutations) => {\n let shouldInit = false;\n\n mutations.forEach((mutation) => {\n if (mutation.type === 'childList' && mutation.addedNodes.length > 0) {\n // Kiểm tra xem có phần tử tooltip nào mới được thêm vào không\n mutation.addedNodes.forEach((node) => {\n if (node.nodeType === Node.ELEMENT_NODE) {\n const element = node as HTMLElement;\n // Kiểm tra nếu phần tử có data-tooltip-id hoặc chứa phần tử con có data-tooltip-id\n if (\n element.hasAttribute('data-tooltip-id') ||\n element.querySelector('[data-tooltip-id]')\n ) {\n shouldInit = true;\n }\n }\n });\n }\n });\n\n // Chỉ gọi initTooltips nếu có phát hiện tooltip mới\n if (shouldInit) {\n initTooltips();\n }\n });\n\n // Bắt đầu theo dõi toàn bộ DOM\n observer.observe(document.body, {\n childList: true,\n subtree: true,\n });\n\n // Lưu observer vào window để tránh tạo nhiều observer\n window.__tooltipObserver = observer;\n}\n\n// Typescript declaration cho window object\ndeclare global {\n interface Window {\n __tooltipObserver?: MutationObserver;\n }\n}\n","// tooltip-runtime.ts\n// Logic đầy đủ cho tooltip, chỉ được tải khi cần thiết\n\nimport type { Middleware, Placement } from '@floating-ui/dom';\nimport { autoUpdate, computePosition, flip, hide, offset, shift } from '@floating-ui/dom';\n\ntype TooltipHost = HTMLElement & {\n dataset: {\n tooltipId: string;\n tooltipType?: string;\n tooltipPlacement?: Placement;\n href?: string;\n };\n};\n\n/** Everything the tooltip system knows about one request, for a custom strategy to build a URL from. */\nexport interface TooltipUrlContext {\n type: string;\n id: string;\n host: TooltipHost;\n}\n\nexport type TooltipUrlStrategy = (ctx: TooltipUrlContext) => string;\n\nconst defaultStrategy: TooltipUrlStrategy = ({ type, id }) => `/tooltip/${type}/${id}`;\n\n/**\n * If the page's own URL already carries a prefix matching `<html lang>` (e.g.\n * `<html lang=\"vi\">` on `/vi/...`), reuse that same prefix — for apps doing\n * URL-prefix locale routing that want each locale to be a distinct,\n * CDN-cacheable tooltip URL with zero per-page setup. A base-locale page\n * (unprefixed URL) naturally infers no prefix.\n */\nconst autoLocaleStrategy: TooltipUrlStrategy = ({ type, id }) => {\n const lang = document.documentElement.lang;\n let prefix = '';\n if (lang) {\n const primary = lang.split('-')[0].toLowerCase();\n const match = location.pathname.match(/^\\/([a-zA-Z-]+)(?:\\/|$)/);\n const segment = match?.[1];\n if (segment && (segment.toLowerCase() === primary || segment.toLowerCase() === lang.toLowerCase())) {\n prefix = `/${segment}`;\n }\n }\n return `${prefix}/tooltip/${type}/${id}`;\n};\n\ndeclare global {\n interface Window {\n // L5E's per-request bundler compiles each view's client script (and\n // client.global.ts) as independent bundles — a view that imports\n // initTooltips()/showTooltip() gets its own inlined copy of this whole\n // module, with its own module-scoped variables. A plain `let` here\n // would only ever be seen by whichever single bundle happens to define\n // it, not by the others — so this has to live on `window`, the one\n // thing every independently-bundled script actually shares.\n __l5eTooltipUrl?: TooltipUrlStrategy;\n }\n}\n\n/**\n * Replace how every tooltip's fetch URL is built. L5E is not an i18n\n * framework and most apps using tooltips don't localize URLs (or need any\n * custom scheme) at all, so the default is `/tooltip/:type/:id` unless an\n * app opts into something else — call this once at startup, e.g. in\n * `client.global.ts` so it runs regardless of which view's own client\n * script actually mounts a tooltip:\n *\n * ```ts\n * configureTooltip('auto-locale'); // infer /vi (or none) from <html lang> + URL\n * // or fully custom:\n * configureTooltip(({ type, id }) => `/api/v2/tooltips/${type}-${id}`);\n * ```\n */\nexport function configureTooltip(strategy: 'auto-locale' | TooltipUrlStrategy): void {\n window.__l5eTooltipUrl = strategy === 'auto-locale' ? autoLocaleStrategy : strategy;\n}\n\nfunction tooltipUrl(host: TooltipHost): string {\n const { tooltipId: id, tooltipType: type } = host.dataset;\n const strategy = window.__l5eTooltipUrl ?? defaultStrategy;\n return strategy({ type: type ?? '', id: id ?? '', host });\n}\n\nexport async function showTooltip(host: TooltipHost): Promise<void> {\n /*\n * Trong lúc chờ dynamic import, con trỏ có thể đã rời khỏi phần tử host.\n * Nếu vậy, việc tạo tooltip là không cần thiết và sẽ không có sự kiện\n * `pointerleave` nào được kích hoạt để ẩn tooltip.\n */\n if (!host.hasAttribute('data-tooltip-active')) return;\n\n const tip = document.createElement('div');\n tip.className = 'tp';\n tip.innerHTML = '<div class=\"tp-loading\">Loading...</div>';\n document.body.append(tip);\n\n // --- Cleanup ---\n let cleanupAutoUpdate: (() => void) | null = null;\n\n const cleanup = () => {\n if (cleanupAutoUpdate) {\n cleanupAutoUpdate();\n cleanupAutoUpdate = null;\n }\n if (document.body.contains(tip)) tip.remove();\n };\n\n host.addEventListener('pointerleave', cleanup);\n\n // Con trỏ đã rời trước khi listener được gắn\n if (!host.hasAttribute('data-tooltip-active')) {\n host.removeEventListener('pointerleave', cleanup);\n tip.remove();\n return;\n }\n\n // --- Position: autoUpdate thay thế manual scroll/resize ---\n cleanupAutoUpdate = autoUpdate(host, tip, () => position(host, tip));\n\n // --- Fetch nội dung từ server ---\n try {\n const html = await fetch(tooltipUrl(host), {\n headers: { Accept: 'text/html' },\n }).then((r) => r.text());\n\n if (!document.body.contains(tip)) return;\n\n tip.innerHTML = html;\n await position(host, tip);\n } catch {\n if (document.body.contains(tip)) {\n tip.innerHTML = '<div class=\"tp-error\">Không thể tải tooltip</div>';\n }\n }\n}\n\n/**\n * Mobile: hiển thị tooltip dạng fullscreen popup.\n * Nếu host có data-href, thêm nút \"Xem chi tiết\" dẫn đến link đó.\n */\nexport async function showTooltipMobile(host: TooltipHost): Promise<void> {\n const overlay = document.createElement('div');\n overlay.className = 'tp-overlay';\n\n const popup = document.createElement('div');\n popup.className = 'tp-mobile';\n popup.innerHTML = '<div class=\"tp-loading\">Loading...</div>';\n\n overlay.append(popup);\n document.body.append(overlay);\n document.body.style.overflow = 'hidden';\n\n const cleanup = () => {\n overlay.remove();\n document.body.style.overflow = '';\n };\n\n // Đóng khi bấm vào overlay (bên ngoài popup)\n overlay.addEventListener('click', (e) => {\n if (e.target === overlay) cleanup();\n });\n\n try {\n const html = await fetch(tooltipUrl(host), {\n headers: { Accept: 'text/html' },\n }).then((r) => r.text());\n\n popup.innerHTML = '';\n\n // Nút đóng\n const closeBtn = document.createElement('button');\n closeBtn.className = 'tp-mobile-close';\n closeBtn.innerHTML = '✕';\n closeBtn.addEventListener('click', cleanup);\n popup.append(closeBtn);\n\n // Nội dung\n const content = document.createElement('div');\n content.className = 'tp-mobile-content';\n content.innerHTML = html;\n popup.append(content);\n\n // Nút \"Xem chi tiết\" nếu có data-href\n const href = host.dataset.href;\n if (href) {\n const link = document.createElement('a');\n link.className = 'tp-mobile-link';\n link.href = href;\n link.textContent = 'Xem chi tiết';\n popup.append(link);\n }\n } catch {\n popup.innerHTML = '<div class=\"tp-error\">Không thể tải tooltip</div>';\n }\n}\n\n/**\n * Khi tooltip cao hơn 60% viewport, bỏ qua placement trên/dưới host\n * và căn giữa theo chiều dọc màn hình + giới hạn maxHeight để scroll.\n */\nfunction centerFallback(): Middleware {\n return {\n name: 'centerFallback',\n fn({ rects }) {\n const vh = window.innerHeight;\n const padding = 8;\n\n if (rects.floating.height <= vh * 0.6) return {};\n\n return {\n y: window.scrollY + Math.max(padding, (vh - rects.floating.height) / 2),\n data: { centered: true, maxHeight: vh - padding * 2 },\n };\n },\n };\n}\n\nfunction position(host: TooltipHost, tip: HTMLDivElement): Promise<void> {\n const preferredPlacement = host.dataset.tooltipPlacement;\n const placement = preferredPlacement ?? 'left';\n\n return computePosition(host, tip, {\n placement,\n middleware: [offset(6), flip(), shift({ padding: 5 }), centerFallback(), hide()],\n }).then(({ x, y, middlewareData }) => {\n Object.assign(tip.style, { left: `${x}px`, top: `${y}px` });\n\n tip.style.visibility = middlewareData.hide?.referenceHidden ? 'hidden' : 'visible';\n\n const center = middlewareData.centerFallback as { centered?: boolean; maxHeight?: number };\n if (center?.centered) {\n tip.style.maxHeight = `${center.maxHeight}px`;\n tip.style.overflowY = 'auto';\n } else {\n tip.style.maxHeight = '';\n tip.style.overflowY = '';\n }\n });\n}\n"],"mappings":";;;AAeA,SAAS,IAA0B;CAEjC,IAAM,IAAY,UAAU,UAAU,YAAY,GAC5C,IACJ,+EAA+E,KAAK,CAAS,GAGzF,IAAgB,OAAO,WAAW,oBAAoB,CAAC,CAAC;CAE9D,OAAO,KAAY;AACrB;AAKA,SAAgB,IAAqB;CACnC,IAAM,IAAkB,SAAS,iBAA8B,mBAAmB;CAClF,IAAI,EAAgB,WAAW,GAAG;CAElC,IAAM,IAAS,EAAe;CAE9B,EAAgB,SAAS,MAAY;EAC/B,EAAQ,aAAa,0BAA0B,MACnD,EAAQ,aAAa,4BAA4B,MAAM,GAEnD,IACF,EAAQ,iBAAiB,SAAS,OAAO,MAAM;GAC7C,EAAE,eAAe;GACjB,IAAM,EAAE,yBAAsB,MAAA,QAAA,QAAA,CAAA,CAAA,WAAA,CAAA;GAC9B,EAAkB,CAAO;EAC3B,CAAC,KAKD,EAAQ,iBAAiB,sBAAsB;GAC7C,EAAQ,aAAa,uBAAuB,MAAM;EACpD,CAAC,GACD,EAAQ,iBAAiB,sBAAsB;GAC7C,EAAQ,gBAAgB,qBAAqB;EAC/C,CAAC,GACD,EAAQ,iBACN,gBACA,YAAY;GACV,IAAM,EAAE,mBAAgB,MAAA,QAAA,QAAA,CAAA,CAAA,WAAA,CAAA;GACxB,EAAY,CAAO;EACrB,GACA,EAAE,SAAS,GAAK,CAClB;CAEJ,CAAC;AACH;AAGA,SAAgB,IAA6B;CAE3C,IAAI,OAAO,mBAAmB;CAG9B,IAAM,IAAW,IAAI,kBAAkB,MAAc;EACnD,IAAI,IAAa;EAqBjB,AAnBA,EAAU,SAAS,MAAa;GAC9B,AAAI,EAAS,SAAS,eAAe,EAAS,WAAW,SAAS,KAEhE,EAAS,WAAW,S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M,YAAY,IACtB,EAAI,MAAM,YAAY;CAE1B,CAAC;AACH"}
|
|
1
|
+
{"version":3,"file":"tooltip.js","names":[],"sources":["../src/tooltip/tooltip-loader.ts","../src/tooltip/index.ts"],"sourcesContent":["// tooltip-loader.ts\n// File này chỉ làm nhiệm vụ wake up tooltip khi cần thiết\n\n// Định nghĩa kiểu cho tooltip host element\ntype TooltipHost = HTMLElement & {\n dataset: {\n tooltipId: string;\n tooltipType?: string;\n };\n};\n\n/**\n * Kiểm tra xem thiết bị hiện tại có phải là thiết bị di động hay không\n * @returns true nếu là thiết bị di động\n */\nfunction isMobileDevice(): boolean {\n // Kiểm tra User Agent\n const userAgent = navigator.userAgent.toLowerCase();\n const isMobile =\n /android|webos|iphone|ipad|ipod|blackberry|iemobile|opera mini|mobile|tablet/i.test(userAgent);\n\n // Kiểm tra thêm kích thước màn hình (dưới 768px thường được coi là thiết bị di động)\n const isTouchScreen = window.matchMedia('(max-width: 768px)').matches;\n\n return isMobile || isTouchScreen;\n}\n\n/**\n * Hàm khởi tạo tooltip, chỉ load runtime khi cần thiết\n */\nexport function initTooltips(): void {\n const tooltipTriggers = document.querySelectorAll<TooltipHost>('[data-tooltip-id]');\n if (tooltipTriggers.length === 0) return;\n\n const mobile = isMobileDevice();\n\n tooltipTriggers.forEach((trigger) => {\n if (trigger.hasAttribute('data-tooltip-initialized')) return;\n trigger.setAttribute('data-tooltip-initialized', 'true');\n\n if (mobile) {\n trigger.addEventListener('click', async (e) => {\n e.preventDefault();\n const { showTooltipMobile } = await import('./tooltip-runtime');\n showTooltipMobile(trigger);\n });\n } else {\n // Keep the interaction state explicitly. Firefox can lose the\n // `:hover` match while the lazily-loaded runtime is being evaluated,\n // even though the pointer is still over the trigger.\n trigger.addEventListener('pointerenter', () => {\n trigger.setAttribute('data-tooltip-active', 'true');\n });\n trigger.addEventListener('pointerleave', () => {\n trigger.removeAttribute('data-tooltip-active');\n });\n trigger.addEventListener(\n 'pointerenter',\n async () => {\n const { showTooltip } = await import('./tooltip-runtime');\n showTooltip(trigger);\n },\n { passive: true },\n );\n }\n });\n}\n\n// Thêm một MutationObserver để theo dõi các phần tử DOM mới (cho React components)\nexport function setupTooltipObserver(): void {\n // Kiểm tra xem đã có observer chưa\n if (window.__tooltipObserver) return;\n\n // Observer theo dõi khi có phần tử mới được thêm vào DOM\n const observer = new MutationObserver((mutations) => {\n let shouldInit = false;\n\n mutations.forEach((mutation) => {\n if (mutation.type === 'childList' && mutation.addedNodes.length > 0) {\n // Kiểm tra xem có phần tử tooltip nào mới được thêm vào không\n mutation.addedNodes.forEach((node) => {\n if (node.nodeType === Node.ELEMENT_NODE) {\n const element = node as HTMLElement;\n // Kiểm tra nếu phần tử có data-tooltip-id hoặc chứa phần tử con có data-tooltip-id\n if (\n element.hasAttribute('data-tooltip-id') ||\n element.querySelector('[data-tooltip-id]')\n ) {\n shouldInit = true;\n }\n }\n });\n }\n });\n\n // Chỉ gọi initTooltips nếu có phát hiện tooltip mới\n if (shouldInit) {\n initTooltips();\n }\n });\n\n // Bắt đầu theo dõi toàn bộ DOM\n observer.observe(document.body, {\n childList: true,\n subtree: true,\n });\n\n // Lưu observer vào window để tránh tạo nhiều observer\n window.__tooltipObserver = observer;\n}\n\n// Typescript declaration cho window object\ndeclare global {\n interface Window {\n __tooltipObserver?: MutationObserver;\n }\n}\n","export { initTooltips, setupTooltipObserver } from './tooltip-loader';\nexport { configureTooltip } from './tooltip-config';\nexport type { TooltipUrlContext, TooltipUrlStrategy } from './tooltip-config';\nimport type { TooltipHost } from './tooltip-config';\n\n// Keep the public API lazy too: a static re-export makes the library build\n// inline the runtime into this entry and erases the loader's import boundary.\nexport async function showTooltip(host: TooltipHost): Promise<void> {\n const runtime = await import('./tooltip-runtime');\n return runtime.showTooltip(host);\n}\n\nexport async function showTooltipMobile(host: TooltipHost): Promise<void> {\n const runtime = await import('./tooltip-runtime');\n return runtime.showTooltipMobile(host);\n}\n"],"mappings":";;AAeA,SAAS,IAA0B;CAEjC,IA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S;CACX,CAAC,GAGD,OAAO,oBAAoB;AAC7B;;;ACtGA,eAAsB,EAAY,GAAkC;CAElE,QAAO,MADe,OAAO,iCAAA,CACd,YAAY,CAAI;AACjC;AAEA,eAAsB,EAAkB,GAAkC;CAExE,QAAO,MADe,OAAO,iCAAA,CACd,kBAAkB,CAAI;AACvC"}
|
|
@@ -110,16 +110,16 @@ function v(e = {}) {
|
|
|
110
110
|
maxSize: t.maxSize,
|
|
111
111
|
includeDependenciesRecursively: e.mode === "compact"
|
|
112
112
|
})),
|
|
113
|
-
{
|
|
114
|
-
name: (e) => s.get(e)?.group === "lazy-react-runtime" ? "lazy-react-runtime" : null,
|
|
115
|
-
includeDependenciesRecursively: !0
|
|
116
|
-
},
|
|
117
113
|
{
|
|
118
114
|
name: (e) => {
|
|
119
115
|
let t = s.get(e)?.group;
|
|
120
116
|
return t === "lazy-react-runtime" ? null : t || null;
|
|
121
117
|
},
|
|
122
118
|
includeDependenciesRecursively: !1
|
|
119
|
+
},
|
|
120
|
+
{
|
|
121
|
+
name: (e) => s.get(e)?.group === "lazy-react-runtime" ? "lazy-react-runtime" : null,
|
|
122
|
+
includeDependenciesRecursively: !0
|
|
123
123
|
}
|
|
124
124
|
];
|
|
125
125
|
},
|
|
@@ -130,13 +130,15 @@ function v(e = {}) {
|
|
|
130
130
|
warnings: [...l],
|
|
131
131
|
chunks: Object.values(t).flatMap((t) => {
|
|
132
132
|
if (t.type !== "chunk") return [];
|
|
133
|
-
let n =
|
|
133
|
+
let n = new Set(Object.keys(t.modules).map((e) => s.get(e)?.group));
|
|
134
|
+
if (e.mode === "compact" && n.has("global-owner") && n.has("lazy-react-runtime")) throw Error(`[l5e chunking] ${t.fileName} mixes global-owned and lazy island runtime modules. Keep eager owners separate before recursively collecting the lazy runtime.`);
|
|
135
|
+
let r = t.facadeModuleId ? u(t.facadeModuleId) : null, i = r === "src/client.global.ts" ? "global" : r && /(?:^|\/)react\//.test(r) ? "island" : t.isEntry || t.isDynamicEntry ? "page" : "shared";
|
|
134
136
|
return [{
|
|
135
137
|
file: t.fileName,
|
|
136
|
-
kind:
|
|
138
|
+
kind: i,
|
|
137
139
|
canonicalShared: e.mode === "compact" && t.name === "shared",
|
|
138
140
|
canonicalGlobal: e.mode === "compact" && t.name === "global-owner",
|
|
139
|
-
source:
|
|
141
|
+
source: r,
|
|
140
142
|
bytes: Buffer.byteLength(t.code),
|
|
141
143
|
imports: t.imports,
|
|
142
144
|
dynamicImports: t.dynamicImports,
|
|
@@ -424,12 +426,12 @@ function R(e = {}) {
|
|
|
424
426
|
resolveId(e) {
|
|
425
427
|
return e === y ? "\0virtual:l5e-views" : e === b ? "\0virtual:l5e-route" : e === x ? "\0virtual:l5e-ssr-entry" : e === S ? "\0virtual:l5e-global-loader" : e === C ? "\0virtual:l5e-island-strategies" : e === w ? "\0virtual:l5e-islands" : e === T ? "\0virtual:l5e-compact-renderer" : e === E ? "\0virtual:l5e-actions" : e === D ? "\0virtual:l5e-middleware" : null;
|
|
426
428
|
},
|
|
427
|
-
async transform(t, n,
|
|
428
|
-
if (n.replace(/\\/g, "/").endsWith("src/client.global.ts") && !
|
|
429
|
-
code: `import '@withl5e/l5e/island/${e.chunking && e.chunking.mode === "compact" ? "compact-runtime" : "runtime"}';\n${t}`,
|
|
429
|
+
async transform(t, n, a) {
|
|
430
|
+
if (n.replace(/\\/g, "/").endsWith("src/client.global.ts") && !a?.ssr) return {
|
|
431
|
+
code: `import '@withl5e/l5e/island/${i && e.chunking && e.chunking.mode === "compact" ? "compact-runtime" : "runtime"}';\n${t}`,
|
|
430
432
|
map: null
|
|
431
433
|
};
|
|
432
|
-
if (!
|
|
434
|
+
if (!a?.ssr) {
|
|
433
435
|
let e = n.replace(/\\/g, "/").match(/\/src\/(.+)\/actions\.(ts|tsx)$/);
|
|
434
436
|
if (e) {
|
|
435
437
|
let n = e[1], r = /export\s+const\s+(\w+)\s*=\s*defineAction\s*\(/g, i = [], a;
|
|
@@ -479,7 +481,7 @@ function R(e = {}) {
|
|
|
479
481
|
} catch (e) {
|
|
480
482
|
throw console.error(`[l5e] Failed to transform JSX in ${n}:`, e), e;
|
|
481
483
|
}
|
|
482
|
-
if (
|
|
484
|
+
if (a?.ssr) {
|
|
483
485
|
let e = t, n = !1;
|
|
484
486
|
if (e = e.replace(/import\.meta\.env\.([a-zA-Z_][a-zA-Z0-9_]*)/g, (e, t) => O.has(t) ? e : (n = !0, `process.env.${t}`)), e = e.replace(/import\.meta\.env\[(['"`])([^'"`]+)\1\]/g, (e, t, r) => O.has(r) ? e : (n = !0, `process.env[${t}${r}${t}]`)), n) return {
|
|
485
487
|
code: e,
|
|
@@ -512,4 +514,4 @@ export const actionRegistry = ${JSON.stringify(e)};`;
|
|
|
512
514
|
//#endregion
|
|
513
515
|
export { R as t };
|
|
514
516
|
|
|
515
|
-
//# sourceMappingURL=vite-plugin-
|
|
517
|
+
//# sourceMappingURL=vite-plugin-Bln1di66.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"vite-plugin-Bln1di66.js","names":["join"],"sources":["../src/core/chunking.ts","../src/core/vite-plugin.ts"],"sourcesContent":["import { createHash } from 'node:crypto';\nimport path from 'node:path';\nimport type { CodeSplittingGroup, ModuleInfo, OutputBundle } from 'rolldown';\n\nexport interface SharedChunkGroup {\n name: string;\n /** Exact package names, including their subpath imports. */\n packages?: string[];\n /** Module specifiers resolved by Vite, including aliases. */\n modules?: string[];\n priority?: number;\n /** Approximate uncompressed maximum; not a hard network byte budget. */\n maxSize?: number;\n}\n\nexport interface ChunkingOptions {\n /**\n * Opt in to at most one global, one page bundle and one canonical shared file.\n * State that must retain identity across page bundles must be listed in `shared`.\n */\n mode?: 'compact';\n shared?: SharedChunkGroup[];\n /** Static UI/runtime roots that join React's canonical lazy activation chunk. */\n islandRuntime?: Pick<SharedChunkGroup, 'packages' | 'modules'>;\n}\n\nexport interface CoreViteOptions {\n /** false leaves chunk placement to Vite; runtime identity protection stays enabled. */\n chunking?: ChunkingOptions | false;\n}\n\nconst normalize = (id: string) => id.replace(/\\\\/g, '/');\nconst digest = (value: string) => createHash('sha256').update(value).digest('hex').slice(0, 8);\n\n/** The last node_modules segment also handles pnpm's nested package layout. */\nfunction packageName(id: string): string | undefined {\n const suffix = normalize(id).split('/node_modules/').at(-1);\n if (suffix === normalize(id)) return undefined;\n const parts = suffix!.split('/');\n return parts[0].startsWith('@') ? parts.slice(0, 2).join('/') : parts[0];\n}\n\ntype Decision = { group: string | null; rule?: string; consumers: string[]; reason: string };\n\n/** One build-time plan drives placement and the diagnostic report. Runtime reads Vite's manifest. */\nexport function createChunkPlanner(options: ChunkingOptions = {}) {\n const rules = options.shared || [];\n const islandRuntimeRule = options.islandRuntime;\n if (\n islandRuntimeRule &&\n !islandRuntimeRule.packages?.length &&\n !islandRuntimeRule.modules?.length\n ) {\n throw new Error('[l5e chunking] islandRuntime needs packages or modules.');\n }\n if (options.mode === 'compact' && rules.length > 1) {\n throw new Error('[l5e chunking] Compact mode accepts one canonical shared group.');\n }\n const names = new Set<string>();\n for (const rule of rules) {\n if (!/^[a-zA-Z0-9][a-zA-Z0-9_-]*$/.test(rule.name) || names.has(rule.name)) {\n throw new Error(`[l5e chunking] Invalid or duplicate shared group: ${rule.name}`);\n }\n if (!rule.packages?.length && !rule.modules?.length) {\n throw new Error(`[l5e chunking] Group ${rule.name} needs packages or modules.`);\n }\n if (rule.maxSize !== undefined && (!Number.isFinite(rule.maxSize) || rule.maxSize <= 0)) {\n throw new Error(`[l5e chunking] Invalid maxSize for ${rule.name}`);\n }\n if (options.mode === 'compact' && rule.maxSize !== undefined) {\n throw new Error(\n `[l5e chunking] Compact mode cannot use maxSize for ${rule.name}; it would split the canonical shared file.`,\n );\n }\n names.add(rule.name);\n }\n let root = '';\n const resolvedRules = new Map<SharedChunkGroup, Set<string>>();\n let resolvedIslandRuntime = new Set<string>();\n const decisions = new Map<string, Decision>();\n const warnings = new Set<string>();\n const portable = (id: string) => {\n const pkg = packageName(id);\n if (pkg) return `npm:${normalize(id).split('/node_modules/').at(-1)}`;\n return normalize(path.relative(root, id));\n };\n\n return {\n async resolve(\n projectRoot: string,\n resolveId: (id: string, importer: string) => Promise<string | null>,\n ) {\n root = projectRoot;\n resolvedRules.clear();\n resolvedIslandRuntime = new Set();\n decisions.clear();\n warnings.clear();\n for (const rule of rules) {\n const ids = new Set<string>();\n for (const specifier of rule.modules || []) {\n const id = await resolveId(specifier, path.join(root, 'index.html'));\n if (!id) throw new Error(`[l5e chunking] Cannot resolve ${specifier} in ${rule.name}`);\n ids.add(id);\n }\n resolvedRules.set(rule, ids);\n }\n if (islandRuntimeRule) {\n for (const specifier of islandRuntimeRule.modules || []) {\n const id = await resolveId(specifier, path.join(root, 'index.html'));\n if (!id) throw new Error(`[l5e chunking] Cannot resolve ${specifier} in islandRuntime`);\n resolvedIslandRuntime.add(id);\n }\n }\n },\n analyze(modules: ModuleInfo[]) {\n decisions.clear();\n const graph = new Map(modules.map((mod) => [mod.id, mod]));\n if (options.mode === 'compact') {\n const reachability = new Map<string, Map<string, boolean>>();\n for (const entry of modules.filter((mod) => mod.isEntry)) {\n const visit = (id: string, lazy: boolean) => {\n const owners = reachability.get(id) || new Map<string, boolean>();\n const previous = owners.get(entry.id);\n if (previous === false || previous === lazy) return;\n owners.set(entry.id, lazy);\n reachability.set(id, owners);\n const module = graph.get(id);\n if (!module) return;\n module.importedIds.forEach((dependency) => visit(dependency, lazy));\n module.dynamicallyImportedIds.forEach((dependency) => visit(dependency, true));\n };\n visit(entry.id, false);\n }\n const globalEntry = modules.find(\n (mod) => mod.isEntry && normalize(mod.id).endsWith('/src/client.global.ts'),\n );\n if (globalEntry) {\n for (const [id, owners] of reachability) {\n if (\n !/\\.css(?:\\?|$)/.test(normalize(id)) &&\n owners.get(globalEntry.id) === true &&\n [...owners.keys()].some((owner) => owner !== globalEntry.id)\n ) {\n throw new Error(\n `[l5e chunking] Compact mode cannot bridge a dynamic-only global overlap: ${portable(id)}. Import it statically from global or place state behind an explicit shared root.`,\n );\n }\n }\n }\n }\n const roots = modules.filter((mod) => mod.isEntry || mod.dynamicImporters.length > 0);\n const consumers = new Map<string, Set<string>>();\n for (const entry of roots) {\n const visited = new Set<string>();\n const visit = (id: string) => {\n if (visited.has(id)) return;\n visited.add(id);\n const mod = graph.get(id);\n if (!mod) return;\n const users = consumers.get(id) || new Set<string>();\n users.add(entry.id);\n consumers.set(id, users);\n mod.importedIds.forEach(visit);\n };\n visit(entry.id);\n }\n const rank = (id: string) => {\n const mod = graph.get(id)!;\n if (!mod.isEntry) return 3;\n if (normalize(id).endsWith('/src/client.global.ts')) return 0;\n if (normalize(id).includes('virtual:l5e-compact-renderer')) return 2;\n if (/\\/react\\//.test(normalize(id)) && !packageName(id)) return 2;\n return 1;\n };\n const matched = new Set<SharedChunkGroup>();\n for (const mod of modules) {\n const users = [...(consumers.get(mod.id) || [])].sort();\n const labels = users.map(portable).sort();\n const matches = rules\n .filter(\n (rule) =>\n resolvedRules.get(rule)?.has(mod.id) ||\n rule.packages?.includes(packageName(mod.id) || ''),\n )\n .sort((a, b) => (b.priority || 0) - (a.priority || 0));\n matches.forEach((rule) => matched.add(rule));\n if (matches.length > 1)\n warnings.add(\n `${portable(mod.id)} matches ${matches.map((r) => r.name).join(', ')}; using ${matches[0].name}.`,\n );\n let group: string | null = null;\n let reason = 'Private dependency stays with its entry or dynamic import.';\n const pkg = packageName(mod.id);\n const islandRuntimeMatch =\n resolvedIslandRuntime.has(mod.id) ||\n islandRuntimeRule?.packages?.includes(pkg || '') === true;\n if (\n options.mode === 'compact' &&\n normalize(mod.id).includes('virtual:l5e-compact-renderer')\n ) {\n group = 'lazy-react-runtime';\n reason = 'Renderer joins the canonical React runtime activation.';\n } else if (\n options.mode === 'compact' &&\n !mod.isEntry &&\n (pkg === 'react' || pkg === 'react-dom' || pkg === 'scheduler') &&\n users.length > 0 &&\n users.every((id) => rank(id) >= 2)\n ) {\n group = 'lazy-react-runtime';\n reason = 'Canonical React runtime is fetched when the first island activates.';\n } else if (!mod.isEntry && users.length && matches.length) {\n // Explicit groups can combine consumers at the same activation tier.\n // Never promote island-only code into global/page, or dynamic-only code\n // into a static entry. Distinct dynamic roots remain separate as well.\n const tier = Math.min(...users.map(rank));\n const activation =\n tier === 3\n ? `lazy-${digest(JSON.stringify(labels))}`\n : ['global', 'page', 'island'][tier];\n group = options.mode === 'compact' ? 'shared' : `shared-${matches[0].name}-${activation}`;\n reason = `Configured group ${matches[0].name}; activation ${activation}.`;\n } else if (options.mode === 'compact' && !mod.isEntry && islandRuntimeMatch) {\n group = 'lazy-react-runtime';\n reason = 'Configured canonical island runtime is fetched with the first island consumer.';\n } else if (\n options.mode === 'compact' &&\n !mod.isEntry &&\n users.some((id) => rank(id) === 0) &&\n users.some((id) => rank(id) > 0)\n ) {\n group = 'global-owner';\n reason = 'Static global/page overlap is exported by the canonical global artifact.';\n } else if (options.mode !== 'compact' && !mod.isEntry && users.length > 1) {\n group = `shared-auto-${digest(JSON.stringify(labels))}`;\n reason = 'Shared by the same static consumers; preserves dynamic import roots.';\n }\n decisions.set(mod.id, { group, rule: matches[0]?.name, consumers: labels, reason });\n }\n for (const rule of rules) {\n if (!matched.has(rule))\n warnings.add(`Group ${rule.name} matched no modules in this client build.`);\n }\n return [...warnings];\n },\n groups(): CodeSplittingGroup[] {\n return [\n ...rules.map((rule) => ({\n name: (id: string) => {\n const decision = decisions.get(id);\n return decision?.rule === rule.name ? decision.group : null;\n },\n maxSize: rule.maxSize,\n includeDependenciesRecursively: options.mode === 'compact',\n })),\n // Reserve eager owners before recursively collecting the lazy UI closure.\n // Otherwise a lazy hook's dynamic import can capture Vite's preload helper\n // and force global to import the entire React renderer chunk for that helper.\n {\n name: (id: string) => {\n const group = decisions.get(id)?.group;\n return group === 'lazy-react-runtime' ? null : group || null;\n },\n includeDependenciesRecursively: false,\n },\n {\n name: (id: string) =>\n decisions.get(id)?.group === 'lazy-react-runtime' ? 'lazy-react-runtime' : null,\n includeDependenciesRecursively: true,\n },\n ];\n },\n report(bundle: OutputBundle) {\n return {\n version: 2,\n mode: options.mode || 'default',\n warnings: [...warnings],\n chunks: Object.values(bundle).flatMap((chunk) => {\n if (chunk.type !== 'chunk') return [];\n const moduleGroups = new Set(\n Object.keys(chunk.modules).map((id) => decisions.get(id)?.group),\n );\n if (\n options.mode === 'compact' &&\n moduleGroups.has('global-owner') &&\n moduleGroups.has('lazy-react-runtime')\n ) {\n throw new Error(\n `[l5e chunking] ${chunk.fileName} mixes global-owned and lazy island runtime modules. ` +\n 'Keep eager owners separate before recursively collecting the lazy runtime.',\n );\n }\n const source = chunk.facadeModuleId ? portable(chunk.facadeModuleId) : null;\n const kind =\n source === 'src/client.global.ts'\n ? 'global'\n : source && /(?:^|\\/)react\\//.test(source)\n ? 'island'\n : chunk.isEntry || chunk.isDynamicEntry\n ? 'page'\n : 'shared';\n return [\n {\n file: chunk.fileName,\n kind,\n canonicalShared: options.mode === 'compact' && chunk.name === 'shared',\n canonicalGlobal: options.mode === 'compact' && chunk.name === 'global-owner',\n source,\n bytes: Buffer.byteLength(chunk.code),\n imports: chunk.imports,\n dynamicImports: chunk.dynamicImports,\n modules: Object.keys(chunk.modules).map((id) => ({\n id: portable(id),\n ...decisions.get(id),\n })),\n },\n ];\n }),\n };\n },\n };\n}\n","import { transform } from 'esbuild';\nimport {\n existsSync,\n mkdirSync,\n readdirSync,\n readFileSync,\n rmSync,\n statSync,\n writeFileSync,\n} from 'fs';\nimport { dirname, join, relative, resolve } from 'path';\nimport type { Plugin, UserConfig } from 'vite';\nimport { findGlobalStyleInput } from './global-style';\nimport { createChunkPlanner, type CoreViteOptions } from './chunking';\nexport type { CoreViteOptions, ChunkingOptions, SharedChunkGroup } from './chunking';\n\nconst VIRTUAL_L5E_VIEWS = 'virtual:l5e-views';\nconst VIRTUAL_L5E_ROUTE = 'virtual:l5e-route';\nconst VIRTUAL_L5E_SSR_ENTRY = 'virtual:l5e-ssr-entry';\nconst VIRTUAL_L5E_GLOBAL_LOADER = 'virtual:l5e-global-loader';\nconst VIRTUAL_L5E_ISLAND_STRATEGIES = 'virtual:l5e-island-strategies';\nconst VIRTUAL_L5E_ISLANDS = 'virtual:l5e-islands';\nconst VIRTUAL_L5E_COMPACT_RENDERER = 'virtual:l5e-compact-renderer';\nconst VIRTUAL_L5E_ACTIONS = 'virtual:l5e-actions';\nconst VIRTUAL_L5E_MIDDLEWARE = 'virtual:l5e-middleware';\n\n/**\n * Vite's built-in env vars on `import.meta.env`. These are statically replaced\n * by Vite itself (DEV/PROD/SSR are booleans, MODE/BASE_URL strings), so the SSR\n * `import.meta.env.* -> process.env.*` rewrite must skip them — otherwise it\n * clobbers Vite defaults (e.g. `import.meta.env.DEV` would become the undefined\n * `process.env.DEV`).\n */\nconst VITE_RESERVED_ENV = new Set(['MODE', 'BASE_URL', 'PROD', 'DEV', 'SSR', 'LEGACY']);\n\n/**\n * Recursively scan directory for .tsx and .ts files\n */\nfunction scanTsFiles(dir: string, fileList: string[] = []): string[] {\n const files = readdirSync(dir);\n\n for (const file of files) {\n const filePath = join(dir, file);\n const stat = statSync(filePath);\n\n if (stat.isDirectory()) {\n // Skip node_modules and dist directories\n if (file === 'node_modules' || file === 'dist' || file === '.git') {\n continue;\n }\n scanTsFiles(filePath, fileList);\n } else if (file.endsWith('.tsx') || file.endsWith('.ts')) {\n fileList.push(filePath);\n }\n }\n\n return fileList;\n}\n\n/**\n * Short hash function for island keys\n */\nfunction shortHash(str: string): string {\n let hash = 0;\n for (let i = 0; i < str.length; i++) {\n hash = (hash << 5) - hash + str.charCodeAt(i);\n hash = hash & hash;\n }\n return Math.abs(hash).toString(16).slice(0, 4);\n}\n\n/**\n * Derive component name from path: \"./react/Counter\" → \"Counter\"\n */\nfunction deriveComponentName(fromPath: string): string {\n const segments = fromPath.split('/');\n let filename = segments[segments.length - 1];\n // Remove extension if present\n filename = filename.replace(/\\.(tsx?|jsx?)$/, '');\n return filename;\n}\n\n/**\n * Create island registry key: \"/src/views/test-island/react/Counter\" → \"Counter_a3f2\"\n */\nfunction makeIslandKey(resolvedPath: string): string {\n const name = deriveComponentName(resolvedPath);\n return `${name}_${shortHash(resolvedPath)}`;\n}\n\n/**\n * Resolve file path with extension (.tsx, .ts, .jsx, .js)\n * Returns the relative path with extension (e.g., \"src/views/.../Counter.tsx\")\n * or null if file not found\n */\nfunction resolveWithExtension(resolvedPath: string, rootDir: string): string | null {\n // resolvedPath: \"/src/views/test-island/react/Counter\" (no extension, leading /)\n const relPath = resolvedPath.replace(/^\\//, ''); // \"src/views/.../Counter\"\n const absBase = resolve(rootDir, relPath);\n\n // Check with extensions\n for (const ext of ['.tsx', '.ts', '.jsx', '.js']) {\n if (existsSync(absBase + ext)) {\n return relPath + ext; // \"src/views/.../Counter.tsx\"\n }\n }\n // Check without extension (file might already have one)\n if (existsSync(absBase)) {\n return relPath;\n }\n return null;\n}\n\n/**\n * Extract island entries from file using regex on JSX source\n */\nfunction extractIslandEntries(\n filePath: string,\n rootDir: string,\n): Array<{ component: string; resolvedPath: string; src: string; key: string }> {\n const content = readFileSync(filePath, 'utf-8');\n const entries: Array<{ component: string; resolvedPath: string; src: string; key: string }> = [];\n\n // Regex scan JSX source (NOT post-transform code).\n // Just find <ClientIsland ... from=\"Y\" ...> — component name derived from path.\n const regex = /<ClientIsland\\s[^>]*?from\\s*=\\s*\"([^\"]+)\"/g;\n\n const seen = new Set<string>();\n let match;\n\n while ((match = regex.exec(content)) !== null) {\n const fromPath = match[1];\n\n // Resolve relative path → absolute\n let resolvedPath: string;\n if (fromPath.startsWith('~/')) {\n // Alias ~/ → /src/ (project convention)\n resolvedPath = '/src/' + fromPath.substring(2);\n } else if (fromPath.startsWith('/src/')) {\n resolvedPath = fromPath;\n } else if (fromPath.startsWith('./') || fromPath.startsWith('../')) {\n const abs = resolve(filePath, '..', fromPath);\n resolvedPath = '/' + relative(rootDir, abs).replace(/\\\\/g, '/');\n } else {\n resolvedPath = fromPath;\n }\n\n // Resolve file extension for manifest compatibility\n const src = resolveWithExtension(resolvedPath, rootDir);\n if (!src) {\n console.warn(\n `[l5e] Island component not found: ${resolvedPath} (from ${fromPath} in ${filePath})`,\n );\n continue;\n }\n\n const key = makeIslandKey(resolvedPath);\n if (!seen.has(key)) {\n seen.add(key);\n entries.push({\n component: deriveComponentName(resolvedPath),\n resolvedPath,\n src, // \"src/views/.../Counter.tsx\" — matches manifest key format\n key,\n });\n }\n }\n return entries;\n}\n\n/**\n * Extract paths from useCss and useClientJs calls using regex\n */\nfunction extractPathsFromFile(filePath: string, rootDir: string): { css: string[]; js: string[] } {\n const content = readFileSync(filePath, 'utf-8');\n const css: string[] = [];\n const js: string[] = [];\n\n // Regex patterns to match useCss('path') or useCss(\"path\")\n // Handles single and double quotes, and escaped quotes\n const useCssPattern = /useCss\\s*\\(\\s*['\"]([^'\"]+)['\"]\\s*,?\\s*\\)/g;\n const useClientJsPattern = /useClientJs\\s*\\(\\s*['\"]([^'\"]+)['\"]\\s*,?\\s*\\)/g;\n\n let match;\n\n // Extract CSS paths\n while ((match = useCssPattern.exec(content)) !== null) {\n const path = match[1];\n // Convert relative path to absolute if needed\n if (path.startsWith('/src/')) {\n css.push(path);\n } else if (path.startsWith('./') || path.startsWith('../')) {\n // Resolve relative path\n const absolutePath = resolve(filePath, '..', path);\n const relativePath = '/' + relative(rootDir, absolutePath).replace(/\\\\/g, '/');\n css.push(relativePath);\n } else {\n css.push(path);\n }\n }\n\n // Extract JS paths\n while ((match = useClientJsPattern.exec(content)) !== null) {\n const path = match[1];\n if (path.startsWith('/src/')) {\n js.push(path);\n } else if (path.startsWith('./') || path.startsWith('../')) {\n const absolutePath = resolve(filePath, '..', path);\n const relativePath = '/' + relative(rootDir, absolutePath).replace(/\\\\/g, '/');\n js.push(relativePath);\n } else {\n js.push(path);\n }\n }\n\n return { css, js };\n}\n\n/**\n * Auto-discover bundler input entries from useCss and useClientJs calls\n */\nfunction discoverBundlerInput(rootDir: string): {\n input: Record<string, string>;\n islandRegistry: Map<string, string>;\n pathToKey: Map<string, string>;\n keyToSrc: Map<string, string>;\n actionRegistry: Map<string, { modulePath: string; actionName: string }>;\n} {\n const input: Record<string, string> = {};\n const srcDir = join(rootDir, 'src');\n\n // Island registries\n const islandRegistry = new Map<string, string>(); // key → resolvedPath\n const pathToKey = new Map<string, string>(); // resolvedPath → key\n const keyToSrc = new Map<string, string>(); // key → src (manifest-compatible path with extension)\n\n // Action registry: actionKey → { modulePath, actionName }\n const actionRegistry = new Map<string, { modulePath: string; actionName: string }>();\n\n try {\n // Check if src directory exists\n if (!statSync(srcDir).isDirectory()) {\n return { input, islandRegistry, pathToKey, keyToSrc, actionRegistry };\n }\n\n // Check if src/client.global.ts exists and add it as an entry\n const globalTsPath = join(rootDir, 'src', 'client.global.ts');\n if (existsSync(globalTsPath)) {\n input['global'] = globalTsPath;\n console.log('[l5e] Detected src/client.global.ts and added as entry');\n }\n\n const globalStyleInput = findGlobalStyleInput(rootDir);\n if (globalStyleInput) {\n input['global-style'] = globalStyleInput;\n console.log('[l5e] Detected src/global.css and added as global stylesheet');\n }\n\n // Scan all .tsx and .ts files\n const tsFiles = scanTsFiles(srcDir);\n\n // Extract all paths\n const allCssPaths = new Set<string>();\n const allJsPaths = new Set<string>();\n\n for (const file of tsFiles) {\n const { css, js } = extractPathsFromFile(file, rootDir);\n css.forEach((path) => allCssPaths.add(path));\n js.forEach((path) => allJsPaths.add(path));\n\n // Extract island entries\n const islandEntries = extractIslandEntries(file, rootDir);\n for (const entry of islandEntries) {\n islandRegistry.set(entry.key, entry.resolvedPath);\n pathToKey.set(entry.resolvedPath, entry.key);\n keyToSrc.set(entry.key, entry.src);\n }\n\n // Extract action entries from actions.ts/tsx files\n const normalizedFile = file.replace(/\\\\/g, '/');\n if (/\\/actions\\.(ts|tsx)$/.test(normalizedFile)) {\n const content = readFileSync(file, 'utf-8');\n const actionExportRegex = /export\\s+const\\s+(\\w+)\\s*=\\s*defineAction\\s*\\(/g;\n let actionMatch;\n\n // Compute modulePath: relative path from src/ to parent dir\n const relFromSrc = relative(srcDir, dirname(file)).replace(/\\\\/g, '/');\n const modulePath = relFromSrc || '.';\n\n while ((actionMatch = actionExportRegex.exec(content)) !== null) {\n const actionName = actionMatch[1];\n const actionKey = `${actionName}_${shortHash(modulePath)}`;\n actionRegistry.set(actionKey, { modulePath, actionName });\n }\n }\n }\n\n // Convert paths to bundler input entries\n // CSS files\n for (const cssPath of allCssPaths) {\n // Remove leading /src/ and convert to relative path\n const relativePath = cssPath.startsWith('/src/')\n ? cssPath.substring(1) // Remove leading /\n : cssPath.startsWith('/')\n ? cssPath.substring(1)\n : cssPath;\n\n const absolutePath = resolve(rootDir, relativePath);\n\n // src/global.css is already a dedicated convention entry. Keeping one\n // Separate input entries avoid collisions if a shared layout also calls useCss().\n if (globalStyleInput && resolve(absolutePath) === resolve(globalStyleInput)) {\n continue;\n }\n\n // Only add if file exists\n if (!existsSync(absolutePath)) {\n console.warn(`[l5e] CSS file not found: ${absolutePath} (from ${cssPath})`);\n continue;\n }\n\n // Generate entry name from path (e.g., /src/views/home/home.css -> views-home-home)\n const entryName = relativePath\n .replace(/^src\\//, '')\n .replace(/\\.css$/, '')\n .replace(/\\//g, '-')\n .replace(/\\\\/g, '-');\n\n input[entryName] = absolutePath;\n }\n\n // JS/TS files\n for (const jsPath of allJsPaths) {\n const relativePath = jsPath.startsWith('/src/')\n ? jsPath.substring(1)\n : jsPath.startsWith('/')\n ? jsPath.substring(1)\n : jsPath;\n\n const absolutePath = resolve(rootDir, relativePath);\n\n // Only add if file exists\n if (!existsSync(absolutePath)) {\n console.warn(`[l5e] JS/TS file not found: ${absolutePath} (from ${jsPath})`);\n continue;\n }\n\n // Generate entry name from path\n const entryName = relativePath\n .replace(/^src\\//, '')\n .replace(/\\.(ts|tsx|js|jsx)$/, '')\n .replace(/\\//g, '-')\n .replace(/\\\\/g, '-');\n\n input[entryName] = absolutePath;\n }\n\n // Add island component files to the bundler input so they appear in the manifest.\n // server.ts looks up manifest at runtime to resolve per-page island URLs.\n for (const [key, src] of keyToSrc) {\n const absolutePath = resolve(rootDir, src);\n input[`island-${key}`] = absolutePath;\n }\n\n if (islandRegistry.size > 0) {\n console.log(`[l5e] Detected ${islandRegistry.size} island(s)`);\n }\n if (actionRegistry.size > 0) {\n console.log(`[l5e] Detected ${actionRegistry.size} action(s)`);\n }\n } catch (error) {\n // Silently fail if directory doesn't exist or other errors\n console.warn('[l5e] Failed to discover bundler input:', error);\n }\n\n return { input, islandRegistry, pathToKey, keyToSrc, actionRegistry };\n}\n\n/**\n * Inject __key prop into ClientIsland calls\n * Use anchor-based approach to avoid fragile regex with nested objects\n */\nfunction injectIslandKeys(\n code: string,\n fileId: string,\n rootDir: string,\n pathToKey: Map<string, string>,\n keyToSrc: Map<string, string>,\n): string {\n // After esbuild, code has form:\n // jsxFactory(ClientIsland, { from: \"./react/Counter\", props: { n: 5 } })\n // ^anchor ^find from here\n\n const result: string[] = [];\n let lastIndex = 0;\n\n // Find each position \"ClientIsland,\" (anchor)\n const anchorRegex = /ClientIsland\\s*,\\s*\\{/g;\n let anchorMatch;\n\n while ((anchorMatch = anchorRegex.exec(code)) !== null) {\n const searchStart = anchorMatch.index + anchorMatch[0].length;\n\n // Scan for from: \"...\" in window ~500 chars after anchor\n const window = code.substring(searchStart, searchStart + 500);\n const fromMatch = /from:\\s*\"([^\"]+)\"/.exec(window);\n\n if (!fromMatch) continue;\n\n const fromPath = fromMatch[1];\n\n // Resolve path (handle ~/ alias)\n let resolved: string;\n if (fromPath.startsWith('~/')) {\n resolved = '/src/' + fromPath.substring(2);\n } else if (fromPath.startsWith('/src/')) {\n resolved = fromPath;\n } else if (fromPath.startsWith('./') || fromPath.startsWith('../')) {\n const abs = resolve(fileId, '..', fromPath);\n resolved = '/' + relative(rootDir, abs).replace(/\\\\/g, '/');\n } else {\n resolved = fromPath;\n }\n\n const key = pathToKey.get(resolved);\n if (!key) continue;\n\n const src = keyToSrc.get(key);\n if (!src) continue;\n\n // Inject __key and __src right after from: \"...\"\n const insertPos = searchStart + fromMatch.index + fromMatch[0].length;\n result.push(code.substring(lastIndex, insertPos));\n result.push(`, __key: \"${key}\", __src: \"${src}\"`);\n lastIndex = insertPos;\n }\n\n result.push(code.substring(lastIndex));\n return result.join('');\n}\n\nexport function coreVite(options: CoreViteOptions = {}): Plugin {\n let rootDir: string = process.cwd();\n let clientBuild = false;\n const planner = options.chunking === false ? null : createChunkPlanner(options.chunking);\n let islandRegistry = new Map<string, string>();\n let pathToKey = new Map<string, string>();\n let keyToSrc = new Map<string, string>();\n let actionRegistry = new Map<string, { modulePath: string; actionName: string }>();\n\n return {\n name: 'l5e-jsx-classic',\n enforce: 'pre',\n\n configResolved(resolvedConfig) {\n // Store root directory for later use\n rootDir = resolvedConfig.root || process.cwd();\n clientBuild = resolvedConfig.command === 'build' && !resolvedConfig.build.ssr;\n },\n\n async buildStart() {\n if (clientBuild && planner) {\n await planner.resolve(rootDir, async (id, importer) => {\n const resolved = await this.resolve(id, importer);\n return resolved && !resolved.external ? resolved.id : null;\n });\n }\n },\n\n generateBundle(_options, bundle) {\n if (clientBuild && planner) {\n this.emitFile({\n type: 'asset',\n fileName: '.vite/l5e-chunks.json',\n source: JSON.stringify(planner.report(bundle), null, 2),\n });\n }\n },\n\n handleHotUpdate({ file, server }) {\n const relPath = relative(rootDir, file);\n\n // Re-scan action registry when an actions file changes\n if (/actions\\.(ts|tsx)$/.test(file)) {\n const discovered = discoverBundlerInput(rootDir);\n actionRegistry = discovered.actionRegistry;\n // Invalidate the virtual:l5e-actions module so server picks up new registry\n const mod = server.moduleGraph.getModuleById('\\0' + VIRTUAL_L5E_ACTIONS);\n if (mod) {\n server.moduleGraph.invalidateModule(mod);\n }\n console.log(\n `[l5e] Action file changed: ${relPath} — re-scanned ${actionRegistry.size} action(s)`,\n );\n }\n\n // Allow Vite's default HMR for CSS and client-side JS files\n if (file.endsWith('.css')) {\n console.log(`[l5e] CSS changed: ${relPath} - using Vite HMR`);\n return; // Let Vite handle CSS HMR\n }\n\n if (file.includes('client.ts')) {\n console.log(`[l5e] Client JS changed: ${relPath} - using Vite HMR`);\n return; // Let Vite handle client JS HMR\n }\n\n // Trigger full page reload for SSR-related file changes (components, loaders, routes)\n // This ensures that server-side rendered components update properly\n if (file.includes('/src/') || file.includes('\\\\src\\\\')) {\n console.log(`[l5e] SSR file changed: ${relPath} - triggering full reload`);\n server.ws.send({\n type: 'full-reload',\n path: '*',\n });\n return []; // Prevent Vite's default HMR behavior\n }\n },\n\n buildEnd(error) {\n if (!error && clientBuild && planner) {\n const modules = [...this.getModuleIds()]\n .map((id) => this.getModuleInfo(id))\n .filter((mod) => mod !== null);\n for (const warning of planner.analyze(modules)) this.warn(`[l5e chunking] ${warning}`);\n }\n // Cleanup temporary files after build\n const tempDir = join(rootDir, '.l5e-temp');\n if (existsSync(tempDir)) {\n try {\n rmSync(tempDir, { recursive: true, force: true });\n console.log('[l5e] Cleaned up temporary files');\n } catch (error) {\n console.warn('[l5e] Failed to cleanup temporary files:', error);\n }\n }\n },\n\n writeBundle(_options, _bundle) {\n // Emit action registry JSON for production server\n if (actionRegistry.size > 0) {\n const outDir = join(rootDir, 'dist', 'server');\n if (!existsSync(outDir)) {\n mkdirSync(outDir, { recursive: true });\n }\n const registryObj = Object.fromEntries(actionRegistry);\n writeFileSync(join(outDir, 'action-registry.json'), JSON.stringify(registryObj), 'utf-8');\n console.log(`[l5e] Wrote action-registry.json (${actionRegistry.size} actions)`);\n }\n },\n\n config(userConfig) {\n // Auto-discover bundler input from useCss and useClientJs\n const projectRoot = userConfig.root || process.cwd();\n const output = userConfig.build?.rolldownOptions?.output;\n const configureChunks = !userConfig.build?.ssr && planner !== null;\n if (\n configureChunks &&\n (Array.isArray(output) || output?.manualChunks || output?.codeSplitting !== undefined)\n ) {\n throw new Error(\n '[l5e chunking] Use coreVite({ chunking: { shared: [...] } }) or set chunking: false when configuring raw Rolldown chunk placement.',\n );\n }\n const discovered = discoverBundlerInput(projectRoot);\n\n // Store island registries for use in other hooks\n islandRegistry = discovered.islandRegistry;\n pathToKey = discovered.pathToKey;\n keyToSrc = discovered.keyToSrc;\n actionRegistry = discovered.actionRegistry;\n\n // Merge with existing rolldownOptions.input if any\n const existingInput = userConfig.build?.rolldownOptions?.input || {};\n const mergedInput =\n typeof existingInput === 'object' && !Array.isArray(existingInput)\n ? { ...discovered.input, ...existingInput }\n : discovered.input;\n if (options.chunking && options.chunking.mode === 'compact') {\n mergedInput['l5e-compact-renderer'] = VIRTUAL_L5E_COMPACT_RENDERER;\n }\n\n return {\n build: {\n ...(options.chunking && options.chunking.mode === 'compact'\n ? {\n modulePreload: {\n resolveDependencies: (\n _filename: string,\n dependencies: string[],\n context: { hostType: 'html' | 'js' },\n ) =>\n context.hostType === 'html'\n ? dependencies.filter(\n (dependency) => !/\\.[cm]?js(?:\\?|$)/.test(dependency),\n )\n : dependencies,\n },\n }\n : {}),\n rolldownOptions: {\n ...userConfig.build?.rolldownOptions,\n input: Object.keys(mergedInput).length > 0 ? mergedInput : undefined,\n // Preserve exports for island component entries — without this,\n // The bundler tree-shakes their exports since nothing imports them\n // (they're loaded at runtime via dynamic import from the island runtime).\n preserveEntrySignatures: configureChunks ? 'allow-extension' : 'exports-only',\n ...(configureChunks\n ? {\n output: {\n ...output,\n strictExecutionOrder: true,\n codeSplitting: { groups: planner!.groups() },\n entryFileNames: (chunk) => {\n const source = chunk.facadeModuleId?.replace(/\\\\/g, '/') || '';\n if (source.endsWith('/src/client.global.ts'))\n return 'assets/global-[hash].js';\n if (/\\/react\\//.test(source))\n return chunk.name.startsWith('island-')\n ? 'assets/[name]-[hash].js'\n : 'assets/island-[name]-[hash].js';\n return 'assets/bundle-[name]-[hash].js';\n },\n chunkFileNames: (chunk) =>\n chunk.name.startsWith('shared-')\n ? 'assets/[name]-[hash].js'\n : chunk.name === 'shared'\n ? 'assets/shared-[hash].js'\n : chunk.name === 'lazy-react-runtime'\n ? 'assets/lazy-react-runtime-[hash].js'\n : chunk.isDynamicEntry\n ? 'assets/bundle-[name]-[hash].js'\n : 'assets/shared-[name]-[hash].js',\n },\n }\n : {}),\n },\n },\n } satisfies UserConfig;\n },\n\n resolveId(id) {\n if (id === VIRTUAL_L5E_VIEWS) {\n return '\\0' + VIRTUAL_L5E_VIEWS;\n }\n if (id === VIRTUAL_L5E_ROUTE) {\n return '\\0' + VIRTUAL_L5E_ROUTE;\n }\n if (id === VIRTUAL_L5E_SSR_ENTRY) {\n return '\\0' + VIRTUAL_L5E_SSR_ENTRY;\n }\n if (id === VIRTUAL_L5E_GLOBAL_LOADER) {\n return '\\0' + VIRTUAL_L5E_GLOBAL_LOADER;\n }\n if (id === VIRTUAL_L5E_ISLAND_STRATEGIES) {\n return '\\0' + VIRTUAL_L5E_ISLAND_STRATEGIES;\n }\n if (id === VIRTUAL_L5E_ISLANDS) {\n return '\\0' + VIRTUAL_L5E_ISLANDS;\n }\n if (id === VIRTUAL_L5E_COMPACT_RENDERER) {\n return '\\0' + VIRTUAL_L5E_COMPACT_RENDERER;\n }\n if (id === VIRTUAL_L5E_ACTIONS) {\n return '\\0' + VIRTUAL_L5E_ACTIONS;\n }\n if (id === VIRTUAL_L5E_MIDDLEWARE) {\n return '\\0' + VIRTUAL_L5E_MIDDLEWARE;\n }\n return null;\n },\n\n async transform(code, id, transformOptions) {\n // Auto-inject island runtime into client.global.ts so it's always loaded globally\n if (id.replace(/\\\\/g, '/').endsWith('src/client.global.ts') && !transformOptions?.ssr) {\n const compactRuntime =\n clientBuild && options.chunking && options.chunking.mode === 'compact';\n return {\n code: `import '@withl5e/l5e/island/${compactRuntime ? 'compact-runtime' : 'runtime'}';\\n${code}`,\n map: null,\n };\n }\n\n // Client-side action transform: replace defineAction exports with fetch stubs\n // Supports actions anywhere under src/ (e.g., src/views/*, src/features/*, etc.)\n if (!transformOptions?.ssr) {\n const normalizedId = id.replace(/\\\\/g, '/');\n const actionMatch = normalizedId.match(/\\/src\\/(.+)\\/actions\\.(ts|tsx)$/);\n if (actionMatch) {\n const modulePath = actionMatch[1];\n\n // Parse exported action names\n const exportRegex = /export\\s+const\\s+(\\w+)\\s*=\\s*defineAction\\s*\\(/g;\n const actions: Array<{ name: string; method: string }> = [];\n let m;\n while ((m = exportRegex.exec(code)) !== null) {\n const name = m[1];\n // Find method for this action — scan from the defineAction( position\n const chunk = code.substring(m.index, m.index + 500);\n const methodMatch = chunk.match(/method:\\s*['\"](\\w+)['\"]/);\n const method = methodMatch ? methodMatch[1].toUpperCase() : 'GET';\n actions.push({ name, method });\n }\n\n if (actions.length > 0) {\n const stubs = actions.map(({ name, method }) => {\n const actionKey = `${name}_${shortHash(modulePath)}`;\n if (method === 'GET') {\n return `export async function ${name}(params) {\n const res = await fetch('/_l5e/action/${actionKey}?' + new URLSearchParams(params));\n if (!res.ok) throw Object.assign(new Error('HTTP ' + res.status), { status: res.status });\n return res;\n}`;\n }\n return `export async function ${name}(body) {\n const res = await fetch('/_l5e/action/${actionKey}', {\n method: '${method}',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify(body),\n });\n if (!res.ok) throw Object.assign(new Error('HTTP ' + res.status), { status: res.status });\n return res;\n}`;\n });\n\n return {\n code: stubs.join('\\n\\n'),\n map: null,\n };\n }\n }\n }\n\n // Skip node_modules\n if (id.includes('node_modules')) {\n return null;\n }\n\n // Skip files in /react/ directories\n if (id.includes('/react/') || id.includes('\\\\react\\\\')) {\n return null;\n }\n\n // Check if this is a JSX/TSX file that needs L5E JSX transformation\n const isJsxFile = /\\.(tsx|jsx)$/.test(id);\n\n if (isJsxFile) {\n try {\n const injected = `import { Fragment as __Fragment, jsxFactory } from \"@withl5e/l5e/jsx-runtime\"\\n${code}`;\n\n // Transform JSX using esbuild with L5E's JSX runtime (async)\n const result = await transform(injected, {\n loader: id.endsWith('.tsx') ? 'tsx' : 'jsx',\n jsx: 'transform',\n jsxFactory: 'jsxFactory',\n jsxFragment: '__Fragment',\n sourcemap: true,\n sourcefile: id,\n target: 'es2020',\n });\n\n let transformedCode = result.code;\n\n // Inject __key and __src for ALL ClientIsland calls\n if (transformedCode.includes('ClientIsland')) {\n transformedCode = injectIslandKeys(transformedCode, id, rootDir, pathToKey, keyToSrc);\n }\n\n return {\n code: transformedCode,\n map: result.map || null,\n };\n } catch (error) {\n // Log error but let Vite handle it\n console.error(`[l5e] Failed to transform JSX in ${id}:`, error);\n throw error;\n }\n }\n\n // Transform import.meta.env thà nh process.env ở server side\n // Server side có thể access tất cả env variables\n // Client side chỉ access được VITE_ env variables\n // Transform nà y chạy ở runtime khi module được load trong SSR context\n if (transformOptions?.ssr) {\n let transformedCode = code;\n let hasChanges = false;\n\n // Thay thế import.meta.env.VARIABLE_NAME thà nh process.env.VARIABLE_NAME\n // Match: import.meta.env.VITE_EVENT_CATEGORY_SLUG\n transformedCode = transformedCode.replace(\n /import\\.meta\\.env\\.([a-zA-Z_][a-zA-Z0-9_]*)/g,\n (match, varName) => {\n // Leave Vite's built-in env vars for Vite to handle.\n if (VITE_RESERVED_ENV.has(varName)) return match;\n hasChanges = true;\n return `process.env.${varName}`;\n },\n );\n\n // Thay thế import.meta.env['VARIABLE_NAME'] hoặc import.meta.env[\"VARIABLE_NAME\"]\n // thà nh process.env['VARIABLE_NAME'] hoặc process.env[\"VARIABLE_NAME\"]\n // Match: import.meta.env['VITE_EVENT_CATEGORY_SLUG'] hoặc import.meta.env[\"VITE_EVENT_CATEGORY_SLUG\"]\n transformedCode = transformedCode.replace(\n /import\\.meta\\.env\\[(['\"`])([^'\"`]+)\\1\\]/g,\n (match, quote, varName) => {\n // Leave Vite's built-in env vars for Vite to handle.\n if (VITE_RESERVED_ENV.has(varName)) return match;\n hasChanges = true;\n return `process.env[${quote}${varName}${quote}]`;\n },\n );\n\n if (hasChanges) {\n return {\n code: transformedCode,\n map: null, // Không cần source map cho env transform\n };\n }\n }\n return null;\n },\n\n load(id) {\n // Virtual module: l5e-views\n if (id === '\\0' + VIRTUAL_L5E_VIEWS) {\n return `\nexport const viewLoaders = import.meta.glob('/src/views/*/loader.{ts,tsx}');\nexport const viewComponents = import.meta.glob('/src/views/*/index.tsx');\n`;\n }\n\n // Virtual module: l5e-route\n if (id === '\\0' + VIRTUAL_L5E_ROUTE) {\n // Load /src/route.ts LAZILY (dynamic import inside the handler) rather\n // than via a static `export { default } from '/src/route.ts'`.\n //\n // A static re-export drags the user's route module — and everything it\n // imports — into entry-server's *static* SSR graph. Route files commonly\n // import the `@withl5e/l5e` barrel (for RedirectException, types, ...),\n // and that barrel re-exports `render` from entry-server. That closes a\n // static import cycle:\n // entry-server → virtual:l5e-route → /src/route.ts → @withl5e/l5e → entry-server\n // On the first dev request Vite can begin evaluating entry-server while\n // it is still suspended awaiting this very import, so `render()` runs\n // before `const __vite_ssr_import_N__ = await import('virtual:l5e-route')`\n // has been assigned — throwing \"Cannot access '__vite_ssr_import_N__'\n // before initialization\". A page reload \"fixes\" it only because the graph\n // is fully warm the second time.\n //\n // Importing lazily removes /src/route.ts from the static graph: entry-server\n // finishes initializing first, and the route module (with its barrel import\n // back to a now-complete entry-server) is pulled only on the first render()\n // call. No manual caching — Vite/ESM caches the evaluated module and later\n // imports still observe HMR invalidations of route.ts.\n return `export default function routeHandler(requestInfo) {\n return import('/src/route.ts').then((mod) => mod.default(requestInfo));\n}`;\n }\n\n // Virtual module: l5e-ssr-entry\n if (id === '\\0' + VIRTUAL_L5E_SSR_ENTRY) {\n return `export { render } from '@withl5e/l5e/entry-server';\nexport { viewActions } from 'virtual:l5e-actions';`;\n }\n\n // Virtual module: l5e-global-loader\n if (id === '\\0' + VIRTUAL_L5E_GLOBAL_LOADER) {\n return `export const globalLoader = import.meta.glob('/src/global-loader.{ts,tsx}', { eager: false });`;\n }\n\n // Virtual module: l5e-actions\n if (id === '\\0' + VIRTUAL_L5E_ACTIONS) {\n const registryObj = Object.fromEntries(actionRegistry);\n return `export const viewActions = import.meta.glob('/src/**/actions.{ts,tsx}');\nexport const actionRegistry = ${JSON.stringify(registryObj)};`;\n }\n\n // Virtual module: l5e-middleware\n if (id === '\\0' + VIRTUAL_L5E_MIDDLEWARE) {\n return `\nconst middlewareModules = import.meta.glob([\n '/src/middleware.{ts,tsx,js,jsx}',\n '/src/middleware/index.{ts,tsx,js,jsx}',\n]);\n\nconst middlewarePaths = [\n '/src/middleware.ts',\n '/src/middleware.tsx',\n '/src/middleware.js',\n '/src/middleware.jsx',\n '/src/middleware/index.ts',\n '/src/middleware/index.tsx',\n '/src/middleware/index.js',\n '/src/middleware/index.jsx',\n];\n\nexport async function loadMiddleware() {\n const middlewarePath = middlewarePaths.find((path) => middlewareModules[path]);\n if (!middlewarePath) return undefined;\n\n const mod = await middlewareModules[middlewarePath]();\n return mod.onRequest;\n}\n`;\n }\n\n // Virtual module: l5e-islands\n // Lazy glob of all React island components so the SSR entry can import a\n // component by its __src path and renderToString() it. Non-eager → only\n // islands actually present on a page (with ssr) get imported at runtime.\n if (id === '\\0' + VIRTUAL_L5E_ISLANDS) {\n return `export const islandModules = import.meta.glob('/src/**/react/*.{tsx,jsx}');`;\n }\n if (id === '\\0' + VIRTUAL_L5E_COMPACT_RENDERER) {\n return `export * as reactDomClient from 'react-dom/client'; export { createElement } from 'react';`;\n }\n\n // Virtual module: l5e-island-strategies\n if (id === '\\0' + VIRTUAL_L5E_ISLAND_STRATEGIES) {\n // Check if src/island-strategies.ts exists\n const strategiesFile = join(rootDir, 'src', 'island-strategies.ts');\n if (existsSync(strategiesFile)) {\n // Re-export user's file → Vite will build this file\n return `import '/src/island-strategies.ts';`;\n }\n // No file → empty module, no error\n return `/* no custom island strategies */`;\n }\n\n return null;\n },\n };\n}\n\nexport default coreVite;\n"],"mappings":";;;;;;;AA+BA,IAAM,KAAa,MAAe,EAAG,QAAQ,OAAO,GAAG,GACjD,KAAU,MAAkB,EAAW,QAAQ,CAAC,CAAC,OAAO,CAAK,CAAC,CAAC,OAAO,KAAK,CAAC,CAAC,MAAM,GAAG,CAAC;AAG7F,SAAS,EAAY,GAAgC;CACnD,IAAM,IAAS,EAAU,CAAE,CAAC,CAAC,MAAM,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uBAsBT,OAAO;GAMT,IAAI,MAAO,2BACT,OAAO;GAKT,IAAI,MAAO,+BACT,OAAO;GAIT,IAAI,MAAO,yBAA4B;IACrC,IAAM,IAAc,OAAO,YAAY,CAAc;IACrD,OAAO;gCACiB,KAAK,UAAU,CAAW,EAAE;GACtD;GAGA,IAAI,MAAO,4BACT,OAAO;GA+BT,IAAI,MAAO,yBACT,OAAO;GAET,IAAI,MAAO,kCACT,OAAO;GAIT,IAAI,MAAO,mCAAsC;IAE/C,IAAM,IAAiBA,EAAK,GAAS,OAAO,sBAAsB;IAMlE,OALI,EAAW,CAAc,IAEpB,wCAGF;GACT;GAEA,OAAO;EACT;CACF;AACF"}
|
package/dist/vite-plugin.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import { t as e } from "./vite-plugin-
|
|
1
|
+
import { t as e } from "./vite-plugin-Bln1di66.js";
|
|
2
2
|
export { e as coreVite, e as default };
|
package/package.json
CHANGED
package/src/core/chunking.ts
CHANGED
|
@@ -253,11 +253,9 @@ export function createChunkPlanner(options: ChunkingOptions = {}) {
|
|
|
253
253
|
maxSize: rule.maxSize,
|
|
254
254
|
includeDependenciesRecursively: options.mode === 'compact',
|
|
255
255
|
})),
|
|
256
|
-
|
|
257
|
-
|
|
258
|
-
|
|
259
|
-
includeDependenciesRecursively: true,
|
|
260
|
-
},
|
|
256
|
+
// Reserve eager owners before recursively collecting the lazy UI closure.
|
|
257
|
+
// Otherwise a lazy hook's dynamic import can capture Vite's preload helper
|
|
258
|
+
// and force global to import the entire React renderer chunk for that helper.
|
|
261
259
|
{
|
|
262
260
|
name: (id: string) => {
|
|
263
261
|
const group = decisions.get(id)?.group;
|
|
@@ -265,6 +263,11 @@ export function createChunkPlanner(options: ChunkingOptions = {}) {
|
|
|
265
263
|
},
|
|
266
264
|
includeDependenciesRecursively: false,
|
|
267
265
|
},
|
|
266
|
+
{
|
|
267
|
+
name: (id: string) =>
|
|
268
|
+
decisions.get(id)?.group === 'lazy-react-runtime' ? 'lazy-react-runtime' : null,
|
|
269
|
+
includeDependenciesRecursively: true,
|
|
270
|
+
},
|
|
268
271
|
];
|
|
269
272
|
},
|
|
270
273
|
report(bundle: OutputBundle) {
|
|
@@ -274,6 +277,19 @@ export function createChunkPlanner(options: ChunkingOptions = {}) {
|
|
|
274
277
|
warnings: [...warnings],
|
|
275
278
|
chunks: Object.values(bundle).flatMap((chunk) => {
|
|
276
279
|
if (chunk.type !== 'chunk') return [];
|
|
280
|
+
const moduleGroups = new Set(
|
|
281
|
+
Object.keys(chunk.modules).map((id) => decisions.get(id)?.group),
|
|
282
|
+
);
|
|
283
|
+
if (
|
|
284
|
+
options.mode === 'compact' &&
|
|
285
|
+
moduleGroups.has('global-owner') &&
|
|
286
|
+
moduleGroups.has('lazy-react-runtime')
|
|
287
|
+
) {
|
|
288
|
+
throw new Error(
|
|
289
|
+
`[l5e chunking] ${chunk.fileName} mixes global-owned and lazy island runtime modules. ` +
|
|
290
|
+
'Keep eager owners separate before recursively collecting the lazy runtime.',
|
|
291
|
+
);
|
|
292
|
+
}
|
|
277
293
|
const source = chunk.facadeModuleId ? portable(chunk.facadeModuleId) : null;
|
|
278
294
|
const kind =
|
|
279
295
|
source === 'src/client.global.ts'
|
package/src/core/vite-plugin.ts
CHANGED
|
@@ -673,8 +673,10 @@ export function coreVite(options: CoreViteOptions = {}): Plugin {
|
|
|
673
673
|
async transform(code, id, transformOptions) {
|
|
674
674
|
// Auto-inject island runtime into client.global.ts so it's always loaded globally
|
|
675
675
|
if (id.replace(/\\/g, '/').endsWith('src/client.global.ts') && !transformOptions?.ssr) {
|
|
676
|
+
const compactRuntime =
|
|
677
|
+
clientBuild && options.chunking && options.chunking.mode === 'compact';
|
|
676
678
|
return {
|
|
677
|
-
code: `import '@withl5e/l5e/island/${
|
|
679
|
+
code: `import '@withl5e/l5e/island/${compactRuntime ? 'compact-runtime' : 'runtime'}';\n${code}`,
|
|
678
680
|
map: null,
|
|
679
681
|
};
|
|
680
682
|
}
|
package/src/tooltip/index.ts
CHANGED
|
@@ -1,3 +1,16 @@
|
|
|
1
1
|
export { initTooltips, setupTooltipObserver } from './tooltip-loader';
|
|
2
|
-
export { configureTooltip
|
|
3
|
-
export type { TooltipUrlContext, TooltipUrlStrategy } from './tooltip-
|
|
2
|
+
export { configureTooltip } from './tooltip-config';
|
|
3
|
+
export type { TooltipUrlContext, TooltipUrlStrategy } from './tooltip-config';
|
|
4
|
+
import type { TooltipHost } from './tooltip-config';
|
|
5
|
+
|
|
6
|
+
// Keep the public API lazy too: a static re-export makes the library build
|
|
7
|
+
// inline the runtime into this entry and erases the loader's import boundary.
|
|
8
|
+
export async function showTooltip(host: TooltipHost): Promise<void> {
|
|
9
|
+
const runtime = await import('./tooltip-runtime');
|
|
10
|
+
return runtime.showTooltip(host);
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
export async function showTooltipMobile(host: TooltipHost): Promise<void> {
|
|
14
|
+
const runtime = await import('./tooltip-runtime');
|
|
15
|
+
return runtime.showTooltipMobile(host);
|
|
16
|
+
}
|