Skip to content

Commit

Permalink
Feat: error-decoder (#6214)
Browse files Browse the repository at this point in the history
* Feat: port error-decoder

* Fix: do not choke on empty invariant

* Refactor: read url query from `useRouter`

* Fix: argsList can contains `undefined`

* Fix: handle empty string arg

* Feat: move error decoder to the separate page

* Fix: wrap error decoder header in <Intro />

* Perf: cache GitHub RAW requests

* Refactor: apply code review suggestions

* Fix: build error

* Refactor: apply code review suggestions

* Discard changes to src/content/index.md

* Fix: animation duration/delay

* Refactor: read error page from markdown

* Fix lint

* Fix /error being 404

* Prevent `_default.md` being included in `[[...markdownPath]].md`

* Fix custom error markdown reading

* Updates

---------

Co-authored-by: Ricky Hanlon <rickhanlonii@gmail.com>
  • Loading branch information
SukkaW and rickhanlonii committed Jan 12, 2024
1 parent 6987f0f commit 8d2664b
Show file tree
Hide file tree
Showing 11 changed files with 504 additions and 135 deletions.
23 changes: 23 additions & 0 deletions src/components/ErrorDecoderContext.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
// Error Decoder requires reading pregenerated error message from getStaticProps,
// but MDX component doesn't support props. So we use React Context to populate
// the value without prop-drilling.
// TODO: Replace with React.cache + React.use when migrating to Next.js App Router

import {createContext, useContext} from 'react';

const notInErrorDecoderContext = Symbol('not in error decoder context');

export const ErrorDecoderContext = createContext<
| {errorMessage: string | null; errorCode: string | null}
| typeof notInErrorDecoderContext
>(notInErrorDecoderContext);

export const useErrorDecoderParams = () => {
const params = useContext(ErrorDecoderContext);

if (params === notInErrorDecoderContext) {
throw new Error('useErrorDecoder must be used in error decoder pages only');
}

return params;
};
107 changes: 107 additions & 0 deletions src/components/MDX/ErrorDecoder.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,107 @@
import {useEffect, useState} from 'react';
import {useErrorDecoderParams} from '../ErrorDecoderContext';
import cn from 'classnames';

function replaceArgs(
msg: string,
argList: Array<string | undefined>,
replacer = '[missing argument]'
): string {
let argIdx = 0;
return msg.replace(/%s/g, function () {
const arg = argList[argIdx++];
// arg can be an empty string: ?args[0]=&args[1]=count
return arg === undefined || arg === '' ? replacer : arg;
});
}

/**
* Sindre Sorhus <https://sindresorhus.com>
* Released under MIT license
* https://github.com/sindresorhus/linkify-urls/blob/edd75a64a9c36d7025f102f666ddbb6cf0afa7cd/index.js#L4C25-L4C137
*
* The regex is used to extract URL from the string for linkify.
*/
const urlRegex =
/((?<!\+)https?:\/\/(?:www\.)?(?:[-\w.]+?[.@][a-zA-Z\d]{2,}|localhost)(?:[-\w.:%+~#*$!?&/=@]*?(?:,(?!\s))*?)*)/g;

// When the message contains a URL (like https://fb.me/react-refs-must-have-owner),
// make it a clickable link.
function urlify(str: string): React.ReactNode[] {
const segments = str.split(urlRegex);

return segments.map((message, i) => {
if (i % 2 === 1) {
return (
<a
key={i}
target="_blank"
className="underline"
rel="noopener noreferrer"
href={message}>
{message}
</a>
);
}
return message;
});
}

// `?args[]=foo&args[]=bar`
// or `// ?args[0]=foo&args[1]=bar`
function parseQueryString(search: string): Array<string | undefined> {
const rawQueryString = search.substring(1);
if (!rawQueryString) {
return [];
}

const args: Array<string | undefined> = [];

const queries = rawQueryString.split('&');
for (let i = 0; i < queries.length; i++) {
const query = decodeURIComponent(queries[i]);
if (query.startsWith('args[')) {
args.push(query.slice(query.indexOf(']=') + 2));
}
}

return args;
}

export default function ErrorDecoder() {
const {errorMessage} = useErrorDecoderParams();
/** error messages that contain %s require reading location.search */
const hasParams = errorMessage?.includes('%s');
const [message, setMessage] = useState<React.ReactNode | null>(() =>
errorMessage ? urlify(errorMessage) : null
);

const [isReady, setIsReady] = useState(errorMessage == null || !hasParams);

useEffect(() => {
if (errorMessage == null || !hasParams) {
return;
}

setMessage(
urlify(
replaceArgs(
errorMessage,
parseQueryString(window.location.search),
'[missing argument]'
)
)
);
setIsReady(true);
}, [hasParams, errorMessage]);

return (
<code
className={cn(
'block bg-red-100 text-red-600 py-4 px-6 mt-5 rounded-lg',
isReady ? 'opacity-100' : 'opacity-0'
)}>
<b>{message}</b>
</code>
);
}
3 changes: 3 additions & 0 deletions src/components/MDX/MDXComponents.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,8 @@ import {TocContext} from './TocContext';
import type {Toc, TocItem} from './TocContext';
import {TeamMember} from './TeamMember';

import ErrorDecoder from './ErrorDecoder';

function CodeStep({children, step}: {children: any; step: number}) {
return (
<span
Expand Down Expand Up @@ -441,6 +443,7 @@ export const MDXComponents = {
Solution,
CodeStep,
YouTubeIframe,
ErrorDecoder,
};

for (let key in MDXComponents) {
Expand Down
13 changes: 13 additions & 0 deletions src/content/errors/377.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
<Intro>

In the minified production build of React, we avoid sending down full error messages in order to reduce the number of bytes sent over the wire.

</Intro>

We highly recommend using the development build locally when debugging your app since it tracks additional debug info and provides helpful warnings about potential problems in your apps, but if you encounter an exception while using the production build, this page will reassemble the original error message.

The full text of the error you just encountered is:

<ErrorDecoder />

This error occurs when you pass a BigInt value from a Server Component to a Client Component.
11 changes: 11 additions & 0 deletions src/content/errors/generic.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
<Intro>

In the minified production build of React, we avoid sending down full error messages in order to reduce the number of bytes sent over the wire.

</Intro>

We highly recommend using the development build locally when debugging your app since it tracks additional debug info and provides helpful warnings about potential problems in your apps, but if you encounter an exception while using the production build, this page will reassemble the original error message.

The full text of the error you just encountered is:

<ErrorDecoder />
10 changes: 10 additions & 0 deletions src/content/errors/index.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
<Intro>

In the minified production build of React, we avoid sending down full error messages in order to reduce the number of bytes sent over the wire.

</Intro>


We highly recommend using the development build locally when debugging your app since it tracks additional debug info and provides helpful warnings about potential problems in your apps, but if you encounter an exception while using the production build, the error message will include just a link to the docs for the error.

For an example, see: [https://react.dev/errors/149](/errors/421).
148 changes: 13 additions & 135 deletions src/pages/[[...markdownPath]].js
Original file line number Diff line number Diff line change
Expand Up @@ -4,14 +4,14 @@

import {Fragment, useMemo} from 'react';
import {useRouter} from 'next/router';
import {MDXComponents} from 'components/MDX/MDXComponents';
import {Page} from 'components/Layout/Page';
import sidebarHome from '../sidebarHome.json';
import sidebarLearn from '../sidebarLearn.json';
import sidebarReference from '../sidebarReference.json';
import sidebarCommunity from '../sidebarCommunity.json';
import sidebarBlog from '../sidebarBlog.json';

import {MDXComponents} from 'components/MDX/MDXComponents';
import compileMDX from 'utils/compileMDX';
export default function Layout({content, toc, meta}) {
const parsedContent = useMemo(
() => JSON.parse(content, reviveNodeOnClient),
Expand Down Expand Up @@ -94,20 +94,10 @@ function reviveNodeOnClient(key, val) {
}
}

// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// ~~~~ IMPORTANT: BUMP THIS IF YOU CHANGE ANY CODE BELOW ~~~
const DISK_CACHE_BREAKER = 7;
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

// Put MDX output into JSON for client.
export async function getStaticProps(context) {
const fs = require('fs');
const {
prepareMDX,
PREPARE_MDX_CACHE_BREAKER,
} = require('../utils/prepareMDX');
const rootDir = process.cwd() + '/src/content/';
const mdxComponentNames = Object.keys(MDXComponents);

// Read MDX from the file.
let path = (context.params.markdownPath || []).join('/') || 'index';
Expand All @@ -118,132 +108,14 @@ export async function getStaticProps(context) {
mdx = fs.readFileSync(rootDir + path + '/index.md', 'utf8');
}

// See if we have a cached output first.
const {FileStore, stableHash} = require('metro-cache');
const store = new FileStore({
root: process.cwd() + '/node_modules/.cache/react-docs-mdx/',
});
const hash = Buffer.from(
stableHash({
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// ~~~~ IMPORTANT: Everything that the code below may rely on.
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
mdx,
mdxComponentNames,
DISK_CACHE_BREAKER,
PREPARE_MDX_CACHE_BREAKER,
lockfile: fs.readFileSync(process.cwd() + '/yarn.lock', 'utf8'),
})
);
const cached = await store.get(hash);
if (cached) {
console.log(
'Reading compiled MDX for /' + path + ' from ./node_modules/.cache/'
);
return cached;
}
if (process.env.NODE_ENV === 'production') {
console.log(
'Cache miss for MDX for /' + path + ' from ./node_modules/.cache/'
);
}

// If we don't add these fake imports, the MDX compiler
// will insert a bunch of opaque components we can't introspect.
// This will break the prepareMDX() call below.
let mdxWithFakeImports =
mdx +
'\n\n' +
mdxComponentNames
.map((key) => 'import ' + key + ' from "' + key + '";\n')
.join('\n');

// Turn the MDX we just read into some JS we can execute.
const {remarkPlugins} = require('../../plugins/markdownToHtml');
const {compile: compileMdx} = await import('@mdx-js/mdx');
const visit = (await import('unist-util-visit')).default;
const jsxCode = await compileMdx(mdxWithFakeImports, {
remarkPlugins: [
...remarkPlugins,
(await import('remark-gfm')).default,
(await import('remark-frontmatter')).default,
],
rehypePlugins: [
// Support stuff like ```js App.js {1-5} active by passing it through.
function rehypeMetaAsAttributes() {
return (tree) => {
visit(tree, 'element', (node) => {
if (node.tagName === 'code' && node.data && node.data.meta) {
node.properties.meta = node.data.meta;
}
});
};
},
],
});
const {transform} = require('@babel/core');
const jsCode = await transform(jsxCode, {
plugins: ['@babel/plugin-transform-modules-commonjs'],
presets: ['@babel/preset-react'],
}).code;

// Prepare environment for MDX.
let fakeExports = {};
const fakeRequire = (name) => {
if (name === 'react/jsx-runtime') {
return require('react/jsx-runtime');
} else {
// For each fake MDX import, give back the string component name.
// It will get serialized later.
return name;
}
};
const evalJSCode = new Function('require', 'exports', jsCode);
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// THIS IS A BUILD-TIME EVAL. NEVER DO THIS WITH UNTRUSTED MDX (LIKE FROM CMS)!!!
// In this case it's okay because anyone who can edit our MDX can also edit this file.
evalJSCode(fakeRequire, fakeExports);
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
const reactTree = fakeExports.default({});

// Pre-process MDX output and serialize it.
let {toc, children} = prepareMDX(reactTree.props.children);
if (path === 'index') {
toc = [];
}

// Parse Frontmatter headers from MDX.
const fm = require('gray-matter');
const meta = fm(mdx).data;

const output = {
const {toc, content, meta} = await compileMDX(mdx, path, {});
return {
props: {
content: JSON.stringify(children, stringifyNodeOnServer),
toc: JSON.stringify(toc, stringifyNodeOnServer),
toc,
content,
meta,
},
};

// Serialize a server React tree node to JSON.
function stringifyNodeOnServer(key, val) {
if (val != null && val.$$typeof === Symbol.for('react.element')) {
// Remove fake MDX props.
// eslint-disable-next-line @typescript-eslint/no-unused-vars
const {mdxType, originalType, parentName, ...cleanProps} = val.props;
return [
'$r',
typeof val.type === 'string' ? val.type : mdxType,
val.key,
cleanProps,
];
} else {
return val;
}
}

// Cache it on the disk.
await store.set(hash, output);
return output;
}

// Collect all MDX files for static generation.
Expand All @@ -266,7 +138,12 @@ export async function getStaticPaths() {
: res.slice(rootDir.length + 1);
})
);
return files.flat().filter((file) => file.endsWith('.md'));
return (
files
.flat()
// ignores `errors/*.md`, they will be handled by `pages/errors/[errorCode].tsx`
.filter((file) => file.endsWith('.md') && !file.startsWith('errors/'))
);
}

// 'foo/bar/baz.md' -> ['foo', 'bar', 'baz']
Expand All @@ -280,6 +157,7 @@ export async function getStaticPaths() {
}

const files = await getFiles(rootDir);

const paths = files.map((file) => ({
params: {
markdownPath: getSegments(file),
Expand Down

0 comments on commit 8d2664b

Please sign in to comment.