Skip to content

Commit b8d3046

Browse files
committed
feat(mosaic): render compound components from Server Components
1 parent 89199fa commit b8d3046

13 files changed

Lines changed: 81 additions & 25 deletions

File tree

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
---
2+
'@clerk/mosaic': patch
3+
---
4+
5+
Compound components such as `Avatar`, `Banner`, `DataList`, `EmptyState`, `Entity`, `Item` and `Table` can now be rendered from React Server Components, e.g. `<Avatar.Root>` in a Next.js App Router page. Each compound export is now a module namespace object instead of a plain object, so `X.Part` usage is unchanged, but its parts are read-only: assigning to `X.Part` no longer replaces it.
Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
{
22
"files": [
3-
{ "path": "./dist/index.js", "maxSize": "95KB" },
3+
{ "path": "./dist/.bundlewatch/index.js", "maxSize": "95KB" },
44
{ "path": "./dist/styles.css", "maxSize": "18KB" }
55
]
66
}

‎packages/mosaic/package.json‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -117,14 +117,15 @@
117117
"dist",
118118
"!dist/**/*.d.ts.map",
119119
"!dist/**/*.d.mts.map",
120+
"!dist/.bundlewatch",
120121
"styles.css.d.ts",
121122
"CHANGELOG.md"
122123
],
123124
"scripts": {
124125
"build": "pnpm build:js && pnpm build:css && pnpm check:bundle && pnpm typecheck",
125126
"build:css": "tsdown --config tsdown.css.config.mts",
126127
"build:js": "tsdown --config tsdown.config.mts",
127-
"bundlewatch": "FORCE_COLOR=1 bundlewatch --config bundlewatch.config.json",
128+
"bundlewatch": "node ./scripts/bundle-for-size.mjs && FORCE_COLOR=1 bundlewatch --config bundlewatch.config.json",
128129
"check:bundle": "node ./scripts/check-bundle.mjs",
129130
"clean": "rimraf ./dist ./dist-css",
130131
"dev": "tsdown --config tsdown.config.mts --watch",
Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
import { readFile } from 'node:fs/promises';
2+
import { resolve } from 'node:path';
3+
4+
import { build } from 'rolldown';
5+
6+
const packageDir = resolve(import.meta.dirname, '..');
7+
const packageJson = JSON.parse(await readFile(resolve(packageDir, 'package.json'), 'utf8'));
8+
const externals = Object.keys({ ...packageJson.dependencies, ...packageJson.peerDependencies });
9+
10+
await build({
11+
input: resolve(packageDir, 'dist/index.js'),
12+
platform: 'browser',
13+
external: id => externals.some(name => id === name || id.startsWith(`${name}/`)),
14+
output: { dir: resolve(packageDir, 'dist/.bundlewatch'), entryFileNames: '[name].js', format: 'esm' },
15+
logLevel: 'warn',
16+
});

‎packages/mosaic/scripts/check-bundle.mjs‎

Lines changed: 56 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1,17 +1,64 @@
11
import { readdir, readFile } from 'node:fs/promises';
2-
import { resolve } from 'node:path';
2+
import { dirname, relative, resolve } from 'node:path';
33

44
const distDir = resolve(import.meta.dirname, '../dist');
55
const jsFiles = (await readdir(distDir, { recursive: true })).filter(file => file.endsWith('.js'));
66
const sources = await Promise.all(jsFiles.map(file => readFile(resolve(distDir, file), 'utf8')));
7-
const componentEntries = (await readdir(resolve(distDir, 'components')))
8-
.filter(file => file.endsWith('.js'))
9-
.map(file => `components/${file}`);
10-
11-
for (const entryFile of ['index.js', ...componentEntries]) {
12-
const entry = await readFile(resolve(distDir, entryFile), 'utf8');
13-
if (!entry.startsWith("'use client';") && !entry.startsWith('"use client";')) {
14-
throw new Error(`Published Mosaic JS entry ${entryFile} is missing a top-level 'use client' boundary.`);
7+
const packageJson = JSON.parse(await readFile(resolve(import.meta.dirname, '../package.json'), 'utf8'));
8+
const entryFiles = Object.entries(packageJson.exports)
9+
.filter(([subpath]) => subpath === '.' || /^\.\/(components|primitives)\//.test(subpath))
10+
.map(([, target]) => target)
11+
.map(target => (typeof target === 'string' ? target : target.import))
12+
.filter(file => file?.endsWith('.js'))
13+
.map(file => resolve(import.meta.dirname, '..', file));
14+
15+
const isClientModule = source => source.startsWith("'use client';") || source.startsWith('"use client";');
16+
const importsOf = source =>
17+
[...source.matchAll(/^import\s+(?:[^'"]*?\s+from\s+)?["']([^"']+)["'];?$/gm)].map(m => m[1]);
18+
const importsReact = source =>
19+
importsOf(source).some(specifier => specifier === 'react' || specifier.startsWith('react/'));
20+
const code = source =>
21+
source
22+
.replace(/\/\/.*$/gm, '')
23+
.split('\n')
24+
.map(line => line.trim())
25+
.filter(Boolean);
26+
27+
const checkNamespaceEntry = async (entryFile, source) => {
28+
const display = relative(distDir, entryFile);
29+
const lines = code(source);
30+
const namespaceImport = /^import \{ (\w+) \} from "(\.[^"]+)";$/;
31+
const namespaceExport = /^export \{ (\w+ as \w+(?:, \w+ as \w+)*) \};$/;
32+
if (!lines.every(line => namespaceImport.test(line) || namespaceExport.test(line))) {
33+
throw new Error(
34+
`Published Mosaic JS entry ${display} must start with 'use client' or contain only \`export * as\` namespace re-exports.`,
35+
);
36+
}
37+
for (const line of lines.filter(line => namespaceImport.test(line))) {
38+
const [, binding, specifier] = line.match(namespaceImport);
39+
const partsFile = resolve(dirname(entryFile), specifier);
40+
const parts = await readFile(partsFile, 'utf8');
41+
if (isClientModule(parts) || !new RegExp(`^var ${binding} = /\\* @__PURE__ \\*/ __exportAll\\(`, 'm').test(parts)) {
42+
throw new Error(
43+
`${display} imports ${binding} from ${relative(distDir, partsFile)}, which must be a namespace object with no directive.`,
44+
);
45+
}
46+
for (const leafSpecifier of importsOf(parts).filter(specifier => specifier.startsWith('.'))) {
47+
const leafFile = resolve(dirname(partsFile), leafSpecifier);
48+
const leaf = await readFile(leafFile, 'utf8');
49+
if (importsReact(leaf) && !isClientModule(leaf)) {
50+
throw new Error(
51+
`${relative(distDir, leafFile)}, re-exported by the namespace ${relative(distDir, partsFile)}, imports React but is missing a top-level 'use client' boundary.`,
52+
);
53+
}
54+
}
55+
}
56+
};
57+
58+
for (const entryFile of entryFiles) {
59+
const source = await readFile(entryFile, 'utf8');
60+
if (!isClientModule(source)) {
61+
await checkNamespaceEntry(entryFile, source);
1562
}
1663
}
1764

‎packages/mosaic/src/components/avatar/index.ts‎

Lines changed: 0 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,3 @@
1-
'use client';
2-
31
/**
42
* Compound avatar. `Avatar.Root` positions and sizes the box; `Avatar.Image` renders
53
* once its source loads; `Avatar.Fallback` holds the space until then, as a blank

‎packages/mosaic/src/components/banner/index.ts‎

Lines changed: 0 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,3 @@
1-
'use client';
2-
31
/**
42
* A tinted strip that annotates the surface it sits on with a status message. Composed through
53
* `Banner.Root`, `Banner.Label`, and `Banner.Description`; every part accepts the Mosaic `render`

‎packages/mosaic/src/components/data-list/index.ts‎

Lines changed: 0 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,3 @@
1-
'use client';
2-
31
/**
42
* Mosaic `DataList` — label/value pairs for read-only detail, such as the fields describing a
53
* device or a payment method. Composed via dot syntax: `DataList.Root`, `DataList.Item`,

‎packages/mosaic/src/components/empty-state/index.ts‎

Lines changed: 0 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,3 @@
1-
'use client';
2-
31
export * as EmptyState from './empty-state.parts';
42
export type {
53
EmptyStateActionsProps,
Lines changed: 0 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1 @@
1-
'use client';
2-
31
export * as Entity from './entity.parts';

0 commit comments

Comments
 (0)