@docusaurus/plugin-content-blog 2.0.0-beta.12faed89d → 2.0.0-beta.13

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.
Files changed (65) hide show
  1. package/lib/.tsbuildinfo +1 -1
  2. package/lib/authors.d.ts +23 -0
  3. package/lib/authors.js +147 -0
  4. package/lib/blogFrontMatter.d.ts +19 -6
  5. package/lib/blogFrontMatter.js +31 -19
  6. package/lib/blogUtils.d.ts +10 -4
  7. package/lib/blogUtils.js +141 -136
  8. package/lib/feed.d.ts +20 -0
  9. package/lib/feed.js +90 -0
  10. package/lib/index.js +99 -106
  11. package/lib/markdownLoader.d.ts +3 -6
  12. package/lib/markdownLoader.js +5 -5
  13. package/lib/pluginOptionSchema.d.ts +3 -26
  14. package/lib/pluginOptionSchema.js +28 -7
  15. package/lib/translations.d.ts +10 -0
  16. package/lib/translations.js +53 -0
  17. package/lib/types.d.ts +54 -14
  18. package/package.json +17 -13
  19. package/src/__tests__/__fixtures__/authorsMapFiles/authors.json +29 -0
  20. package/src/__tests__/__fixtures__/authorsMapFiles/authors.yml +27 -0
  21. package/src/__tests__/__fixtures__/authorsMapFiles/authorsBad1.json +5 -0
  22. package/src/__tests__/__fixtures__/authorsMapFiles/authorsBad1.yml +3 -0
  23. package/src/__tests__/__fixtures__/authorsMapFiles/authorsBad2.json +3 -0
  24. package/src/__tests__/__fixtures__/authorsMapFiles/authorsBad2.yml +2 -0
  25. package/src/__tests__/__fixtures__/authorsMapFiles/authorsBad3.json +8 -0
  26. package/src/__tests__/__fixtures__/authorsMapFiles/authorsBad3.yml +3 -0
  27. package/src/__tests__/__fixtures__/component/Typography.tsx +6 -0
  28. package/src/__tests__/__fixtures__/getAuthorsMapFilePath/contentPathEmpty/empty +0 -0
  29. package/src/__tests__/__fixtures__/getAuthorsMapFilePath/contentPathJson1/authors.json +0 -0
  30. package/src/__tests__/__fixtures__/getAuthorsMapFilePath/contentPathJson2/authors.json +0 -0
  31. package/src/__tests__/__fixtures__/getAuthorsMapFilePath/contentPathNestedYml/sub/folder/authors.yml +0 -0
  32. package/src/__tests__/__fixtures__/getAuthorsMapFilePath/contentPathYml1/authors.yml +0 -0
  33. package/src/__tests__/__fixtures__/getAuthorsMapFilePath/contentPathYml2/authors.yml +0 -0
  34. package/src/__tests__/__fixtures__/website/blog/2018-12-14-Happy-First-Birthday-Slash.md +3 -0
  35. package/src/__tests__/__fixtures__/website/blog/_partials/somePartial.md +3 -0
  36. package/src/__tests__/__fixtures__/website/blog/_partials/subfolder/somePartial.md +3 -0
  37. package/src/__tests__/__fixtures__/website/blog/_somePartial.md +3 -0
  38. package/src/__tests__/__fixtures__/website/blog/authors.yml +4 -0
  39. package/src/__tests__/__fixtures__/website/blog/mdx-blog-post.mdx +36 -0
  40. package/src/__tests__/__fixtures__/website/blog/mdx-require-blog-post.mdx +14 -0
  41. package/src/__tests__/__fixtures__/website/blog/simple-slug.md +4 -0
  42. package/src/__tests__/__fixtures__/website/i18n/en/docusaurus-plugin-content-blog/2018-12-14-Happy-First-Birthday-Slash.md +3 -0
  43. package/src/__tests__/__fixtures__/website/i18n/en/docusaurus-plugin-content-blog/authors.yml +5 -0
  44. package/src/__tests__/__fixtures__/website/static/img/docusaurus.png +0 -0
  45. package/src/__tests__/__snapshots__/feed.test.ts.snap +164 -0
  46. package/src/__tests__/__snapshots__/translations.test.ts.snap +64 -0
  47. package/src/__tests__/authors.test.ts +608 -0
  48. package/src/__tests__/blogFrontMatter.test.ts +93 -16
  49. package/src/__tests__/blogUtils.test.ts +94 -0
  50. package/src/__tests__/{generateBlogFeed.test.ts → feed.test.ts} +35 -9
  51. package/src/__tests__/index.test.ts +84 -12
  52. package/src/__tests__/pluginOptionSchema.test.ts +3 -3
  53. package/src/__tests__/translations.test.ts +92 -0
  54. package/src/authors.ts +198 -0
  55. package/src/blogFrontMatter.ts +71 -33
  56. package/src/blogUtils.ts +202 -179
  57. package/{types.d.ts → src/deps.d.ts} +0 -0
  58. package/src/feed.ts +129 -0
  59. package/src/index.ts +118 -107
  60. package/src/markdownLoader.ts +8 -12
  61. package/{index.d.ts → src/plugin-content-blog.d.ts} +35 -31
  62. package/src/pluginOptionSchema.ts +31 -9
  63. package/src/translations.ts +63 -0
  64. package/src/types.ts +69 -16
  65. package/src/__tests__/__snapshots__/generateBlogFeed.test.ts.snap +0 -76
@@ -0,0 +1,92 @@
1
+ /**
2
+ * Copyright (c) Facebook, Inc. and its affiliates.
3
+ *
4
+ * This source code is licensed under the MIT license found in the
5
+ * LICENSE file in the root directory of this source tree.
6
+ */
7
+
8
+ import {BlogPost, BlogContent, PluginOptions} from '../types';
9
+ import {getTranslationFiles, translateContent} from '../translations';
10
+ import {DEFAULT_OPTIONS} from '../pluginOptionSchema';
11
+ import {updateTranslationFileMessages} from '@docusaurus/utils';
12
+
13
+ const sampleBlogOptions: PluginOptions = {
14
+ ...DEFAULT_OPTIONS,
15
+ blogSidebarTitle: 'All my posts',
16
+ blogTitle: 'My blog',
17
+ blogDescription: "Someone's random blog",
18
+ };
19
+
20
+ const sampleBlogPosts: BlogPost[] = [
21
+ {
22
+ id: 'hello',
23
+ metadata: {
24
+ permalink: '/blog/2021/06/19/hello',
25
+ source: '/blog/2021/06/19/hello',
26
+ description: '/blog/2021/06/19/hello',
27
+ date: new Date(2021, 6, 19),
28
+ formattedDate: 'June 19, 2021',
29
+ tags: [],
30
+ title: 'Hello',
31
+ truncated: true,
32
+ },
33
+ },
34
+ ];
35
+
36
+ const sampleBlogContent: BlogContent = {
37
+ blogSidebarTitle: sampleBlogOptions.blogSidebarTitle,
38
+ blogListPaginated: [
39
+ {
40
+ items: ['hello'],
41
+ metadata: {
42
+ permalink: '/',
43
+ page: 1,
44
+ postsPerPage: 10,
45
+ totalPages: 1,
46
+ totalCount: 1,
47
+ previousPage: null,
48
+ nextPage: null,
49
+ blogTitle: sampleBlogOptions.blogTitle,
50
+ blogDescription: sampleBlogOptions.blogDescription,
51
+ },
52
+ },
53
+ ],
54
+ blogPosts: sampleBlogPosts,
55
+ blogTags: {},
56
+ blogTagsListPath: '/tags',
57
+ };
58
+
59
+ function getSampleTranslationFiles() {
60
+ return getTranslationFiles(sampleBlogOptions);
61
+ }
62
+ function getSampleTranslationFilesTranslated() {
63
+ const translationFiles = getSampleTranslationFiles();
64
+ return translationFiles.map((translationFile) =>
65
+ updateTranslationFileMessages(
66
+ translationFile,
67
+ (message) => `${message} (translated)`,
68
+ ),
69
+ );
70
+ }
71
+
72
+ describe('getContentTranslationFiles', () => {
73
+ test('should return translation files matching snapshot', async () => {
74
+ expect(getSampleTranslationFiles()).toMatchSnapshot();
75
+ });
76
+ });
77
+
78
+ describe('translateContent', () => {
79
+ test('should not translate anything if translation files are untranslated', () => {
80
+ const translationFiles = getSampleTranslationFiles();
81
+ expect(translateContent(sampleBlogContent, translationFiles)).toEqual(
82
+ sampleBlogContent,
83
+ );
84
+ });
85
+
86
+ test('should return translated loaded content matching snapshot', () => {
87
+ const translationFiles = getSampleTranslationFilesTranslated();
88
+ expect(
89
+ translateContent(sampleBlogContent, translationFiles),
90
+ ).toMatchSnapshot();
91
+ });
92
+ });
package/src/authors.ts ADDED
@@ -0,0 +1,198 @@
1
+ /**
2
+ * Copyright (c) Facebook, Inc. and its affiliates.
3
+ *
4
+ * This source code is licensed under the MIT license found in the
5
+ * LICENSE file in the root directory of this source tree.
6
+ */
7
+
8
+ import fs from 'fs-extra';
9
+ import chalk from 'chalk';
10
+ import path from 'path';
11
+ import {Author, BlogContentPaths} from './types';
12
+ import {findFolderContainingFile} from '@docusaurus/utils';
13
+ import {Joi, URISchema} from '@docusaurus/utils-validation';
14
+ import {
15
+ BlogPostFrontMatter,
16
+ BlogPostFrontMatterAuthor,
17
+ BlogPostFrontMatterAuthors,
18
+ } from './blogFrontMatter';
19
+ import {getContentPathList} from './blogUtils';
20
+ import Yaml from 'js-yaml';
21
+
22
+ export type AuthorsMap = Record<string, Author>;
23
+
24
+ const AuthorsMapSchema = Joi.object<AuthorsMap>().pattern(
25
+ Joi.string(),
26
+ Joi.object({
27
+ name: Joi.string().required(),
28
+ url: URISchema,
29
+ imageURL: URISchema,
30
+ title: Joi.string(),
31
+ })
32
+ .rename('image_url', 'imageURL')
33
+ .unknown()
34
+ .required(),
35
+ );
36
+
37
+ export function validateAuthorsMapFile(content: unknown): AuthorsMap {
38
+ return Joi.attempt(content, AuthorsMapSchema);
39
+ }
40
+
41
+ export async function readAuthorsMapFile(
42
+ filePath: string,
43
+ ): Promise<AuthorsMap | undefined> {
44
+ if (await fs.pathExists(filePath)) {
45
+ const contentString = await fs.readFile(filePath, {encoding: 'utf8'});
46
+ try {
47
+ const unsafeContent = Yaml.load(contentString);
48
+ return validateAuthorsMapFile(unsafeContent);
49
+ } catch (e) {
50
+ // TODO replace later by error cause: see https://v8.dev/features/error-cause
51
+ console.error(chalk.red('The author list file looks invalid!'));
52
+ throw e;
53
+ }
54
+ }
55
+ return undefined;
56
+ }
57
+
58
+ type AuthorsMapParams = {
59
+ authorsMapPath: string;
60
+ contentPaths: BlogContentPaths;
61
+ };
62
+
63
+ export async function getAuthorsMapFilePath({
64
+ authorsMapPath,
65
+ contentPaths,
66
+ }: AuthorsMapParams): Promise<string | undefined> {
67
+ // Useful to load an eventually localize authors map
68
+ const contentPath = await findFolderContainingFile(
69
+ getContentPathList(contentPaths),
70
+ authorsMapPath,
71
+ );
72
+
73
+ if (contentPath) {
74
+ return path.join(contentPath, authorsMapPath);
75
+ }
76
+
77
+ return undefined;
78
+ }
79
+
80
+ export async function getAuthorsMap(
81
+ params: AuthorsMapParams,
82
+ ): Promise<AuthorsMap | undefined> {
83
+ const filePath = await getAuthorsMapFilePath(params);
84
+ if (!filePath) {
85
+ return undefined;
86
+ }
87
+ try {
88
+ return await readAuthorsMapFile(filePath);
89
+ } catch (e) {
90
+ // TODO replace later by error cause, see https://v8.dev/features/error-cause
91
+ console.error(
92
+ chalk.red(`Couldn't read blog authors map at path ${filePath}`),
93
+ );
94
+ throw e;
95
+ }
96
+ }
97
+
98
+ type AuthorsParam = {
99
+ frontMatter: BlogPostFrontMatter;
100
+ authorsMap: AuthorsMap | undefined;
101
+ };
102
+
103
+ // Legacy v1/early-v2 frontmatter fields
104
+ // We may want to deprecate those in favor of using only frontMatter.authors
105
+ function getFrontMatterAuthorLegacy(
106
+ frontMatter: BlogPostFrontMatter,
107
+ ): BlogPostFrontMatterAuthor | undefined {
108
+ const name = frontMatter.author;
109
+ const title = frontMatter.author_title ?? frontMatter.authorTitle;
110
+ const url = frontMatter.author_url ?? frontMatter.authorURL;
111
+ const imageURL = frontMatter.author_image_url ?? frontMatter.authorImageURL;
112
+
113
+ // Shouldn't we require at least an author name?
114
+ if (name || title || url || imageURL) {
115
+ return {
116
+ name,
117
+ title,
118
+ url,
119
+ imageURL,
120
+ };
121
+ }
122
+
123
+ return undefined;
124
+ }
125
+
126
+ function normalizeFrontMatterAuthors(
127
+ frontMatterAuthors: BlogPostFrontMatterAuthors = [],
128
+ ): BlogPostFrontMatterAuthor[] {
129
+ function normalizeAuthor(
130
+ authorInput: string | BlogPostFrontMatterAuthor,
131
+ ): BlogPostFrontMatterAuthor {
132
+ if (typeof authorInput === 'string') {
133
+ // Technically, we could allow users to provide an author's name here
134
+ // IMHO it's better to only support keys here
135
+ // Reason: a typo in a key would fallback to becoming a name and may end-up un-noticed
136
+ return {key: authorInput};
137
+ }
138
+ return authorInput;
139
+ }
140
+
141
+ return Array.isArray(frontMatterAuthors)
142
+ ? frontMatterAuthors.map(normalizeAuthor)
143
+ : [normalizeAuthor(frontMatterAuthors)];
144
+ }
145
+
146
+ function getFrontMatterAuthors(params: AuthorsParam): Author[] {
147
+ const {authorsMap} = params;
148
+ const frontMatterAuthors = normalizeFrontMatterAuthors(
149
+ params.frontMatter.authors,
150
+ );
151
+
152
+ function getAuthorsMapAuthor(key: string | undefined): Author | undefined {
153
+ if (key) {
154
+ if (!authorsMap || Object.keys(authorsMap).length === 0) {
155
+ throw new Error(`Can't reference blog post authors by a key (such as '${key}') because no authors map file could be loaded.
156
+ Please double-check your blog plugin config (in particular 'authorsMapPath'), ensure the file exists at the configured path, is not empty, and is valid!`);
157
+ }
158
+ const author = authorsMap[key];
159
+ if (!author) {
160
+ throw Error(`Blog author with key "${key}" not found in the authors map file.
161
+ Valid author keys are:
162
+ ${Object.keys(authorsMap)
163
+ .map((validKey) => `- ${validKey}`)
164
+ .join('\n')}`);
165
+ }
166
+ return author;
167
+ }
168
+ return undefined;
169
+ }
170
+
171
+ function toAuthor(frontMatterAuthor: BlogPostFrontMatterAuthor): Author {
172
+ return {
173
+ // Author def from authorsMap can be locally overridden by frontmatter
174
+ ...getAuthorsMapAuthor(frontMatterAuthor.key),
175
+ ...frontMatterAuthor,
176
+ };
177
+ }
178
+
179
+ return frontMatterAuthors.map(toAuthor);
180
+ }
181
+
182
+ export function getBlogPostAuthors(params: AuthorsParam): Author[] {
183
+ const authorLegacy = getFrontMatterAuthorLegacy(params.frontMatter);
184
+ const authors = getFrontMatterAuthors(params);
185
+
186
+ if (authorLegacy) {
187
+ // Technically, we could allow mixing legacy/authors frontmatter, but do we really want to?
188
+ if (authors.length > 0) {
189
+ throw new Error(
190
+ `To declare blog post authors, use the 'authors' FrontMatter in priority.
191
+ Don't mix 'authors' with other existing 'author_*' FrontMatter. Choose one or the other, not both at the same time.`,
192
+ );
193
+ }
194
+ return [authorLegacy];
195
+ }
196
+
197
+ return authors;
198
+ }
@@ -5,81 +5,119 @@
5
5
  * LICENSE file in the root directory of this source tree.
6
6
  */
7
7
 
8
- /* eslint-disable camelcase */
9
-
10
8
  import {
11
9
  JoiFrontMatter as Joi, // Custom instance for frontmatter
12
10
  URISchema,
13
11
  validateFrontMatter,
12
+ FrontMatterTagsSchema,
13
+ FrontMatterTOCHeadingLevels,
14
14
  } from '@docusaurus/utils-validation';
15
- import {Tag} from './types';
15
+ import type {FrontMatterTag} from '@docusaurus/utils';
16
+
17
+ export type BlogPostFrontMatterAuthor = Record<string, unknown> & {
18
+ key?: string;
19
+ name?: string;
20
+ imageURL?: string;
21
+ url?: string;
22
+ title?: string;
23
+ };
24
+
25
+ // All the possible variants that the user can use for convenience
26
+ export type BlogPostFrontMatterAuthors =
27
+ | string
28
+ | BlogPostFrontMatterAuthor
29
+ | (string | BlogPostFrontMatterAuthor)[];
30
+
31
+ const BlogPostFrontMatterAuthorSchema = Joi.object({
32
+ key: Joi.string(),
33
+ name: Joi.string(),
34
+ title: Joi.string(),
35
+ url: URISchema,
36
+ imageURL: Joi.string(),
37
+ })
38
+ .or('key', 'name')
39
+ .rename('image_url', 'imageURL', {alias: true});
16
40
 
17
41
  export type BlogPostFrontMatter = {
18
42
  id?: string;
19
43
  title?: string;
20
44
  description?: string;
21
- tags?: (string | Tag)[];
45
+ tags?: FrontMatterTag[];
22
46
  slug?: string;
23
47
  draft?: boolean;
24
- date?: Date;
48
+ date?: Date | string; // Yaml automagically convert some string patterns as Date, but not all
49
+
50
+ authors?: BlogPostFrontMatterAuthors;
25
51
 
52
+ // We may want to deprecate those older author frontmatter fields later:
26
53
  author?: string;
27
54
  author_title?: string;
28
55
  author_url?: string;
29
56
  author_image_url?: string;
30
57
 
31
- image?: string;
32
- keywords?: string[];
33
- hide_table_of_contents?: boolean;
34
-
35
58
  /** @deprecated */
36
59
  authorTitle?: string;
60
+ /** @deprecated */
37
61
  authorURL?: string;
62
+ /** @deprecated */
38
63
  authorImageURL?: string;
64
+
65
+ image?: string;
66
+ keywords?: string[];
67
+ hide_table_of_contents?: boolean;
68
+ toc_min_heading_level?: number;
69
+ toc_max_heading_level?: number;
39
70
  };
40
71
 
41
- // NOTE: we don't add any default value on purpose here
42
- // We don't want default values to magically appear in doc metadatas and props
43
- // While the user did not provide those values explicitly
44
- // We use default values in code instead
45
- const BlogTagSchema = Joi.alternatives().try(
46
- Joi.string().required(),
47
- Joi.object<Tag>({
48
- label: Joi.string().required(),
49
- permalink: Joi.string().required(),
50
- }),
51
- );
72
+ const FrontMatterAuthorErrorMessage =
73
+ '{{#label}} does not look like a valid blog post author. Please use an author key or an author object (with a key and/or name).';
52
74
 
53
75
  const BlogFrontMatterSchema = Joi.object<BlogPostFrontMatter>({
54
76
  id: Joi.string(),
55
77
  title: Joi.string().allow(''),
56
78
  description: Joi.string().allow(''),
57
- tags: Joi.array().items(BlogTagSchema),
79
+ tags: FrontMatterTagsSchema,
58
80
  draft: Joi.boolean(),
59
81
  date: Joi.date().raw(),
60
82
 
83
+ // New multi-authors frontmatter:
84
+ authors: Joi.alternatives()
85
+ .try(
86
+ Joi.string(),
87
+ BlogPostFrontMatterAuthorSchema,
88
+ Joi.array()
89
+ .items(Joi.string(), BlogPostFrontMatterAuthorSchema)
90
+ .messages({
91
+ 'array.sparse': FrontMatterAuthorErrorMessage,
92
+ 'array.includes': FrontMatterAuthorErrorMessage,
93
+ }),
94
+ )
95
+ .messages({
96
+ 'alternatives.match': FrontMatterAuthorErrorMessage,
97
+ }),
98
+ // Legacy author frontmatter
61
99
  author: Joi.string(),
62
100
  author_title: Joi.string(),
63
101
  author_url: URISchema,
64
102
  author_image_url: URISchema,
65
- slug: Joi.string(),
66
- image: URISchema,
67
- keywords: Joi.array().items(Joi.string().required()),
68
- hide_table_of_contents: Joi.boolean(),
69
-
70
- // TODO re-enable warnings later, our v1 blog posts use those older frontmatter fields
103
+ // TODO enable deprecation warnings later
71
104
  authorURL: URISchema,
72
105
  // .warning('deprecate.error', { alternative: '"author_url"'}),
73
106
  authorTitle: Joi.string(),
74
107
  // .warning('deprecate.error', { alternative: '"author_title"'}),
75
108
  authorImageURL: URISchema,
76
109
  // .warning('deprecate.error', { alternative: '"author_image_url"'}),
77
- })
78
- .unknown()
79
- .messages({
80
- 'deprecate.error':
81
- '{#label} blog frontMatter field is deprecated. Please use {#alternative} instead.',
82
- });
110
+
111
+ slug: Joi.string(),
112
+ image: URISchema,
113
+ keywords: Joi.array().items(Joi.string().required()),
114
+ hide_table_of_contents: Joi.boolean(),
115
+
116
+ ...FrontMatterTOCHeadingLevels,
117
+ }).messages({
118
+ 'deprecate.error':
119
+ '{#label} blog frontMatter field is deprecated. Please use {#alternative} instead.',
120
+ });
83
121
 
84
122
  export function validateBlogPostFrontMatter(
85
123
  frontMatter: Record<string, unknown>,