From 41d9288e3dbe0c3d747fcd2e5a4d803deaaf1d26 Mon Sep 17 00:00:00 2001 From: Alexey Pyltsyn Date: Wed, 16 Jun 2021 12:37:28 +0300 Subject: [PATCH] refactor(v2): cleanup console output (#4979) * refactor(v2): cleanup console output * fix jest issue Co-authored-by: slorber --- packages/docusaurus-init/bin/index.js | 6 +- packages/docusaurus-init/src/index.ts | 35 +++--- .../__snapshots__/index.test.js.snap | 2 +- .../src/remark/transformImage/index.js | 4 +- .../__snapshots__/index.test.js.snap | 2 +- .../src/remark/transformLinks/index.js | 4 +- packages/docusaurus-migrate/bin/index.js | 12 +- .../collectRedirects.test.ts.snap | 6 +- .../redirectValidation.test.ts.snap | 6 +- .../src/__tests__/extensionRedirects.test.ts | 109 +++++++++++------- .../src/__tests__/writeRedirectFiles.test.ts | 2 +- .../src/extensionRedirects.ts | 12 +- .../src/writeRedirectFiles.ts | 4 +- .../src/blogUtils.ts | 4 +- .../src/index.ts | 2 +- .../__snapshots__/index.test.ts.snap | 6 +- .../src/__tests__/cli.test.ts | 32 ++--- .../src/__tests__/docs.test.ts | 2 +- .../src/__tests__/index.test.ts | 18 +-- .../src/__tests__/sidebars.test.ts | 17 +-- .../src/__tests__/versions.test.ts | 18 +-- .../docusaurus-plugin-content-docs/src/cli.ts | 18 +-- .../client/__tests__/docsClientUtils.test.ts | 4 +- .../src/client/docsClientUtils.ts | 2 +- .../src/docs.ts | 2 +- .../src/index.ts | 6 +- .../src/markdown/linkify.ts | 2 +- .../src/options.ts | 4 +- .../src/props.ts | 4 +- .../src/sidebarItemsGenerator.ts | 6 +- .../src/sidebars.ts | 32 ++--- .../src/slug.ts | 4 +- .../src/versions.ts | 32 ++--- .../src/index.js | 4 +- .../src/index.js | 4 +- .../src/__tests__/createSitemap.test.ts | 4 +- .../src/createSitemap.ts | 2 +- .../docusaurus-plugin-sitemap/src/index.ts | 2 +- .../src/theme/NavbarItem/DocNavbarItem.tsx | 4 +- .../src/theme/NavbarItem/index.tsx | 2 +- .../src/theme/hooks/useThemeContext.ts | 2 +- .../theme/hooks/useUserPreferencesContext.ts | 2 +- .../DocsPreferredVersionProvider.tsx | 2 +- .../src/utils/storageUtils.ts | 6 +- .../src/utils/usePluralForm.ts | 2 +- .../src/__tests__/validationUtils.test.ts | 2 +- .../src/validationSchemas.ts | 2 +- .../src/validationUtils.ts | 6 +- .../__snapshots__/index.test.ts.snap | 2 +- .../src/__tests__/index.test.ts | 4 +- packages/docusaurus-utils/src/index.ts | 6 +- .../docusaurus-utils/src/markdownParser.ts | 7 +- packages/docusaurus/bin/docusaurus.js | 68 +++++------ packages/docusaurus/src/choosePort.ts | 2 +- .../client/exports/useDocusaurusContext.ts | 2 +- .../src/client/exports/useGlobalData.ts | 6 +- packages/docusaurus/src/client/serverEntry.js | 2 +- .../__tests__/writeHeadingIds.test.ts | 2 +- packages/docusaurus/src/commands/build.ts | 8 +- packages/docusaurus/src/commands/clear.ts | 4 +- packages/docusaurus/src/commands/deploy.ts | 26 +++-- packages/docusaurus/src/commands/serve.ts | 6 +- packages/docusaurus/src/commands/start.ts | 8 +- packages/docusaurus/src/commands/swizzle.ts | 6 +- .../src/commands/writeHeadingIds.ts | 6 +- .../src/commands/writeTranslations.ts | 5 +- .../__snapshots__/config.test.ts.snap | 4 +- .../configValidation.test.ts.snap | 10 +- .../src/server/__tests__/config.test.ts | 2 +- .../src/server/__tests__/i18n.test.ts | 2 +- .../src/server/__tests__/routes.test.ts | 4 +- packages/docusaurus/src/server/config.ts | 2 +- .../docusaurus/src/server/configValidation.ts | 4 +- .../html-tags/__tests__/htmlTags.test.ts | 8 +- .../src/server/html-tags/htmlTags.ts | 6 +- packages/docusaurus/src/server/i18n.ts | 8 +- packages/docusaurus/src/server/index.ts | 2 +- .../__snapshots__/pluginIds.test.ts.snap | 6 +- .../docusaurus/src/server/plugins/index.ts | 2 +- .../docusaurus/src/server/plugins/init.ts | 2 +- .../src/server/plugins/pluginIds.ts | 2 +- packages/docusaurus/src/server/routes.ts | 2 +- .../__tests__/translations.test.ts | 2 +- .../src/server/translations/translations.ts | 10 +- .../src/webpack/plugins/CleanWebpackPlugin.ts | 2 +- packages/docusaurus/src/webpack/utils.ts | 6 +- 86 files changed, 382 insertions(+), 339 deletions(-) diff --git a/packages/docusaurus-init/bin/index.js b/packages/docusaurus-init/bin/index.js index f1316d0707..458eaa159c 100755 --- a/packages/docusaurus-init/bin/index.js +++ b/packages/docusaurus-init/bin/index.js @@ -18,9 +18,9 @@ const requiredVersion = require('../package.json').engines.node; if (!semver.satisfies(process.version, requiredVersion)) { console.log( - chalk.red(`\nMinimum node version not met :)`) + + chalk.red(`\nMinimum Node.js version not met :)`) + chalk.yellow( - `\nYou are using Node ${process.version}, Requirement: Node ${requiredVersion}.\n`, + `\nYou are using Node.js ${process.version}, Requirement: Node.js ${requiredVersion}.\n`, ), ); process.exit(1); @@ -42,7 +42,7 @@ program .command('init [siteName] [template] [rootDir]') .option('--use-npm') .option('--skip-install') - .description('Initialize website') + .description('Initialize website.') .action((siteName, template, rootDir = '.', {useNpm, skipInstall}) => { wrapCommand(init)(path.resolve(rootDir), siteName, template, { useNpm, diff --git a/packages/docusaurus-init/src/index.ts b/packages/docusaurus-init/src/index.ts index bb096f6f2d..9c16eb98f9 100644 --- a/packages/docusaurus-init/src/index.ts +++ b/packages/docusaurus-init/src/index.ts @@ -76,12 +76,12 @@ export default async function init( } if (!name) { - throw new Error(chalk.red('A site name is required')); + throw new Error(chalk.red('A website name is required.')); } const dest = path.resolve(rootDir, name); if (fs.existsSync(dest)) { - throw new Error(`Directory already exists at ${dest} !`); + throw new Error(`Directory already exists at "${dest}"!`); } let template = reqTemplate; @@ -108,22 +108,22 @@ export default async function init( return chalk.red(`Invalid repository URL`); }, message: - 'Enter a repository URL from GitHub, BitBucket, GitLab, or any other public repo. \n(e.g: https://github.com/ownerName/repoName.git)', + 'Enter a repository URL from GitHub, Bitbucket, GitLab, or any other public repo.\n(e.g: https://github.com/ownerName/repoName.git)', }); template = repoPrompt.gitRepoUrl; } console.log(); - console.log(chalk.cyan('Creating new Docusaurus project ...')); + console.log(chalk.cyan('Creating new Docusaurus project...')); console.log(); if (template && isValidGitRepoUrl(template)) { - console.log(`Cloning Git template: ${chalk.cyan(template)}`); + console.log(`Cloning Git template ${chalk.cyan(template)}...`); if ( shell.exec(`git clone --recursive ${template} ${dest}`, {silent: true}) .code !== 0 ) { - throw new Error(chalk.red(`Cloning Git template: ${template} failed!`)); + throw new Error(chalk.red(`Cloning Git template ${template} failed!`)); } } else if (template && templates.includes(template)) { // Docusaurus templates. @@ -131,12 +131,12 @@ export default async function init( await fs.copy(path.resolve(templatesDir, template), dest); } catch (err) { console.log( - `Copying Docusaurus template: ${chalk.cyan(template)} failed!`, + `Copying Docusaurus template ${chalk.cyan(template)} failed!`, ); throw err; } } else { - throw new Error('Invalid template'); + throw new Error('Invalid template.'); } // Update package.json info. @@ -147,7 +147,7 @@ export default async function init( private: true, }); } catch (err) { - console.log(chalk.red('Failed to update package.json')); + console.log(chalk.red('Failed to update package.json.')); throw err; } @@ -164,12 +164,12 @@ export default async function init( const pkgManager = useYarn ? 'yarn' : 'npm'; if (!cliOptions.skipInstall) { - console.log(`Installing dependencies with: ${chalk.cyan(pkgManager)}`); + console.log(`Installing dependencies with ${chalk.cyan(pkgManager)}...`); try { shell.exec(`cd "${name}" && ${useYarn ? 'yarn' : 'npm install'}`); } catch (err) { - console.log(chalk.red('Installation failed')); + console.log(chalk.red('Installation failed.')); throw err; } } @@ -182,23 +182,26 @@ export default async function init( : path.relative(process.cwd(), name); console.log(); - console.log(`Success! Created ${chalk.cyan(cdpath)}`); + console.log(`Successfully created "${chalk.cyan(cdpath)}".`); console.log('Inside that directory, you can run several commands:'); console.log(); console.log(chalk.cyan(` ${pkgManager} start`)); console.log(' Starts the development server.'); console.log(); console.log(chalk.cyan(` ${pkgManager} ${useYarn ? '' : 'run '}build`)); - console.log(' Bundles the app into static files for production.'); + console.log(' Bundles your website into static files for production.'); + console.log(); + console.log(chalk.cyan(` ${pkgManager} ${useYarn ? '' : 'run '}serve`)); + console.log(' Serve the built website locally.'); console.log(); console.log(chalk.cyan(` ${pkgManager} deploy`)); - console.log(' Publish website to GitHub pages.'); + console.log(' Publish the website to GitHub pages.'); console.log(); - console.log('We suggest that you begin by typing:'); + console.log('We recommend that you begin by typing:'); console.log(); console.log(chalk.cyan(' cd'), cdpath); console.log(` ${chalk.cyan(`${pkgManager} start`)}`); console.log(); - console.log('Happy hacking!'); + console.log('Happy building awesome websites!'); } diff --git a/packages/docusaurus-mdx-loader/src/remark/transformImage/__tests__/__snapshots__/index.test.js.snap b/packages/docusaurus-mdx-loader/src/remark/transformImage/__tests__/__snapshots__/index.test.js.snap index 46c4e1dded..571131fa51 100644 --- a/packages/docusaurus-mdx-loader/src/remark/transformImage/__tests__/__snapshots__/index.test.js.snap +++ b/packages/docusaurus-mdx-loader/src/remark/transformImage/__tests__/__snapshots__/index.test.js.snap @@ -2,7 +2,7 @@ exports[`transformImage plugin fail if image does not exist 1`] = `"Image packages/docusaurus-mdx-loader/src/remark/transformImage/__tests__/fixtures/img/doesNotExist.png used in packages/docusaurus-mdx-loader/src/remark/transformImage/__tests__/fixtures/fail.md not found."`; -exports[`transformImage plugin fail if image url is absent 1`] = `"Markdown image url is mandatory. filePath=packages/docusaurus-mdx-loader/src/remark/transformImage/__tests__/fixtures/noUrl.md"`; +exports[`transformImage plugin fail if image url is absent 1`] = `"Markdown image URL is mandatory in \\"packages/docusaurus-mdx-loader/src/remark/transformImage/__tests__/fixtures/noUrl.md\\" file"`; exports[`transformImage plugin pathname protocol 1`] = ` "![img](/img/unchecked.png) diff --git a/packages/docusaurus-mdx-loader/src/remark/transformImage/index.js b/packages/docusaurus-mdx-loader/src/remark/transformImage/index.js index 42122ab4a3..4afcc5136e 100644 --- a/packages/docusaurus-mdx-loader/src/remark/transformImage/index.js +++ b/packages/docusaurus-mdx-loader/src/remark/transformImage/index.js @@ -57,9 +57,9 @@ async function ensureImageFileExist(imagePath, sourceFilePath) { async function processImageNode(node, {filePath, staticDir}) { if (!node.url) { throw new Error( - `Markdown image url is mandatory. filePath=${toMessageRelativeFilePath( + `Markdown image URL is mandatory in "${toMessageRelativeFilePath( filePath, - )}`, + )}" file`, ); } diff --git a/packages/docusaurus-mdx-loader/src/remark/transformLinks/__tests__/__snapshots__/index.test.js.snap b/packages/docusaurus-mdx-loader/src/remark/transformLinks/__tests__/__snapshots__/index.test.js.snap index 1de13c618b..57d77f8a74 100644 --- a/packages/docusaurus-mdx-loader/src/remark/transformLinks/__tests__/__snapshots__/index.test.js.snap +++ b/packages/docusaurus-mdx-loader/src/remark/transformLinks/__tests__/__snapshots__/index.test.js.snap @@ -1,6 +1,6 @@ // Jest Snapshot v1, https://goo.gl/fbAQLP -exports[`transformAsset plugin fail if asset url is absent 1`] = `"Markdown link url is mandatory. filePath=packages/docusaurus-mdx-loader/src/remark/transformLinks/__tests__/fixtures/noUrl.md, title=asset, line=1"`; +exports[`transformAsset plugin fail if asset url is absent 1`] = `"Markdown link URL is mandatory in \\"packages/docusaurus-mdx-loader/src/remark/transformLinks/__tests__/fixtures/noUrl.md\\" file (title: asset, line: 1)."`; exports[`transformAsset plugin pathname protocol 1`] = ` "[asset](pathname:///asset/unchecked.pdf) diff --git a/packages/docusaurus-mdx-loader/src/remark/transformLinks/index.js b/packages/docusaurus-mdx-loader/src/remark/transformLinks/index.js index 50bc4d7f71..4ca56997eb 100644 --- a/packages/docusaurus-mdx-loader/src/remark/transformLinks/index.js +++ b/packages/docusaurus-mdx-loader/src/remark/transformLinks/index.js @@ -111,9 +111,9 @@ async function processLinkNode({node, _index, _parent, filePath, staticDir}) { const line = (node.position && node.position.start && node.position.start.line) || '?'; throw new Error( - `Markdown link url is mandatory. filePath=${toMessageRelativeFilePath( + `Markdown link URL is mandatory in "${toMessageRelativeFilePath( filePath, - )}, title=${title}, line=${line}`, + )}" file (title: ${title}, line: ${line}).`, ); } diff --git a/packages/docusaurus-migrate/bin/index.js b/packages/docusaurus-migrate/bin/index.js index 22abe761dd..a5fd00f108 100755 --- a/packages/docusaurus-migrate/bin/index.js +++ b/packages/docusaurus-migrate/bin/index.js @@ -28,9 +28,9 @@ function wrapCommand(fn) { if (!semver.satisfies(process.version, requiredVersion)) { console.log( - chalk.red(`\nMinimum Node version not met :(`) + + chalk.red(`\nMinimum Node.js version not met :(`) + chalk.yellow( - `\n\nYou are using Node ${process.version}. We require Node ${requiredVersion} or up!\n`, + `\n\nYou are using Node ${process.version}. We require Node.js ${requiredVersion} or up!\n`, ), ); process.exit(1); @@ -38,9 +38,9 @@ if (!semver.satisfies(process.version, requiredVersion)) { cli .command('migrate [siteDir] [newDir]') - .option('--mdx', 'Try to migrate MD to MDX too') - .option('--page', 'Try to migrate pages too') - .description('Migrate between versions of docusaurus website') + .option('--mdx', 'try to migrate MD to MDX too') + .option('--page', 'try to migrate pages too') + .description('Migrate between versions of Docusaurus website.') .action((siteDir = '.', newDir = '.', {mdx, page}) => { const sitePath = path.resolve(siteDir); const newSitePath = path.resolve(newDir); @@ -49,7 +49,7 @@ cli cli .command('mdx [siteDir] [newDir]') - .description('Migrate markdown files to MDX') + .description('Migrate markdown files to MDX.') .action((siteDir = '.', newDir = '.') => { const sitePath = path.resolve(siteDir); const newSitePath = path.resolve(newDir); diff --git a/packages/docusaurus-plugin-client-redirects/src/__tests__/__snapshots__/collectRedirects.test.ts.snap b/packages/docusaurus-plugin-client-redirects/src/__tests__/__snapshots__/collectRedirects.test.ts.snap index bf371adc8a..785f7e3478 100644 --- a/packages/docusaurus-plugin-client-redirects/src/__tests__/__snapshots__/collectRedirects.test.ts.snap +++ b/packages/docusaurus-plugin-client-redirects/src/__tests__/__snapshots__/collectRedirects.test.ts.snap @@ -20,8 +20,8 @@ exports[`collectRedirects should throw if redirect creator creates array of arra exports[`collectRedirects should throw if redirect creator creates invalid redirects 1`] = ` "Some created redirects are invalid: -- {\\"from\\":\\"https://google.com/\\",\\"to\\":\\"/\\"} => Validation error: \\"from\\" is not a valid pathname. Pathname should start with / and not contain any domain or query string -- {\\"from\\":\\"//abc\\",\\"to\\":\\"/\\"} => Validation error: \\"from\\" is not a valid pathname. Pathname should start with / and not contain any domain or query string -- {\\"from\\":\\"/def?queryString=toto\\",\\"to\\":\\"/\\"} => Validation error: \\"from\\" is not a valid pathname. Pathname should start with / and not contain any domain or query string +- {\\"from\\":\\"https://google.com/\\",\\"to\\":\\"/\\"} => Validation error: \\"from\\" is not a valid pathname. Pathname should start with slash and not contain any domain or query string. +- {\\"from\\":\\"//abc\\",\\"to\\":\\"/\\"} => Validation error: \\"from\\" is not a valid pathname. Pathname should start with slash and not contain any domain or query string. +- {\\"from\\":\\"/def?queryString=toto\\",\\"to\\":\\"/\\"} => Validation error: \\"from\\" is not a valid pathname. Pathname should start with slash and not contain any domain or query string. " `; diff --git a/packages/docusaurus-plugin-client-redirects/src/__tests__/__snapshots__/redirectValidation.test.ts.snap b/packages/docusaurus-plugin-client-redirects/src/__tests__/__snapshots__/redirectValidation.test.ts.snap index 87c6a074c4..62b3059d0e 100644 --- a/packages/docusaurus-plugin-client-redirects/src/__tests__/__snapshots__/redirectValidation.test.ts.snap +++ b/packages/docusaurus-plugin-client-redirects/src/__tests__/__snapshots__/redirectValidation.test.ts.snap @@ -1,10 +1,10 @@ // Jest Snapshot v1, https://goo.gl/fbAQLP -exports[`validateRedirect throw for bad redirects 1`] = `"{\\"from\\":\\"https://fb.com/fromSomePath\\",\\"to\\":\\"/toSomePath\\"} => Validation error: \\"from\\" is not a valid pathname. Pathname should start with / and not contain any domain or query string"`; +exports[`validateRedirect throw for bad redirects 1`] = `"{\\"from\\":\\"https://fb.com/fromSomePath\\",\\"to\\":\\"/toSomePath\\"} => Validation error: \\"from\\" is not a valid pathname. Pathname should start with slash and not contain any domain or query string."`; -exports[`validateRedirect throw for bad redirects 2`] = `"{\\"from\\":\\"/fromSomePath\\",\\"to\\":\\"https://fb.com/toSomePath\\"} => Validation error: \\"to\\" is not a valid pathname. Pathname should start with / and not contain any domain or query string"`; +exports[`validateRedirect throw for bad redirects 2`] = `"{\\"from\\":\\"/fromSomePath\\",\\"to\\":\\"https://fb.com/toSomePath\\"} => Validation error: \\"to\\" is not a valid pathname. Pathname should start with slash and not contain any domain or query string."`; -exports[`validateRedirect throw for bad redirects 3`] = `"{\\"from\\":\\"/fromSomePath\\",\\"to\\":\\"/toSomePath?queryString=xyz\\"} => Validation error: \\"to\\" is not a valid pathname. Pathname should start with / and not contain any domain or query string"`; +exports[`validateRedirect throw for bad redirects 3`] = `"{\\"from\\":\\"/fromSomePath\\",\\"to\\":\\"/toSomePath?queryString=xyz\\"} => Validation error: \\"to\\" is not a valid pathname. Pathname should start with slash and not contain any domain or query string."`; exports[`validateRedirect throw for bad redirects 4`] = `"{\\"from\\":null,\\"to\\":\\"/toSomePath?queryString=xyz\\"} => Validation error: \\"from\\" must be a string"`; diff --git a/packages/docusaurus-plugin-client-redirects/src/__tests__/extensionRedirects.test.ts b/packages/docusaurus-plugin-client-redirects/src/__tests__/extensionRedirects.test.ts index 1bb284447e..32518cc40a 100644 --- a/packages/docusaurus-plugin-client-redirects/src/__tests__/extensionRedirects.test.ts +++ b/packages/docusaurus-plugin-client-redirects/src/__tests__/extensionRedirects.test.ts @@ -9,46 +9,43 @@ import { createFromExtensionsRedirects, createToExtensionsRedirects, } from '../extensionRedirects'; -import {RedirectMetadata} from '../types'; - -const createExtensionValidationTests = ( - extensionRedirectCreatorFn: ( - paths: string[], - extensions: string[], - ) => RedirectMetadata[], -) => { - test('should reject empty extensions', () => { - expect(() => { - extensionRedirectCreatorFn(['/'], ['.html']); - }).toThrowErrorMatchingInlineSnapshot( - `"Extension=['.html'] contains a . (dot) and is not allowed. If the redirect extension system is not good enough for your usecase, you can create redirects yourself with the 'createRedirects' plugin option."`, - ); - }); - test('should reject extensions with .', () => { - expect(() => { - extensionRedirectCreatorFn(['/'], ['.html']); - }).toThrowErrorMatchingInlineSnapshot( - `"Extension=['.html'] contains a . (dot) and is not allowed. If the redirect extension system is not good enough for your usecase, you can create redirects yourself with the 'createRedirects' plugin option."`, - ); - }); - test('should reject extensions with /', () => { - expect(() => { - extensionRedirectCreatorFn(['/'], ['ht/ml']); - }).toThrowErrorMatchingInlineSnapshot( - `"Extension=['ht/ml'] contains a / and is not allowed. If the redirect extension system is not good enough for your usecase, you can create redirects yourself with the 'createRedirects' plugin option."`, - ); - }); - test('should reject extensions with illegal url char', () => { - expect(() => { - extensionRedirectCreatorFn(['/'], [',']); - }).toThrowErrorMatchingInlineSnapshot( - `"Extension=[','] contains invalid uri characters. If the redirect extension system is not good enough for your usecase, you can create redirects yourself with the 'createRedirects' plugin option."`, - ); - }); -}; describe('createToExtensionsRedirects', () => { - createExtensionValidationTests(createToExtensionsRedirects); + test('should reject empty extensions', () => { + expect(() => { + createToExtensionsRedirects(['/'], ['.html']); + }).toThrowErrorMatchingInlineSnapshot(` + "Extension \\".html\\" contains a \\".\\" (dot) which is not allowed. + If the redirect extension system is not good enough for your usecase, you can create redirects yourself with the \\"createRedirects\\" plugin option." + `); + }); + + test('should reject extensions with .', () => { + expect(() => { + createToExtensionsRedirects(['/'], ['.html']); + }).toThrowErrorMatchingInlineSnapshot(` + "Extension \\".html\\" contains a \\".\\" (dot) which is not allowed. + If the redirect extension system is not good enough for your usecase, you can create redirects yourself with the \\"createRedirects\\" plugin option." + `); + }); + + test('should reject extensions with /', () => { + expect(() => { + createToExtensionsRedirects(['/'], ['ht/ml']); + }).toThrowErrorMatchingInlineSnapshot(` + "Extension \\"ht/ml\\" contains a \\"/\\" (slash) which is not allowed. + If the redirect extension system is not good enough for your usecase, you can create redirects yourself with the \\"createRedirects\\" plugin option." + `); + }); + + test('should reject extensions with illegal url char', () => { + expect(() => { + createToExtensionsRedirects(['/'], [',']); + }).toThrowErrorMatchingInlineSnapshot(` + "Extension \\",\\" contains invalid URI characters. + If the redirect extension system is not good enough for your usecase, you can create redirects yourself with the \\"createRedirects\\" plugin option." + `); + }); test('should create redirects from html/htm extensions', () => { const ext = ['html', 'htm']; @@ -78,7 +75,41 @@ describe('createToExtensionsRedirects', () => { }); describe('createFromExtensionsRedirects', () => { - createExtensionValidationTests(createFromExtensionsRedirects); + test('should reject empty extensions', () => { + expect(() => { + createFromExtensionsRedirects(['/'], ['.html']); + }).toThrowErrorMatchingInlineSnapshot(` + "Extension \\".html\\" contains a \\".\\" (dot) which is not allowed. + If the redirect extension system is not good enough for your usecase, you can create redirects yourself with the \\"createRedirects\\" plugin option." + `); + }); + + test('should reject extensions with .', () => { + expect(() => { + createFromExtensionsRedirects(['/'], ['.html']); + }).toThrowErrorMatchingInlineSnapshot(` + "Extension \\".html\\" contains a \\".\\" (dot) which is not allowed. + If the redirect extension system is not good enough for your usecase, you can create redirects yourself with the \\"createRedirects\\" plugin option." + `); + }); + + test('should reject extensions with /', () => { + expect(() => { + createFromExtensionsRedirects(['/'], ['ht/ml']); + }).toThrowErrorMatchingInlineSnapshot(` + "Extension \\"ht/ml\\" contains a \\"/\\" (slash) which is not allowed. + If the redirect extension system is not good enough for your usecase, you can create redirects yourself with the \\"createRedirects\\" plugin option." + `); + }); + + test('should reject extensions with illegal url char', () => { + expect(() => { + createFromExtensionsRedirects(['/'], [',']); + }).toThrowErrorMatchingInlineSnapshot(` + "Extension \\",\\" contains invalid URI characters. + If the redirect extension system is not good enough for your usecase, you can create redirects yourself with the \\"createRedirects\\" plugin option." + `); + }); test('should create redirects to html/htm extensions', () => { const ext = ['html', 'htm']; diff --git a/packages/docusaurus-plugin-client-redirects/src/__tests__/writeRedirectFiles.test.ts b/packages/docusaurus-plugin-client-redirects/src/__tests__/writeRedirectFiles.test.ts index d2edb39fbc..9c9aa00740 100644 --- a/packages/docusaurus-plugin-client-redirects/src/__tests__/writeRedirectFiles.test.ts +++ b/packages/docusaurus-plugin-client-redirects/src/__tests__/writeRedirectFiles.test.ts @@ -140,7 +140,7 @@ describe('writeRedirectFiles', () => { ); await expect(writeRedirectFiles(filesMetadata)).rejects.toThrowError( - `Redirect file creation error for path=${filesMetadata[0].fileAbsolutePath}: Error: The redirect plugin is not supposed to override existing files`, + `Redirect file creation error for "${filesMetadata[0].fileAbsolutePath}" path: Error: The redirect plugin is not supposed to override existing files.`, ); }); }); diff --git a/packages/docusaurus-plugin-client-redirects/src/extensionRedirects.ts b/packages/docusaurus-plugin-client-redirects/src/extensionRedirects.ts index 9adebf43b4..99f95a38f3 100644 --- a/packages/docusaurus-plugin-client-redirects/src/extensionRedirects.ts +++ b/packages/docusaurus-plugin-client-redirects/src/extensionRedirects.ts @@ -10,29 +10,27 @@ import {removeSuffix} from '@docusaurus/utils'; import {RedirectMetadata} from './types'; const ExtensionAdditionalMessage = - "If the redirect extension system is not good enough for your usecase, you can create redirects yourself with the 'createRedirects' plugin option."; + 'If the redirect extension system is not good enough for your usecase, you can create redirects yourself with the "createRedirects" plugin option.'; const validateExtension = (ext: string) => { if (!ext) { throw new Error( - `Extension=['${String( - ext, - )}'] is not allowed. ${ExtensionAdditionalMessage}`, + `Extension "${ext}" is not allowed.\n${ExtensionAdditionalMessage}`, ); } if (ext.includes('.')) { throw new Error( - `Extension=['${ext}'] contains a . (dot) and is not allowed. ${ExtensionAdditionalMessage}`, + `Extension "${ext}" contains a "." (dot) which is not allowed.\n${ExtensionAdditionalMessage}`, ); } if (ext.includes('/')) { throw new Error( - `Extension=['${ext}'] contains a / and is not allowed. ${ExtensionAdditionalMessage}`, + `Extension "${ext}" contains a "/" (slash) which is not allowed.\n${ExtensionAdditionalMessage}`, ); } if (encodeURIComponent(ext) !== ext) { throw new Error( - `Extension=['${ext}'] contains invalid uri characters. ${ExtensionAdditionalMessage}`, + `Extension "${ext}" contains invalid URI characters.\n${ExtensionAdditionalMessage}`, ); } }; diff --git a/packages/docusaurus-plugin-client-redirects/src/writeRedirectFiles.ts b/packages/docusaurus-plugin-client-redirects/src/writeRedirectFiles.ts index 9c3f3cbd6d..93ebf72b2a 100644 --- a/packages/docusaurus-plugin-client-redirects/src/writeRedirectFiles.ts +++ b/packages/docusaurus-plugin-client-redirects/src/writeRedirectFiles.ts @@ -59,7 +59,7 @@ export async function writeRedirectFile( // User-friendly security to prevent file overrides if (await fs.pathExists(file.fileAbsolutePath)) { throw new Error( - 'The redirect plugin is not supposed to override existing files', + 'The redirect plugin is not supposed to override existing files.', ); } await fs.ensureDir(path.dirname(file.fileAbsolutePath)); @@ -72,7 +72,7 @@ export async function writeRedirectFile( ); } catch (err) { throw new Error( - `Redirect file creation error for path=${file.fileAbsolutePath}: ${err}`, + `Redirect file creation error for "${file.fileAbsolutePath}" path: ${err}.`, ); } } diff --git a/packages/docusaurus-plugin-content-blog/src/blogUtils.ts b/packages/docusaurus-plugin-content-blog/src/blogUtils.ts index ff7f3ef333..9e5bec3468 100644 --- a/packages/docusaurus-plugin-content-blog/src/blogUtils.ts +++ b/packages/docusaurus-plugin-content-blog/src/blogUtils.ts @@ -62,7 +62,7 @@ export async function generateBlogFeed( ): Promise { if (!options.feedOptions) { throw new Error( - 'Invalid options - `feedOptions` is not expected to be null.', + 'Invalid options: "feedOptions" is not expected to be null.', ); } const {siteConfig} = context; @@ -160,7 +160,7 @@ export async function generateBlogPosts( if (frontMatter.id) { console.warn( chalk.yellow( - `${blogFileName} - 'id' header option is deprecated. Please use 'slug' option instead.`, + `"id" header option is deprecated in ${blogFileName} file. Please use "slug" option instead.`, ), ); } diff --git a/packages/docusaurus-plugin-content-blog/src/index.ts b/packages/docusaurus-plugin-content-blog/src/index.ts index 0c095bffb3..0238e6c8a6 100644 --- a/packages/docusaurus-plugin-content-blog/src/index.ts +++ b/packages/docusaurus-plugin-content-blog/src/index.ts @@ -500,7 +500,7 @@ export default function pluginContentBlog( try { await fs.outputFile(feedPath, feedContent); } catch (err) { - throw new Error(`Generating ${feedType} feed failed: ${err}`); + throw new Error(`Generating ${feedType} feed failed: ${err}.`); } }), ); diff --git a/packages/docusaurus-plugin-content-docs/src/__tests__/__snapshots__/index.test.ts.snap b/packages/docusaurus-plugin-content-docs/src/__tests__/__snapshots__/index.test.ts.snap index 06516cd23f..aee2f20a6d 100644 --- a/packages/docusaurus-plugin-content-docs/src/__tests__/__snapshots__/index.test.ts.snap +++ b/packages/docusaurus-plugin-content-docs/src/__tests__/__snapshots__/index.test.ts.snap @@ -1,11 +1,11 @@ // Jest Snapshot v1, https://goo.gl/fbAQLP exports[`sidebar site with wrong sidebar content 1`] = ` -"Bad sidebar file at 'packages/docusaurus-plugin-content-docs/src/__tests__/__fixtures__/simple-site/wrong-sidebars.json'. +"Invalid sidebar file at \\"packages/docusaurus-plugin-content-docs/src/__tests__/__fixtures__/simple-site/wrong-sidebars.json\\". These sidebar document ids do not exist: -- goku, +- goku -Available document ids= +Available document ids are: - foo/bar - foo/baz - headingAsTitle diff --git a/packages/docusaurus-plugin-content-docs/src/__tests__/cli.test.ts b/packages/docusaurus-plugin-content-docs/src/__tests__/cli.test.ts index b296aa17a3..0f6db9eded 100644 --- a/packages/docusaurus-plugin-content-docs/src/__tests__/cli.test.ts +++ b/packages/docusaurus-plugin-content-docs/src/__tests__/cli.test.ts @@ -35,7 +35,7 @@ describe('docsVersion', () => { DEFAULT_OPTIONS, ), ).toThrowErrorMatchingInlineSnapshot( - `"[docs] No version tag specified!. Pass the version you wish to create as an argument. Ex: 1.0.0"`, + `"[docs]: no version tag specified! Pass the version you wish to create as an argument, for example: 1.0.0."`, ); expect(() => cliDocsVersionCommand( @@ -45,7 +45,7 @@ describe('docsVersion', () => { DEFAULT_OPTIONS, ), ).toThrowErrorMatchingInlineSnapshot( - `"[docs] No version tag specified!. Pass the version you wish to create as an argument. Ex: 1.0.0"`, + `"[docs]: no version tag specified! Pass the version you wish to create as an argument, for example: 1.0.0."`, ); expect(() => cliDocsVersionCommand( @@ -55,7 +55,7 @@ describe('docsVersion', () => { DEFAULT_OPTIONS, ), ).toThrowErrorMatchingInlineSnapshot( - `"[docs] No version tag specified!. Pass the version you wish to create as an argument. Ex: 1.0.0"`, + `"[docs]: no version tag specified! Pass the version you wish to create as an argument, for example: 1.0.0."`, ); }); @@ -68,7 +68,7 @@ describe('docsVersion', () => { DEFAULT_OPTIONS, ), ).toThrowErrorMatchingInlineSnapshot( - `"[docs] Invalid version tag specified! Do not include slash (/) or (\\\\). Try something like: 1.0.0"`, + `"[docs]: invalid version tag specified! Do not include slash (/) or backslash (\\\\). Try something like: 1.0.0."`, ); expect(() => cliDocsVersionCommand( @@ -78,7 +78,7 @@ describe('docsVersion', () => { DEFAULT_OPTIONS, ), ).toThrowErrorMatchingInlineSnapshot( - `"[docs] Invalid version tag specified! Do not include slash (/) or (\\\\). Try something like: 1.0.0"`, + `"[docs]: invalid version tag specified! Do not include slash (/) or backslash (\\\\). Try something like: 1.0.0."`, ); }); @@ -91,7 +91,7 @@ describe('docsVersion', () => { DEFAULT_OPTIONS, ), ).toThrowErrorMatchingInlineSnapshot( - `"[docs] Invalid version tag specified! Length must <= 32 characters. Try something like: 1.0.0"`, + `"[docs]: invalid version tag specified! Length cannot exceed 32 characters. Try something like: 1.0.0."`, ); }); @@ -104,7 +104,7 @@ describe('docsVersion', () => { DEFAULT_OPTIONS, ), ).toThrowErrorMatchingInlineSnapshot( - `"[docs] Invalid version tag specified! Do not name your version \\".\\" or \\"..\\". Try something like: 1.0.0"`, + `"[docs]: invalid version tag specified! Do not name your version \\".\\" or \\"..\\". Try something like: 1.0.0."`, ); expect(() => cliDocsVersionCommand( @@ -114,7 +114,7 @@ describe('docsVersion', () => { DEFAULT_OPTIONS, ), ).toThrowErrorMatchingInlineSnapshot( - `"[docs] Invalid version tag specified! Do not name your version \\".\\" or \\"..\\". Try something like: 1.0.0"`, + `"[docs]: invalid version tag specified! Do not name your version \\".\\" or \\"..\\". Try something like: 1.0.0."`, ); }); @@ -127,7 +127,7 @@ describe('docsVersion', () => { DEFAULT_OPTIONS, ), ).toThrowErrorMatchingInlineSnapshot( - `"[docs] Invalid version tag specified! Please ensure its a valid pathname too. Try something like: 1.0.0"`, + `"[docs]: invalid version tag specified! Please ensure its a valid pathname too. Try something like: 1.0.0."`, ); expect(() => cliDocsVersionCommand( @@ -137,7 +137,7 @@ describe('docsVersion', () => { DEFAULT_OPTIONS, ), ).toThrowErrorMatchingInlineSnapshot( - `"[docs] Invalid version tag specified! Please ensure its a valid pathname too. Try something like: 1.0.0"`, + `"[docs]: invalid version tag specified! Please ensure its a valid pathname too. Try something like: 1.0.0."`, ); expect(() => cliDocsVersionCommand( @@ -147,7 +147,7 @@ describe('docsVersion', () => { DEFAULT_OPTIONS, ), ).toThrowErrorMatchingInlineSnapshot( - `"[docs] Invalid version tag specified! Please ensure its a valid pathname too. Try something like: 1.0.0"`, + `"[docs]: invalid version tag specified! Please ensure its a valid pathname too. Try something like: 1.0.0."`, ); }); @@ -160,7 +160,7 @@ describe('docsVersion', () => { DEFAULT_OPTIONS, ), ).toThrowErrorMatchingInlineSnapshot( - `"[docs] This version already exists!. Use a version tag that does not already exist."`, + `"[docs]: this version already exists! Use a version tag that does not already exist."`, ); }); @@ -174,7 +174,7 @@ describe('docsVersion', () => { DEFAULT_OPTIONS, ), ).toThrowErrorMatchingInlineSnapshot( - `"[docs] There is no docs to version !"`, + `"[docs]: there is no docs to version!"`, ); }); @@ -218,7 +218,7 @@ describe('docsVersion', () => { getVersionsFilePath(simpleSiteDir, DEFAULT_PLUGIN_ID), ); expect(versions).toEqual(['1.0.0']); - expect(consoleMock).toHaveBeenCalledWith('[docs] Version 1.0.0 created!'); + expect(consoleMock).toHaveBeenCalledWith('[docs]: version 1.0.0 created!'); copyMock.mockRestore(); writeMock.mockRestore(); @@ -271,7 +271,7 @@ describe('docsVersion', () => { getVersionsFilePath(versionedSiteDir, DEFAULT_PLUGIN_ID), ); expect(versions).toEqual(['2.0.0', '1.0.1', '1.0.0', 'withSlugs']); - expect(consoleMock).toHaveBeenCalledWith('[docs] Version 2.0.0 created!'); + expect(consoleMock).toHaveBeenCalledWith('[docs]: version 2.0.0 created!'); copyMock.mockRestore(); writeMock.mockRestore(); @@ -322,7 +322,7 @@ describe('docsVersion', () => { ); expect(versions).toEqual(['2.0.0', '1.0.0']); expect(consoleMock).toHaveBeenCalledWith( - '[community] Version 2.0.0 created!', + '[community]: version 2.0.0 created!', ); copyMock.mockRestore(); diff --git a/packages/docusaurus-plugin-content-docs/src/__tests__/docs.test.ts b/packages/docusaurus-plugin-content-docs/src/__tests__/docs.test.ts index 1d27acf4f8..0332df79b0 100644 --- a/packages/docusaurus-plugin-content-docs/src/__tests__/docs.test.ts +++ b/packages/docusaurus-plugin-content-docs/src/__tests__/docs.test.ts @@ -453,7 +453,7 @@ describe('simple site', () => { }), ); }).toThrowErrorMatchingInlineSnapshot( - `"Document id [Hello/world] cannot include \\"/\\"."`, + `"Document id \\"Hello/world\\" cannot include slash."`, ); }); diff --git a/packages/docusaurus-plugin-content-docs/src/__tests__/index.test.ts b/packages/docusaurus-plugin-content-docs/src/__tests__/index.test.ts index 8efde44476..e741ce2d98 100644 --- a/packages/docusaurus-plugin-content-docs/src/__tests__/index.test.ts +++ b/packages/docusaurus-plugin-content-docs/src/__tests__/index.test.ts @@ -44,8 +44,10 @@ function getDocById(version: LoadedVersion, unversionedId: string) { const doc = findDocById(version, unversionedId); if (!doc) { throw new Error( - `No doc found with id=${unversionedId} in version ${version.versionName}. -Available ids=\n- ${version.docs.map((d) => d.unversionedId).join('\n- ')}`, + `No doc found with id "${unversionedId}" in version ${ + version.versionName + }. +Available ids are:\n- ${version.docs.map((d) => d.unversionedId).join('\n- ')}`, ); } return doc; @@ -85,7 +87,7 @@ const createFakeActions = (contentDir: string) => { key.startsWith(prefix), ); if (!entry) { - throw new Error(`No created entry found for prefix=[${prefix}] + throw new Error(`No created entry found for prefix "${prefix}". Entries created: - ${Object.keys(dataContainer).join('\n- ')} `); @@ -151,8 +153,8 @@ describe('sidebar', () => { ); await plugin.loadContent!(); }).rejects.toThrowErrorMatchingInlineSnapshot(` - "The path to the sidebar file does not exist at [wrong-path-sidebar.json]. - Please set the docs [sidebarPath] field in your config file to: + "The path to the sidebar file does not exist at \\"wrong-path-sidebar.json\\". + Please set the docs \\"sidebarPath\\" field in your config file to: - a sidebars path that exists - false: to disable the sidebar - undefined: for Docusaurus generates it automatically" @@ -217,7 +219,7 @@ describe('empty/no docs website', () => { await expect( plugin.loadContent!(), ).rejects.toThrowErrorMatchingInlineSnapshot( - `"Docs version current has no docs! At least one doc should exist at path=[docs]"`, + `"Docs version \\"current\\" has no docs! At least one doc should exist at \\"docs\\"."`, ); }); @@ -231,11 +233,11 @@ describe('empty/no docs website', () => { }), ), ).toThrowError( - `The docs folder does not exist for version [current]. A docs folder is expected to be found at ${ + `The docs folder does not exist for version "current". A docs folder is expected to be found at ${ process.platform === 'win32' ? 'path\\doesnt\\exist' : 'path/doesnt/exist' - }`, + }.`, ); }); }); diff --git a/packages/docusaurus-plugin-content-docs/src/__tests__/sidebars.test.ts b/packages/docusaurus-plugin-content-docs/src/__tests__/sidebars.test.ts index a21899653f..7f33856441 100644 --- a/packages/docusaurus-plugin-content-docs/src/__tests__/sidebars.test.ts +++ b/packages/docusaurus-plugin-content-docs/src/__tests__/sidebars.test.ts @@ -60,7 +60,7 @@ describe('loadSidebars', () => { 'sidebars-category-wrong-items.json', ); expect(() => loadSidebars(sidebarPath)).toThrowErrorMatchingInlineSnapshot( - `"Error loading {\\"type\\":\\"category\\",\\"label\\":\\"Category Label\\",\\"items\\":\\"doc1\\"}. \\"items\\" must be an array."`, + `"Error loading {\\"type\\":\\"category\\",\\"label\\":\\"Category Label\\",\\"items\\":\\"doc1\\"}: \\"items\\" must be an array."`, ); }); @@ -70,7 +70,7 @@ describe('loadSidebars', () => { 'sidebars-category-wrong-label.json', ); expect(() => loadSidebars(sidebarPath)).toThrowErrorMatchingInlineSnapshot( - `"Error loading {\\"type\\":\\"category\\",\\"label\\":true,\\"items\\":[\\"doc1\\"]}. \\"label\\" must be a string."`, + `"Error loading {\\"type\\":\\"category\\",\\"label\\":true,\\"items\\":[\\"doc1\\"]}: \\"label\\" must be a string."`, ); }); @@ -80,7 +80,7 @@ describe('loadSidebars', () => { 'sidebars-doc-id-not-string.json', ); expect(() => loadSidebars(sidebarPath)).toThrowErrorMatchingInlineSnapshot( - `"Error loading {\\"type\\":\\"doc\\",\\"id\\":[\\"doc1\\"]}. \\"id\\" must be a string."`, + `"Error loading {\\"type\\":\\"doc\\",\\"id\\":[\\"doc1\\"]}: \\"id\\" must be a string."`, ); }); @@ -102,22 +102,23 @@ describe('loadSidebars', () => { test('sidebars link wrong label', async () => { const sidebarPath = path.join(fixtureDir, 'sidebars-link-wrong-label.json'); expect(() => loadSidebars(sidebarPath)).toThrowErrorMatchingInlineSnapshot( - `"Error loading {\\"type\\":\\"link\\",\\"label\\":false,\\"href\\":\\"https://github.com\\"}. \\"label\\" must be a string."`, + `"Error loading {\\"type\\":\\"link\\",\\"label\\":false,\\"href\\":\\"https://github.com\\"}: \\"label\\" must be a string."`, ); }); test('sidebars link wrong href', async () => { const sidebarPath = path.join(fixtureDir, 'sidebars-link-wrong-href.json'); expect(() => loadSidebars(sidebarPath)).toThrowErrorMatchingInlineSnapshot( - `"Error loading {\\"type\\":\\"link\\",\\"label\\":\\"GitHub\\",\\"href\\":[\\"example.com\\"]}. \\"href\\" must be a string."`, + `"Error loading {\\"type\\":\\"link\\",\\"label\\":\\"GitHub\\",\\"href\\":[\\"example.com\\"]}: \\"href\\" must be a string."`, ); }); test('sidebars with unknown sidebar item type', async () => { const sidebarPath = path.join(fixtureDir, 'sidebars-unknown-type.json'); - expect(() => loadSidebars(sidebarPath)).toThrowErrorMatchingInlineSnapshot( - `"Unknown sidebar item type [superman]. Sidebar item={\\"type\\":\\"superman\\"} "`, - ); + expect(() => loadSidebars(sidebarPath)).toThrowErrorMatchingInlineSnapshot(` + "Unknown sidebar item type \\"superman\\". Sidebar item is {\\"type\\":\\"superman\\"}. + " + `); }); test('sidebars with known sidebar item type but wrong field', async () => { diff --git a/packages/docusaurus-plugin-content-docs/src/__tests__/versions.test.ts b/packages/docusaurus-plugin-content-docs/src/__tests__/versions.test.ts index 818d070f81..97fb3a67ce 100644 --- a/packages/docusaurus-plugin-content-docs/src/__tests__/versions.test.ts +++ b/packages/docusaurus-plugin-content-docs/src/__tests__/versions.test.ts @@ -174,7 +174,7 @@ describe('simple site', () => { context: defaultContext, }), ).toThrowErrorMatchingInlineSnapshot( - `"Bad docs options.versions: unknown versions found: unknownVersionName1,unknownVersionName2. Available version names are: current"`, + `"Invalid docs option \\"versions\\": unknown versions (unknownVersionName1,unknownVersionName2) found. Available version names are: current"`, ); }); @@ -187,7 +187,7 @@ describe('simple site', () => { context: defaultContext, }), ).toThrowErrorMatchingInlineSnapshot( - `"Docs: using disableVersioning=true option on a non-versioned site does not make sense"`, + `"Docs: using \\"disableVersioning=true\\" option on a non-versioned site does not make sense."`, ); }); @@ -200,7 +200,7 @@ describe('simple site', () => { context: defaultContext, }), ).toThrowErrorMatchingInlineSnapshot( - `"It is not possible to use docs without any version. Please check the configuration of these options: includeCurrentVersion=false disableVersioning=false"`, + `"It is not possible to use docs without any version. Please check the configuration of these options: \\"includeCurrentVersion=false\\", \\"disableVersioning=false\\"."`, ); }); }); @@ -527,7 +527,7 @@ describe('versioned site, pluginId=default', () => { context: defaultContext, }), ).toThrowErrorMatchingInlineSnapshot( - `"It is not possible to use docs without any version. Please check the configuration of these options: includeCurrentVersion=false disableVersioning=true"`, + `"It is not possible to use docs without any version. Please check the configuration of these options: \\"includeCurrentVersion=false\\", \\"disableVersioning=true\\"."`, ); }); @@ -543,7 +543,7 @@ describe('versioned site, pluginId=default', () => { context: defaultContext, }), ).toThrowErrorMatchingInlineSnapshot( - `"Bad docs options.onlyIncludeVersions: an empty array is not allowed, at least one version is needed"`, + `"Invalid docs option \\"onlyIncludeVersions\\": an empty array is not allowed, at least one version is needed."`, ); }); @@ -559,7 +559,7 @@ describe('versioned site, pluginId=default', () => { context: defaultContext, }), ).toThrowErrorMatchingInlineSnapshot( - `"Bad docs options.onlyIncludeVersions: unknown versions found: unknownVersion1,unknownVersion2. Available version names are: current, 1.0.1, 1.0.0, withSlugs"`, + `"Invalid docs option \\"onlyIncludeVersions\\": unknown versions (unknownVersion1,unknownVersion2) found. Available version names are: current, 1.0.1, 1.0.0, withSlugs"`, ); }); @@ -576,7 +576,7 @@ describe('versioned site, pluginId=default', () => { context: defaultContext, }), ).toThrowErrorMatchingInlineSnapshot( - `"Bad docs options.lastVersion: if you use both the onlyIncludeVersions and lastVersion options, then lastVersion must be present in the provided onlyIncludeVersions array"`, + `"Invalid docs option \\"lastVersion\\": if you use both the \\"onlyIncludeVersions\\" and \\"lastVersion\\" options, then \\"lastVersion\\" must be present in the provided \\"onlyIncludeVersions\\" array."`, ); }); @@ -595,7 +595,7 @@ describe('versioned site, pluginId=default', () => { context: defaultContext, }); }).toThrowErrorMatchingInlineSnapshot( - `"The versions file should contain an array of versions! Found content={\\"invalid\\":\\"json\\"}"`, + `"The versions file should contain an array of versions! Found content: {\\"invalid\\":\\"json\\"}"`, ); mock.mockRestore(); }); @@ -712,7 +712,7 @@ describe('versioned site, pluginId=community', () => { context: defaultContext, }), ).toThrowErrorMatchingInlineSnapshot( - `"It is not possible to use docs without any version. Please check the configuration of these options: includeCurrentVersion=false disableVersioning=true"`, + `"It is not possible to use docs without any version. Please check the configuration of these options: \\"includeCurrentVersion=false\\", \\"disableVersioning=true\\"."`, ); }); }); diff --git a/packages/docusaurus-plugin-content-docs/src/cli.ts b/packages/docusaurus-plugin-content-docs/src/cli.ts index 92d85128d1..cabadff8d5 100644 --- a/packages/docusaurus-plugin-content-docs/src/cli.ts +++ b/packages/docusaurus-plugin-content-docs/src/cli.ts @@ -92,23 +92,23 @@ export function cliDocsVersionCommand( // It wouldn't be very user-friendly to show a [default] log prefix, // so we use [docs] instead of [default] const pluginIdLogPrefix = - pluginId === DEFAULT_PLUGIN_ID ? '[docs] ' : `[${pluginId}] `; + pluginId === DEFAULT_PLUGIN_ID ? '[docs]' : `[${pluginId}]`; if (!version) { throw new Error( - `${pluginIdLogPrefix}No version tag specified!. Pass the version you wish to create as an argument. Ex: 1.0.0`, + `${pluginIdLogPrefix}: no version tag specified! Pass the version you wish to create as an argument, for example: 1.0.0.`, ); } if (version.includes('/') || version.includes('\\')) { throw new Error( - `${pluginIdLogPrefix}Invalid version tag specified! Do not include slash (/) or (\\). Try something like: 1.0.0`, + `${pluginIdLogPrefix}: invalid version tag specified! Do not include slash (/) or backslash (\\). Try something like: 1.0.0.`, ); } if (version.length > 32) { throw new Error( - `${pluginIdLogPrefix}Invalid version tag specified! Length must <= 32 characters. Try something like: 1.0.0`, + `${pluginIdLogPrefix}: invalid version tag specified! Length cannot exceed 32 characters. Try something like: 1.0.0.`, ); } @@ -117,13 +117,13 @@ export function cliDocsVersionCommand( // eslint-disable-next-line no-control-regex if (/[<>:"|?*\x00-\x1F]/g.test(version)) { throw new Error( - `${pluginIdLogPrefix}Invalid version tag specified! Please ensure its a valid pathname too. Try something like: 1.0.0`, + `${pluginIdLogPrefix}: invalid version tag specified! Please ensure its a valid pathname too. Try something like: 1.0.0.`, ); } if (/^\.\.?$/.test(version)) { throw new Error( - `${pluginIdLogPrefix}Invalid version tag specified! Do not name your version "." or "..". Try something like: 1.0.0`, + `${pluginIdLogPrefix}: invalid version tag specified! Do not name your version "." or "..". Try something like: 1.0.0.`, ); } @@ -137,7 +137,7 @@ export function cliDocsVersionCommand( // Check if version already exists. if (versions.includes(version)) { throw new Error( - `${pluginIdLogPrefix}This version already exists!. Use a version tag that does not already exist.`, + `${pluginIdLogPrefix}: this version already exists! Use a version tag that does not already exist.`, ); } @@ -151,7 +151,7 @@ export function cliDocsVersionCommand( const newVersionDir = path.join(versionedDir, `version-${version}`); fs.copySync(docsDir, newVersionDir); } else { - throw new Error(`${pluginIdLogPrefix}There is no docs to version !`); + throw new Error(`${pluginIdLogPrefix}: there is no docs to version!`); } createVersionedSidebarFile({ @@ -166,5 +166,5 @@ export function cliDocsVersionCommand( fs.ensureDirSync(path.dirname(versionsJSONFile)); fs.writeFileSync(versionsJSONFile, `${JSON.stringify(versions, null, 2)}\n`); - console.log(`${pluginIdLogPrefix}Version ${version} created!`); + console.log(`${pluginIdLogPrefix}: version ${version} created!`); } diff --git a/packages/docusaurus-plugin-content-docs/src/client/__tests__/docsClientUtils.test.ts b/packages/docusaurus-plugin-content-docs/src/client/__tests__/docsClientUtils.test.ts index de41979a7b..5427b9b7a0 100644 --- a/packages/docusaurus-plugin-content-docs/src/client/__tests__/docsClientUtils.test.ts +++ b/packages/docusaurus-plugin-content-docs/src/client/__tests__/docsClientUtils.test.ts @@ -35,12 +35,12 @@ describe('docsClientUtils', () => { expect(() => getActivePlugin(data, '/', {failfast: true}), ).toThrowErrorMatchingInlineSnapshot( - `"Can't find active docs plugin for pathname=/, while it was expected to be found. Maybe you tried to use a docs feature that can only be used on a docs-related page? Existing docs plugin paths are: /ios, /android"`, + `"Can't find active docs plugin for \\"/\\" pathname, while it was expected to be found. Maybe you tried to use a docs feature that can only be used on a docs-related page? Existing docs plugin paths are: /ios, /android"`, ); expect(() => getActivePlugin(data, '/xyz', {failfast: true}), ).toThrowErrorMatchingInlineSnapshot( - `"Can't find active docs plugin for pathname=/xyz, while it was expected to be found. Maybe you tried to use a docs feature that can only be used on a docs-related page? Existing docs plugin paths are: /ios, /android"`, + `"Can't find active docs plugin for \\"/xyz\\" pathname, while it was expected to be found. Maybe you tried to use a docs feature that can only be used on a docs-related page? Existing docs plugin paths are: /ios, /android"`, ); const activePluginIos: ActivePlugin = { diff --git a/packages/docusaurus-plugin-content-docs/src/client/docsClientUtils.ts b/packages/docusaurus-plugin-content-docs/src/client/docsClientUtils.ts index bb7fadff2e..8e2e7d6645 100644 --- a/packages/docusaurus-plugin-content-docs/src/client/docsClientUtils.ts +++ b/packages/docusaurus-plugin-content-docs/src/client/docsClientUtils.ts @@ -57,7 +57,7 @@ export function getActivePlugin( if (!activePlugin && options.failfast) { throw new Error( - `Can't find active docs plugin for pathname=${pathname}, while it was expected to be found. Maybe you tried to use a docs feature that can only be used on a docs-related page? Existing docs plugin paths are: ${Object.values( + `Can't find active docs plugin for "${pathname}" pathname, while it was expected to be found. Maybe you tried to use a docs feature that can only be used on a docs-related page? Existing docs plugin paths are: ${Object.values( allPluginDatas, ) .map((plugin) => plugin.path) diff --git a/packages/docusaurus-plugin-content-docs/src/docs.ts b/packages/docusaurus-plugin-content-docs/src/docs.ts index b12e2df7c8..e2d8b6bd11 100644 --- a/packages/docusaurus-plugin-content-docs/src/docs.ts +++ b/packages/docusaurus-plugin-content-docs/src/docs.ts @@ -149,7 +149,7 @@ export function processDocMetadata({ const baseID: string = frontMatter.id ?? unprefixedFileName; if (baseID.includes('/')) { - throw new Error(`Document id [${baseID}] cannot include "/".`); + throw new Error(`Document id "${baseID}" cannot include slash.`); } // For autogenerated sidebars, sidebar position can come from filename number prefix or frontmatter diff --git a/packages/docusaurus-plugin-content-docs/src/index.ts b/packages/docusaurus-plugin-content-docs/src/index.ts index 7eee0d569a..b4be7fb1fc 100644 --- a/packages/docusaurus-plugin-content-docs/src/index.ts +++ b/packages/docusaurus-plugin-content-docs/src/index.ts @@ -144,12 +144,12 @@ export default function pluginContentDocs( const docFiles = await readVersionDocs(versionMetadata, options); if (docFiles.length === 0) { throw new Error( - `Docs version ${ + `Docs version "${ versionMetadata.versionName - } has no docs! At least one doc should exist at path=[${path.relative( + }" has no docs! At least one doc should exist at "${path.relative( siteDir, versionMetadata.contentPath, - )}]`, + )}".`, ); } async function processVersionDoc(docFile: DocFile) { diff --git a/packages/docusaurus-plugin-content-docs/src/markdown/linkify.ts b/packages/docusaurus-plugin-content-docs/src/markdown/linkify.ts index 6490739ab7..bf88545071 100644 --- a/packages/docusaurus-plugin-content-docs/src/markdown/linkify.ts +++ b/packages/docusaurus-plugin-content-docs/src/markdown/linkify.ts @@ -17,7 +17,7 @@ function getVersion(filePath: string, options: DocsMarkdownOption) { ); if (!versionFound) { throw new Error( - `Unexpected, markdown file does not belong to any docs version! file=${filePath}`, + `Unexpected error: Markdown file at "${filePath}" does not belong to any docs version!`, ); } return versionFound; diff --git a/packages/docusaurus-plugin-content-docs/src/options.ts b/packages/docusaurus-plugin-content-docs/src/options.ts index 1805e4ea71..70d86dd843 100644 --- a/packages/docusaurus-plugin-content-docs/src/options.ts +++ b/packages/docusaurus-plugin-content-docs/src/options.ts @@ -130,9 +130,9 @@ export function validateOptions({ if (typeof options.excludeNextVersionDocs !== 'undefined') { console.log( chalk.red( - `The docs plugin option excludeNextVersionDocs=${ + `The docs plugin option "excludeNextVersionDocs=${ options.excludeNextVersionDocs - } is deprecated. Use the includeCurrentVersion=${!options.excludeNextVersionDocs} option instead!"`, + }" is deprecated. Use the "includeCurrentVersion=${!options.excludeNextVersionDocs}" option instead!"`, ), ); options.includeCurrentVersion = !options.excludeNextVersionDocs; diff --git a/packages/docusaurus-plugin-content-docs/src/props.ts b/packages/docusaurus-plugin-content-docs/src/props.ts index 9908f67902..9827abcc0e 100644 --- a/packages/docusaurus-plugin-content-docs/src/props.ts +++ b/packages/docusaurus-plugin-content-docs/src/props.ts @@ -27,8 +27,8 @@ export function toSidebarsProp(loadedVersion: LoadedVersion): PropSidebars { if (!docMetadata) { throw new Error( - `Bad sidebars file. The document id '${docId}' was used in the sidebar, but no document with this id could be found. -Available document ids= + `Invalid sidebars file. The document with id "${docId}" was used in the sidebar, but no document with this id could be found. +Available document ids are: - ${Object.keys(docsById).sort().join('\n- ')}`, ); } diff --git a/packages/docusaurus-plugin-content-docs/src/sidebarItemsGenerator.ts b/packages/docusaurus-plugin-content-docs/src/sidebarItemsGenerator.ts index d09a2afdbe..da80765cde 100644 --- a/packages/docusaurus-plugin-content-docs/src/sidebarItemsGenerator.ts +++ b/packages/docusaurus-plugin-content-docs/src/sidebarItemsGenerator.ts @@ -74,7 +74,7 @@ async function readCategoryMetadatasFile( } catch (e) { console.error( chalk.red( - `The docs sidebar category metadata file looks invalid!\nPath=${filePath}`, + `The docs sidebar category metadata file looks invalid!\nPath: ${filePath}`, ), ); throw e; @@ -139,7 +139,7 @@ export const DefaultSidebarItemsGenerator: SidebarItemsGenerator = async functio ): string { if (!isInAutogeneratedDir(doc)) { throw new Error( - 'getDocDirRelativeToAutogenDir() can only be called for subdocs of the sidebar autogen dir', + 'getDocDirRelativeToAutogenDir() can only be called for subdocs of the sidebar autogen dir.', ); } // Is there a node API to compare 2 relative paths more easily? @@ -160,7 +160,7 @@ export const DefaultSidebarItemsGenerator: SidebarItemsGenerator = async functio if (docs.length === 0) { console.warn( chalk.yellow( - `No docs found in dir ${item.dirName}: can't auto-generate a sidebar`, + `No docs found in dir ${item.dirName}: can't auto-generate a sidebar.`, ), ); } diff --git a/packages/docusaurus-plugin-content-docs/src/sidebars.ts b/packages/docusaurus-plugin-content-docs/src/sidebars.ts index 5f07907fd2..4c00c41ef3 100644 --- a/packages/docusaurus-plugin-content-docs/src/sidebars.ts +++ b/packages/docusaurus-plugin-content-docs/src/sidebars.ts @@ -118,18 +118,18 @@ function assertIsCategory( assertItem(item, ['items', 'label', 'collapsed', 'customProps']); if (typeof item.label !== 'string') { throw new Error( - `Error loading ${JSON.stringify(item)}. "label" must be a string.`, + `Error loading ${JSON.stringify(item)}: "label" must be a string.`, ); } if (!Array.isArray(item.items)) { throw new Error( - `Error loading ${JSON.stringify(item)}. "items" must be an array.`, + `Error loading ${JSON.stringify(item)}: "items" must be an array.`, ); } // "collapsed" is an optional property if (item.hasOwnProperty('collapsed') && typeof item.collapsed !== 'boolean') { throw new Error( - `Error loading ${JSON.stringify(item)}. "collapsed" must be a boolean.`, + `Error loading ${JSON.stringify(item)}: "collapsed" must be a boolean.`, ); } } @@ -140,14 +140,14 @@ function assertIsAutogenerated( assertItem(item, ['dirName', 'customProps']); if (typeof item.dirName !== 'string') { throw new Error( - `Error loading ${JSON.stringify(item)}. "dirName" must be a string.`, + `Error loading ${JSON.stringify(item)}: "dirName" must be a string.`, ); } if (item.dirName.startsWith('/') || item.dirName.endsWith('/')) { throw new Error( `Error loading ${JSON.stringify( item, - )}. "dirName" must be a dir path relative to the docs folder root, and should not start or end with /`, + )}: "dirName" must be a dir path relative to the docs folder root, and should not start or end with slash`, ); } } @@ -158,13 +158,13 @@ function assertIsDoc( assertItem(item, ['id', 'label', 'customProps']); if (typeof item.id !== 'string') { throw new Error( - `Error loading ${JSON.stringify(item)}. "id" must be a string.`, + `Error loading ${JSON.stringify(item)}: "id" must be a string.`, ); } if (item.label && typeof item.label !== 'string') { throw new Error( - `Error loading ${JSON.stringify(item)}. "label" must be a string.`, + `Error loading ${JSON.stringify(item)}: "label" must be a string.`, ); } } @@ -175,12 +175,12 @@ function assertIsLink( assertItem(item, ['href', 'label', 'customProps']); if (typeof item.href !== 'string') { throw new Error( - `Error loading ${JSON.stringify(item)}. "href" must be a string.`, + `Error loading ${JSON.stringify(item)}: "href" must be a string.`, ); } if (typeof item.label !== 'string') { throw new Error( - `Error loading ${JSON.stringify(item)}. "label" must be a string.`, + `Error loading ${JSON.stringify(item)}: "label" must be a string.`, ); } } @@ -224,12 +224,12 @@ function normalizeItem(item: SidebarItemJSON): UnprocessedSidebarItem[] { default: { const extraMigrationError = item.type === 'subcategory' - ? "Docusaurus v2: 'subcategory' has been renamed as 'category'" + ? 'Docusaurus v2: "subcategory" has been renamed as "category".' : ''; throw new Error( - `Unknown sidebar item type [${ + `Unknown sidebar item type "${ item.type - }]. Sidebar item=${JSON.stringify(item)} ${extraMigrationError}`, + }". Sidebar item is ${JSON.stringify(item)}.\n${extraMigrationError}`, ); } } @@ -485,11 +485,13 @@ export function createSidebarsUtils(sidebars: Sidebars) { const invalidSidebarDocIds = difference(allSidebarDocIds, validDocIds); if (invalidSidebarDocIds.length > 0) { throw new Error( - `Bad sidebar file at '${toMessageRelativeFilePath(sidebarFilePath)}'. + `Invalid sidebar file at "${toMessageRelativeFilePath( + sidebarFilePath, + )}". These sidebar document ids do not exist: -- ${invalidSidebarDocIds.sort().join('\n- ')}, +- ${invalidSidebarDocIds.sort().join('\n- ')} -Available document ids= +Available document ids are: - ${validDocIds.sort().join('\n- ')}`, ); } diff --git a/packages/docusaurus-plugin-content-docs/src/slug.ts b/packages/docusaurus-plugin-content-docs/src/slug.ts index 4ca410cbf1..f48f02846c 100644 --- a/packages/docusaurus-plugin-content-docs/src/slug.ts +++ b/packages/docusaurus-plugin-content-docs/src/slug.ts @@ -47,8 +47,8 @@ export default function getSlug({ if (!isValidPathname(slug)) { throw new Error( - `We couldn't compute a valid slug for document with id=${baseID} in folder=${dirName} -The slug we computed looks invalid: ${slug} + `We couldn't compute a valid slug for document with id "${baseID}" in "${dirName}" directory. +The slug we computed looks invalid: ${slug}. Maybe your slug frontmatter is incorrect or you use weird chars in the file path? By using the slug frontmatter, you should be able to fix this error, by using the slug of your choice: diff --git a/packages/docusaurus-plugin-content-docs/src/versions.ts b/packages/docusaurus-plugin-content-docs/src/versions.ts index 3183d0f3df..bc6052e180 100644 --- a/packages/docusaurus-plugin-content-docs/src/versions.ts +++ b/packages/docusaurus-plugin-content-docs/src/versions.ts @@ -59,12 +59,12 @@ export function getVersionsFilePath(siteDir: string, pluginId: string): string { function ensureValidVersionString(version: unknown): asserts version is string { if (typeof version !== 'string') { throw new Error( - `versions should be strings. Found type=[${typeof version}] for version=[${version}]`, + `Versions should be strings. Found type "${typeof version}" for version "${version}".`, ); } // Should we forbid versions with special chars like / ? if (version.trim().length === 0) { - throw new Error(`Invalid version=[${version}]`); + throw new Error(`Invalid version "${version}".`); } } @@ -73,7 +73,7 @@ function ensureValidVersionArray( ): asserts versionArray is string[] { if (!(versionArray instanceof Array)) { throw new Error( - `The versions file should contain an array of versions! Found content=${JSON.stringify( + `The versions file should contain an array of versions! Found content: ${JSON.stringify( versionArray, )}`, ); @@ -106,7 +106,7 @@ function readVersionNames( if (!versionFileContent && options.disableVersioning) { throw new Error( - `Docs: using disableVersioning=${options.disableVersioning} option on a non-versioned site does not make sense`, + `Docs: using "disableVersioning=${options.disableVersioning}" option on a non-versioned site does not make sense.`, ); } @@ -124,7 +124,7 @@ function readVersionNames( if (versions.length === 0) { throw new Error( - `It is not possible to use docs without any version. Please check the configuration of these options: includeCurrentVersion=${options.includeCurrentVersion} disableVersioning=${options.disableVersioning}`, + `It is not possible to use docs without any version. Please check the configuration of these options: "includeCurrentVersion=${options.includeCurrentVersion}", "disableVersioning=${options.disableVersioning}".`, ); } @@ -342,10 +342,10 @@ function checkVersionMetadataPaths({ if (!fs.existsSync(contentPath)) { throw new Error( - `The docs folder does not exist for version [${versionName}]. A docs folder is expected to be found at ${path.relative( + `The docs folder does not exist for version "${versionName}". A docs folder is expected to be found at ${path.relative( siteDir, contentPath, - )}`, + )}.`, ); } @@ -358,11 +358,11 @@ function checkVersionMetadataPaths({ typeof sidebarFilePath === 'string' && !fs.existsSync(sidebarFilePath) ) { - throw new Error(`The path to the sidebar file does not exist at [${path.relative( + throw new Error(`The path to the sidebar file does not exist at "${path.relative( siteDir, sidebarFilePath, - )}]. -Please set the docs [sidebarPath] field in your config file to: + )}". +Please set the docs "sidebarPath" field in your config file to: - a sidebars path that exists - false: to disable the sidebar - undefined: for Docusaurus generates it automatically`); @@ -403,16 +403,16 @@ function checkVersionsOptions( ); if (unknownVersionConfigNames.length > 0) { throw new Error( - `Bad docs options.versions: unknown versions found: ${unknownVersionConfigNames.join( + `Invalid docs option "versions": unknown versions (${unknownVersionConfigNames.join( ',', - )}. ${availableVersionNamesMsg}`, + )}) found. ${availableVersionNamesMsg}`, ); } if (options.onlyIncludeVersions) { if (options.onlyIncludeVersions.length === 0) { throw new Error( - `Bad docs options.onlyIncludeVersions: an empty array is not allowed, at least one version is needed`, + `Invalid docs option "onlyIncludeVersions": an empty array is not allowed, at least one version is needed.`, ); } const unknownOnlyIncludeVersionNames = difference( @@ -421,9 +421,9 @@ function checkVersionsOptions( ); if (unknownOnlyIncludeVersionNames.length > 0) { throw new Error( - `Bad docs options.onlyIncludeVersions: unknown versions found: ${unknownOnlyIncludeVersionNames.join( + `Invalid docs option "onlyIncludeVersions": unknown versions (${unknownOnlyIncludeVersionNames.join( ',', - )}. ${availableVersionNamesMsg}`, + )}) found. ${availableVersionNamesMsg}`, ); } if ( @@ -431,7 +431,7 @@ function checkVersionsOptions( !options.onlyIncludeVersions.includes(options.lastVersion) ) { throw new Error( - `Bad docs options.lastVersion: if you use both the onlyIncludeVersions and lastVersion options, then lastVersion must be present in the provided onlyIncludeVersions array`, + `Invalid docs option "lastVersion": if you use both the "onlyIncludeVersions" and "lastVersion" options, then "lastVersion" must be present in the provided "onlyIncludeVersions" array.`, ); } } diff --git a/packages/docusaurus-plugin-google-analytics/src/index.js b/packages/docusaurus-plugin-google-analytics/src/index.js index 77117faaba..f30fe359a9 100644 --- a/packages/docusaurus-plugin-google-analytics/src/index.js +++ b/packages/docusaurus-plugin-google-analytics/src/index.js @@ -14,7 +14,7 @@ module.exports = function (context) { if (!googleAnalytics) { throw new Error( - `You need to specify 'googleAnalytics' object in 'themeConfig' with 'trackingId' field in it to use docusaurus-plugin-google-analytics`, + `You need to specify "googleAnalytics" object in "themeConfig" with "trackingId" field in it to use docusaurus-plugin-google-analytics.`, ); } @@ -22,7 +22,7 @@ module.exports = function (context) { if (!trackingID) { throw new Error( - 'You specified the `googleAnalytics` object in `themeConfig` but the `trackingID` field was missing. ' + + 'You specified the "googleAnalytics" object in "themeConfig" but the "trackingID" field was missing. ' + 'Please ensure this is not a mistake.', ); } diff --git a/packages/docusaurus-plugin-google-gtag/src/index.js b/packages/docusaurus-plugin-google-gtag/src/index.js index 0d6d8d29ca..263e56a9fb 100644 --- a/packages/docusaurus-plugin-google-gtag/src/index.js +++ b/packages/docusaurus-plugin-google-gtag/src/index.js @@ -14,7 +14,7 @@ module.exports = function (context) { if (!gtag) { throw new Error( - `You need to specify 'gtag' object in 'themeConfig' with 'trackingId' field in it to use docusaurus-plugin-google-gtag`, + `You need to specify "gtag" object in "themeConfig" with "trackingId" field in it to use docusaurus-plugin-google-gtag.`, ); } @@ -22,7 +22,7 @@ module.exports = function (context) { if (!trackingID) { throw new Error( - 'You specified the `gtag` object in `themeConfig` but the `trackingID` field was missing. ' + + 'You specified the "gtag" object in "themeConfig" but the "trackingID" field was missing. ' + 'Please ensure this is not a mistake.', ); } diff --git a/packages/docusaurus-plugin-sitemap/src/__tests__/createSitemap.test.ts b/packages/docusaurus-plugin-sitemap/src/__tests__/createSitemap.test.ts index dd24962292..4aae97421a 100644 --- a/packages/docusaurus-plugin-sitemap/src/__tests__/createSitemap.test.ts +++ b/packages/docusaurus-plugin-sitemap/src/__tests__/createSitemap.test.ts @@ -29,7 +29,9 @@ describe('createSitemap', () => { test('empty site', () => { return expect(async () => { await createSitemap({} as DocusaurusConfig, [], {}); - }).rejects.toThrow('url in docusaurus.config.js cannot be empty/undefined'); + }).rejects.toThrow( + 'URL in docusaurus.config.js cannot be empty/undefined.', + ); }); test('exclusion of 404 page', async () => { diff --git a/packages/docusaurus-plugin-sitemap/src/createSitemap.ts b/packages/docusaurus-plugin-sitemap/src/createSitemap.ts index 86a8282973..e574bd0718 100644 --- a/packages/docusaurus-plugin-sitemap/src/createSitemap.ts +++ b/packages/docusaurus-plugin-sitemap/src/createSitemap.ts @@ -18,7 +18,7 @@ export default async function createSitemap( ): Promise { const {url: hostname} = siteConfig; if (!hostname) { - throw new Error('url in docusaurus.config.js cannot be empty/undefined'); + throw new Error('URL in docusaurus.config.js cannot be empty/undefined.'); } const {changefreq, priority, trailingSlash} = options; diff --git a/packages/docusaurus-plugin-sitemap/src/index.ts b/packages/docusaurus-plugin-sitemap/src/index.ts index 8fd84f975b..979bdda3e4 100644 --- a/packages/docusaurus-plugin-sitemap/src/index.ts +++ b/packages/docusaurus-plugin-sitemap/src/index.ts @@ -38,7 +38,7 @@ export default function pluginSitemap( try { await fs.outputFile(sitemapPath, generatedSitemap); } catch (err) { - throw new Error(`Sitemap error: ${err}`); + throw new Error(`Writing sitemap failed: ${err}`); } }, }; diff --git a/packages/docusaurus-theme-classic/src/theme/NavbarItem/DocNavbarItem.tsx b/packages/docusaurus-theme-classic/src/theme/NavbarItem/DocNavbarItem.tsx index a0b496bec8..8fc176341c 100644 --- a/packages/docusaurus-theme-classic/src/theme/NavbarItem/DocNavbarItem.tsx +++ b/packages/docusaurus-theme-classic/src/theme/NavbarItem/DocNavbarItem.tsx @@ -29,8 +29,8 @@ export default function DocNavbarItem({ if (!doc) { const docIds = version.docs.map((versionDoc) => versionDoc.id).join('\n- '); throw new Error( - `DocNavbarItem: couldn't find any doc with id=${docId} in version ${version.name}. -Available docIds=\n- ${docIds}`, + `DocNavbarItem: couldn't find any doc with "${docId}" id in version "${version.name}". +Available doc ids:\n- ${docIds}`, ); } diff --git a/packages/docusaurus-theme-classic/src/theme/NavbarItem/index.tsx b/packages/docusaurus-theme-classic/src/theme/NavbarItem/index.tsx index f1ed6f5a44..6dce56b449 100644 --- a/packages/docusaurus-theme-classic/src/theme/NavbarItem/index.tsx +++ b/packages/docusaurus-theme-classic/src/theme/NavbarItem/index.tsx @@ -34,7 +34,7 @@ const getNavbarItemComponent = ( ) => { const navbarItemComponent = NavbarItemComponents[type]; if (!navbarItemComponent) { - throw new Error(`No NavbarItem component found for type=${type}.`); + throw new Error(`No NavbarItem component found for type "${type}".`); } return navbarItemComponent(); }; diff --git a/packages/docusaurus-theme-classic/src/theme/hooks/useThemeContext.ts b/packages/docusaurus-theme-classic/src/theme/hooks/useThemeContext.ts index 1463e68708..737d310d3b 100644 --- a/packages/docusaurus-theme-classic/src/theme/hooks/useThemeContext.ts +++ b/packages/docusaurus-theme-classic/src/theme/hooks/useThemeContext.ts @@ -14,7 +14,7 @@ function useThemeContext(): ThemeContextProps { const context = useContext(ThemeContext); if (context == null) { throw new Error( - '`useThemeContext` is used outside of `Layout` Component. See https://docusaurus.io/docs/api/themes/configuration#usethemecontext.', + '"useThemeContext" is used outside of "Layout" component. Please see https://docusaurus.io/docs/api/themes/configuration#usethemecontext.', ); } return context; diff --git a/packages/docusaurus-theme-classic/src/theme/hooks/useUserPreferencesContext.ts b/packages/docusaurus-theme-classic/src/theme/hooks/useUserPreferencesContext.ts index 18ac644501..91b8c05efa 100644 --- a/packages/docusaurus-theme-classic/src/theme/hooks/useUserPreferencesContext.ts +++ b/packages/docusaurus-theme-classic/src/theme/hooks/useUserPreferencesContext.ts @@ -16,7 +16,7 @@ function useUserPreferencesContext(): UserPreferencesContextProps { ); if (context == null) { throw new Error( - '`useUserPreferencesContext` is used outside of `Layout` Component.', + '"useUserPreferencesContext" is used outside of "Layout" component.', ); } return context; diff --git a/packages/docusaurus-theme-common/src/utils/docsPreferredVersion/DocsPreferredVersionProvider.tsx b/packages/docusaurus-theme-common/src/utils/docsPreferredVersion/DocsPreferredVersionProvider.tsx index 5cf52bd4ce..2daaac2747 100644 --- a/packages/docusaurus-theme-common/src/utils/docsPreferredVersion/DocsPreferredVersionProvider.tsx +++ b/packages/docusaurus-theme-common/src/utils/docsPreferredVersion/DocsPreferredVersionProvider.tsx @@ -158,7 +158,7 @@ export function useDocsPreferredVersionContext(): DocsPreferredVersionContextVal const value = useContext(Context); if (!value) { throw new Error( - "Can't find docs preferred context, maybe you forgot to use the DocsPreferredVersionContextProvider ?", + 'Can\'t find docs preferred context, maybe you forgot to use the "DocsPreferredVersionContextProvider"?', ); } return value; diff --git a/packages/docusaurus-theme-common/src/utils/storageUtils.ts b/packages/docusaurus-theme-common/src/utils/storageUtils.ts index 87411dd040..a2ac1fd6f8 100644 --- a/packages/docusaurus-theme-common/src/utils/storageUtils.ts +++ b/packages/docusaurus-theme-common/src/utils/storageUtils.ts @@ -18,7 +18,7 @@ function getBrowserStorage( ): Storage | null { if (typeof window === 'undefined') { throw new Error( - 'Browser storage is not available on NodeJS / Docusaurus SSR process', + 'Browser storage is not available on Node.js/Docusaurus SSR process.', ); } if (storageType === 'none') { @@ -42,7 +42,7 @@ function logOnceBrowserStorageNotAvailableWarning(error: Error) { if (!hasLoggedBrowserStorageNotAvailableWarning) { console.warn( `Docusaurus browser storage is not available. -Possible reasons: running Docusaurus in an Iframe, in an Incognito browser session, or using too strict browser privacy settings.`, +Possible reasons: running Docusaurus in an iframe, in an incognito browser session, or using too strict browser privacy settings.`, error, ); hasLoggedBrowserStorageNotAvailableWarning = true; @@ -65,7 +65,7 @@ const NoopStorageSlot: StorageSlot = { // Fail-fast, as storage APIs should not be used during the SSR process function createServerStorageSlot(key: string): StorageSlot { function throwError(): never { - throw new Error(`Illegal storage API usage for storage key=${key}. + throw new Error(`Illegal storage API usage for storage key "${key}". Docusaurus storage APIs are not supposed to be called on the server-rendering process. Please only call storage APIs in effects and event handlers.`); } diff --git a/packages/docusaurus-theme-common/src/utils/usePluralForm.ts b/packages/docusaurus-theme-common/src/utils/usePluralForm.ts index 8c908fb042..19d853dfeb 100644 --- a/packages/docusaurus-theme-common/src/utils/usePluralForm.ts +++ b/packages/docusaurus-theme-common/src/utils/usePluralForm.ts @@ -70,7 +70,7 @@ function useLocalePluralForms(): LocalePluralForms { try { return createLocalePluralForms(currentLocale); } catch (e) { - console.error(`Failed to use Intl.PluralRules for locale=${currentLocale}. + console.error(`Failed to use Intl.PluralRules for locale "${currentLocale}". Docusaurus will fallback to a default/fallback (English) Intl.PluralRules implementation. `); return EnglishPluralForms; diff --git a/packages/docusaurus-utils-validation/src/__tests__/validationUtils.test.ts b/packages/docusaurus-utils-validation/src/__tests__/validationUtils.test.ts index 7ecb1c081c..f1e9db11f0 100644 --- a/packages/docusaurus-utils-validation/src/__tests__/validationUtils.test.ts +++ b/packages/docusaurus-utils-validation/src/__tests__/validationUtils.test.ts @@ -31,7 +31,7 @@ describe('validateFrontMatter', () => { validateFrontMatter(frontMatter, schema), ).toThrowErrorMatchingInlineSnapshot(`"\\"test\\" must be a string"`); expect(consoleError).toHaveBeenCalledWith( - expect.stringContaining('The following FrontMatter'), + expect.stringContaining('The following frontmatter'), ); }); diff --git a/packages/docusaurus-utils-validation/src/validationSchemas.ts b/packages/docusaurus-utils-validation/src/validationSchemas.ts index 5d5f4d0f1f..efe8420da9 100644 --- a/packages/docusaurus-utils-validation/src/validationSchemas.ts +++ b/packages/docusaurus-utils-validation/src/validationSchemas.ts @@ -50,5 +50,5 @@ export const PathnameSchema = Joi.string() } }) .message( - '{{#label}} is not a valid pathname. Pathname should start with / and not contain any domain or query string', + '{{#label}} is not a valid pathname. Pathname should start with slash and not contain any domain or query string.', ); diff --git a/packages/docusaurus-utils-validation/src/validationUtils.ts b/packages/docusaurus-utils-validation/src/validationUtils.ts index 3c15dbb125..10e03eb1a9 100644 --- a/packages/docusaurus-utils-validation/src/validationUtils.ts +++ b/packages/docusaurus-utils-validation/src/validationUtils.ts @@ -20,14 +20,14 @@ export const isValidationDisabledEscapeHatch = if (isValidationDisabledEscapeHatch) { console.error( chalk.red( - 'You should avoid using DISABLE_DOCUSAURUS_VALIDATION escape hatch, this will be removed', + 'You should avoid using DISABLE_DOCUSAURUS_VALIDATION escape hatch, this will be removed.', ), ); } export const logValidationBugReportHint = (): void => { console.log( - `\n${chalk.red('A validation error occured.')}${chalk.cyanBright( + `\n${chalk.red('A validation error occurred.')}${chalk.cyanBright( '\nThe validation system was added recently to Docusaurus as an attempt to avoid user configuration errors.' + '\nWe may have made some mistakes.' + '\nIf you think your configuration is valid and should keep working, please open a bug report.', @@ -141,7 +141,7 @@ export function validateFrontMatter( console.error( chalk.red( - `The following FrontMatter:\n${chalk.yellow( + `The following frontmatter:\n${chalk.yellow( frontMatterString, )}\ncontains invalid values for field(s): ${invalidFields}.\n${errorMessages}\n`, ), diff --git a/packages/docusaurus-utils/src/__tests__/__snapshots__/index.test.ts.snap b/packages/docusaurus-utils/src/__tests__/__snapshots__/index.test.ts.snap index 58a2706fd1..0ef40ce9a5 100644 --- a/packages/docusaurus-utils/src/__tests__/__snapshots__/index.test.ts.snap +++ b/packages/docusaurus-utils/src/__tests__/__snapshots__/index.test.ts.snap @@ -1,7 +1,7 @@ // Jest Snapshot v1, https://goo.gl/fbAQLP exports[`getFolderContainingFile throw if no folder contain such file 1`] = ` -"relativeFilePath=[index.test.ts] does not exist in any of these folders: +"File \\"index.test.ts\\" does not exist in any of these folders: - /abcdef - /gehij - /klmn]" diff --git a/packages/docusaurus-utils/src/__tests__/index.test.ts b/packages/docusaurus-utils/src/__tests__/index.test.ts index de065102ae..17bf9e077a 100644 --- a/packages/docusaurus-utils/src/__tests__/index.test.ts +++ b/packages/docusaurus-utils/src/__tests__/index.test.ts @@ -441,12 +441,12 @@ describe('getElementsAround', () => { expect(() => getElementsAround(['a', 'b', 'c', 'd'], -1), ).toThrowErrorMatchingInlineSnapshot( - `"Valid aroundIndex for array (of size 4) are between 0 and 3, but you provided aroundIndex=-1"`, + `"Valid \\"aroundIndex\\" for array (of size 4) are between 0 and 3, but you provided -1."`, ); expect(() => getElementsAround(['a', 'b', 'c', 'd'], 4), ).toThrowErrorMatchingInlineSnapshot( - `"Valid aroundIndex for array (of size 4) are between 0 and 3, but you provided aroundIndex=4"`, + `"Valid \\"aroundIndex\\" for array (of size 4) are between 0 and 3, but you provided 4."`, ); }); }); diff --git a/packages/docusaurus-utils/src/index.ts b/packages/docusaurus-utils/src/index.ts index 10954d14fd..638d0a34b0 100644 --- a/packages/docusaurus-utils/src/index.ts +++ b/packages/docusaurus-utils/src/index.ts @@ -342,7 +342,7 @@ export function getElementsAround( const max = array.length - 1; if (aroundIndex < min || aroundIndex > max) { throw new Error( - `Valid aroundIndex for array (of size ${array.length}) are between ${min} and ${max}, but you provided aroundIndex=${aroundIndex}`, + `Valid "aroundIndex" for array (of size ${array.length}) are between ${min} and ${max}, but you provided ${aroundIndex}.`, ); } const previous = aroundIndex === min ? undefined : array[aroundIndex - 1]; @@ -427,7 +427,7 @@ export async function getFolderContainingFile( // should never happen, as the source was read from the FS anyway... if (!maybeFolderPath) { throw new Error( - `relativeFilePath=[${relativeFilePath}] does not exist in any of these folders: \n- ${folderPaths.join( + `File "${relativeFilePath}" does not exist in any of these folders:\n- ${folderPaths.join( '\n- ', )}]`, ); @@ -455,7 +455,7 @@ export function reportMessage( throw new Error(message); default: throw new Error( - `unexpected reportingSeverity value: ${reportingSeverity}`, + `Unexpected "reportingSeverity" value: ${reportingSeverity}.`, ); } } diff --git a/packages/docusaurus-utils/src/markdownParser.ts b/packages/docusaurus-utils/src/markdownParser.ts index 6270a791c1..00ee44e213 100644 --- a/packages/docusaurus-utils/src/markdownParser.ts +++ b/packages/docusaurus-utils/src/markdownParser.ts @@ -160,8 +160,8 @@ export function parseMarkdownString( }; } catch (e) { console.error( - chalk.red(`Error while parsing markdown front matter. -This can happen if you use special characters like : in frontmatter values (try using "" around that value)`), + chalk.red(`Error while parsing Markdown frontmatter. +This can happen if you use special characters in frontmatter values (try using double quotes around that value).`), ); throw e; } @@ -176,8 +176,7 @@ export async function parseMarkdownFile( return parseMarkdownString(markdownString, options); } catch (e) { throw new Error( - `Error while parsing markdown file ${source} -${e.message}`, + `Error while parsing Markdown file ${source}: "${e.message}".`, ); } } diff --git a/packages/docusaurus/bin/docusaurus.js b/packages/docusaurus/bin/docusaurus.js index c00e5d9546..badc1cd33d 100755 --- a/packages/docusaurus/bin/docusaurus.js +++ b/packages/docusaurus/bin/docusaurus.js @@ -83,9 +83,9 @@ if (notifier.update && semver.gt(this.update.latest, this.update.current)) { // notify user if node version needs to be updated if (!semver.satisfies(process.version, requiredVersion)) { console.log( - chalk.red(`\nMinimum Node version not met :(`) + + chalk.red(`\nMinimum Node.js version not met :(`) + chalk.yellow( - `\n\nYou are using Node ${process.version}. We require Node ${requiredVersion} or up!\n`, + `\n\nYou are using Node.js ${process.version}. We require Node.js ${requiredVersion} or up!\n`, ), ); process.exit(1); @@ -95,26 +95,26 @@ cli.version(require('../package.json').version).usage(' [options]'); cli .command('build [siteDir]') - .description('Build website') + .description('Build website.') .option( '--bundle-analyzer', - 'Visualize size of webpack output files with an interactive zoomable treemap (default: false)', + 'visualize size of webpack output files with an interactive zoomable treemap (default: false)', ) .option( '--out-dir ', - 'The full path for the new output directory, relative to the current workspace (default: build).', + 'the full path for the new output directory, relative to the current workspace (default: build)', ) .option( '--config ', - 'Path to docusaurus config file, default to `[siteDir]/docusaurus.config.js`', + 'path to docusaurus config file (default: `[siteDir]/docusaurus.config.js`)', ) .option( '-l, --locale ', - 'Build the site in a specified locale. Build all known locales otherwise.', + 'build the site in a specified locale. Build all known locales otherwise', ) .option( '--no-minify', - 'Build website without minimizing JS bundles (default: false)', + 'build website without minimizing JS bundles (default: false)', ) .action((siteDir = '.', {bundleAnalyzer, config, outDir, locale, minify}) => { build(path.resolve(siteDir), { @@ -131,9 +131,9 @@ cli .description('Copy the theme files into website folder for customization.') .option( '--typescript', - 'Copy TypeScript theme files when possible (default: false)', + 'copy TypeScript theme files when possible (default: false)', ) - .option('--danger', 'Enable swizzle for internal component of themes') + .option('--danger', 'enable swizzle for internal component of themes') .action((themeName, componentName, siteDir = '.', {typescript, danger}) => { swizzle( path.resolve(siteDir), @@ -146,22 +146,22 @@ cli cli .command('deploy [siteDir]') - .description('Deploy website to GitHub pages') + .description('Deploy website to GitHub pages.') .option( '-l, --locale ', - 'Deploy the site in a specified locale. Deploy all known locales otherwise.', + 'deploy the site in a specified locale. Deploy all known locales otherwise', ) .option( '--out-dir ', - 'The full path for the new output directory, relative to the current workspace (default: build).', + 'the full path for the new output directory, relative to the current workspace (default: build)', ) .option( '--config ', - 'Path to docusaurus config file, default to `[siteDir]/docusaurus.config.js`', + 'path to Docusaurus config file (default: `[siteDir]/docusaurus.config.js`)', ) .option( '--skip-build', - 'Skip building website before deploy it (default: false)', + 'skip building website before deploy it (default: false)', ) .action((siteDir = '.', {outDir, skipBuild, config}) => { deploy(path.resolve(siteDir), { @@ -173,22 +173,22 @@ cli cli .command('start [siteDir]') - .description('Start the development server') + .description('Start the development server.') .option('-p, --port ', 'use specified port (default: 3000)') - .option('-h, --host ', 'use specified host (default: localhost') + .option('-h, --host ', 'use specified host (default: localhost)') .option('-l, --locale ', 'use specified site locale') .option( '--hot-only', - 'Do not fallback to page refresh if hot reload fails (default: false)', + 'do not fallback to page refresh if hot reload fails (default: false)', ) .option( '--config ', - 'Path to docusaurus config file, default to `[siteDir]/docusaurus.config.js`', + 'path to Docusaurus config file (default: `[siteDir]/docusaurus.config.js`)', ) - .option('--no-open', 'Do not open page in the browser (default: false)') + .option('--no-open', 'do not open page in the browser (default: false)') .option( '--poll [interval]', - 'Use polling rather than watching for reload (default: false). Can specify a poll interval in milliseconds.', + 'use polling rather than watching for reload (default: false). Can specify a poll interval in milliseconds', ) .action( (siteDir = '.', {port, host, locale, config, hotOnly, open, poll}) => { @@ -206,18 +206,18 @@ cli cli .command('serve [siteDir]') - .description('Serve website') + .description('Serve website locally.') .option( '--dir ', - 'The full path for the new output directory, relative to the current workspace (default: build).', + 'the full path for the new output directory, relative to the current workspace (default: build)', ) .option( '--config ', - 'Path to docusaurus config file, default to `[siteDir]/docusaurus.config.js`', + 'path to Docusaurus config file (default: `[siteDir]/docusaurus.config.js`)', ) .option('-p, --port ', 'use specified port (default: 3000)') - .option('--build', 'Build website before serving (default: false)') - .option('-h, --host ', 'use specified host (default: localhost') + .option('--build', 'build website before serving (default: false)') + .option('-h, --host ', 'use specified host (default: localhost)') .action( ( siteDir = '.', @@ -241,29 +241,29 @@ cli cli .command('clear [siteDir]') - .description('Remove build artifacts') + .description('Remove build artifacts.') .action((siteDir = '.') => { clear(path.resolve(siteDir)); }); cli .command('write-translations [siteDir]') - .description('Extract required translations of your site') + .description('Extract required translations of your site.') .option( '-l, --locale ', - 'The locale folder to write the translations\n"--locale fr" will write translations in ./i18n/fr folder)', + 'the locale folder to write the translations\n"--locale fr" will write translations in ./i18n/fr folder)', ) .option( '--override', - 'By default, we only append missing translation messages to existing translation files. This option allows to override existing translation messages. Make sure to commit or backup your existing translations, as they may be overridden.', + 'by default, we only append missing translation messages to existing translation files. This option allows to override existing translation messages. Make sure to commit or backup your existing translations, as they may be overridden', ) .option( '--config ', - 'Path to docusaurus config file, default to `[siteDir]/docusaurus.config.js`', + 'path to Docusaurus config file (default:`[siteDir]/docusaurus.config.js`)', ) .option( '--messagePrefix ', - 'Allows to init new written messages with a given prefix. This might help you to highlight untranslated message to make them stand out in the UI.', + 'allows to init new written messages with a given prefix. This might help you to highlight untranslated message to make them stand out in the UI', ) .action( ( @@ -281,14 +281,14 @@ cli cli .command('write-heading-ids [contentDir]') - .description('Generate heading ids in Markdown content') + .description('Generate heading ids in Markdown content.') .action((siteDir = '.') => { writeHeadingIds(siteDir); }); cli.arguments('').action((cmd) => { cli.outputHelp(); - console.log(` ${chalk.red(`\n Unknown command ${chalk.yellow(cmd)}.`)}`); + console.log(` ${chalk.red(`\n Unknown command ${chalk.yellow(cmd)}.`)}.`); console.log(); }); diff --git a/packages/docusaurus/src/choosePort.ts b/packages/docusaurus/src/choosePort.ts index de6879cfec..1a65837268 100644 --- a/packages/docusaurus/src/choosePort.ts +++ b/packages/docusaurus/src/choosePort.ts @@ -127,7 +127,7 @@ export default async function choosePort( (err) => { throw new Error( `${chalk.red(`Could not find an open port at ${chalk.bold(host)}.`)}\n${ - `Network error message: ${err.message}` || err + `Network error message: "${err.message}".` || err }\n`, ); }, diff --git a/packages/docusaurus/src/client/exports/useDocusaurusContext.ts b/packages/docusaurus/src/client/exports/useDocusaurusContext.ts index eb67a6a638..9edc455dac 100644 --- a/packages/docusaurus/src/client/exports/useDocusaurusContext.ts +++ b/packages/docusaurus/src/client/exports/useDocusaurusContext.ts @@ -13,7 +13,7 @@ function useDocusaurusContext(): DocusaurusContext { const docusaurusContext = useContext(context); if (docusaurusContext === null) { // should not happen normally - throw new Error('Docusaurus context not provided'); + throw new Error('Docusaurus context not provided.'); } return docusaurusContext; } diff --git a/packages/docusaurus/src/client/exports/useGlobalData.ts b/packages/docusaurus/src/client/exports/useGlobalData.ts index 8ed4a1a284..15c9034acc 100644 --- a/packages/docusaurus/src/client/exports/useGlobalData.ts +++ b/packages/docusaurus/src/client/exports/useGlobalData.ts @@ -16,7 +16,7 @@ const DEFAULT_PLUGIN_ID = 'default'; export default function useGlobalData(): Record { const {globalData} = useDocusaurusContext(); if (!globalData) { - throw new Error('Docusaurus global data not found'); + throw new Error('Docusaurus global data not found.'); } return globalData; } @@ -28,7 +28,7 @@ export function useAllPluginInstancesData( const pluginGlobalData = globalData[pluginName]; if (!pluginGlobalData) { throw new Error( - `Docusaurus plugin global data not found for pluginName=${pluginName}`, + `Docusaurus plugin global data not found for "${pluginName}" plugin.`, ); } return pluginGlobalData as Record; @@ -42,7 +42,7 @@ export function usePluginData( const pluginInstanceGlobalData = pluginGlobalData[pluginId]; if (!pluginInstanceGlobalData) { throw new Error( - `Docusaurus plugin global data not found for pluginName=${pluginName} and pluginId=${pluginId}`, + `Docusaurus plugin global data not found for "${pluginName}" plugin with id "${pluginId}".`, ); } return pluginInstanceGlobalData as T; diff --git a/packages/docusaurus/src/client/serverEntry.js b/packages/docusaurus/src/client/serverEntry.js index 2d3d46a1c2..7e2eafc355 100644 --- a/packages/docusaurus/src/client/serverEntry.js +++ b/packages/docusaurus/src/client/serverEntry.js @@ -159,7 +159,7 @@ async function doRender(locals) { ) { console.error( chalk.red( - '\nDocusaurus user: you probably have this known error due to using a monorepo/workspace.\nWe have a workaround for you, check https://github.com/facebook/docusaurus/issues/3515\n', + '\nDocusaurus user: you probably have this known error due to using a monorepo/workspace.\nWe have a workaround for you, please see https://github.com/facebook/docusaurus/issues/3515\n', ), ); } diff --git a/packages/docusaurus/src/commands/__tests__/writeHeadingIds.test.ts b/packages/docusaurus/src/commands/__tests__/writeHeadingIds.test.ts index ac26332316..44cc3bb607 100644 --- a/packages/docusaurus/src/commands/__tests__/writeHeadingIds.test.ts +++ b/packages/docusaurus/src/commands/__tests__/writeHeadingIds.test.ts @@ -16,7 +16,7 @@ describe('transformMarkdownHeadingLine', () => { expect(() => transformMarkdownHeadingLine('ABC', new GithubSlugger()), ).toThrowErrorMatchingInlineSnapshot( - `"Line is not a markdown heading: ABC"`, + `"Line is not a Markdown heading: ABC."`, ); }); diff --git a/packages/docusaurus/src/commands/build.ts b/packages/docusaurus/src/commands/build.ts index 3b54b4c43f..25c0e8d3ac 100644 --- a/packages/docusaurus/src/commands/build.ts +++ b/packages/docusaurus/src/commands/build.ts @@ -53,7 +53,7 @@ export default async function build( isLastLocale, }); } catch (e) { - console.error(`Unable to build website for locale ${locale}.`); + console.error(`Unable to build website for locale "${locale}".`); throw e; } } @@ -72,7 +72,7 @@ export default async function build( if (i18n.locales.length > 1) { console.log( chalk.yellow( - `\nSite will be built for all these locales: + `\nWebsite will be built for all these locales: - ${i18n.locales.join('\n- ')}`, ), ); @@ -239,7 +239,7 @@ async function buildLocale({ }); console.log( - `${chalk.green(`Success!`)} Generated static files in ${chalk.cyan( + `${chalk.green(`Success!`)} Generated static files in "${chalk.cyan( path.relative(process.cwd(), outDir), )}.`, ); @@ -248,7 +248,7 @@ async function buildLocale({ console.log( `\nUse ${chalk.greenBright( '`npm run serve`', - )} to test your build locally.\n`, + )} command to test your build locally.\n`, ); } diff --git a/packages/docusaurus/src/commands/clear.ts b/packages/docusaurus/src/commands/clear.ts index 0338960665..4486ac9b41 100644 --- a/packages/docusaurus/src/commands/clear.ts +++ b/packages/docusaurus/src/commands/clear.ts @@ -13,10 +13,10 @@ function removePath(fsPath: string) { return fs .remove(path.join(fsPath)) .then(() => { - console.log(`${chalk.green(`Removing ${fsPath}`)}`); + console.log(chalk.green(`Successfully removed "${fsPath}" directory.`)); }) .catch((err) => { - console.error(`Could not remove ${fsPath}`); + console.error(`Could not remove ${fsPath} directory.`); console.error(err); }); } diff --git a/packages/docusaurus/src/commands/deploy.ts b/packages/docusaurus/src/commands/deploy.ts index ddf1e0695a..93ed25a4e9 100644 --- a/packages/docusaurus/src/commands/deploy.ts +++ b/packages/docusaurus/src/commands/deploy.ts @@ -28,7 +28,7 @@ function shellExecLog(cmd) { const result = shell.exec(cmd); console.log( `${chalk.cyan('CMD:')} ${obfuscateGitPass(cmd)} ${chalk.cyan( - `(code=${result.code})`, + `(code: ${result.code})`, )}`, ); return result; @@ -47,7 +47,7 @@ export default async function deploy( customOutDir: cliOptions.outDir, }); - console.log('Deploy command invoked ...'); + console.log('Deploy command invoked...'); if (!shell.which('git')) { throw new Error('Git not installed or on the PATH!'); } @@ -68,7 +68,7 @@ export default async function deploy( siteConfig.organizationName; if (!organizationName) { throw new Error( - `Missing project organization name. Did you forget to define 'organizationName' in ${siteConfigPath}? You may also export it via the ORGANIZATION_NAME environment variable.`, + `Missing project organization name. Did you forget to define "organizationName" in ${siteConfigPath}? You may also export it via the ORGANIZATION_NAME environment variable.`, ); } console.log(`${chalk.cyan('organizationName:')} ${organizationName}`); @@ -79,7 +79,7 @@ export default async function deploy( siteConfig.projectName; if (!projectName) { throw new Error( - `Missing project name. Did you forget to define 'projectName' in ${siteConfigPath}? You may also export it via the PROJECT_NAME environment variable.`, + `Missing project name. Did you forget to define "projectName" in ${siteConfigPath}? You may also export it via the PROJECT_NAME environment variable.`, ); } console.log(`${chalk.cyan('projectName:')} ${projectName}`); @@ -88,7 +88,7 @@ export default async function deploy( const isPullRequest = process.env.CI_PULL_REQUEST || process.env.CIRCLE_PULL_REQUEST; if (isPullRequest) { - shell.echo('Skipping deploy on a pull request'); + shell.echo('Skipping deploy on a pull request.'); shell.exit(0); } @@ -148,7 +148,7 @@ export default async function deploy( path.join(os.tmpdir(), `${projectName}-${deploymentBranch}`), ); if (shellExecLog(`git clone ${remoteBranch} ${toPath}`).code !== 0) { - throw new Error(`Error: git clone failed in ${toPath}`); + throw new Error(`Running "git clone" command in "${toPath}" failed.`); } shell.cd(toPath); @@ -164,7 +164,9 @@ export default async function deploy( if ( shellExecLog(`git checkout --orphan ${deploymentBranch}`).code !== 0 ) { - throw new Error(`Error: Git checkout ${deploymentBranch} failed`); + throw new Error( + `Running "git checkout ${deploymentBranch}" command failed.`, + ); } } else if ( shellExecLog(`git checkout -b ${deploymentBranch}`).code + @@ -173,7 +175,9 @@ export default async function deploy( ).code !== 0 ) { - throw new Error(`Error: Git checkout ${deploymentBranch} failed`); + throw new Error( + `Running "git checkout ${deploymentBranch}" command failed.`, + ); } } @@ -182,7 +186,7 @@ export default async function deploy( await fs.copy(fromPath, toPath); } catch (error) { throw new Error( - `Error: Copying build assets from "${fromPath}" to "${toPath}" failed with error '${error}'`, + `Copying build assets from "${fromPath}" to "${toPath}" failed with error "${error}".`, ); } shell.cd(toPath); @@ -195,7 +199,7 @@ export default async function deploy( if ( shellExecLog(`git push --force origin ${deploymentBranch}`).code !== 0 ) { - throw new Error('Error: Git push failed'); + throw new Error('Running "git push" command failed.'); } else if (commitResults.code === 0) { // The commit might return a non-zero value when site is up to date. let websiteURL = ''; @@ -207,7 +211,7 @@ export default async function deploy( // GitHub enterprise hosting. websiteURL = `https://${githubHost}/pages/${organizationName}/${projectName}/`; } - shell.echo(`Website is live at ${websiteURL}`); + shell.echo(`Website is live at "${websiteURL}".`); shell.exit(0); } }; diff --git a/packages/docusaurus/src/commands/serve.ts b/packages/docusaurus/src/commands/serve.ts index d2dec0a5c2..34fd5f49d7 100644 --- a/packages/docusaurus/src/commands/serve.ts +++ b/packages/docusaurus/src/commands/serve.ts @@ -73,9 +73,9 @@ export default async function serve( console.log( boxen( - `${chalk.green( - `Serving "${cliOptions.dir}" directory at ${servingUrl + baseUrl}`, - )}`, + chalk.green( + `Serving "${cliOptions.dir}" directory at "${servingUrl + baseUrl}".`, + ), { borderColor: 'green', padding: 1, diff --git a/packages/docusaurus/src/commands/start.ts b/packages/docusaurus/src/commands/start.ts index f60afa20c9..893293661d 100644 --- a/packages/docusaurus/src/commands/start.ts +++ b/packages/docusaurus/src/commands/start.ts @@ -65,7 +65,9 @@ export default async function start( const urls = prepareUrls(protocol, host, port); const openUrl = normalizeUrl([urls.localUrlForBrowser, baseUrl]); - console.log(chalk.cyanBright(`Docusaurus website is running at: ${openUrl}`)); + console.log( + chalk.cyanBright(`Docusaurus website is running at "${openUrl}".`), + ); // Reload files processing. const reload = debounce(() => { @@ -74,7 +76,9 @@ export default async function start( const newOpenUrl = normalizeUrl([urls.localUrlForBrowser, newBaseUrl]); if (newOpenUrl !== openUrl) { console.log( - chalk.cyanBright(`Docusaurus website is running at: ${newOpenUrl}`), + chalk.cyanBright( + `Docusaurus website is running at "${newOpenUrl}".`, + ), ); } }) diff --git a/packages/docusaurus/src/commands/swizzle.ts b/packages/docusaurus/src/commands/swizzle.ts index 2b4acda2d1..8ee6ef693b 100644 --- a/packages/docusaurus/src/commands/swizzle.ts +++ b/packages/docusaurus/src/commands/swizzle.ts @@ -100,11 +100,11 @@ function themeComponents( const components = colorCode(themePath, plugin); if (components.length === 0) { - return `${chalk.red('No component to swizzle')}`; + return `${chalk.red('No component to swizzle.')}`; } return ` -${chalk.cyan('Theme components available for swizzle')} +${chalk.cyan('Theme components available for swizzle.')} ${chalk.green('green =>')} safe: lower breaking change risk ${chalk.red('red =>')} unsafe: higher breaking change risk @@ -114,7 +114,7 @@ ${components.join('\n')} } function formattedThemeNames(themeNames: string[]): string { - return `Themes available for swizzle:\n${themeNames.join('\n')}`; + return `Themes available for swizzle:\n- ${themeNames.join('\n- ')}`; } function colorCode( diff --git a/packages/docusaurus/src/commands/writeHeadingIds.ts b/packages/docusaurus/src/commands/writeHeadingIds.ts index a93b51f4e9..8049ce923d 100644 --- a/packages/docusaurus/src/commands/writeHeadingIds.ts +++ b/packages/docusaurus/src/commands/writeHeadingIds.ts @@ -37,7 +37,7 @@ export function transformMarkdownHeadingLine( slugger: GithubSlugger, ): string { if (!line.startsWith('#')) { - throw new Error(`Line is not a markdown heading: ${line}`); + throw new Error(`Line is not a Markdown heading: ${line}.`); } const parsedHeading = parseMarkdownHeadingId(line); @@ -118,7 +118,7 @@ export default async function writeHeadingIds(siteDir: string): Promise { if (pathsModified.length) { console.log( - chalk.green(`Heading ids added to markdown files (${ + chalk.green(`Heading ids added to Markdown files (${ pathsModified.length }/${markdownFiles.length} files): - ${pathsModified.join('\n- ')}`), @@ -126,7 +126,7 @@ export default async function writeHeadingIds(siteDir: string): Promise { } else { console.log( chalk.yellow( - `${markdownFiles.length} markdown files already have explicit heading ids`, + `${markdownFiles.length} Markdown files already have explicit heading ids.`, ), ); } diff --git a/packages/docusaurus/src/commands/writeTranslations.ts b/packages/docusaurus/src/commands/writeTranslations.ts index 34a2f00ed9..a6b8bd6db9 100644 --- a/packages/docusaurus/src/commands/writeTranslations.ts +++ b/packages/docusaurus/src/commands/writeTranslations.ts @@ -67,9 +67,8 @@ export default async function writeTranslations( if (!context.i18n.locales.includes(locale)) { throw new Error( - `Can't write-translation for locale that is not in the locale configuration file. -Unknown locale=[${locale}]. -Available locales=[${context.i18n.locales.join(',')}]`, + `Can't write-translation for locale "${locale}" that is not in the locale configuration file. +Available locales are: ${context.i18n.locales.join(',')}.`, ); } diff --git a/packages/docusaurus/src/server/__tests__/__snapshots__/config.test.ts.snap b/packages/docusaurus/src/server/__tests__/__snapshots__/config.test.ts.snap index 5d2166940c..27a2e819d1 100644 --- a/packages/docusaurus/src/server/__tests__/__snapshots__/config.test.ts.snap +++ b/packages/docusaurus/src/server/__tests__/__snapshots__/config.test.ts.snap @@ -8,8 +8,8 @@ exports[`loadConfig website with incomplete siteConfig 1`] = ` exports[`loadConfig website with useless field (wrong field) in siteConfig 1`] = ` "\\"favicon\\" is required -These field(s) [\\"useLessField\\",] are not recognized in docusaurus.config.js. -If you still want these fields to be in your configuration, put them in the 'customFields' attribute. +These field(s) (\\"useLessField\\",) are not recognized in docusaurus.config.js. +If you still want these fields to be in your configuration, put them in the \\"customFields\\" field. See https://docusaurus.io/docs/docusaurus.config.js/#customfields" `; diff --git a/packages/docusaurus/src/server/__tests__/__snapshots__/configValidation.test.ts.snap b/packages/docusaurus/src/server/__tests__/__snapshots__/configValidation.test.ts.snap index 69fa24bdb6..75fa0a3c0b 100644 --- a/packages/docusaurus/src/server/__tests__/__snapshots__/configValidation.test.ts.snap +++ b/packages/docusaurus/src/server/__tests__/__snapshots__/configValidation.test.ts.snap @@ -1,7 +1,7 @@ // Jest Snapshot v1, https://goo.gl/fbAQLP exports[`normalizeConfig should throw error for baseUrl without trailing \`/\` 1`] = ` -"\\"baseUrl\\" must be a string with a trailing \`/\` +"\\"baseUrl\\" must be a string with a trailing slash. " `; @@ -14,14 +14,14 @@ exports[`normalizeConfig should throw error for required fields 1`] = ` \\"presets\\" must be an array \\"scripts\\" must be an array \\"stylesheets\\" must be an array -These field(s) [\\"invalidField\\",] are not recognized in docusaurus.config.js. -If you still want these fields to be in your configuration, put them in the 'customFields' attribute. +These field(s) (\\"invalidField\\",) are not recognized in docusaurus.config.js. +If you still want these fields to be in your configuration, put them in the \\"customFields\\" field. See https://docusaurus.io/docs/docusaurus.config.js/#customfields" `; exports[`normalizeConfig should throw error for unknown field 1`] = ` -"These field(s) [\\"invalid\\",] are not recognized in docusaurus.config.js. -If you still want these fields to be in your configuration, put them in the 'customFields' attribute. +"These field(s) (\\"invalid\\",) are not recognized in docusaurus.config.js. +If you still want these fields to be in your configuration, put them in the \\"customFields\\" field. See https://docusaurus.io/docs/docusaurus.config.js/#customfields" `; diff --git a/packages/docusaurus/src/server/__tests__/config.test.ts b/packages/docusaurus/src/server/__tests__/config.test.ts index 7c2f0ff276..15481372ec 100644 --- a/packages/docusaurus/src/server/__tests__/config.test.ts +++ b/packages/docusaurus/src/server/__tests__/config.test.ts @@ -55,7 +55,7 @@ describe('loadConfig', () => { expect(() => { loadConfig(siteDir); }).toThrowError( - /Config file "(.*?)__fixtures__[/\\]nonExisting[/\\]docusaurus.config.js" not found$/, + /Config file at "(.*?)__fixtures__[/\\]nonExisting[/\\]docusaurus.config.js" not found.$/, ); }); }); diff --git a/packages/docusaurus/src/server/__tests__/i18n.test.ts b/packages/docusaurus/src/server/__tests__/i18n.test.ts index 5a9869aa68..6c2a30e585 100644 --- a/packages/docusaurus/src/server/__tests__/i18n.test.ts +++ b/packages/docusaurus/src/server/__tests__/i18n.test.ts @@ -174,7 +174,7 @@ describe('loadI18n', () => { 'it', ); expect(consoleSpy.mock.calls[0][0]).toMatch( - /The locale=it was not found in your site configuration/, + /The locale "it" was not found in your site configuration/, ); }); }); diff --git a/packages/docusaurus/src/server/__tests__/routes.test.ts b/packages/docusaurus/src/server/__tests__/routes.test.ts index 5748c6d175..881db5c4ae 100644 --- a/packages/docusaurus/src/server/__tests__/routes.test.ts +++ b/packages/docusaurus/src/server/__tests__/routes.test.ts @@ -75,7 +75,7 @@ describe('loadRoutes', () => { expect(loadRoutes([routeConfigWithoutPath], '/')).rejects .toMatchInlineSnapshot(` - [Error: Invalid routeConfig (Path must be a string and component is required) + [Error: Invalid route config: path must be a string and component is required. {"component":"hello/world.js"}] `); @@ -85,7 +85,7 @@ describe('loadRoutes', () => { expect(loadRoutes([routeConfigWithoutComponent], '/')).rejects .toMatchInlineSnapshot(` - [Error: Invalid routeConfig (Path must be a string and component is required) + [Error: Invalid route config: path must be a string and component is required. {"path":"/hello/world"}] `); }); diff --git a/packages/docusaurus/src/server/config.ts b/packages/docusaurus/src/server/config.ts index 2f08307c88..72d2200e4f 100644 --- a/packages/docusaurus/src/server/config.ts +++ b/packages/docusaurus/src/server/config.ts @@ -12,7 +12,7 @@ import {validateConfig} from './configValidation'; export default function loadConfig(configPath: string): DocusaurusConfig { if (!fs.existsSync(configPath)) { - throw new Error(`Config file "${configPath}" not found`); + throw new Error(`Config file at "${configPath}" not found.`); } const loadedConfig = importFresh(configPath) as Partial; diff --git a/packages/docusaurus/src/server/configValidation.ts b/packages/docusaurus/src/server/configValidation.ts index 673c130f87..08aa8dd1cc 100644 --- a/packages/docusaurus/src/server/configValidation.ts +++ b/packages/docusaurus/src/server/configValidation.ts @@ -125,7 +125,7 @@ export const ConfigSchema = Joi.object({ baseUrl: Joi.string() .required() .regex(new RegExp('/$', 'm')) - .message('{{#label}} must be a string with a trailing `/`'), + .message('{{#label}} must be a string with a trailing slash.'), baseUrlIssueBanner: Joi.boolean().default(DEFAULT_CONFIG.baseUrlIssueBanner), favicon: Joi.string().required(), title: Joi.string().required(), @@ -212,7 +212,7 @@ export function validateConfig( '', ); formattedError = unknownFields - ? `${formattedError}These field(s) [${unknownFields}] are not recognized in ${DEFAULT_CONFIG_FILE_NAME}.\nIf you still want these fields to be in your configuration, put them in the 'customFields' attribute.\nSee https://docusaurus.io/docs/docusaurus.config.js/#customfields` + ? `${formattedError}These field(s) (${unknownFields}) are not recognized in ${DEFAULT_CONFIG_FILE_NAME}.\nIf you still want these fields to be in your configuration, put them in the "customFields" field.\nSee https://docusaurus.io/docs/docusaurus.config.js/#customfields` : formattedError; throw new Error(formattedError); } else { diff --git a/packages/docusaurus/src/server/html-tags/__tests__/htmlTags.test.ts b/packages/docusaurus/src/server/html-tags/__tests__/htmlTags.test.ts index 34e7017e99..5365a325ae 100644 --- a/packages/docusaurus/src/server/html-tags/__tests__/htmlTags.test.ts +++ b/packages/docusaurus/src/server/html-tags/__tests__/htmlTags.test.ts @@ -93,7 +93,7 @@ describe('htmlTagObjectToString', () => { }, }), ).toThrowErrorMatchingInlineSnapshot( - `"Error loading {\\"tagName\\":\\"endiliey\\",\\"attributes\\":{\\"this\\":\\"is invalid\\"}}, \\"endiliey\\" is not a valid HTML tags"`, + `"Error loading {\\"tagName\\":\\"endiliey\\",\\"attributes\\":{\\"this\\":\\"is invalid\\"}}, \\"endiliey\\" is not a valid HTML tags."`, ); }); @@ -103,7 +103,7 @@ describe('htmlTagObjectToString', () => { tagName: true, }), ).toThrowErrorMatchingInlineSnapshot( - `"{\\"tagName\\":true} is not a valid HTML tag object. \\"tagName\\" must be defined as a string"`, + `"{\\"tagName\\":true} is not a valid HTML tag object. \\"tagName\\" must be defined as a string."`, ); }); @@ -111,13 +111,13 @@ describe('htmlTagObjectToString', () => { expect(() => htmlTagObjectToString('fooofofoofo'), ).toThrowErrorMatchingInlineSnapshot( - `"\\"fooofofoofo\\" is not a valid HTML tag object"`, + `"\\"fooofofoofo\\" is not a valid HTML tag object."`, ); expect(() => htmlTagObjectToString(null), ).toThrowErrorMatchingInlineSnapshot( - `"\\"null\\" is not a valid HTML tag object"`, + `"\\"null\\" is not a valid HTML tag object."`, ); }); }); diff --git a/packages/docusaurus/src/server/html-tags/htmlTags.ts b/packages/docusaurus/src/server/html-tags/htmlTags.ts index 8033ef42ae..c27d64487a 100644 --- a/packages/docusaurus/src/server/html-tags/htmlTags.ts +++ b/packages/docusaurus/src/server/html-tags/htmlTags.ts @@ -13,14 +13,14 @@ import escapeHTML from 'escape-html'; function assertIsHtmlTagObject(val: unknown): asserts val is HtmlTagObject { if (!isPlainObject(val)) { - throw new Error(`"${val}" is not a valid HTML tag object`); + throw new Error(`"${val}" is not a valid HTML tag object.`); } // @ts-expect-error: If tagName doesn't exist, it will throw. if (typeof val.tagName !== 'string') { throw new Error( `${JSON.stringify( val, - )} is not a valid HTML tag object. "tagName" must be defined as a string`, + )} is not a valid HTML tag object. "tagName" must be defined as a string.`, ); } } @@ -31,7 +31,7 @@ export default function htmlTagObjectToString(tagDefinition: unknown): string { throw new Error( `Error loading ${JSON.stringify(tagDefinition)}, "${ tagDefinition.tagName - }" is not a valid HTML tags`, + }" is not a valid HTML tags.`, ); } const isVoidTag = voidHtmlTags.indexOf(tagDefinition.tagName) !== -1; diff --git a/packages/docusaurus/src/server/i18n.ts b/packages/docusaurus/src/server/i18n.ts index db26fc6345..fa8a021dde 100644 --- a/packages/docusaurus/src/server/i18n.ts +++ b/packages/docusaurus/src/server/i18n.ts @@ -46,9 +46,9 @@ export async function loadI18n( if (!i18nConfig.locales.includes(currentLocale)) { console.warn( chalk.yellow( - `The locale=${currentLocale} was not found in your site configuration: config.i18n.locales=[${i18nConfig.locales.join( + `The locale "${currentLocale}" was not found in your site configuration: Available locales are: ${i18nConfig.locales.join( ',', - )}] + )}. Note: Docusaurus only support running one locale at a time.`, ), ); @@ -61,7 +61,7 @@ Note: Docusaurus only support running one locale at a time.`, if (shouldWarnAboutNodeVersion(NODE_MAJOR_VERSION, locales)) { console.warn( chalk.yellow( - `To use Docusaurus i18n, it is strongly advised to use NodeJS >= 14 (instead of ${NODE_MAJOR_VERSION})`, + `To use Docusaurus i18n, it is strongly advised to use Node.js 14 or later (instead of ${NODE_MAJOR_VERSION}).`, ), ); } @@ -113,7 +113,7 @@ export function localizePath({ } // should never happen else { - throw new Error(`unhandled pathType=${pathType}`); + throw new Error(`Unhandled path type "${pathType}".`); } } else { return originalPath; diff --git a/packages/docusaurus/src/server/index.ts b/packages/docusaurus/src/server/index.ts index c4ff3bdb5d..7a0dce4ddb 100644 --- a/packages/docusaurus/src/server/index.ts +++ b/packages/docusaurus/src/server/index.ts @@ -375,7 +375,7 @@ function checkDocusaurusPackagesVersion(siteMetadata: DocusaurusSiteMetadata) { // It still could work with different versions console.warn( chalk.red( - `Bad ${plugin} version ${versionInfo.version}.\nAll official @docusaurus/* packages should have the exact same version as @docusaurus/core (${docusaurusVersion}).\nMaybe you want to check, or regenerate your yarn.lock or package-lock.json file?`, + `Invalid ${plugin} version ${versionInfo.version}.\nAll official @docusaurus/* packages should have the exact same version as @docusaurus/core (${docusaurusVersion}).\nMaybe you want to check, or regenerate your yarn.lock or package-lock.json file?`, ), ); } diff --git a/packages/docusaurus/src/server/plugins/__tests__/__snapshots__/pluginIds.test.ts.snap b/packages/docusaurus/src/server/plugins/__tests__/__snapshots__/pluginIds.test.ts.snap index 8715e96b6e..fc9593b908 100644 --- a/packages/docusaurus/src/server/plugins/__tests__/__snapshots__/pluginIds.test.ts.snap +++ b/packages/docusaurus/src/server/plugins/__tests__/__snapshots__/pluginIds.test.ts.snap @@ -1,16 +1,16 @@ // Jest Snapshot v1, https://goo.gl/fbAQLP exports[`ensureUniquePluginInstanceIds reject multi instance plugins with same id 1`] = ` -"Plugin plugin-docs is used 2 times with id=sameId. +"Plugin \\"plugin-docs\\" is used 2 times with id sameId. To use the same plugin multiple times on a Docusaurus site, you need to assign a unique id to each plugin instance." `; exports[`ensureUniquePluginInstanceIds reject multi instance plugins without id 1`] = ` -"Plugin plugin-docs is used 2 times with id=default. +"Plugin \\"plugin-docs\\" is used 2 times with id default. To use the same plugin multiple times on a Docusaurus site, you need to assign a unique id to each plugin instance." `; exports[`ensureUniquePluginInstanceIds reject multi instance plugins without id 2`] = ` -"Plugin plugin-docs is used 2 times with id=default. +"Plugin \\"plugin-docs\\" is used 2 times with id default. To use the same plugin multiple times on a Docusaurus site, you need to assign a unique id to each plugin instance." `; diff --git a/packages/docusaurus/src/server/plugins/index.ts b/packages/docusaurus/src/server/plugins/index.ts index 3a7b54689b..0a1f8764c4 100644 --- a/packages/docusaurus/src/server/plugins/index.ts +++ b/packages/docusaurus/src/server/plugins/index.ts @@ -201,7 +201,7 @@ export async function loadPlugins({ // TODO, 1 user reported usage of this lifecycle! https://github.com/facebook/docusaurus/issues/3918 console.error( chalk.red( - 'plugin routesLoaded lifecycle is deprecated. If you think we should keep this lifecycle, please report here: https://github.com/facebook/docusaurus/issues/3918', + 'Plugin routesLoaded lifecycle is deprecated. If you think we should keep this lifecycle, please report here: https://github.com/facebook/docusaurus/issues/3918', ), ); diff --git a/packages/docusaurus/src/server/plugins/init.ts b/packages/docusaurus/src/server/plugins/init.ts index b21875efa7..da1b8ba931 100644 --- a/packages/docusaurus/src/server/plugins/init.ts +++ b/packages/docusaurus/src/server/plugins/init.ts @@ -90,7 +90,7 @@ function normalizePluginConfig( } throw new Error( - `Unexpected: cant load plugin for plugin config = ${JSON.stringify( + `Unexpected: can't load plugin for following plugin config.\n${JSON.stringify( pluginConfig, )}`, ); diff --git a/packages/docusaurus/src/server/plugins/pluginIds.ts b/packages/docusaurus/src/server/plugins/pluginIds.ts index 7c4c028833..d48a1ba625 100644 --- a/packages/docusaurus/src/server/plugins/pluginIds.ts +++ b/packages/docusaurus/src/server/plugins/pluginIds.ts @@ -22,7 +22,7 @@ export function ensureUniquePluginInstanceIds(plugins: InitPlugin[]): void { ([pluginId, pluginInstancesWithId]) => { if (pluginInstancesWithId.length !== 1) { throw new Error( - `Plugin ${pluginName} is used ${pluginInstancesWithId.length} times with id=${pluginId}.\nTo use the same plugin multiple times on a Docusaurus site, you need to assign a unique id to each plugin instance.`, + `Plugin "${pluginName}" is used ${pluginInstancesWithId.length} times with id ${pluginId}.\nTo use the same plugin multiple times on a Docusaurus site, you need to assign a unique id to each plugin instance.`, ); } }, diff --git a/packages/docusaurus/src/server/routes.ts b/packages/docusaurus/src/server/routes.ts index f566ede5d8..904be52f72 100644 --- a/packages/docusaurus/src/server/routes.ts +++ b/packages/docusaurus/src/server/routes.ts @@ -110,7 +110,7 @@ export default async function loadRoutes( if (!isString(routePath) || !component) { throw new Error( - `Invalid routeConfig (Path must be a string and component is required) \n${JSON.stringify( + `Invalid route config: path must be a string and component is required.\n${JSON.stringify( routeConfig, )}`, ); diff --git a/packages/docusaurus/src/server/translations/__tests__/translations.test.ts b/packages/docusaurus/src/server/translations/__tests__/translations.test.ts index 2b816a4acf..adc16aaacf 100644 --- a/packages/docusaurus/src/server/translations/__tests__/translations.test.ts +++ b/packages/docusaurus/src/server/translations/__tests__/translations.test.ts @@ -266,7 +266,7 @@ describe('writeTranslationFileContent', () => { key1: {message: 'key1 message'}, }, }), - ).rejects.toThrowError(/Invalid translation file at path/); + ).rejects.toThrowError(/Invalid translation file at/); }); }); diff --git a/packages/docusaurus/src/server/translations/translations.ts b/packages/docusaurus/src/server/translations/translations.ts index 205632e0bc..bc154f8414 100644 --- a/packages/docusaurus/src/server/translations/translations.ts +++ b/packages/docusaurus/src/server/translations/translations.ts @@ -56,9 +56,7 @@ export async function readTranslationFileContent( ensureTranslationFileContent(content); return content; } catch (e) { - throw new Error( - `Invalid translation file at path=${filePath}.\n${e.message}`, - ); + throw new Error(`Invalid translation file at ${filePath}.\n${e.message}`); } } return undefined; @@ -135,9 +133,9 @@ Maybe you should remove them? .padStart( 3, ' ', - )} translations will be written at ${toMessageRelativeFilePath( + )} translations will be written at "${toMessageRelativeFilePath( filePath, - )}`, + )}".`, ); await fs.ensureDir(path.dirname(filePath)); await fs.writeFile(filePath, JSON.stringify(mergedContent, null, 2)); @@ -183,7 +181,7 @@ export async function writeCodeTranslations( function addTranslationFileExtension(translationFilePath: string) { if (translationFilePath.endsWith('.json')) { throw new Error( - `Translation file path does not need to end with .json, we addt the extension automatically. translationFilePath=${translationFilePath}`, + `Translation file path at "${translationFilePath}" does not need to end with ".json", we add the extension automatically.`, ); } return `${translationFilePath}.json`; diff --git a/packages/docusaurus/src/webpack/plugins/CleanWebpackPlugin.ts b/packages/docusaurus/src/webpack/plugins/CleanWebpackPlugin.ts index 99c088430a..55c2b20146 100644 --- a/packages/docusaurus/src/webpack/plugins/CleanWebpackPlugin.ts +++ b/packages/docusaurus/src/webpack/plugins/CleanWebpackPlugin.ts @@ -244,7 +244,7 @@ class CleanWebpackPlugin { if (needsForce) { const message = - 'clean-webpack-plugin: Cannot delete files/folders outside the current working directory. Can be overridden with the `dangerouslyAllowCleanPatternsOutsideProject` option.'; + 'clean-webpack-plugin: Cannot delete files/folders outside the current working directory. Can be overridden with the "dangerouslyAllowCleanPatternsOutsideProject" option.'; throw new Error(message); } diff --git a/packages/docusaurus/src/webpack/utils.ts b/packages/docusaurus/src/webpack/utils.ts index 0ecf28f45b..e760fbcb36 100644 --- a/packages/docusaurus/src/webpack/utils.ts +++ b/packages/docusaurus/src/webpack/utils.ts @@ -167,7 +167,7 @@ export const getCustomizableJSLoader = ( const warnBabelLoaderOnce = memoize(function () { console.warn( chalk.yellow( - 'Docusaurus plans to support multiple JS loader strategies (Babel, esbuild...): getBabelLoader(isServer) is now deprecated in favor of getJSLoader({isServer})', + 'Docusaurus plans to support multiple JS loader strategies (Babel, esbuild...): "getBabelLoader(isServer)" is now deprecated in favor of "getJSLoader({isServer})".', ), ); }); @@ -183,7 +183,7 @@ const getBabelLoaderDeprecated = function getBabelLoaderDeprecated( const warnCacheLoaderOnce = memoize(function () { console.warn( chalk.yellow( - 'Docusaurus uses Webpack 5 and getCacheLoader() usage is now deprecated', + 'Docusaurus uses Webpack 5 and getCacheLoader() usage is now deprecated.', ), ); }); @@ -288,7 +288,7 @@ export function compile(config: Configuration[]): Promise { compiler.close((errClose) => { if (errClose) { console.error( - chalk.red('Error while closing Webpack compiler', errClose), + chalk.red('Error while closing Webpack compiler:', errClose), ); reject(errClose); } else {