Skip to content

[code-infra] Setup error message minification #1463

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 28 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
28 commits
Select commit Hold shift + click to select a range
8eb79a0
Initial setup for minified error messages
Janpot Feb 18, 2025
e355a4d
fix interpollation
Janpot Feb 18, 2025
fb2f0e6
cleaner
Janpot Feb 18, 2025
e605606
codeblock
Janpot Feb 18, 2025
f6635c0
improvements
Janpot Feb 19, 2025
d180a4f
Update createPackageManifest.mts
Janpot Feb 19, 2025
d5a840f
Update createPackageManifest.mts
Janpot Feb 19, 2025
9c54353
fix export
Janpot Feb 19, 2025
cb39f96
unnecessary plugin
Janpot Feb 19, 2025
7d6b1e1
Update .markdownlint-cli2.cjs
Janpot Feb 19, 2025
d6ae187
types
Janpot Feb 19, 2025
b3be462
fix reportBrokenLinks
Janpot Feb 19, 2025
e17fb21
fix mdlint
Janpot Feb 19, 2025
7994f59
Update reportBrokenLinks.mts
Janpot Feb 19, 2025
7e31f0a
explainer
Janpot Feb 19, 2025
491b354
Update PageContent.mdx
Janpot Feb 19, 2025
7af37ce
Let's build this resolution in the babel plugin
Janpot Feb 20, 2025
b465e67
fix imports
Janpot Feb 20, 2025
05f89ec
Merge remote-tracking branch 'upstream/master' into setup-minify-erro…
Janpot Feb 20, 2025
82ab7de
Make it opt-out
Janpot Feb 20, 2025
86ff537
extension handling
Janpot Feb 26, 2025
518741b
Update docs/src/app/(public)/(content)/production-error/[code]/ErrorD…
Janpot Mar 19, 2025
247f1d9
Update packages/react/src/utils/formatErrorMessage.ts
Janpot Mar 20, 2025
8fa10ed
Update docs/src/app/(public)/(content)/production-error/[code]/PageCo…
Janpot Mar 20, 2025
16c2407
Merge remote-tracking branch 'upstream/master' into setup-minify-erro…
Janpot May 29, 2025
cf60053
Update pnpm-lock.yaml
Janpot May 29, 2025
b452a4f
Update babel.config.js
Janpot May 29, 2025
8e6427d
Update error-codes.json
Janpot May 29, 2025
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
23 changes: 13 additions & 10 deletions babel.config.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
const { resolve } = require('node:path');

const errorCodesPath = resolve(__dirname, './docs/public/static/error-codes.json');
const errorCodesPath = resolve(__dirname, './docs/src/error-codes.json');
const missingError = process.env.MUI_EXTRACT_ERROR_CODES === 'true' ? 'write' : 'annotate';
const baseUIPackageJson = require('./packages/react/package.json');

Expand Down Expand Up @@ -29,15 +29,7 @@ module.exports = function getBabelConfig(api) {
];

const plugins = [
[
'babel-plugin-macros',
{
muiError: {
errorCodesPath,
missingError,
},
},
],
'babel-plugin-optimize-clsx',
[
'@babel/plugin-transform-runtime',
{ regenerator: false, version: baseUIPackageJson.dependencies['@babel/runtime'] },
Expand All @@ -46,6 +38,17 @@ module.exports = function getBabelConfig(api) {
...(useESModules
? [['@mui/internal-babel-plugin-resolve-imports', { outExtension: '.js' }]]
: []),
[
'@mui/internal-babel-plugin-minify-errors',
{
errorCodesPath,
missingError,
runtimeModule: '#formatErrorMessage',
detection: 'opt-out',
// Just strip the extension, extensions are handled by babel-plugin-add-import-extension
outExtension: '',
},
],
];

return {
Expand Down
1 change: 0 additions & 1 deletion docs/public/static/error-codes.json

This file was deleted.

Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
'use client';
import * as React from 'react';
import { useSearchParams } from 'next/navigation';

export interface ErrorDisplayProps {
msg: string;
}

function ErrorMessageWithArgs({ msg }: ErrorDisplayProps) {
const searchParams = useSearchParams();
return React.useMemo(() => {
const args = searchParams.getAll('args[]');
let index = 0;
return msg.replace(/%s/g, () => {
const replacement = args[index];
index += 1;
return replacement === undefined ? '[missing argument]' : replacement;
});
}, [msg, searchParams]);
}

/**
* Client component that interpolates arguments in an error message. Must be
* a client component because it reads the search params.
*/
export default function ErrorDisplay({ msg }: ErrorDisplayProps) {
const fallbackMsg = React.useMemo(() => msg.replace(/%s/g, '…'), [msg]);

return (
<code>
<React.Suspense fallback={fallbackMsg}>
<ErrorMessageWithArgs msg={msg} />
</React.Suspense>
</code>
);
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
# Production error

{/**
@typedef Props
@property {string} msg The raw error message.
**/}

<Subtitle>Explanation for minified production error message.</Subtitle>
<Meta
name="description"
content="In the production build, error messages are minified to keep your application lightweight."
/>

A minified Base UI error occurred in the production build of React.

The full error message:

<ErrorDisplay msg={props.msg} />
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
import * as React from 'react';
import { notFound } from 'next/navigation';
import PageContent from './PageContent.mdx';
import codes from '../../../../../error-codes.json';
import ErrorDisplay from './ErrorDisplay';

export const dynamicParams = false;

export async function generateStaticParams() {
return Object.keys(codes).map((code) => ({ code }));
}

export default async function ProductionError(props: {
params: Promise<{ code: string }>;
}) {
const params = await props.params;
const code = Number(params.code);

if (Number.isNaN(code)) {
notFound();
}

const msg = (codes as Partial<Record<string, string>>)[code];

if (!msg) {
notFound();
}

return <PageContent components={{ ErrorDisplay }} msg={msg} />;
}
64 changes: 64 additions & 0 deletions docs/src/error-codes.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
{
"1": "Base UI: AccordionItemContext is missing. Accordion parts must be placed within <Accordion.Item>.",
"2": "Base UI: AccordionRootContext is missing. Accordion parts must be placed within <Accordion.Root>.",
"3": "Base UI: <AlertDialog.Portal> is missing.",
"4": "Base UI: AlertDialogRootContext is missing. AlertDialog parts must be placed within <AlertDialog.Root>.",
"5": "Base UI: AvatarRootContext is missing. Avatar parts must be placed within <Avatar.Root>.",
"6": "Base UI: CheckboxRootContext is missing. Checkbox parts must be placed within <Checkbox.Root>.",
"7": "Base UI: CheckboxGroupContext is missing. CheckboxGroup parts must be placed within <CheckboxGroup>.",
"8": "Base UI: CollapsibleRootContext is missing. Collapsible parts must be placed within <Collapsible.Root>.",
"9": "Base UI: CompositeRootContext is missing. Composite parts must be placed within <Composite.Root>.",
"10": "Base UI: ContextMenuRootContext is missing. ContextMenu parts must be placed within <ContextMenu.Root>.",
"11": "Base UI: <Dialog.Portal> is missing.",
"12": "Base UI: DialogRootContext is missing. Dialog parts must be placed within <Dialog.Root>.",
"13": "Base UI: DirectionContext is missing.",
"14": "Base UI: FieldRootContext is missing. Field parts must be placed within <Field.Root>.",
"15": "Base UI: MenuCheckboxItemContext is missing. MenuCheckboxItem parts must be placed within <Menu.CheckboxItem>.",
"16": "Base UI: Missing MenuGroupRootContext provider",
"17": "Base UI: <Menu.Portal> is missing.",
"18": "Base UI: MenuPositionerContext is missing. MenuPositioner parts must be placed within <Menu.Positioner>.",
"19": "Base UI: MenuRadioGroupContext is missing. MenuRadioGroup parts must be placed within <Menu.RadioGroup>.",
"20": "Base UI: MenuRadioItemContext is missing. MenuRadioItem parts must be placed within <Menu.RadioItem>.",
"21": "Base UI: MenuRootContext is missing. Menu parts must be placed within <Menu.Root>.",
"22": "Base UI: SubmenuTrigger must be placed in a nested Menu.",
"23": "Base UI: MenubarContext is missing. Menubar parts must be placed within <Menubar>.",
"24": "Base UI: MeterRootContext is missing. Meter parts must be placed within <Meter.Root>.",
"25": "Base UI: NavigationMenuItem parts must be used within a <NavigationMenu.Item>.",
"26": "Base UI: <NavigationMenu.Portal> is missing.",
"27": "Base UI: NavigationMenuPositionerContext is missing. NavigationMenuPositioner parts must be placed within <NavigationMenu.Positioner>.",
"28": "Base UI: NavigationMenuRootContext is missing. Navigation Menu parts must be placed within <NavigationMenu.Root>.",
"29": "Base UI: NumberFieldRootContext is missing. NumberField parts must be placed within <NumberField.Root>.",
"30": "Base UI: NumberFieldScrubAreaContext is missing. NumberFieldScrubArea parts must be placed within <NumberField.ScrubArea>.",
"31": "Base UI: <Popover.Portal> is missing.",
"32": "Base UI: PopoverPositionerContext is missing. PopoverPositioner parts must be placed within <Popover.Positioner>.",
"33": "Base UI: PopoverRootContext is missing. Popover parts must be placed within <Popover.Root>.",
"34": "Base UI: <PreviewCard.Portal> is missing.",
"35": "Base UI: <PreviewCard.Popup> and <PreviewCard.Arrow> must be used within the <PreviewCard.Positioner> component",
"36": "Base UI: PreviewCardRootContext is missing. PreviewCard parts must be placed within <PreviewCard.Root>.",
"37": "Base UI: ProgressRootContext is missing. Progress parts must be placed within <Progress.Root>.",
"38": "Base UI: RadioRootContext is missing. Radio parts must be placed within <Radio.Root>.",
"39": "Base UI: ScrollAreaRootContext is missing. ScrollArea parts must be placed within <ScrollArea.Root>.",
"40": "Base UI: ScrollAreaScrollbarContext is missing. ScrollAreaScrollbar parts must be placed within <ScrollArea.Scrollbar>.",
"41": "Base UI: ScrollAreaViewportContext missing. ScrollAreaViewport parts must be placed within <ScrollArea.Viewport>.",
"42": "Base UI: SelectGroupContext is missing. SelectGroup parts must be placed within <Select.Group>.",
"43": "Base UI: SelectItemContext is missing. SelectItem parts must be placed within <Select.Item>.",
"44": "Base UI: <Select.Portal> is missing.",
"45": "Base UI: SelectPositionerContext is missing. SelectPositioner parts must be placed within <Select.Positioner>.",
"46": "Base UI: SelectIndexContext is missing. Select parts must be placed within <Select.Root>.",
"47": "useSelectRootContext must be used within a SelectRoot",
"48": "Base UI: SliderRootContext is missing. Slider parts must be placed within <Slider.Root>.",
"49": "Base UI: SwitchRootContext is missing. Switch parts must be placed within <Switch.Root>.",
"50": "Base UI: TabsListContext is missing. TabsList parts must be placed within <Tabs.List>.",
"51": "Base UI: TabsRootContext is missing. Tabs parts must be placed within <Tabs.Root>.",
"52": "Base UI: useToast must be used within <Toast.Provider>.",
"53": "useToastRoot must be used within a ToastRoot",
"54": "Base UI: ToastViewportContext is missing. Toast parts must be placed within <Toast.Viewport>.",
"55": "Base UI: ToggleGroupContext is missing. ToggleGroup parts must be placed within <ToggleGroup>.",
"56": "Base UI: ToolbarGroupContext is missing. ToolbarGroup parts must be placed within <Toolbar.Group>.",
"57": "Base UI: ToolbarRootContext is missing. Toolbar parts must be placed within <Toolbar.Root>.",
"58": "Base UI: <Tooltip.Portal> is missing.",
"59": "Base UI: TooltipPositionerContext is missing. TooltipPositioner parts must be placed within <Tooltip.Positioner>.",
"60": "Base UI: TooltipRootContext is missing. Tooltip parts must be placed within <Tooltip.Root>.",
"61": "Cannot call an event handler while rendering.",
"62": "Need either element or render to be defined"
}
5 changes: 5 additions & 0 deletions docs/types.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,3 +2,8 @@

declare module 'gtag.js';
declare module '@mui/monorepo/docs/nextConfigDocsInfra.js';

declare module '*.mdx' {
const MDXComponent: (props) => JSX.Element;
export default MDXComponent;
}
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -78,6 +78,7 @@
"@mui/internal-markdown": "^2.0.4",
"@mui/internal-scripts": "^2.0.7",
"@mui/internal-test-utils": "^2.0.7",
"@mui/internal-babel-plugin-minify-errors": "^2.0.4",
"@mui/monorepo": "github:mui/material-ui#v7.0.2",
"@next/eslint-plugin-next": "^15.3.2",
"@octokit/rest": "^21.1.1",
Expand All @@ -96,7 +97,6 @@
"@vitest/coverage-istanbul": "3.1.2",
"@vitest/ui": "3.1.2",
"babel-loader": "^10.0.0",
"babel-plugin-macros": "^3.1.0",
"babel-plugin-module-resolver": "^5.0.2",
"babel-plugin-optimize-clsx": "^2.6.2",
"babel-plugin-react-remove-properties": "^0.3.0",
Expand Down
3 changes: 2 additions & 1 deletion packages/react/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -68,7 +68,8 @@
"./utils": "./src/utils/index.ts"
},
"imports": {
"#test-utils": "./test/index.ts"
"#test-utils": "./test/index.ts",
"#formatErrorMessage": "./src/utils/formatErrorMessage.ts"
},
"type": "commonjs",
"scripts": {
Expand Down
15 changes: 15 additions & 0 deletions packages/react/src/utils/formatErrorMessage.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
/**
* WARNING: Don't import this directly. It's imported by the code generated by
* `@mui/interal-babel-plugin-minify-errors`. Make sure to always use string literals in `Error`
* constructors to ensure the plugin works as expected. Supported patterns include:
* throw new Error('My message');
* throw new Error(`My message: ${foo}`);
* throw new Error(`My message: ${foo}` + 'another string');
* ...
* @param {number} code
*/
export default function formatErrorMessage(code: number, ...args: string[]): string {
const url = new URL(`https://base-ui.com/production-error/${code}`);
args.forEach((arg) => url.searchParams.append('args[]', arg));
return `Base UI error #${code}; visit ${url} for the full message.`;
}
25 changes: 22 additions & 3 deletions pnpm-lock.yaml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.