@docusaurus/utils-validation 2.0.0-beta.1decd6f80 → 2.0.0-beta.20

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -4,20 +4,29 @@
4
4
  * This source code is licensed under the MIT license found in the
5
5
  * LICENSE file in the root directory of this source tree.
6
6
  */
7
+
7
8
  import Joi from './Joi';
8
- import {isValidPathname} from '@docusaurus/utils';
9
+ import {isValidPathname, DEFAULT_PLUGIN_ID, type Tag} from '@docusaurus/utils';
10
+ import {JoiFrontMatter} from './JoiFrontMatter';
9
11
 
10
12
  export const PluginIdSchema = Joi.string()
11
- .regex(/^[a-zA-Z_-]+$/)
12
- // duplicate core constant, otherwise cyclic dependency is created :(
13
- .default('default');
13
+ .regex(/^[\w-]+$/)
14
+ .message(
15
+ 'Illegal plugin ID value "{#value}": it should only contain alphanumerics, underscores, and dashes.',
16
+ )
17
+ .default(DEFAULT_PLUGIN_ID);
14
18
 
15
19
  const MarkdownPluginsSchema = Joi.array()
16
20
  .items(
17
- Joi.array().ordered(Joi.function().required(), Joi.object().required()),
21
+ Joi.array().ordered(Joi.function().required(), Joi.any().required()),
18
22
  Joi.function(),
19
23
  Joi.object(),
20
24
  )
25
+ .messages({
26
+ 'array.includes': `{#label} does not look like a valid MDX plugin config. A plugin config entry should be one of:
27
+ - A tuple, like \`[require("rehype-katex"), \\{ strict: false \\}]\`, or
28
+ - A simple module, like \`require("remark-math")\``,
29
+ })
21
30
  .default([]);
22
31
 
23
32
  export const RemarkPluginsSchema = MarkdownPluginsSchema;
@@ -25,30 +34,64 @@ export const RehypePluginsSchema = MarkdownPluginsSchema;
25
34
 
26
35
  export const AdmonitionsSchema = Joi.object().default({});
27
36
 
37
+ // TODO how can we make this emit a custom error message :'(
38
+ // Joi is such a pain, good luck to annoying trying to improve this
28
39
  export const URISchema = Joi.alternatives(
29
40
  Joi.string().uri({allowRelative: true}),
41
+ // This custom validation logic is required notably because Joi does not
42
+ // accept paths like /a/b/c ...
30
43
  Joi.custom((val, helpers) => {
31
44
  try {
32
- const url = new URL(val);
33
- if (url) {
34
- return val;
35
- } else {
36
- return helpers.error('any.invalid');
37
- }
45
+ // eslint-disable-next-line no-new
46
+ new URL(val);
47
+ return val;
38
48
  } catch {
39
49
  return helpers.error('any.invalid');
40
50
  }
41
51
  }),
42
- );
52
+ ).messages({
53
+ 'alternatives.match':
54
+ "{{#label}} does not look like a valid url (value='{{.value}}')",
55
+ });
43
56
 
44
57
  export const PathnameSchema = Joi.string()
45
58
  .custom((val) => {
46
59
  if (!isValidPathname(val)) {
47
60
  throw new Error();
48
- } else {
49
- return val;
50
61
  }
62
+ return val;
51
63
  })
52
64
  .message(
53
- '{{#label}} is not a valid pathname. Pathname should start with / and not contain any domain or query string',
65
+ '{{#label}} is not a valid pathname. Pathname should start with slash and not contain any domain or query string.',
54
66
  );
67
+
68
+ const FrontMatterTagSchema = JoiFrontMatter.alternatives()
69
+ .try(
70
+ JoiFrontMatter.string().required(),
71
+ JoiFrontMatter.object<Tag>({
72
+ label: JoiFrontMatter.string().required(),
73
+ permalink: JoiFrontMatter.string().required(),
74
+ }).required(),
75
+ )
76
+ .messages({
77
+ 'alternatives.match': '{{#label}} does not look like a valid tag',
78
+ 'alternatives.types': '{{#label}} does not look like a valid tag',
79
+ });
80
+
81
+ export const FrontMatterTagsSchema = JoiFrontMatter.array()
82
+ .items(FrontMatterTagSchema)
83
+ .messages({
84
+ 'array.base':
85
+ '{{#label}} does not look like a valid front matter Yaml array.',
86
+ });
87
+
88
+ export const FrontMatterTOCHeadingLevels = {
89
+ toc_min_heading_level: JoiFrontMatter.number().when('toc_max_heading_level', {
90
+ is: JoiFrontMatter.exist(),
91
+ then: JoiFrontMatter.number()
92
+ .min(2)
93
+ .max(JoiFrontMatter.ref('toc_max_heading_level')),
94
+ otherwise: JoiFrontMatter.number().min(2).max(6),
95
+ }),
96
+ toc_max_heading_level: JoiFrontMatter.number().min(2).max(6),
97
+ };
@@ -4,106 +4,80 @@
4
4
  * This source code is licensed under the MIT license found in the
5
5
  * LICENSE file in the root directory of this source tree.
6
6
  */
7
- import Joi from './Joi';
8
- import chalk from 'chalk';
9
- import {PluginIdSchema} from './validationSchemas';
10
7
 
11
- // TODO temporary escape hatch for alpha-60: to be removed soon
12
- // Our validation schemas might be buggy at first
13
- // will permit users to bypass validation until we fix all validation errors
14
- // see for example: https://github.com/facebook/docusaurus/pull/3120
15
- // Undocumented on purpose, as we don't want users to keep using it over time
16
- // Maybe we'll make this escape hatch official some day, with a better api?
17
- export const isValidationDisabledEscapeHatch =
18
- process.env.DISABLE_DOCUSAURUS_VALIDATION === 'true';
8
+ import type Joi from './Joi';
9
+ import logger from '@docusaurus/logger';
10
+ import Yaml from 'js-yaml';
11
+ import {PluginIdSchema} from './validationSchemas';
19
12
 
20
- if (isValidationDisabledEscapeHatch) {
21
- console.error(
22
- chalk.red(
23
- 'You should avoid using DISABLE_DOCUSAURUS_VALIDATION escape hatch, this will be removed',
24
- ),
25
- );
13
+ /** Print warnings returned from Joi validation. */
14
+ export function printWarning(warning?: Joi.ValidationError): void {
15
+ if (warning) {
16
+ const warningMessages = warning.details
17
+ .map(({message}) => message)
18
+ .join('\n');
19
+ logger.warn(warningMessages);
20
+ }
26
21
  }
27
22
 
28
- export const logValidationBugReportHint = (): void => {
29
- console.log(
30
- `\n${chalk.red('A validation error occured.')}${chalk.cyanBright(
31
- '\nThe validation system was added recently to Docusaurus as an attempt to avoid user configuration errors.' +
32
- '\nWe may have made some mistakes.' +
33
- '\nIf you think your configuration is valid and should keep working, please open a bug report.',
34
- )}\n`,
35
- );
36
- };
37
-
23
+ /**
24
+ * The callback that should be used to validate plugin options. Handles plugin
25
+ * IDs on a generic level: no matter what the schema declares, this callback
26
+ * would require a string ID or default to "default".
27
+ */
38
28
  export function normalizePluginOptions<T extends {id?: string}>(
39
29
  schema: Joi.ObjectSchema<T>,
40
- options: Partial<T>,
30
+ // This allows us to automatically normalize undefined to { id: "default" }
31
+ options: Partial<T> = {},
41
32
  ): T {
42
33
  // All plugins can be provided an "id" option (multi-instance support)
43
34
  // we add schema validation automatically
44
35
  const finalSchema = schema.append({
45
36
  id: PluginIdSchema,
46
37
  });
47
- const {error, value} = finalSchema.validate(options, {
38
+ const {error, warning, value} = finalSchema.validate(options, {
48
39
  convert: false,
49
40
  });
41
+
42
+ printWarning(warning);
43
+
50
44
  if (error) {
51
- logValidationBugReportHint();
52
- if (isValidationDisabledEscapeHatch) {
53
- console.error(error);
54
- return options as T;
55
- } else {
56
- throw error;
57
- }
45
+ throw error;
58
46
  }
47
+
59
48
  return value;
60
49
  }
61
50
 
51
+ /**
52
+ * The callback that should be used to validate theme config. No matter what the
53
+ * schema declares, this callback would allow unknown attributes.
54
+ */
62
55
  export function normalizeThemeConfig<T>(
63
56
  schema: Joi.ObjectSchema<T>,
64
57
  themeConfig: Partial<T>,
65
58
  ): T {
66
- // A theme should only validate his "slice" of the full themeConfig,
59
+ // A theme should only validate its "slice" of the full themeConfig,
67
60
  // not the whole object, so we allow unknown attributes
68
61
  // otherwise one theme would fail validating the data of another theme
69
62
  const finalSchema = schema.unknown();
70
63
 
71
- const {error, value} = finalSchema.validate(themeConfig, {
64
+ const {error, warning, value} = finalSchema.validate(themeConfig, {
72
65
  convert: false,
73
66
  });
74
67
 
68
+ printWarning(warning);
69
+
75
70
  if (error) {
76
- logValidationBugReportHint();
77
- if (isValidationDisabledEscapeHatch) {
78
- console.error(error);
79
- return themeConfig as T;
80
- } else {
81
- throw error;
82
- }
71
+ throw error;
83
72
  }
84
73
  return value;
85
74
  }
86
75
 
87
- // Enhance the default Joi.string() type so that it can convert number to strings
88
- // If user use frontmatter "tag: 2021", we shouldn't need to ask the user to write "tag: '2021'"
89
- // Also yaml tries to convert patterns like "2019-01-01" to dates automatically
90
- // see https://github.com/facebook/docusaurus/issues/4642
91
- // see https://github.com/sideway/joi/issues/1442#issuecomment-823997884
92
- const JoiFrontMatterString: Joi.Extension = {
93
- type: 'string',
94
- base: Joi.string(),
95
- // Fix Yaml that tries to auto-convert many things to string out of the box
96
- prepare: (value) => {
97
- if (typeof value === 'number' || value instanceof Date) {
98
- return {value: value.toString()};
99
- }
100
- return {value};
101
- },
102
- };
103
- export const JoiFrontMatter: typeof Joi = Joi.extend(JoiFrontMatterString);
104
-
76
+ /**
77
+ * Validate front matter with better error message
78
+ */
105
79
  export function validateFrontMatter<T>(
106
- frontMatter: Record<string, unknown>,
80
+ frontMatter: {[key: string]: unknown},
107
81
  schema: Joi.ObjectSchema<T>,
108
82
  ): T {
109
83
  const {value, error, warning} = schema.validate(frontMatter, {
@@ -112,32 +86,20 @@ export function validateFrontMatter<T>(
112
86
  abortEarly: false,
113
87
  });
114
88
 
89
+ printWarning(warning);
90
+
115
91
  if (error) {
116
- const frontMatterString = JSON.stringify(frontMatter, null, 2);
117
92
  const errorDetails = error.details;
118
93
  const invalidFields = errorDetails.map(({path}) => path).join(', ');
119
- const errorMessages = errorDetails
120
- .map(({message}) => ` - ${message}`)
121
- .join('\n');
122
94
 
123
- logValidationBugReportHint();
124
-
125
- console.error(
126
- chalk.red(
127
- `The following FrontMatter:\n${chalk.yellow(
128
- frontMatterString,
129
- )}\ncontains invalid values for field(s): ${invalidFields}.\n${errorMessages}\n`,
130
- ),
131
- );
95
+ logger.error`The following front matter:
96
+ ---
97
+ ${Yaml.dump(frontMatter)}---
98
+ contains invalid values for field(s): code=${invalidFields}.
99
+ ${errorDetails.map(({message}) => message)}
100
+ `;
132
101
  throw error;
133
102
  }
134
103
 
135
- if (warning) {
136
- const warningMessages = warning.details
137
- .map(({message}) => message)
138
- .join('\n');
139
- console.log(chalk.yellow(warningMessages));
140
- }
141
-
142
104
  return value;
143
105
  }