diff --git a/errors.json b/errors.json new file mode 100644 index 0000000000..49e6c98a69 --- /dev/null +++ b/errors.json @@ -0,0 +1,19 @@ +{ + "0": "It looks like you are passing several store enhancers to createStore(). This is not supported. Instead, compose them together to a single function.", + "1": "Expected the enhancer to be a function.", + "2": "Expected the reducer to be a function.", + "3": "You may not call store.getState() while the reducer is executing. The reducer has already received the state as an argument. Pass it down from the top reducer instead of reading it from the store.", + "4": "Expected the listener to be a function.", + "5": "You may not call store.subscribe() while the reducer is executing. If you would like to be notified after the store has been updated, subscribe from a component and invoke store.getState() in the callback to access the latest state. See https://redux.js.org/api/store#subscribelistener for more details.", + "6": "You may not unsubscribe from a store listener while the reducer is executing. See https://redux.js.org/api/store#subscribelistener for more details.", + "7": "Actions must be plain objects. Use custom middleware for async actions.", + "8": "Actions may not have an undefined \"type\" property. Have you misspelled a constant?", + "9": "Reducers may not dispatch actions.", + "10": "Expected the nextReducer to be a function.", + "11": "Expected the observer to be an object.", + "12": "bindActionCreators expected an object or a function, instead received . Did you write \"import ActionCreators from\" instead of \"import * as ActionCreators from\"?", + "13": "Dispatching while constructing your middleware is not allowed. Other middleware would not be applied to this dispatch.", + "14": "Reducer \"\" returned undefined during initialization. If the state passed to the reducer is undefined, you must explicitly return the initial state. The initial state may not be undefined. If you don't want to set a value for this reducer, you can use null instead of undefined.", + "15": "Reducer \"\" returned undefined when probed with a random type. Don't try to handle or other actions in \"redux/*\" namespace. They are considered private. Instead, you must return the current state for any unknown actions, unless it is undefined, in which case you must return the initial state, regardless of the action type. The initial state may not be undefined, but can be null.", + "16": "Super expression must either be null or a function" +} \ No newline at end of file diff --git a/package-lock.json b/package-lock.json index 02ce5a160e..79c7a20628 100644 --- a/package-lock.json +++ b/package-lock.json @@ -3768,9 +3768,9 @@ } }, "@rollup/plugin-babel": { - "version": "5.2.2", - "resolved": "https://registry.npmjs.org/@rollup/plugin-babel/-/plugin-babel-5.2.2.tgz", - "integrity": "sha512-MjmH7GvFT4TW8xFdIeFS3wqIX646y5tACdxkTO+khbHvS3ZcVJL6vkAHLw2wqPmkhwCfWHoNsp15VYNwW6JEJA==", + "version": "5.3.0", + "resolved": "https://registry.npmjs.org/@rollup/plugin-babel/-/plugin-babel-5.3.0.tgz", + "integrity": "sha512-9uIC8HZOnVLrLHxayq/PTzw+uS25E14KPUBh5ktF+18Mjo5yK0ToMMx6epY0uEgkjwJw0aBW4x2horYXh8juWw==", "dev": true, "requires": { "@babel/helper-module-imports": "^7.10.4", @@ -3778,12 +3778,12 @@ }, "dependencies": { "@babel/helper-module-imports": { - "version": "7.12.5", - "resolved": "https://registry.npmjs.org/@babel/helper-module-imports/-/helper-module-imports-7.12.5.tgz", - "integrity": "sha512-SR713Ogqg6++uexFRORf/+nPXMmWIn80TALu0uaFb+iQIUoR7bOC7zBWyzBs5b3tBBJXuyD0cRu1F15GyzjOWA==", + "version": "7.13.12", + "resolved": "https://registry.npmjs.org/@babel/helper-module-imports/-/helper-module-imports-7.13.12.tgz", + "integrity": "sha512-4cVvR2/1B693IuOvSI20xqqa/+bl7lqAMR59R4iu39R9aOX8/JoYY1sFaNvUMyMBGnHdwvJgUrzNLoUZxXypxA==", "dev": true, "requires": { - "@babel/types": "^7.12.5" + "@babel/types": "^7.13.12" } }, "@babel/helper-validator-identifier": { @@ -3793,9 +3793,9 @@ "dev": true }, "@babel/types": { - "version": "7.12.12", - "resolved": "https://registry.npmjs.org/@babel/types/-/types-7.12.12.tgz", - "integrity": "sha512-lnIX7piTxOH22xE7fDXDbSHg9MM1/6ORnafpJmov5rs0kX5g4BZxeXNJLXsMRiO0U5Rb8/FvMS6xlTnTHvxonQ==", + "version": "7.13.13", + "resolved": "https://registry.npmjs.org/@babel/types/-/types-7.13.13.tgz", + "integrity": "sha512-kt+EpC6qDfIaqlP+DIbIJOclYy/A1YXs9dAf/ljbi+39Bcbc073H6jKVpXEr/EoIh5anGn5xq/yRVzKl+uIc9w==", "dev": true, "requires": { "@babel/helper-validator-identifier": "^7.12.11", @@ -3821,9 +3821,9 @@ "dev": true }, "lodash": { - "version": "4.17.20", - "resolved": "https://registry.npmjs.org/lodash/-/lodash-4.17.20.tgz", - "integrity": "sha512-PlhdFcillOINfeV7Ni6oF1TAEayyZBoZ8bcshTHqOYJYlrqzRK5hagpagky5o4HfCzzd1TRkXPMFq6cKk9rGmA==", + "version": "4.17.21", + "resolved": "https://registry.npmjs.org/lodash/-/lodash-4.17.21.tgz", + "integrity": "sha512-v2kDEe57lecTulaDIuNTPy3Ry4gLGJ6Z1O3vE1krgXZNrsQ+LFTGHVxVjcXPs17LhbZVGedAJv8XZ1tvj5FvSg==", "dev": true } } diff --git a/package.json b/package.json index 34c25b409d..54e797b90e 100644 --- a/package.json +++ b/package.json @@ -63,7 +63,7 @@ "@babel/preset-flow": "^7.9.0", "@babel/preset-typescript": "^7.9.0", "@babel/register": "^7.9.0", - "@rollup/plugin-babel": "^5.2.2", + "@rollup/plugin-babel": "^5.3.0", "@rollup/plugin-node-resolve": "^7.1.3", "@rollup/plugin-replace": "^2.3.2", "@types/jest": "^25.2.1", diff --git a/rollup.config.js b/rollup.config.js index 7b22bd3aa6..5f2104ef6d 100644 --- a/rollup.config.js +++ b/rollup.config.js @@ -14,12 +14,12 @@ const babelRuntimeVersion = pkg.dependencies['@babel/runtime'].replace( '' ) -const makeExternalPredicate = (externalArr) => { +const makeExternalPredicate = externalArr => { if (externalArr.length === 0) { return () => false } const pattern = new RegExp(`^(${externalArr.join('|')})($|/)`) - return (id) => pattern.test(id) + return id => pattern.test(id) } export default [ @@ -29,21 +29,22 @@ export default [ output: { file: 'lib/redux.js', format: 'cjs', indent: false }, external: makeExternalPredicate([ ...Object.keys(pkg.dependencies || {}), - ...Object.keys(pkg.peerDependencies || {}), + ...Object.keys(pkg.peerDependencies || {}) ]), plugins: [ nodeResolve({ - extensions, + extensions }), typescript({ useTsconfigDeclarationDir: true }), babel({ extensions, plugins: [ ['@babel/plugin-transform-runtime', { version: babelRuntimeVersion }], + ['./scripts/mangleErrors.js', { minify: false }] ], babelHelpers: 'runtime' - }), - ], + }) + ] }, // ES @@ -52,11 +53,11 @@ export default [ output: { file: 'es/redux.js', format: 'es', indent: false }, external: makeExternalPredicate([ ...Object.keys(pkg.dependencies || {}), - ...Object.keys(pkg.peerDependencies || {}), + ...Object.keys(pkg.peerDependencies || {}) ]), plugins: [ nodeResolve({ - extensions, + extensions }), typescript({ tsconfigOverride: noDeclarationFiles }), babel({ @@ -64,12 +65,13 @@ export default [ plugins: [ [ '@babel/plugin-transform-runtime', - { version: babelRuntimeVersion, useESModules: true }, + { version: babelRuntimeVersion, useESModules: true } ], + ['./scripts/mangleErrors.js', { minify: false }] ], babelHelpers: 'runtime' - }), - ], + }) + ] }, // ES for Browsers @@ -78,25 +80,27 @@ export default [ output: { file: 'es/redux.mjs', format: 'es', indent: false }, plugins: [ nodeResolve({ - extensions, + extensions }), replace({ - 'process.env.NODE_ENV': JSON.stringify('production'), + 'process.env.NODE_ENV': JSON.stringify('production') }), typescript({ tsconfigOverride: noDeclarationFiles }), babel({ extensions, exclude: 'node_modules/**', + plugins: [['./scripts/mangleErrors.js', { minify: true }]], + skipPreflightCheck: true }), terser({ compress: { pure_getters: true, unsafe: true, unsafe_comps: true, - warnings: false, - }, - }), - ], + warnings: false + } + }) + ] }, // UMD Development @@ -106,21 +110,22 @@ export default [ file: 'dist/redux.js', format: 'umd', name: 'Redux', - indent: false, + indent: false }, plugins: [ nodeResolve({ - extensions, + extensions }), typescript({ tsconfigOverride: noDeclarationFiles }), babel({ extensions, exclude: 'node_modules/**', + plugins: [['./scripts/mangleErrors.js', { minify: false }]] }), replace({ - 'process.env.NODE_ENV': JSON.stringify('development'), - }), - ], + 'process.env.NODE_ENV': JSON.stringify('development') + }) + ] }, // UMD Production @@ -130,28 +135,30 @@ export default [ file: 'dist/redux.min.js', format: 'umd', name: 'Redux', - indent: false, + indent: false }, plugins: [ nodeResolve({ - extensions, + extensions }), typescript({ tsconfigOverride: noDeclarationFiles }), babel({ extensions, exclude: 'node_modules/**', + plugins: [['./scripts/mangleErrors.js', { minify: true }]], + skipPreflightCheck: true }), replace({ - 'process.env.NODE_ENV': JSON.stringify('production'), + 'process.env.NODE_ENV': JSON.stringify('production') }), terser({ compress: { pure_getters: true, unsafe: true, unsafe_comps: true, - warnings: false, - }, - }), - ], - }, + warnings: false + } + }) + ] + } ] diff --git a/scripts/mangleErrors.js b/scripts/mangleErrors.js new file mode 100644 index 0000000000..d8b8502a52 --- /dev/null +++ b/scripts/mangleErrors.js @@ -0,0 +1,146 @@ +const fs = require('fs') +const helperModuleImports = require('@babel/helper-module-imports') + +/** + * Converts an AST type into a javascript string so that it can be added to the error message lookup. + * + * Adapted from React (https://github.com/facebook/react/blob/master/scripts/shared/evalToString.js) with some + * adjustments + */ +const evalToString = ast => { + switch (ast.type) { + case 'StringLiteral': + case 'Literal': // ESLint + return ast.value + case 'BinaryExpression': // `+` + if (ast.operator !== '+') { + throw new Error('Unsupported binary operator ' + ast.operator) + } + return evalToString(ast.left) + evalToString(ast.right) + case 'TemplateLiteral': + return ast.quasis.reduce( + (concatenatedValue, templateElement) => + concatenatedValue + templateElement.value.raw, + '' + ) + case 'Identifier': + return ast.name + default: + throw new Error('Unsupported type ' + ast.type) + } +} + +/** + * Takes a `throw new error` statement and transforms it depending on the minify argument. Either option results in a + * smaller bundle size in production for consumers. + * + * If minify is enabled, we'll replace the error message with just an index that maps to an arrow object lookup. + * + * If minify is disabled, we'll add in a conditional statement to check the process.env.NODE_ENV which will output a + * an error number index in production or the actual error message in development. This allows consumers using webpak + * or another build tool to have these messages in development but have just the error index in production. + * + * E.g. + * Before: + * throw new Error("This is my error message."); + * throw new Error("This is a second error message."); + * + * After (with minify): + * throw new Error(0); + * throw new Error(1); + * + * After: (without minify): + * throw new Error(node.process.NODE_ENV === 'production' ? 0 : "This is my error message."); + * throw new Error(node.process.NODE_ENV === 'production' ? 1 : "This is a second error message."); + */ +module.exports = babel => { + const t = babel.types + // When the plugin starts up, we'll load in the existing file. This allows us to continually add to it so that the + // indexes do not change between builds. + let errorsFiles = '' + if (fs.existsSync('errors.json')) { + errorsFiles = fs.readFileSync('errors.json').toString() + } + let errors = Object.values(JSON.parse(errorsFiles || '{}')) + // This variable allows us to skip writing back to the file if the errors array hasn't changed + let changeInArray = false + + return { + pre: () => { + changeInArray = false + }, + visitor: { + ThrowStatement(path, file) { + const arguments = path.node.argument.arguments + const minify = file.opts.minify + + if (arguments && arguments[0]) { + // Skip running this logic when certain types come up: + // Identifier comes up when a variable is thrown (E.g. throw new error(message)) + // NumericLiteral, CallExpression, and ConditionalExpression is code we have already processed + if ( + path.node.argument.arguments[0].type === 'Identifier' || + path.node.argument.arguments[0].type === 'NumericLiteral' || + path.node.argument.arguments[0].type === 'ConditionalExpression' || + path.node.argument.arguments[0].type === 'CallExpression' + ) { + return + } + + const errorMsgLiteral = evalToString(path.node.argument.arguments[0]) + + // Attempt to get the existing index of the error. If it is not found, add it to the array as a new error. + let errorIndex = errors.indexOf(errorMsgLiteral) + if (errorIndex === -1) { + errors.push(errorMsgLiteral) + errorIndex = errors.length - 1 + changeInArray = true + } + + // Import the error message function + const formatProdErrorMessageIdentifier = helperModuleImports.addDefault( + path, + 'src/utils/formatProdErrorMessage', + { nameHint: 'formatProdErrorMessage' } + ) + + // Creates a function call to output the message to the error code page on the website + const prodMessage = t.callExpression( + formatProdErrorMessageIdentifier, + [t.numericLiteral(errorIndex)] + ) + + if (minify) { + path.replaceWith( + t.throwStatement( + t.newExpression(t.identifier('Error'), [prodMessage]) + ) + ) + } else { + path.replaceWith( + t.throwStatement( + t.newExpression(t.identifier('Error'), [ + t.conditionalExpression( + t.binaryExpression( + '===', + t.identifier('process.env.NODE_ENV'), + t.stringLiteral('production') + ), + prodMessage, + path.node.argument.arguments[0] + ) + ]) + ) + ) + } + } + } + }, + post: () => { + // If there is a new error in the array, convert it to an indexed object and write it back to the file. + if (changeInArray) { + fs.writeFileSync('errors.json', JSON.stringify({ ...errors }, null, 2)) + } + } + } +} diff --git a/src/utils/formatProdErrorMessage.ts b/src/utils/formatProdErrorMessage.ts new file mode 100644 index 0000000000..a0ec70e46f --- /dev/null +++ b/src/utils/formatProdErrorMessage.ts @@ -0,0 +1,15 @@ +/** + * Adapted from React: https://github.com/facebook/react/blob/master/packages/shared/formatProdErrorMessage.js + * + * Do not require this module directly! Use normal throw error calls. These messages will be replaced with error codes + * during build. + * @param {number} code + */ +function formatProdErrorMessage(code: number) { + return ( + `Minified Redux error #${code}; visit https://redux.js.org/Errors?code=${code} for the full message or ` + + 'use the non-minified dev environment for full errors. ' + ) +} + +export default formatProdErrorMessage diff --git a/website/package-lock.json b/website/package-lock.json index 86c0869a84..8906e567d9 100644 --- a/website/package-lock.json +++ b/website/package-lock.json @@ -12520,6 +12520,11 @@ } } }, + "url-search-params-polyfill": { + "version": "8.1.0", + "resolved": "https://registry.npmjs.org/url-search-params-polyfill/-/url-search-params-polyfill-8.1.0.tgz", + "integrity": "sha512-MRG3vzXyG20BJ2fox50/9ZRoe+2h3RM7DIudVD2u/GY9MtayO1Dkrna76IUOak+uoUPVWbyR0pHCzxctP/eDYQ==" + }, "use": { "version": "3.1.1", "resolved": "https://registry.npmjs.org/use/-/use-3.1.1.tgz", diff --git a/website/package.json b/website/package.json index b4c4e4b215..a17070eda9 100755 --- a/website/package.json +++ b/website/package.json @@ -10,7 +10,8 @@ "@docusaurus/preset-classic": "2.0.0-alpha.70", "classnames": "2.2.6", "react": "16.13.0", - "react-dom": "16.13.0" + "react-dom": "16.13.0", + "url-search-params-polyfill": "^8.1.0" }, "browserslist": { "production": [ diff --git a/website/src/pages/errors.js b/website/src/pages/errors.js new file mode 100644 index 0000000000..4a9fe31369 --- /dev/null +++ b/website/src/pages/errors.js @@ -0,0 +1,62 @@ +import React from 'react' +import Layout from '@theme/Layout' +import { useLocation } from '@docusaurus/router' +import useDocusaurusContext from '@docusaurus/useDocusaurusContext' +import styles from './styles.module.css' +import errorCodes from '../../../errors.json' +import 'url-search-params-polyfill' + +function Errors() { + const location = useLocation() + const context = useDocusaurusContext() + const { siteConfig = {} } = context + const errorCode = new URLSearchParams(location.search).get('code') + const error = errorCodes[errorCode] + + return ( + +
+

Production Error Codes

+

+ When Redux is built and running in production, error text is replaced + by indexed error codes to save on bundle size. These errors will + provide a link to this page with more information about the error + below. +

+ {error && ( + +

+ + The full text of the error you just encountered is: + +

+ {error} +
+ )} + +

All Error Codes

+ + + + + + + + + {Object.keys(errorCodes).map(code => ( + + + + + ))} + +
CodeMessage
{code}{errorCodes[code]}
+
+
+ ) +} + +export default Errors diff --git a/website/src/pages/styles.module.css b/website/src/pages/styles.module.css index 7015247dc8..cb8fc5f824 100755 --- a/website/src/pages/styles.module.css +++ b/website/src/pages/styles.module.css @@ -41,3 +41,31 @@ max-height: 16px; fill: var(--ifm-color-primary); } + +.mainFull { + padding: 34px 16px; + width: 100%; + max-width: var(--ifm-container-width); + margin: 0px auto; +} +.mainFull h1 { + font-size: 3rem; + color: var(--ifm-heading-color); + font-weight: var(--ifm-heading-font-weight); + line-height: var(--ifm-heading-line-height); +} + +.mainFull p { + margin-bottom: var(--ifm-leading); + margin-top: 0; +} + +.errorDetails { + color: #ff6464; + border-radius: 0.5rem; + padding: 1rem; + margin: 30px 0; + font-weight: bold; + background-color: rgba(255, 100, 100, 0.1); + display: block; +}