Skip to content

🀯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.

⚑️ perf(spa): gate the first-screen import graph and shrink it 41% (#19033)

Inneifabe719a180c
diff --git a/.github/scripts/bundle-size-gate.cjs b/.github/scripts/bundle-size-gate.cjs
index c6afac1e965..76845be9dfb 100644
--- a/.github/scripts/bundle-size-gate.cjs
+++ b/.github/scripts/bundle-size-gate.cjs
@@ -4,22 +4,36 @@
* baseline artifact uploaded by canary branch builds.
*
* Usage:
- * node bundle-size-gate.js measure --type <web|asar> --out <file.json>
- * node bundle-size-gate.js check --current <file.json> --baseline <file.json> [--label <name>] [--report <file.md>]
+ * node bundle-size-gate.js measure --type <web|asar|entry-graph> --out <file.json>
+ * node bundle-size-gate.js check --current <file.json> --baseline <file.json> [--label <name>] [--report <file.md>] [--percent <n>] [--floor <bytes>]
*
- * Thresholds (env):
+ * Thresholds (env, overridable per check via --percent / --floor):
* SIZE_GATE_PERCENT max allowed increase in percent (default 3)
* SIZE_GATE_FLOOR_BYTES min absolute increase before failing (default 512 KiB)
*
* An entry fails when: increase > max(baseline * percent / 100, floor).
+ *
+ * `entry-graph` measures the gzip size of every JS chunk reachable from the SPA
+ * entry through *static* imports only (dynamic `import()` excluded). Total dist
+ * size cannot see a lazy chunk being pulled back into the sync graph; this can.
+ * A chunk name (hash stripped) that is absent from the baseline graph fails the
+ * check regardless of size.
* Missing baseline or missing current report degrades to a warning + exit 0,
* so the gate never blocks before the first baseline exists.
*/
const fs = require('node:fs');
const os = require('node:os');
const path = require('node:path');
+const zlib = require('node:zlib');
const WEB_TARGETS = ['dist/desktop', 'dist/auth', 'dist/workbench'];
+const ENTRY_GRAPH_TARGETS = [
+ { dir: 'dist/desktop', html: 'index.html' },
+ { dir: 'dist/mobile', html: 'index.mobile.html' },
+ { dir: 'dist/auth', html: 'index.auth.html' },
+];
+const STATIC_IMPORT_RE =
+ /(?:^|[;{}\s)])(?:import(?:[\w$*{},\s]+from\s*)?|export\s*(?:\*|\{[^}]*\})\s*from\s*)["']([^"']+\.js)["']/g;
const ASAR_SEARCH_ROOT = 'apps/desktop/release';
const die = (message) => {
@@ -84,6 +98,37 @@ const findAsar = (root) => {
return null;
};
+const stripHash = (file) => file.replace(/-[\w-]{8}\.js$/, '.js');
+
+const measureEntryGraph = (root, htmlFile = 'index.html') => {
+ const html = fs.readFileSync(path.join(root, htmlFile), 'utf8');
+ const entryMatch = html.match(
+ /<script[^>]*type="module"[^>]*src="[^"]*?\/((?:assets|vendor)\/[^"]+\.js)"/,
+ );
+ if (!entryMatch) die(`no module entry script found in ${root}/${htmlFile}`);
+ const entry = entryMatch[1];
+
+ const visited = new Set();
+ let gz = 0;
+ const walk = (rel) => {
+ const abs = path.resolve(root, rel);
+ if (visited.has(abs)) return;
+ visited.add(abs);
+ const src = fs.readFileSync(abs, 'utf8');
+ gz += zlib.gzipSync(src).length;
+ for (const match of src.matchAll(STATIC_IMPORT_RE))
+ walk(path.join(path.dirname(rel), match[1]));
+ };
+ walk(entry);
+
+ const chunks = {};
+ for (const abs of visited) {
+ const name = stripHash(path.relative(root, abs));
+ chunks[name] = (chunks[name] || 0) + 1;
+ }
+ return { chunks, count: visited.size, entry, gz };
+};
+
const measure = (args) => {
const { type, out } = args;
if (!type || !out) die('measure requires --type <web|asar> and --out <file.json>');
@@ -101,6 +146,21 @@ const measure = (args) => {
if (Object.keys(sizes).length === 0) die('no dist targets found β€” did the build run?');
sizes.total = Object.values(sizes).reduce((sum, size) => sum + size, 0);
result = { sizes, type };
+ } else if (type === 'entry-graph') {
+ const sizes = {};
+ const graphs = {};
+ for (const { dir, html } of ENTRY_GRAPH_TARGETS) {
+ if (!fs.existsSync(path.join(dir, html))) {
+ console.warn(`⚠️ ${dir}/${html} not found, skipping`);
+ continue;
+ }
+ const graph = measureEntryGraph(dir, html);
+ sizes[dir] = graph.gz;
+ graphs[dir] = graph;
+ console.log(` ${dir}: ${graph.count} chunks reachable from ${graph.entry}`);
+ }
+ if (Object.keys(sizes).length === 0) die('no dist targets found β€” did the build run?');
+ result = { graphs, sizes, type };
} else if (type === 'asar') {
const asarPath = findAsar(ASAR_SEARCH_ROOT);
if (!asarPath) die(`app.asar not found under ${ASAR_SEARCH_ROOT}`);
@@ -111,7 +171,7 @@ const measure = (args) => {
type,
};
} else {
- die(`unknown --type "${type}" (expected web|asar)`);
+ die(`unknown --type "${type}" (expected web|asar|entry-graph)`);
}
fs.mkdirSync(path.dirname(out), { recursive: true });
@@ -157,7 +217,8 @@ const check = (args) => {
);
return;
}
- const currentSizes = JSON.parse(fs.readFileSync(current, 'utf8')).sizes || {};
+ const currentReport = JSON.parse(fs.readFileSync(current, 'utf8'));
+ const currentSizes = currentReport.sizes || {};
if (!baseline || !fs.existsSync(baseline)) {
skipWithNotice(
@@ -165,10 +226,11 @@ const check = (args) => {
);
return;
}
- const baselineSizes = JSON.parse(fs.readFileSync(baseline, 'utf8')).sizes || {};
+ const baselineReport = JSON.parse(fs.readFileSync(baseline, 'utf8'));
+ const baselineSizes = baselineReport.sizes || {};
- const percent = Number(process.env.SIZE_GATE_PERCENT || 3);
- const floor = Number(process.env.SIZE_GATE_FLOOR_BYTES || 512 * 1024);
+ const percent = Number(args.percent || process.env.SIZE_GATE_PERCENT || 3);
+ const floor = Number(args.floor || process.env.SIZE_GATE_FLOOR_BYTES || 512 * 1024);
const keys = [...new Set([...Object.keys(baselineSizes), ...Object.keys(currentSizes)])];
const rows = [];
@@ -194,6 +256,21 @@ const check = (args) => {
);
}
+ const graphRows = [];
+ if (currentReport.graphs && baselineReport.graphs) {
+ for (const key of Object.keys(currentReport.graphs)) {
+ const base = baselineReport.graphs[key];
+ if (!base) continue;
+ const cur = currentReport.graphs[key];
+ const added = Object.keys(cur.chunks).filter((name) => !base.chunks[name]);
+ const removed = Object.keys(base.chunks).filter((name) => !cur.chunks[name]);
+ if (added.length > 0) failed = true;
+ graphRows.push(
+ `| ${key} | ${base.count} | ${cur.count} | ${added.map((n) => `\`${n}\``).join(', ') || 'β€”'} | ${removed.map((n) => `\`${n}\``).join(', ') || 'β€”'} | ${added.length > 0 ? '❌' : 'βœ…'} |`,
+ );
+ }
+ }
+
const section = [
`### ${failed ? '❌' : 'βœ…'} ${label}`,
'',
@@ -202,6 +279,16 @@ const check = (args) => {
...rows,
'',
`> Gate: fails when increase > max(${percent}% of baseline, ${humanSize(floor)}). Baseline: latest canary build.`,
+ ...(graphRows.length > 0
+ ? [
+ '',
+ `| Entry | Baseline chunks | Current chunks | Added to sync graph | Removed | Result |`,
+ `| --- | --- | --- | --- | --- | --- |`,
+ ...graphRows,
+ '',
+ `> A chunk newly reachable through static imports fails the gate β€” it was lazy before and is now on the first-screen path.`,
+ ]
+ : []),
].join('\n');
console.log(`\n${section}\n`);
@@ -211,16 +298,20 @@ const check = (args) => {
if (failed) {
console.error(
- `❌ ${label} size increase exceeds the gate threshold (+${percent}% / +${humanSize(floor)}). ` +
- 'Inspect the added dependencies or assets, or adjust SIZE_GATE_PERCENT / SIZE_GATE_FLOOR_BYTES if this is expected.',
+ `❌ ${label} exceeds the gate: size increase > max(${percent}%, ${humanSize(floor)}) or a new chunk entered the static import graph. ` +
+ 'Inspect the added dependencies or imports, or adjust SIZE_GATE_PERCENT / SIZE_GATE_FLOOR_BYTES if this is expected.',
);
process.exit(1);
}
};
-const [command, ...rest] = process.argv.slice(2);
-const args = parseArgs(rest);
+module.exports = { measureEntryGraph, stripHash };
+
+if (require.main === module) {
+ const [command, ...rest] = process.argv.slice(2);
+ const args = parseArgs(rest);
-if (command === 'measure') measure(args);
-else if (command === 'check') check(args);
-else die('usage: bundle-size-gate.js <measure|check> [--flags]');
+ if (command === 'measure') measure(args);
+ else if (command === 'check') check(args);
+ else die('usage: bundle-size-gate.js <measure|check> [--flags]');
+}
diff --git a/.github/scripts/bundle-size-gate.test.cjs b/.github/scripts/bundle-size-gate.test.cjs
new file mode 100644
index 00000000000..d7929360fe2
--- /dev/null
+++ b/.github/scripts/bundle-size-gate.test.cjs
@@ -0,0 +1,51 @@
+const assert = require('node:assert/strict');
+const fs = require('node:fs');
+const os = require('node:os');
+const path = require('node:path');
+const { test } = require('node:test');
+
+const { measureEntryGraph, stripHash } = require('./bundle-size-gate.cjs');
+
+const writeDist = (files) => {
+ const root = fs.mkdtempSync(path.join(os.tmpdir(), 'entry-graph-'));
+ for (const [rel, content] of Object.entries(files)) {
+ const abs = path.join(root, rel);
+ fs.mkdirSync(path.dirname(abs), { recursive: true });
+ fs.writeFileSync(abs, content);
+ }
+ return root;
+};
+
+test('walks static imports only and skips dynamic import()', () => {
+ const root = writeDist({
+ 'index.html':
+ '<script type="module" crossorigin src="/_spa/assets/index-AAAAAAAA.js"></script>',
+ 'assets/index-AAAAAAAA.js':
+ 'import{a}from"./sync-BBBBBBBB.js";import"../vendor/vendor-react-CCCCCCCC.js";const x=()=>import("./lazy-DDDDDDDD.js");export*from"./reexport-EEEEEEEE.js";',
+ 'assets/sync-BBBBBBBB.js': 'import{b}from"./sync-BBBBBBBB.js";export const a=1;',
+ 'assets/reexport-EEEEEEEE.js': 'export const r=1;',
+ 'assets/lazy-DDDDDDDD.js': 'export const lazy=1;',
+ 'vendor/vendor-react-CCCCCCCC.js': 'export const react=1;',
+ });
+
+ const graph = measureEntryGraph(root);
+
+ assert.equal(graph.entry, 'assets/index-AAAAAAAA.js');
+ assert.equal(graph.count, 4);
+ assert.deepEqual(graph.chunks, {
+ 'assets/index.js': 1,
+ 'assets/reexport.js': 1,
+ 'assets/sync.js': 1,
+ 'vendor/vendor-react.js': 1,
+ });
+ assert.ok(graph.gz > 0);
+});
+
+test('stripHash removes the trailing rolldown hash including hashes starting with a dash', () => {
+ assert.equal(
+ stripHash('i18n/i18n-ja-JP-ui-runtime--Jre4geO.js'),
+ 'i18n/i18n-ja-JP-ui-runtime.js',
+ );
+ assert.equal(stripHash('assets/es-DBDe-NCK.js'), 'assets/es.js');
+ assert.equal(stripHash('assets/index-CDFWou5k.js'), 'assets/index.js');
+});
diff --git a/.github/scripts/size-gate-comment.cjs b/.github/scripts/size-gate-comment.cjs
index f328325d4e4..09845a9b476 100644
--- a/.github/scripts/size-gate-comment.cjs
+++ b/.github/scripts/size-gate-comment.cjs
@@ -4,12 +4,21 @@
*
* Usage (inside actions/github-script):
* const comment = require('<workspace>/.github/scripts/size-gate-comment.cjs');
- * await comment({ github, context, title: 'Web dist', report, failed, identifier: 'web' });
+ * await comment({ github, context, title: 'Web dist', report, failed, identifier: 'web', issueNumber });
*
* `identifier` keeps one comment per gate: the web (e2e) and desktop (asar)
* workflows run independently on the same PR and must not overwrite each other.
*/
-const sizeGateComment = async ({ github, context, title, report, failed, identifier }) => {
+const sizeGateComment = async ({
+ github,
+ context,
+ title,
+ report,
+ failed,
+ identifier,
+ issueNumber,
+}) => {
+ const number = issueNumber ?? context.issue.number;
if (!identifier)
throw new Error('sizeGateComment requires an `identifier` (e.g. "web" | "asar")');
const commentIdentifier = `<!-- SIZE-GATE-COMMENT-${identifier} -->`;
@@ -23,7 +32,7 @@ ${report}
*Baseline: latest \`canary\` build (workflow artifact). Thresholds configurable via \`SIZE_GATE_PERCENT\` / \`SIZE_GATE_FLOOR_BYTES\`.*`;
const { data: comments } = await github.rest.issues.listComments({
- issue_number: context.issue.number,
+ issue_number: number,
owner: context.repo.owner,
repo: context.repo.repo,
});
@@ -43,7 +52,7 @@ ${report}
const result = await github.rest.issues.createComment({
body,
- issue_number: context.issue.number,
+ issue_number: number,
owner: context.repo.owner,
repo: context.repo.repo,
});
diff --git a/.github/workflows/e2e.yml b/.github/workflows/e2e.yml
index a0247a04aea..9b77cbb09e4 100644
--- a/.github/workflows/e2e.yml
+++ b/.github/workflows/e2e.yml
@@ -12,6 +12,9 @@ concurrency:
cancel-in-progress: true
env:
+ # Same-repo PRs get their pull_request run skipped as a duplicate of the push run,
+ # so the size gates must also run on pushes to feature branches.
+ SIZE_GATE_ENABLED: ${{ github.event_name == 'pull_request' || (github.event_name == 'push' && github.ref != 'refs/heads/canary' && github.ref != 'refs/heads/main') }}
APP_URL: http://localhost:3006
DATABASE_URL: postgresql://postgres:postgres@localhost:5432/postgres
DATABASE_DRIVER: node
@@ -42,9 +45,7 @@ jobs:
e2e:
needs: check-duplicate-run
if: >-
- github.ref == 'refs/heads/main' ||
- github.ref == 'refs/heads/canary' ||
- needs.check-duplicate-run.outputs.should_skip != 'true'
+ github.ref == 'refs/heads/main' || github.ref == 'refs/heads/canary' || needs.check-duplicate-run.outputs.should_skip != 'true'
name: Test Web App
runs-on: ubuntu-latest
services:
@@ -95,7 +96,7 @@ jobs:
# ===== Bundle size gate (web dist) =====
# Baseline: artifact uploaded by the latest successful canary push run of this workflow.
- name: Find latest canary baseline run
- if: github.event_name == 'pull_request'
+ if: env.SIZE_GATE_ENABLED == 'true'
id: baseline_run
uses: actions/github-script@v8
with:
@@ -106,7 +107,7 @@ jobs:
return await finder({ github, context, workflowId: 'e2e.yml', artifactName: 'bundle-size-baseline-web' });
- name: Download web dist size baseline
- if: github.event_name == 'pull_request' && steps.baseline_run.outputs.result != ''
+ if: env.SIZE_GATE_ENABLED == 'true' && steps.baseline_run.outputs.result != ''
uses: actions/download-artifact@v7
with:
name: bundle-size-baseline-web
@@ -126,12 +127,49 @@ jobs:
retention-days: 30
- name: Check web dist size against baseline
- if: github.event_name == 'pull_request'
+ if: env.SIZE_GATE_ENABLED == 'true'
id: dist_size_check
run: node .github/scripts/bundle-size-gate.cjs check --current size-report/web.json --baseline .size-baseline/web.json --label "Web dist" --report size-report/report.md
+ # ===== Entry static-import graph gate =====
+ # Total dist size cannot see a lazy chunk being pulled back into the first-screen sync graph; this can.
+ - name: Find latest canary entry-graph baseline run
+ if: env.SIZE_GATE_ENABLED == 'true'
+ id: entry_graph_baseline_run
+ uses: actions/github-script@v8
+ with:
+ result-encoding: string
+ script: |
+ const finder = require('${{ github.workspace }}/.github/scripts/find-size-baseline.cjs');
+ return await finder({ github, context, workflowId: 'e2e.yml', artifactName: 'bundle-size-baseline-entry-graph' });
+
+ - name: Download entry-graph baseline
+ if: env.SIZE_GATE_ENABLED == 'true' && steps.entry_graph_baseline_run.outputs.result != ''
+ uses: actions/download-artifact@v7
+ with:
+ name: bundle-size-baseline-entry-graph
+ path: .size-baseline/
+ run-id: ${{ steps.entry_graph_baseline_run.outputs.result }}
+ github-token: ${{ secrets.GITHUB_TOKEN }}
+
+ - name: Measure entry static-import graph
+ run: node .github/scripts/bundle-size-gate.cjs measure --type entry-graph --out size-report/entry-graph.json
+
+ - name: Upload entry-graph baseline (canary only)
+ if: github.event_name == 'push' && github.ref == 'refs/heads/canary'
+ uses: actions/upload-artifact@v6
+ with:
+ name: bundle-size-baseline-entry-graph
+ path: size-report/entry-graph.json
+ retention-days: 30
+
+ - name: Check entry static-import graph against baseline
+ if: env.SIZE_GATE_ENABLED == 'true'
+ id: entry_graph_check
+ run: node .github/scripts/bundle-size-gate.cjs check --current size-report/entry-graph.json --baseline .size-baseline/entry-graph.json --label "First-screen static import graph (gzip)" --report size-report/report.md --floor 65536
+
- name: Comment bundle size report on PR
- if: always() && github.event_name == 'pull_request' && github.event.pull_request.head.repo.full_name == github.repository
+ if: always() && env.SIZE_GATE_ENABLED == 'true' && (github.event_name == 'push' || github.event.pull_request.head.repo.full_name == github.repository)
uses: actions/github-script@v8
with:
github-token: ${{ secrets.GITHUB_TOKEN }}
@@ -141,12 +179,24 @@ jobs:
? fs.readFileSync('size-report/report.md', 'utf8')
: 'Build did not reach the size gate step.';
const comment = require('${{ github.workspace }}/.github/scripts/size-gate-comment.cjs');
+ const issueNumber =
+ context.issue?.number ??
+ (await github.rest.repos.listPullRequestsAssociatedWithCommit({
+ commit_sha: context.sha,
+ owner: context.repo.owner,
+ repo: context.repo.repo,
+ })).data.find((pr) => pr.state === 'open')?.number;
+ if (!issueNumber) {
+ console.log('No open PR for this commit, skipping the size gate comment.');
+ return;
+ }
await comment({
github,
context,
+ issueNumber,
title: 'Web dist',
report,
- failed: ${{ steps.dist_size_check.outcome == 'failure' }},
+ failed: ${{ steps.dist_size_check.outcome == 'failure' || steps.entry_graph_check.outcome == 'failure' }},
identifier: 'web',
});
diff --git a/eslint.config.mjs b/eslint.config.mjs
index d29b5f88948..667b3c12382 100644
--- a/eslint.config.mjs
+++ b/eslint.config.mjs
@@ -155,6 +155,56 @@ export default eslint(
'no-restricted-imports': createRestrictedImportRule(),
},
},
+ {
+ // Boot-path trees are statically reachable from the SPA entry. A heavy
+ // @lobehub/ui member imported here lands in the first-screen chunk together
+ // with shiki / katex / elkjs / emoji data; the CI entry-graph gate catches
+ // the regression, this rule explains it at the import site.
+ files: [
+ 'src/layout/**/*.{ts,tsx}',
+ 'src/spa/**/*.{ts,tsx}',
+ 'src/store/**/*.{ts,tsx}',
+ 'src/utils/**/*.{ts,tsx}',
+ ],
+ ignores: ['src/**/*.test.{ts,tsx}', 'src/layout/AuthProvider/MarketAuth/ProfileSetupModal.tsx'],
+ rules: {
+ 'no-restricted-imports': createRestrictedImportRule({
+ paths: [
+ {
+ importNames: [
+ 'CodeDiff',
+ 'CodeEditor',
+ 'EmojiPicker',
+ 'Highlighter',
+ 'HtmlPreview',
+ 'Markdown',
+ 'Mermaid',
+ 'PatchDiff',
+ 'Snippet',
+ 'SortableList',
+ 'SyntaxHighlighter',
+ 'SyntaxMermaid',
+ ],
+ message:
+ 'Boot-path modules must not statically import heavy @lobehub/ui members. Load them with lazy(() => import("@lobehub/ui/es/<Member>/index")) or move the consumer into a route tree.',
+ name: '@lobehub/ui',
+ },
+ {
+ message:
+ 'Boot-path modules must load EmojiPicker with lazy(); it carries the emoji-mart dataset.',
+ name: '@/components/EmojiPicker',
+ },
+ ],
+ patterns: [
+ {
+ message:
+ 'The builtin tool client barrel exports the whole render registry. Import the dedicated subpath (e.g. "/client/displayControls") or resolve renders lazily.',
+ regex: '^@lobechat/builtin-tool-[^/]+/client(?:$|/index$)',
+ },
+ ],
+ }),
+ },
+ },
{
files: ['src/features/Conversation/**/*.{ts,tsx}'],
rules: {
diff --git a/packages/builtin-tool-claude-code/package.json b/packages/builtin-tool-claude-code/package.json
index 7434fe61952..884181932e9 100644
--- a/packages/builtin-tool-claude-code/package.json
+++ b/packages/builtin-tool-claude-code/package.json
@@ -5,6 +5,7 @@
"exports": {
".": "./src/index.ts",
"./client": "./src/client/index.ts",
+ "./client/displayControls": "./src/client/Render/displayControls.ts",
"./client/labels": "./src/client/labels.ts"
},
"main": "./src/index.ts",
diff --git a/packages/builtin-tools/src/displayControls.ts b/packages/builtin-tools/src/displayControls.ts
index 89be683f448..8ee1b5bfb1d 100644
--- a/packages/builtin-tools/src/displayControls.ts
+++ b/packages/builtin-tools/src/displayControls.ts
@@ -1,7 +1,5 @@
-import {
- ClaudeCodeIdentifier,
- resolveClaudeCodeRenderDisplayControl,
-} from '@lobechat/builtin-tool-claude-code/client';
+import { ClaudeCodeIdentifier } from '@lobechat/builtin-tool-claude-code';
+import { resolveClaudeCodeRenderDisplayControl } from '@lobechat/builtin-tool-claude-code/client/displayControls';
import { type RenderDisplayControl } from '@lobechat/types';
import { CodexRenderDisplayControls } from './codex/displayControls';
diff --git a/plugins/vite/lobeUiImports.test.ts b/plugins/vite/lobeUiImports.test.ts
new file mode 100644
index 00000000000..abd5b881e17
--- /dev/null
+++ b/plugins/vite/lobeUiImports.test.ts
@@ -0,0 +1,77 @@
+import { build, type Plugin } from 'vite';
+import { describe, expect, it } from 'vitest';
+
+import { lobeUiImports, parseBarrel } from './lobeUiImports';
+
+const ENTRY_ID = '\0lobe-ui-imports-fixture.mjs';
+
+const fixturePlugin: Plugin = {
+ name: 'lobe-ui-imports-fixture',
+ load(id) {
+ if (id !== ENTRY_ID) return;
+
+ return `
+ import { ConfigProvider, ErrorBoundary, Flexbox } from '@lobehub/ui';
+ import { Button } from '@lobehub/ui/base-ui';
+ export { ConfigProvider, ErrorBoundary, Flexbox, Button };
+ `;
+ },
+ resolveId(id) {
+ if (id === 'virtual:lobe-ui-imports-fixture') return ENTRY_ID;
+ },
+};
+
+describe('parseBarrel', () => {
+ it('maps exported members to their source modules', () => {
+ const code = [
+ 'import FlexBasic_default from "./Flex/FlexBasic.mjs";',
+ 'import Foo, { bar, baz as qux } from "./Foo/index.mjs";',
+ 'import { rehypeStreamAnimated } from "@lobehub/streamdown";',
+ 'export { FlexBasic_default as Flexbox, Foo, bar, qux, rehypeStreamAnimated };',
+ ].join('\n');
+
+ expect(parseBarrel(code, '')).toEqual({
+ Flexbox: { imported: 'default', source: '@lobehub/ui/es/Flex/FlexBasic' },
+ Foo: { imported: 'default', source: '@lobehub/ui/es/Foo/index' },
+ bar: { imported: 'bar', source: '@lobehub/ui/es/Foo/index' },
+ qux: { imported: 'baz', source: '@lobehub/ui/es/Foo/index' },
+ rehypeStreamAnimated: { imported: 'rehypeStreamAnimated', source: '@lobehub/streamdown' },
+ });
+ expect(parseBarrel('import X from "../Foo/X.mjs";\nexport { X };', 'chat/')).toEqual({
+ X: { imported: 'default', source: '@lobehub/ui/es/Foo/X' },
+ });
+ });
+});
+
+describe('lobeUiImports', () => {
+ it('rewrites barrel imports to deep imports', async () => {
+ const result = await build({
+ build: {
+ minify: false,
+ rolldownOptions: {
+ external: [/^@lobehub\/ui\/es\//, /node_modules\/react-error-boundary\//],
+ input: 'virtual:lobe-ui-imports-fixture',
+ },
+ write: false,
+ },
+ configFile: false,
+ logLevel: 'silent',
+ plugins: [fixturePlugin, ...lobeUiImports()],
+ });
+
+ const outputs = Array.isArray(result) ? result : [result];
+ const code = outputs
+ .flatMap(({ output }) => output)
+ .filter((item) => item.type === 'chunk')
+ .map((item) => item.code)
+ .join('\n');
+
+ expect(code).toContain('@lobehub/ui/es/ConfigProvider/');
+ expect(code).toContain('@lobehub/ui/es/Flex/FlexBasic');
+ expect(code).toContain('@lobehub/ui/es/base-ui/');
+ expect(code).toContain('react-error-boundary');
+ expect(code).not.toMatch(/from ["']react-error-boundary["']/);
+ expect(code).not.toMatch(/from ["']@lobehub\/ui["']/);
+ expect(code).not.toMatch(/from ["']@lobehub\/ui\/base-ui["']/);
+ });
+});
diff --git a/plugins/vite/lobeUiImports.ts b/plugins/vite/lobeUiImports.ts
new file mode 100644
index 00000000000..771fc4c8e4d
--- /dev/null
+++ b/plugins/vite/lobeUiImports.ts
@@ -0,0 +1,134 @@
+import { readFileSync, realpathSync } from 'node:fs';
+import path from 'node:path';
+import { fileURLToPath } from 'node:url';
+
+import transformImports from '@rolldown/plugin-transform-imports';
+import type { Plugin, PluginOption } from 'vite';
+
+const NAMED_EXPORT_PREFIX = 'virtual:lobe-ui-named:';
+const RESOLVED_NAMED_EXPORT_PREFIX = `\0${NAMED_EXPORT_PREFIX}`;
+
+const BARRELS = ['', 'awesome', 'base-ui', 'brand', 'chat', 'color', 'icons', 'mdx'] as const;
+
+interface MemberSource {
+ imported: string;
+ source: string;
+}
+
+type BarrelMap = Record<string, MemberSource>;
+
+interface Barrel {
+ file: string;
+ members: BarrelMap;
+}
+
+const toSubpath = (barrelDir: string, specifier: string) => {
+ if (!specifier.startsWith('.')) return specifier;
+ const relative = path.posix.join(barrelDir, specifier).replace(/\.mjs$/, '');
+ return `@lobehub/ui/es/${relative}`;
+};
+
+export const parseBarrel = (code: string, barrelDir: string): BarrelMap => {
+ const locals: BarrelMap = {};
+ for (const match of code.matchAll(/^import\s(.+?)\sfrom\s"([^"]+)";?$/gm)) {
+ const [, clause, specifier] = match;
+ const source = toSubpath(barrelDir, specifier);
+ const brace = clause.indexOf('{');
+ const defaultLocal = (brace === -1 ? clause : clause.slice(0, brace)).replace(',', '').trim();
+ if (defaultLocal) locals[defaultLocal] = { imported: 'default', source };
+ const named = brace === -1 ? '' : clause.slice(brace + 1, clause.indexOf('}'));
+ for (const part of named.split(',')) {
+ const [imported, local = imported] = part.trim().split(/\sas\s/);
+ if (imported) locals[local] = { imported, source };
+ }
+ }
+
+ const members: BarrelMap = {};
+ for (const match of code.matchAll(/^export\s*\{([^}]*)\};?$/gm)) {
+ for (const part of match[1].split(',')) {
+ const [local, exported = local] = part.trim().split(/\sas\s/);
+ if (local && locals[local]) members[exported] = locals[local];
+ }
+ }
+ return members;
+};
+
+const loadBarrelMaps = () => {
+ // realpath so bare specifiers resolve from pnpm's isolated store, not the root symlink
+ const esRoot = realpathSync(
+ path.resolve(fileURLToPath(import.meta.url), '../../../node_modules/@lobehub/ui/es'),
+ );
+ const maps: Record<string, Barrel> = {};
+ for (const barrel of BARRELS) {
+ const barrelDir = barrel ? `${barrel}/` : '';
+ const file = path.join(esRoot, barrelDir, 'index.mjs');
+ maps[barrel] = { file, members: parseBarrel(readFileSync(file, 'utf8'), barrelDir) };
+ }
+ return maps;
+};
+
+const namedExportProxy = (maps: Record<string, Barrel>): Plugin => ({
+ name: 'lobe-ui-named-export-proxy',
+ async load(id) {
+ if (!id.startsWith(RESOLVED_NAMED_EXPORT_PREFIX)) return;
+
+ const [barrel, member] = id.slice(RESOLVED_NAMED_EXPORT_PREFIX.length).split(':');
+ const entry = maps[barrel]?.members[member];
+ if (!entry)
+ return `export { ${member} as default } from '@lobehub/ui/es/${barrel ? `${barrel}/` : ''}index';`;
+
+ // Bare specifiers such as react-error-boundary are dependencies of
+ // @lobehub/ui, not of the app, so they only resolve from the barrel's own
+ // location under pnpm's isolated node_modules.
+ const source = entry.source.startsWith('@lobehub/ui/es/')
+ ? entry.source
+ : ((await this.resolve(entry.source, maps[barrel].file))?.id ?? entry.source);
+
+ return `export { ${entry.imported} as default } from ${JSON.stringify(source)};`;
+ },
+ resolveId(id) {
+ if (!id.startsWith(NAMED_EXPORT_PREFIX)) return;
+
+ return `\0${id}`;
+ },
+});
+
+const includeModuleExtensions = (plugin: ReturnType<typeof transformImports>) => {
+ if (typeof plugin.transform !== 'object' || !plugin.transform) return plugin;
+
+ plugin.transform = {
+ ...plugin.transform,
+ filter: {
+ ...plugin.transform.filter,
+ id: /\.[cm]?[jt]sx?$/,
+ },
+ };
+
+ return plugin;
+};
+
+/**
+ * Rewrites the @lobehub/ui barrels to deep imports.
+ *
+ * Rolldown assigns chunks by static reachability, and the barrel keeps static
+ * edges to every member. Once any lazy route uses Markdown, Mermaid or
+ * EmojiPicker, their full dependency trees (shiki, katex, elkjs, emoji data)
+ * are promoted into the first-screen chunk even though the entry only touches
+ * ConfigProvider and Flexbox. The member→module map is read from the barrel
+ * files themselves so it tracks upstream releases.
+ */
+export const lobeUiImports = (): PluginOption[] => {
+ const maps = loadBarrelMaps();
+ const uiImports = transformImports(
+ Object.fromEntries(
+ BARRELS.map((barrel) => [
+ barrel ? `@lobehub/ui/${barrel}` : '@lobehub/ui',
+ { transform: [['*', `${NAMED_EXPORT_PREFIX}${barrel}:{{member}}`]] },
+ ]),
+ ),
+ );
+
+ return [namedExportProxy(maps), includeModuleExtensions(uiImports)];
+};
+
+export const __testing = { NAMED_EXPORT_PREFIX, RESOLVED_NAMED_EXPORT_PREFIX };
diff --git a/plugins/vite/sharedRendererConfig.ts b/plugins/vite/sharedRendererConfig.ts
index 5f5f715a6e7..05859829e8c 100644
--- a/plugins/vite/sharedRendererConfig.ts
+++ b/plugins/vite/sharedRendererConfig.ts
@@ -4,6 +4,7 @@ import type { ModulePreloadOptions } from 'vite';
import { viteEmotionSpeedy } from './emotionSpeedy';
import { lobeIconImports } from './lobeIconImports';
+import { lobeUiImports } from './lobeUiImports';
import { viteMarkdownImport } from './markdownImport';
import { viteNodeModuleStub } from './nodeModuleStub';
import { vitePlatformResolve } from './platformResolve';
@@ -361,7 +362,7 @@ export function sharedRendererPlugins(options: SharedRendererOptions) {
hotKeys: ['altKey', 'ctrlKey'],
}),
react(),
- ...(options.platform === 'desktop' ? [] : lobeIconImports()),
+ ...(options.platform === 'desktop' ? [] : [...lobeIconImports(), ...lobeUiImports()]),
];
}
diff --git a/src/components/Error/index.tsx b/src/components/Error/index.tsx
index 94498509c0d..12f3de5b264 100644
--- a/src/components/Error/index.tsx
+++ b/src/components/Error/index.tsx
@@ -1,13 +1,15 @@
'use client';
-import { Accordion, AccordionItem, Block, Flexbox, FluentEmoji, Highlighter } from '@lobehub/ui';
+import { Accordion, AccordionItem, Block, Flexbox, FluentEmoji } from '@lobehub/ui';
import { Button } from '@lobehub/ui/base-ui';
import type { Key } from 'react';
-import { useState } from 'react';
+import { lazy, Suspense, useState } from 'react';
import { useTranslation } from 'react-i18next';
import { MAX_WIDTH } from '@/const/layoutTokens';
+const Highlighter = lazy(() => import('@lobehub/ui/es/Highlighter/index'));
+
export type ErrorType = Error & { digest?: string };
interface ErrorCaptureProps {
@@ -66,9 +68,11 @@ const ErrorCapture = ({ error, resetPath = '/' }: ErrorCaptureProps) => {
onExpandedChange={setExpandedKeys}
>
<AccordionItem indicatorPlacement={'start'} itemKey={'stack'} title={t('error.stack')}>
- <Highlighter language={'plaintext'} padding={12} variant={'borderless'}>
- {error.stack!}
- </Highlighter>
+ <Suspense fallback={null}>
+ <Highlighter language={'plaintext'} padding={12} variant={'borderless'}>
+ {error.stack!}
+ </Highlighter>
+ </Suspense>
</AccordionItem>
</Accordion>
</Block>
diff --git a/src/layout/AuthProvider/MarketAuth/MarketAuthProvider.tsx b/src/layout/AuthProvider/MarketAuth/MarketAuthProvider.tsx
index 12a508ddb17..44cf77b2353 100644
--- a/src/layout/AuthProvider/MarketAuth/MarketAuthProvider.tsx
+++ b/src/layout/AuthProvider/MarketAuth/MarketAuthProvider.tsx
@@ -2,7 +2,7 @@
import { toast } from '@lobehub/ui/base-ui';
import { type ReactNode } from 'react';
-import { createContext, use, useCallback, useEffect, useState } from 'react';
+import { createContext, lazy, Suspense, use, useCallback, useEffect, useState } from 'react';
import { useTranslation } from 'react-i18next';
import { mutate as globalMutate } from 'swr';
@@ -19,7 +19,6 @@ import { MarketAuthError } from './errors';
import { marketAuthEvents } from './events';
import MarketAuthConfirmModal from './MarketAuthConfirmModal';
import { MarketOIDC } from './oidc';
-import ProfileSetupModal from './ProfileSetupModal';
import type { MarketAuthScene } from './scenes';
import { createSingleFlight } from './singleFlight';
import {
@@ -32,6 +31,8 @@ import {
import { useMarketUserProfile } from './useMarketUserProfile';
import { type ClaimableResources } from './useSocialConnect';
+const ProfileSetupModal = lazy(() => import('./ProfileSetupModal'));
+
const MarketAuthContext = createContext<MarketAuthContextType | null>(null);
interface MarketAuthProviderProps {
@@ -833,16 +834,20 @@ export const MarketAuthProvider = ({ children, isDesktop }: MarketAuthProviderPr
onCancel={handleCancelAuth}
onConfirm={handleConfirmAuth}
/>
- <ProfileSetupModal
- accessToken={session?.accessToken ?? null}
- defaultDisplayName={userProfile?.displayName || ''}
- isFirstTimeSetup={isFirstTimeSetup}
- open={showProfileSetupModal}
- userProfile={userProfile}
- onClose={handleCloseProfileSetup}
- onShowClaimResources={handleShowClaimResources}
- onSuccess={handleProfileSuccess}
- />
+ {showProfileSetupModal && (
+ <Suspense fallback={null}>
+ <ProfileSetupModal
+ open
+ accessToken={session?.accessToken ?? null}
+ defaultDisplayName={userProfile?.displayName || ''}
+ isFirstTimeSetup={isFirstTimeSetup}
+ userProfile={userProfile}
+ onClose={handleCloseProfileSetup}
+ onShowClaimResources={handleShowClaimResources}
+ onSuccess={handleProfileSuccess}
+ />
+ </Suspense>
+ )}
{claimableResources && (
<ClaimResourcesModal
open={showClaimModal}