@docusaurus/plugin-content-blog 2.0.0-beta.8e9b829d9 → 2.0.0-beta.9

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 (60) hide show
  1. package/lib/.tsbuildinfo +1 -1
  2. package/lib/authors.d.ts +23 -0
  3. package/lib/authors.js +150 -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 -135
  8. package/lib/feed.d.ts +20 -0
  9. package/lib/feed.js +90 -0
  10. package/lib/index.js +86 -85
  11. package/lib/markdownLoader.d.ts +3 -6
  12. package/lib/markdownLoader.js +5 -5
  13. package/lib/pluginOptionSchema.d.ts +3 -27
  14. package/lib/pluginOptionSchema.js +21 -7
  15. package/lib/translations.d.ts +10 -0
  16. package/lib/translations.js +53 -0
  17. package/lib/types.d.ts +52 -14
  18. package/package.json +15 -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/authors.yml +4 -0
  36. package/src/__tests__/__fixtures__/website/blog/mdx-blog-post.mdx +36 -0
  37. package/src/__tests__/__fixtures__/website/blog/mdx-require-blog-post.mdx +14 -0
  38. package/src/__tests__/__fixtures__/website/blog/simple-slug.md +4 -0
  39. package/src/__tests__/__fixtures__/website/i18n/en/docusaurus-plugin-content-blog/2018-12-14-Happy-First-Birthday-Slash.md +3 -0
  40. package/src/__tests__/__fixtures__/website/i18n/en/docusaurus-plugin-content-blog/authors.yml +5 -0
  41. package/src/__tests__/__fixtures__/website/static/img/docusaurus.png +0 -0
  42. package/src/__tests__/__snapshots__/{generateBlogFeed.test.ts.snap → feed.test.ts.snap} +55 -7
  43. package/src/__tests__/__snapshots__/translations.test.ts.snap +64 -0
  44. package/src/__tests__/authors.test.ts +608 -0
  45. package/src/__tests__/blogFrontMatter.test.ts +93 -16
  46. package/src/__tests__/blogUtils.test.ts +94 -0
  47. package/src/__tests__/{generateBlogFeed.test.ts → feed.test.ts} +32 -8
  48. package/src/__tests__/index.test.ts +73 -12
  49. package/src/__tests__/pluginOptionSchema.test.ts +3 -3
  50. package/src/__tests__/translations.test.ts +92 -0
  51. package/src/authors.ts +202 -0
  52. package/src/blogFrontMatter.ts +73 -33
  53. package/src/blogUtils.ts +201 -180
  54. package/src/feed.ts +129 -0
  55. package/src/index.ts +105 -88
  56. package/src/markdownLoader.ts +8 -12
  57. package/{index.d.ts → src/plugin-content-blog.d.ts} +35 -31
  58. package/src/pluginOptionSchema.ts +24 -9
  59. package/src/translations.ts +63 -0
  60. package/src/types.ts +67 -16
@@ -7,44 +7,56 @@
7
7
  */
8
8
  Object.defineProperty(exports, "__esModule", { value: true });
9
9
  exports.validateBlogPostFrontMatter = void 0;
10
- /* eslint-disable camelcase */
11
10
  const utils_validation_1 = require("@docusaurus/utils-validation");
12
- // NOTE: we don't add any default value on purpose here
13
- // We don't want default values to magically appear in doc metadatas and props
14
- // While the user did not provide those values explicitly
15
- // We use default values in code instead
16
- const BlogTagSchema = utils_validation_1.JoiFrontMatter.alternatives().try(utils_validation_1.JoiFrontMatter.string().required(), utils_validation_1.JoiFrontMatter.object({
17
- label: utils_validation_1.JoiFrontMatter.string().required(),
18
- permalink: utils_validation_1.JoiFrontMatter.string().required(),
19
- }));
11
+ const BlogPostFrontMatterAuthorSchema = utils_validation_1.JoiFrontMatter.object({
12
+ key: utils_validation_1.JoiFrontMatter.string(),
13
+ name: utils_validation_1.JoiFrontMatter.string(),
14
+ title: utils_validation_1.JoiFrontMatter.string(),
15
+ url: utils_validation_1.URISchema,
16
+ imageURL: utils_validation_1.JoiFrontMatter.string(),
17
+ })
18
+ .or('key', 'name')
19
+ .rename('image_url', 'imageURL', { alias: true });
20
+ const FrontMatterAuthorErrorMessage = '{{#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).';
20
21
  const BlogFrontMatterSchema = utils_validation_1.JoiFrontMatter.object({
21
22
  id: utils_validation_1.JoiFrontMatter.string(),
22
23
  title: utils_validation_1.JoiFrontMatter.string().allow(''),
23
24
  description: utils_validation_1.JoiFrontMatter.string().allow(''),
24
- tags: utils_validation_1.JoiFrontMatter.array().items(BlogTagSchema),
25
+ tags: utils_validation_1.FrontMatterTagsSchema,
25
26
  draft: utils_validation_1.JoiFrontMatter.boolean(),
26
27
  date: utils_validation_1.JoiFrontMatter.date().raw(),
28
+ // New multi-authors frontmatter:
29
+ authors: utils_validation_1.JoiFrontMatter.alternatives()
30
+ .try(utils_validation_1.JoiFrontMatter.string(), BlogPostFrontMatterAuthorSchema, utils_validation_1.JoiFrontMatter.array()
31
+ .items(utils_validation_1.JoiFrontMatter.string(), BlogPostFrontMatterAuthorSchema)
32
+ .messages({
33
+ 'array.sparse': FrontMatterAuthorErrorMessage,
34
+ 'array.includes': FrontMatterAuthorErrorMessage,
35
+ }))
36
+ .messages({
37
+ 'alternatives.match': FrontMatterAuthorErrorMessage,
38
+ }),
39
+ // Legacy author frontmatter
27
40
  author: utils_validation_1.JoiFrontMatter.string(),
28
41
  author_title: utils_validation_1.JoiFrontMatter.string(),
29
42
  author_url: utils_validation_1.URISchema,
30
43
  author_image_url: utils_validation_1.URISchema,
31
- slug: utils_validation_1.JoiFrontMatter.string(),
32
- image: utils_validation_1.URISchema,
33
- keywords: utils_validation_1.JoiFrontMatter.array().items(utils_validation_1.JoiFrontMatter.string().required()),
34
- hide_table_of_contents: utils_validation_1.JoiFrontMatter.boolean(),
35
- // TODO re-enable warnings later, our v1 blog posts use those older frontmatter fields
44
+ // TODO enable deprecation warnings later
36
45
  authorURL: utils_validation_1.URISchema,
37
46
  // .warning('deprecate.error', { alternative: '"author_url"'}),
38
47
  authorTitle: utils_validation_1.JoiFrontMatter.string(),
39
48
  // .warning('deprecate.error', { alternative: '"author_title"'}),
40
49
  authorImageURL: utils_validation_1.URISchema,
41
50
  // .warning('deprecate.error', { alternative: '"author_image_url"'}),
42
- })
43
- .unknown()
44
- .messages({
51
+ slug: utils_validation_1.JoiFrontMatter.string(),
52
+ image: utils_validation_1.URISchema,
53
+ keywords: utils_validation_1.JoiFrontMatter.array().items(utils_validation_1.JoiFrontMatter.string().required()),
54
+ hide_table_of_contents: utils_validation_1.JoiFrontMatter.boolean(),
55
+ ...utils_validation_1.FrontMatterTOCHeadingLevels,
56
+ }).messages({
45
57
  'deprecate.error': '{#label} blog frontMatter field is deprecated. Please use {#alternative} instead.',
46
58
  });
47
59
  function validateBlogPostFrontMatter(frontMatter) {
48
- return utils_validation_1.validateFrontMatter(frontMatter, BlogFrontMatterSchema);
60
+ return (0, utils_validation_1.validateFrontMatter)(frontMatter, BlogFrontMatterSchema);
49
61
  }
50
62
  exports.validateBlogPostFrontMatter = validateBlogPostFrontMatter;
@@ -4,16 +4,22 @@
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 { Feed } from 'feed';
8
- import { PluginOptions, BlogPost, BlogContentPaths, BlogMarkdownLoaderOptions } from './types';
7
+ import { PluginOptions, BlogPost, BlogContentPaths, BlogMarkdownLoaderOptions, BlogTags } from './types';
9
8
  import { LoadContext } from '@docusaurus/types';
10
9
  export declare function truncate(fileString: string, truncateMarker: RegExp): string;
11
10
  export declare function getSourceToPermalink(blogPosts: BlogPost[]): Record<string, string>;
12
- export declare function generateBlogFeed(contentPaths: BlogContentPaths, context: LoadContext, options: PluginOptions): Promise<Feed | null>;
13
- export declare function generateBlogPosts(contentPaths: BlogContentPaths, { siteConfig, siteDir, i18n }: LoadContext, options: PluginOptions): Promise<BlogPost[]>;
11
+ export declare function getBlogTags(blogPosts: BlogPost[]): BlogTags;
12
+ declare type ParsedBlogFileName = {
13
+ date: Date | undefined;
14
+ text: string;
15
+ slug: string;
16
+ };
17
+ export declare function parseBlogFileName(blogSourceRelative: string): ParsedBlogFileName;
18
+ export declare function generateBlogPosts(contentPaths: BlogContentPaths, context: LoadContext, options: PluginOptions): Promise<BlogPost[]>;
14
19
  export declare type LinkifyParams = {
15
20
  filePath: string;
16
21
  fileString: string;
17
22
  } & Pick<BlogMarkdownLoaderOptions, 'sourceToPermalink' | 'siteDir' | 'contentPaths' | 'onBrokenMarkdownLink'>;
18
23
  export declare function linkify({ filePath, contentPaths, fileString, siteDir, sourceToPermalink, onBrokenMarkdownLink, }: LinkifyParams): string;
19
24
  export declare function getContentPathList(contentPaths: BlogContentPaths): string[];
25
+ export {};
package/lib/blogUtils.js CHANGED
@@ -6,33 +6,54 @@
6
6
  * LICENSE file in the root directory of this source tree.
7
7
  */
8
8
  Object.defineProperty(exports, "__esModule", { value: true });
9
- exports.getContentPathList = exports.linkify = exports.generateBlogPosts = exports.generateBlogFeed = exports.getSourceToPermalink = exports.truncate = void 0;
9
+ exports.getContentPathList = exports.linkify = exports.generateBlogPosts = exports.parseBlogFileName = exports.getBlogTags = exports.getSourceToPermalink = exports.truncate = void 0;
10
10
  const tslib_1 = require("tslib");
11
- const fs_extra_1 = tslib_1.__importDefault(require("fs-extra"));
12
- const chalk_1 = tslib_1.__importDefault(require("chalk"));
13
- const path_1 = tslib_1.__importDefault(require("path"));
14
- const reading_time_1 = tslib_1.__importDefault(require("reading-time"));
15
- const feed_1 = require("feed");
11
+ const fs_extra_1 = (0, tslib_1.__importDefault)(require("fs-extra"));
12
+ const chalk_1 = (0, tslib_1.__importDefault)(require("chalk"));
13
+ const path_1 = (0, tslib_1.__importDefault)(require("path"));
14
+ const reading_time_1 = (0, tslib_1.__importDefault)(require("reading-time"));
16
15
  const lodash_1 = require("lodash");
17
16
  const utils_1 = require("@docusaurus/utils");
18
17
  const blogFrontMatter_1 = require("./blogFrontMatter");
18
+ const authors_1 = require("./authors");
19
19
  function truncate(fileString, truncateMarker) {
20
20
  return fileString.split(truncateMarker, 1).shift();
21
21
  }
22
22
  exports.truncate = truncate;
23
23
  function getSourceToPermalink(blogPosts) {
24
- return lodash_1.mapValues(lodash_1.keyBy(blogPosts, (item) => item.metadata.source), (v) => v.metadata.permalink);
24
+ return (0, lodash_1.mapValues)((0, lodash_1.keyBy)(blogPosts, (item) => item.metadata.source), (v) => v.metadata.permalink);
25
25
  }
26
26
  exports.getSourceToPermalink = getSourceToPermalink;
27
- // YYYY-MM-DD-{name}.mdx?
28
- // Prefer named capture, but older Node versions do not support it.
29
- const DATE_FILENAME_PATTERN = /^(\d{4}-\d{1,2}-\d{1,2})-?(.*?).mdx?$/;
30
- function toUrl({ date, link }) {
31
- return `${date
32
- .toISOString()
33
- .substring(0, '2019-01-01'.length)
34
- .replace(/-/g, '/')}/${link}`;
27
+ function getBlogTags(blogPosts) {
28
+ const groups = (0, utils_1.groupTaggedItems)(blogPosts, (blogPost) => blogPost.metadata.tags);
29
+ return (0, lodash_1.mapValues)(groups, (group) => {
30
+ return {
31
+ name: group.tag.label,
32
+ items: group.items.map((item) => item.id),
33
+ permalink: group.tag.permalink,
34
+ };
35
+ });
36
+ }
37
+ exports.getBlogTags = getBlogTags;
38
+ const DATE_FILENAME_REGEX = /^(?<date>\d{4}[-/]\d{1,2}[-/]\d{1,2})[-/]?(?<text>.*?)(\/index)?.mdx?$/;
39
+ function parseBlogFileName(blogSourceRelative) {
40
+ const dateFilenameMatch = blogSourceRelative.match(DATE_FILENAME_REGEX);
41
+ if (dateFilenameMatch) {
42
+ const dateString = dateFilenameMatch.groups.date;
43
+ const text = dateFilenameMatch.groups.text;
44
+ // Always treat dates as UTC by adding the `Z`
45
+ const date = new Date(`${dateString}Z`);
46
+ const slugDate = dateString.replace(/-/g, '/');
47
+ const slug = `/${slugDate}/${text}`;
48
+ return { date, text, slug };
49
+ }
50
+ else {
51
+ const text = blogSourceRelative.replace(/(\/index)?\.mdx?$/, '');
52
+ const slug = `/${text}`;
53
+ return { date: undefined, text, slug };
54
+ }
35
55
  }
56
+ exports.parseBlogFileName = parseBlogFileName;
36
57
  function formatBlogPostDate(locale, date) {
37
58
  try {
38
59
  return new Intl.DateTimeFormat(locale, {
@@ -46,147 +67,132 @@ function formatBlogPostDate(locale, date) {
46
67
  throw new Error(`Can't format blog post date "${date}"`);
47
68
  }
48
69
  }
49
- async function generateBlogFeed(contentPaths, context, options) {
50
- if (!options.feedOptions) {
51
- throw new Error('Invalid options: "feedOptions" is not expected to be null.');
70
+ async function parseBlogPostMarkdownFile(blogSourceAbsolute) {
71
+ const result = await (0, utils_1.parseMarkdownFile)(blogSourceAbsolute, {
72
+ removeContentTitle: true,
73
+ });
74
+ return {
75
+ ...result,
76
+ frontMatter: (0, blogFrontMatter_1.validateBlogPostFrontMatter)(result.frontMatter),
77
+ };
78
+ }
79
+ const defaultReadingTime = ({ content, options }) => {
80
+ return (0, reading_time_1.default)(content, options).minutes;
81
+ };
82
+ async function processBlogSourceFile(blogSourceRelative, contentPaths, context, options, authorsMap) {
83
+ var _a, _b, _c, _d, _e;
84
+ const { siteConfig: { baseUrl }, siteDir, i18n, } = context;
85
+ const { routeBasePath, tagsBasePath: tagsRouteBasePath, truncateMarker, showReadingTime, editUrl, } = options;
86
+ // Lookup in localized folder in priority
87
+ const blogDirPath = await (0, utils_1.getFolderContainingFile)(getContentPathList(contentPaths), blogSourceRelative);
88
+ const blogSourceAbsolute = path_1.default.join(blogDirPath, blogSourceRelative);
89
+ const { frontMatter, content, contentTitle, excerpt } = await parseBlogPostMarkdownFile(blogSourceAbsolute);
90
+ const aliasedSource = (0, utils_1.aliasedSitePath)(blogSourceAbsolute, siteDir);
91
+ if (frontMatter.draft && process.env.NODE_ENV === 'production') {
92
+ return undefined;
52
93
  }
53
- const { siteConfig } = context;
54
- const blogPosts = await generateBlogPosts(contentPaths, context, options);
55
- if (!blogPosts.length) {
56
- return null;
94
+ if (frontMatter.id) {
95
+ console.warn(chalk_1.default.yellow(`"id" header option is deprecated in ${blogSourceRelative} file. Please use "slug" option instead.`));
57
96
  }
58
- const { feedOptions, routeBasePath } = options;
59
- const { url: siteUrl, baseUrl, title, favicon } = siteConfig;
60
- const blogBaseUrl = utils_1.normalizeUrl([siteUrl, baseUrl, routeBasePath]);
61
- const updated = (blogPosts[0] && blogPosts[0].metadata.date) ||
62
- new Date('2015-10-25T16:29:00.000-07:00');
63
- const feed = new feed_1.Feed({
64
- id: blogBaseUrl,
65
- title: feedOptions.title || `${title} Blog`,
66
- updated,
67
- language: feedOptions.language,
68
- link: blogBaseUrl,
69
- description: feedOptions.description || `${siteConfig.title} Blog`,
70
- favicon: favicon ? utils_1.normalizeUrl([siteUrl, baseUrl, favicon]) : undefined,
71
- copyright: feedOptions.copyright,
72
- });
73
- blogPosts.forEach((post) => {
74
- const { id, metadata: { title: metadataTitle, permalink, date, description }, } = post;
75
- feed.addItem({
76
- title: metadataTitle,
77
- id,
78
- link: utils_1.normalizeUrl([siteUrl, permalink]),
79
- date,
97
+ const parsedBlogFileName = parseBlogFileName(blogSourceRelative);
98
+ async function getDate() {
99
+ // Prefer user-defined date.
100
+ if (frontMatter.date) {
101
+ return new Date(frontMatter.date);
102
+ }
103
+ else if (parsedBlogFileName.date) {
104
+ return parsedBlogFileName.date;
105
+ }
106
+ // Fallback to file create time
107
+ return (await fs_extra_1.default.stat(blogSourceAbsolute)).birthtime;
108
+ }
109
+ const date = await getDate();
110
+ const formattedDate = formatBlogPostDate(i18n.currentLocale, date);
111
+ const title = (_b = (_a = frontMatter.title) !== null && _a !== void 0 ? _a : contentTitle) !== null && _b !== void 0 ? _b : parsedBlogFileName.text;
112
+ const description = (_d = (_c = frontMatter.description) !== null && _c !== void 0 ? _c : excerpt) !== null && _d !== void 0 ? _d : '';
113
+ const slug = frontMatter.slug || parsedBlogFileName.slug;
114
+ const permalink = (0, utils_1.normalizeUrl)([baseUrl, routeBasePath, slug]);
115
+ function getBlogEditUrl() {
116
+ const blogPathRelative = path_1.default.relative(blogDirPath, path_1.default.resolve(blogSourceAbsolute));
117
+ if (typeof editUrl === 'function') {
118
+ return editUrl({
119
+ blogDirPath: (0, utils_1.posixPath)(path_1.default.relative(siteDir, blogDirPath)),
120
+ blogPath: (0, utils_1.posixPath)(blogPathRelative),
121
+ permalink,
122
+ locale: i18n.currentLocale,
123
+ });
124
+ }
125
+ else if (typeof editUrl === 'string') {
126
+ const isLocalized = blogDirPath === contentPaths.contentPathLocalized;
127
+ const fileContentPath = isLocalized && options.editLocalizedFiles
128
+ ? contentPaths.contentPathLocalized
129
+ : contentPaths.contentPath;
130
+ const contentPathEditUrl = (0, utils_1.normalizeUrl)([
131
+ editUrl,
132
+ (0, utils_1.posixPath)(path_1.default.relative(siteDir, fileContentPath)),
133
+ ]);
134
+ return (0, utils_1.getEditUrl)(blogPathRelative, contentPathEditUrl);
135
+ }
136
+ return undefined;
137
+ }
138
+ const tagsBasePath = (0, utils_1.normalizeUrl)([
139
+ baseUrl,
140
+ routeBasePath,
141
+ tagsRouteBasePath,
142
+ ]);
143
+ const authors = (0, authors_1.getBlogPostAuthors)({ authorsMap, frontMatter });
144
+ return {
145
+ id: (_e = frontMatter.slug) !== null && _e !== void 0 ? _e : title,
146
+ metadata: {
147
+ permalink,
148
+ editUrl: getBlogEditUrl(),
149
+ source: aliasedSource,
150
+ title,
80
151
  description,
81
- });
82
- });
83
- return feed;
152
+ date,
153
+ formattedDate,
154
+ tags: (0, utils_1.normalizeFrontMatterTags)(tagsBasePath, frontMatter.tags),
155
+ readingTime: showReadingTime
156
+ ? options.readingTime({
157
+ content,
158
+ frontMatter,
159
+ defaultReadingTime,
160
+ })
161
+ : undefined,
162
+ truncated: (truncateMarker === null || truncateMarker === void 0 ? void 0 : truncateMarker.test(content)) || false,
163
+ authors,
164
+ },
165
+ content,
166
+ };
84
167
  }
85
- exports.generateBlogFeed = generateBlogFeed;
86
- async function generateBlogPosts(contentPaths, { siteConfig, siteDir, i18n }, options) {
87
- const { include, exclude, routeBasePath, truncateMarker, showReadingTime, editUrl, } = options;
168
+ async function generateBlogPosts(contentPaths, context, options) {
169
+ const { include, exclude } = options;
88
170
  if (!fs_extra_1.default.existsSync(contentPaths.contentPath)) {
89
171
  return [];
90
172
  }
91
- const { baseUrl = '' } = siteConfig;
92
- const blogSourceFiles = await utils_1.Globby(include, {
173
+ const blogSourceFiles = await (0, utils_1.Globby)(include, {
93
174
  cwd: contentPaths.contentPath,
94
175
  ignore: exclude,
95
176
  });
96
- const blogPosts = [];
97
- async function processBlogSourceFile(blogSourceFile) {
98
- var _a, _b, _c, _d, _e, _f;
99
- // Lookup in localized folder in priority
100
- const blogDirPath = await utils_1.getFolderContainingFile(getContentPathList(contentPaths), blogSourceFile);
101
- const source = path_1.default.join(blogDirPath, blogSourceFile);
102
- const { frontMatter: unsafeFrontMatter, content, contentTitle, excerpt, } = await utils_1.parseMarkdownFile(source, { removeContentTitle: true });
103
- const frontMatter = blogFrontMatter_1.validateBlogPostFrontMatter(unsafeFrontMatter);
104
- const aliasedSource = utils_1.aliasedSitePath(source, siteDir);
105
- const blogFileName = path_1.default.basename(blogSourceFile);
106
- if (frontMatter.draft && process.env.NODE_ENV === 'production') {
107
- return;
108
- }
109
- if (frontMatter.id) {
110
- console.warn(chalk_1.default.yellow(`"id" header option is deprecated in ${blogFileName} file. Please use "slug" option instead.`));
111
- }
112
- let date;
113
- // Extract date and title from filename.
114
- const dateFilenameMatch = blogFileName.match(DATE_FILENAME_PATTERN);
115
- let linkName = blogFileName.replace(/\.mdx?$/, '');
116
- if (dateFilenameMatch) {
117
- const [, dateString, name] = dateFilenameMatch;
118
- // Always treat dates as UTC by adding the `Z`
119
- date = new Date(`${dateString}Z`);
120
- linkName = name;
121
- }
122
- // Prefer user-defined date.
123
- if (frontMatter.date) {
124
- date = new Date(frontMatter.date);
125
- }
126
- // Use file create time for blog.
127
- date = date !== null && date !== void 0 ? date : (await fs_extra_1.default.stat(source)).birthtime;
128
- const formattedDate = formatBlogPostDate(i18n.currentLocale, date);
129
- const title = (_b = (_a = frontMatter.title) !== null && _a !== void 0 ? _a : contentTitle) !== null && _b !== void 0 ? _b : linkName;
130
- const description = (_d = (_c = frontMatter.description) !== null && _c !== void 0 ? _c : excerpt) !== null && _d !== void 0 ? _d : '';
131
- const slug = frontMatter.slug ||
132
- (dateFilenameMatch ? toUrl({ date, link: linkName }) : linkName);
133
- const permalink = utils_1.normalizeUrl([baseUrl, routeBasePath, slug]);
134
- function getBlogEditUrl() {
135
- const blogPathRelative = path_1.default.relative(blogDirPath, path_1.default.resolve(source));
136
- if (typeof editUrl === 'function') {
137
- return editUrl({
138
- blogDirPath: utils_1.posixPath(path_1.default.relative(siteDir, blogDirPath)),
139
- blogPath: utils_1.posixPath(blogPathRelative),
140
- permalink,
141
- locale: i18n.currentLocale,
142
- });
143
- }
144
- else if (typeof editUrl === 'string') {
145
- const isLocalized = blogDirPath === contentPaths.contentPathLocalized;
146
- const fileContentPath = isLocalized && options.editLocalizedFiles
147
- ? contentPaths.contentPathLocalized
148
- : contentPaths.contentPath;
149
- const contentPathEditUrl = utils_1.normalizeUrl([
150
- editUrl,
151
- utils_1.posixPath(path_1.default.relative(siteDir, fileContentPath)),
152
- ]);
153
- return utils_1.getEditUrl(blogPathRelative, contentPathEditUrl);
154
- }
155
- else {
156
- return undefined;
157
- }
158
- }
159
- blogPosts.push({
160
- id: (_e = frontMatter.slug) !== null && _e !== void 0 ? _e : title,
161
- metadata: {
162
- permalink,
163
- editUrl: getBlogEditUrl(),
164
- source: aliasedSource,
165
- title,
166
- description,
167
- date,
168
- formattedDate,
169
- tags: (_f = frontMatter.tags) !== null && _f !== void 0 ? _f : [],
170
- readingTime: showReadingTime ? reading_time_1.default(content).minutes : undefined,
171
- truncated: (truncateMarker === null || truncateMarker === void 0 ? void 0 : truncateMarker.test(content)) || false,
172
- },
173
- });
174
- }
175
- await Promise.all(blogSourceFiles.map(async (blogSourceFile) => {
177
+ const authorsMap = await (0, authors_1.getAuthorsMap)({
178
+ contentPaths,
179
+ authorsMapPath: options.authorsMapPath,
180
+ });
181
+ const blogPosts = (await Promise.all(blogSourceFiles.map(async (blogSourceFile) => {
176
182
  try {
177
- return await processBlogSourceFile(blogSourceFile);
183
+ return await processBlogSourceFile(blogSourceFile, contentPaths, context, options, authorsMap);
178
184
  }
179
185
  catch (e) {
180
186
  console.error(chalk_1.default.red(`Processing of blog source file failed for path "${blogSourceFile}"`));
181
187
  throw e;
182
188
  }
183
- }));
189
+ }))).filter(Boolean);
184
190
  blogPosts.sort((a, b) => b.metadata.date.getTime() - a.metadata.date.getTime());
185
191
  return blogPosts;
186
192
  }
187
193
  exports.generateBlogPosts = generateBlogPosts;
188
194
  function linkify({ filePath, contentPaths, fileString, siteDir, sourceToPermalink, onBrokenMarkdownLink, }) {
189
- const { newContent, brokenMarkdownLinks } = utils_1.replaceMarkdownLinks({
195
+ const { newContent, brokenMarkdownLinks } = (0, utils_1.replaceMarkdownLinks)({
190
196
  siteDir,
191
197
  fileString,
192
198
  filePath,
package/lib/feed.d.ts ADDED
@@ -0,0 +1,20 @@
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
+ import { Feed } from 'feed';
8
+ import { PluginOptions, BlogPost } from './types';
9
+ import { DocusaurusConfig } from '@docusaurus/types';
10
+ export declare function generateBlogFeed({ blogPosts, options, siteConfig, }: {
11
+ blogPosts: BlogPost[];
12
+ options: PluginOptions;
13
+ siteConfig: DocusaurusConfig;
14
+ }): Promise<Feed | null>;
15
+ export declare function createBlogFeedFiles({ blogPosts, options, siteConfig, outDir, }: {
16
+ blogPosts: BlogPost[];
17
+ options: PluginOptions;
18
+ siteConfig: DocusaurusConfig;
19
+ outDir: string;
20
+ }): Promise<void>;
package/lib/feed.js ADDED
@@ -0,0 +1,90 @@
1
+ "use strict";
2
+ /**
3
+ * Copyright (c) Facebook, Inc. and its affiliates.
4
+ *
5
+ * This source code is licensed under the MIT license found in the
6
+ * LICENSE file in the root directory of this source tree.
7
+ */
8
+ Object.defineProperty(exports, "__esModule", { value: true });
9
+ exports.createBlogFeedFiles = exports.generateBlogFeed = void 0;
10
+ const tslib_1 = require("tslib");
11
+ const feed_1 = require("feed");
12
+ const utils_1 = require("@docusaurus/utils");
13
+ const path_1 = (0, tslib_1.__importDefault)(require("path"));
14
+ const fs_extra_1 = (0, tslib_1.__importDefault)(require("fs-extra"));
15
+ // TODO this is temporary until we handle mdxToHtml better
16
+ // It's hard to convert reliably JSX/require calls to an html feed content
17
+ // See https://github.com/facebook/docusaurus/issues/5664
18
+ function mdxToFeedContent(mdxContent) {
19
+ try {
20
+ return (0, utils_1.mdxToHtml)(mdxContent);
21
+ }
22
+ catch (e) {
23
+ // TODO will we need a plugin option to configure how to handle such an error
24
+ // Swallow the error on purpose for now, until we understand better the problem space
25
+ return undefined;
26
+ }
27
+ }
28
+ async function generateBlogFeed({ blogPosts, options, siteConfig, }) {
29
+ if (!blogPosts.length) {
30
+ return null;
31
+ }
32
+ const { feedOptions, routeBasePath } = options;
33
+ const { url: siteUrl, baseUrl, title, favicon } = siteConfig;
34
+ const blogBaseUrl = (0, utils_1.normalizeUrl)([siteUrl, baseUrl, routeBasePath]);
35
+ const updated = (blogPosts[0] && blogPosts[0].metadata.date) ||
36
+ new Date('2015-10-25T16:29:00.000-07:00'); // weird legacy magic date
37
+ const feed = new feed_1.Feed({
38
+ id: blogBaseUrl,
39
+ title: feedOptions.title || `${title} Blog`,
40
+ updated,
41
+ language: feedOptions.language,
42
+ link: blogBaseUrl,
43
+ description: feedOptions.description || `${siteConfig.title} Blog`,
44
+ favicon: favicon ? (0, utils_1.normalizeUrl)([siteUrl, baseUrl, favicon]) : undefined,
45
+ copyright: feedOptions.copyright,
46
+ });
47
+ function toFeedAuthor(author) {
48
+ // TODO ask author emails?
49
+ // RSS feed requires email to render authors
50
+ return { name: author.name, link: author.url };
51
+ }
52
+ blogPosts.forEach((post) => {
53
+ const { id, metadata: { title: metadataTitle, permalink, date, description, authors }, } = post;
54
+ feed.addItem({
55
+ title: metadataTitle,
56
+ id,
57
+ link: (0, utils_1.normalizeUrl)([siteUrl, permalink]),
58
+ date,
59
+ description,
60
+ content: mdxToFeedContent(post.content),
61
+ author: authors.map(toFeedAuthor),
62
+ });
63
+ });
64
+ return feed;
65
+ }
66
+ exports.generateBlogFeed = generateBlogFeed;
67
+ async function createBlogFeedFile({ feed, feedType, filePath, }) {
68
+ const feedContent = feedType === 'rss' ? feed.rss2() : feed.atom1();
69
+ try {
70
+ await fs_extra_1.default.outputFile(filePath, feedContent);
71
+ }
72
+ catch (err) {
73
+ throw new Error(`Generating ${feedType} feed failed: ${err}.`);
74
+ }
75
+ }
76
+ async function createBlogFeedFiles({ blogPosts, options, siteConfig, outDir, }) {
77
+ const feed = await generateBlogFeed({ blogPosts, options, siteConfig });
78
+ const feedTypes = options.feedOptions.type;
79
+ if (!feed || !feedTypes) {
80
+ return;
81
+ }
82
+ await Promise.all(feedTypes.map(async function (feedType) {
83
+ await createBlogFeedFile({
84
+ feed,
85
+ feedType,
86
+ filePath: path_1.default.join(outDir, options.routeBasePath, `${feedType}.xml`),
87
+ });
88
+ }));
89
+ }
90
+ exports.createBlogFeedFiles = createBlogFeedFiles;