@docusaurus/plugin-content-blog 2.0.0-beta.1 → 2.0.0-beta.10

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 (66) 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 +35 -23
  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.d.ts +1 -1
  11. package/lib/index.js +109 -112
  12. package/lib/markdownLoader.d.ts +3 -6
  13. package/lib/markdownLoader.js +5 -5
  14. package/lib/pluginOptionSchema.d.ts +3 -26
  15. package/lib/pluginOptionSchema.js +28 -7
  16. package/lib/translations.d.ts +10 -0
  17. package/lib/translations.js +53 -0
  18. package/lib/types.d.ts +54 -14
  19. package/package.json +19 -13
  20. package/src/__tests__/__fixtures__/authorsMapFiles/authors.json +29 -0
  21. package/src/__tests__/__fixtures__/authorsMapFiles/authors.yml +27 -0
  22. package/src/__tests__/__fixtures__/authorsMapFiles/authorsBad1.json +5 -0
  23. package/src/__tests__/__fixtures__/authorsMapFiles/authorsBad1.yml +3 -0
  24. package/src/__tests__/__fixtures__/authorsMapFiles/authorsBad2.json +3 -0
  25. package/src/__tests__/__fixtures__/authorsMapFiles/authorsBad2.yml +2 -0
  26. package/src/__tests__/__fixtures__/authorsMapFiles/authorsBad3.json +8 -0
  27. package/src/__tests__/__fixtures__/authorsMapFiles/authorsBad3.yml +3 -0
  28. package/src/__tests__/__fixtures__/component/Typography.tsx +6 -0
  29. package/src/__tests__/__fixtures__/getAuthorsMapFilePath/contentPathEmpty/empty +0 -0
  30. package/src/__tests__/__fixtures__/getAuthorsMapFilePath/contentPathJson1/authors.json +0 -0
  31. package/src/__tests__/__fixtures__/getAuthorsMapFilePath/contentPathJson2/authors.json +0 -0
  32. package/src/__tests__/__fixtures__/getAuthorsMapFilePath/contentPathNestedYml/sub/folder/authors.yml +0 -0
  33. package/src/__tests__/__fixtures__/getAuthorsMapFilePath/contentPathYml1/authors.yml +0 -0
  34. package/src/__tests__/__fixtures__/getAuthorsMapFilePath/contentPathYml2/authors.yml +0 -0
  35. package/src/__tests__/__fixtures__/website/blog/2018-12-14-Happy-First-Birthday-Slash.md +3 -0
  36. package/src/__tests__/__fixtures__/website/blog/_partials/somePartial.md +3 -0
  37. package/src/__tests__/__fixtures__/website/blog/_partials/subfolder/somePartial.md +3 -0
  38. package/src/__tests__/__fixtures__/website/blog/_somePartial.md +3 -0
  39. package/src/__tests__/__fixtures__/website/blog/authors.yml +4 -0
  40. package/src/__tests__/__fixtures__/website/blog/mdx-blog-post.mdx +36 -0
  41. package/src/__tests__/__fixtures__/website/blog/mdx-require-blog-post.mdx +14 -0
  42. package/src/__tests__/__fixtures__/website/blog/simple-slug.md +4 -0
  43. package/src/__tests__/__fixtures__/website/i18n/en/docusaurus-plugin-content-blog/2018-12-14-Happy-First-Birthday-Slash.md +3 -0
  44. package/src/__tests__/__fixtures__/website/i18n/en/docusaurus-plugin-content-blog/authors.yml +5 -0
  45. package/src/__tests__/__fixtures__/website/static/img/docusaurus.png +0 -0
  46. package/src/__tests__/__snapshots__/feed.test.ts.snap +164 -0
  47. package/src/__tests__/__snapshots__/translations.test.ts.snap +64 -0
  48. package/src/__tests__/authors.test.ts +608 -0
  49. package/src/__tests__/blogFrontMatter.test.ts +165 -36
  50. package/src/__tests__/blogUtils.test.ts +94 -0
  51. package/src/__tests__/{generateBlogFeed.test.ts → feed.test.ts} +35 -9
  52. package/src/__tests__/index.test.ts +84 -12
  53. package/src/__tests__/pluginOptionSchema.test.ts +3 -3
  54. package/src/__tests__/translations.test.ts +92 -0
  55. package/src/authors.ts +198 -0
  56. package/src/blogFrontMatter.ts +76 -37
  57. package/src/blogUtils.ts +202 -179
  58. package/{types.d.ts → src/deps.d.ts} +0 -0
  59. package/src/feed.ts +129 -0
  60. package/src/index.ts +131 -112
  61. package/src/markdownLoader.ts +8 -12
  62. package/{index.d.ts → src/plugin-content-blog.d.ts} +35 -31
  63. package/src/pluginOptionSchema.ts +31 -9
  64. package/src/translations.ts +63 -0
  65. package/src/types.ts +69 -16
  66. package/src/__tests__/__snapshots__/generateBlogFeed.test.ts.snap +0 -76
@@ -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
- author_url: utils_validation_1.JoiFrontMatter.string().uri(),
30
- author_image_url: utils_validation_1.JoiFrontMatter.string().uri(),
31
- slug: utils_validation_1.JoiFrontMatter.string(),
32
- image: utils_validation_1.JoiFrontMatter.string().uri({ relativeOnly: true }),
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
36
- authorURL: utils_validation_1.JoiFrontMatter.string().uri(),
42
+ author_url: utils_validation_1.URISchema,
43
+ author_image_url: utils_validation_1.URISchema,
44
+ // TODO enable deprecation warnings later
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
- authorImageURL: utils_validation_1.JoiFrontMatter.string().uri(),
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,34 +6,52 @@
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 globby_1 = tslib_1.__importDefault(require("globby"));
13
- const chalk_1 = tslib_1.__importDefault(require("chalk"));
14
- const path_1 = tslib_1.__importDefault(require("path"));
15
- const reading_time_1 = tslib_1.__importDefault(require("reading-time"));
16
- 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"));
17
15
  const lodash_1 = require("lodash");
18
16
  const utils_1 = require("@docusaurus/utils");
19
17
  const blogFrontMatter_1 = require("./blogFrontMatter");
18
+ const authors_1 = require("./authors");
20
19
  function truncate(fileString, truncateMarker) {
21
20
  return fileString.split(truncateMarker, 1).shift();
22
21
  }
23
22
  exports.truncate = truncate;
24
23
  function getSourceToPermalink(blogPosts) {
25
- 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);
26
25
  }
27
26
  exports.getSourceToPermalink = getSourceToPermalink;
28
- // YYYY-MM-DD-{name}.mdx?
29
- // Prefer named capture, but older Node versions do not support it.
30
- const DATE_FILENAME_PATTERN = /^(\d{4}-\d{1,2}-\d{1,2})-?(.*?).mdx?$/;
31
- function toUrl({ date, link }) {
32
- return `${date
33
- .toISOString()
34
- .substring(0, '2019-01-01'.length)
35
- .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
+ name: group.tag.label,
31
+ items: group.items.map((item) => item.id),
32
+ permalink: group.tag.permalink,
33
+ }));
34
+ }
35
+ exports.getBlogTags = getBlogTags;
36
+ const DATE_FILENAME_REGEX = /^(?<date>\d{4}[-/]\d{1,2}[-/]\d{1,2})[-/]?(?<text>.*?)(\/index)?.mdx?$/;
37
+ function parseBlogFileName(blogSourceRelative) {
38
+ const dateFilenameMatch = blogSourceRelative.match(DATE_FILENAME_REGEX);
39
+ if (dateFilenameMatch) {
40
+ const dateString = dateFilenameMatch.groups.date;
41
+ const text = dateFilenameMatch.groups.text;
42
+ // Always treat dates as UTC by adding the `Z`
43
+ const date = new Date(`${dateString}Z`);
44
+ const slugDate = dateString.replace(/-/g, '/');
45
+ const slug = `/${slugDate}/${text}`;
46
+ return { date, text, slug };
47
+ }
48
+ else {
49
+ const text = blogSourceRelative.replace(/(\/index)?\.mdx?$/, '');
50
+ const slug = `/${text}`;
51
+ return { date: undefined, text, slug };
52
+ }
36
53
  }
54
+ exports.parseBlogFileName = parseBlogFileName;
37
55
  function formatBlogPostDate(locale, date) {
38
56
  try {
39
57
  return new Intl.DateTimeFormat(locale, {
@@ -47,146 +65,133 @@ function formatBlogPostDate(locale, date) {
47
65
  throw new Error(`Can't format blog post date "${date}"`);
48
66
  }
49
67
  }
50
- async function generateBlogFeed(contentPaths, context, options) {
51
- if (!options.feedOptions) {
52
- throw new Error('Invalid options: "feedOptions" is not expected to be null.');
53
- }
54
- const { siteConfig } = context;
55
- const blogPosts = await generateBlogPosts(contentPaths, context, options);
56
- if (!blogPosts.length) {
57
- return null;
58
- }
59
- const { feedOptions, routeBasePath } = options;
60
- const { url: siteUrl, baseUrl, title, favicon } = siteConfig;
61
- const blogBaseUrl = utils_1.normalizeUrl([siteUrl, baseUrl, routeBasePath]);
62
- const updated = (blogPosts[0] && blogPosts[0].metadata.date) ||
63
- new Date('2015-10-25T16:29:00.000-07:00');
64
- const feed = new feed_1.Feed({
65
- id: blogBaseUrl,
66
- title: feedOptions.title || `${title} Blog`,
67
- updated,
68
- language: feedOptions.language,
69
- link: blogBaseUrl,
70
- description: feedOptions.description || `${siteConfig.title} Blog`,
71
- favicon: utils_1.normalizeUrl([siteUrl, baseUrl, favicon]),
72
- copyright: feedOptions.copyright,
73
- });
74
- blogPosts.forEach((post) => {
75
- const { id, metadata: { title: metadataTitle, permalink, date, description }, } = post;
76
- feed.addItem({
77
- title: metadataTitle,
78
- id,
79
- link: utils_1.normalizeUrl([siteUrl, permalink]),
80
- date,
81
- description,
82
- });
68
+ async function parseBlogPostMarkdownFile(blogSourceAbsolute) {
69
+ const result = await (0, utils_1.parseMarkdownFile)(blogSourceAbsolute, {
70
+ removeContentTitle: true,
83
71
  });
84
- return feed;
72
+ return {
73
+ ...result,
74
+ frontMatter: (0, blogFrontMatter_1.validateBlogPostFrontMatter)(result.frontMatter),
75
+ };
85
76
  }
86
- exports.generateBlogFeed = generateBlogFeed;
87
- async function generateBlogPosts(contentPaths, { siteConfig, siteDir, i18n }, options) {
88
- const { include, routeBasePath, truncateMarker, showReadingTime, editUrl, } = options;
89
- if (!fs_extra_1.default.existsSync(contentPaths.contentPath)) {
90
- return [];
77
+ const defaultReadingTime = ({ content, options }) => (0, reading_time_1.default)(content, options).minutes;
78
+ async function processBlogSourceFile(blogSourceRelative, contentPaths, context, options, authorsMap) {
79
+ var _a, _b, _c, _d;
80
+ const { siteConfig: { baseUrl }, siteDir, i18n, } = context;
81
+ const { routeBasePath, tagsBasePath: tagsRouteBasePath, truncateMarker, showReadingTime, editUrl, } = options;
82
+ // Lookup in localized folder in priority
83
+ const blogDirPath = await (0, utils_1.getFolderContainingFile)(getContentPathList(contentPaths), blogSourceRelative);
84
+ const blogSourceAbsolute = path_1.default.join(blogDirPath, blogSourceRelative);
85
+ const { frontMatter, content, contentTitle, excerpt } = await parseBlogPostMarkdownFile(blogSourceAbsolute);
86
+ const aliasedSource = (0, utils_1.aliasedSitePath)(blogSourceAbsolute, siteDir);
87
+ if (frontMatter.draft && process.env.NODE_ENV === 'production') {
88
+ return undefined;
91
89
  }
92
- const { baseUrl = '' } = siteConfig;
93
- const blogSourceFiles = await globby_1.default(include, {
94
- cwd: contentPaths.contentPath,
95
- });
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
- }
90
+ if (frontMatter.id) {
91
+ console.warn(chalk_1.default.yellow(`"id" header option is deprecated in ${blogSourceRelative} file. Please use "slug" option instead.`));
92
+ }
93
+ const parsedBlogFileName = parseBlogFileName(blogSourceRelative);
94
+ async function getDate() {
122
95
  // Prefer user-defined date.
123
96
  if (frontMatter.date) {
124
- date = frontMatter.date;
97
+ return new Date(frontMatter.date);
125
98
  }
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
- }
99
+ else if (parsedBlogFileName.date) {
100
+ return parsedBlogFileName.date;
158
101
  }
159
- blogPosts.push({
160
- id: (_e = frontMatter.slug) !== null && _e !== void 0 ? _e : title,
161
- metadata: {
102
+ // Fallback to file create time
103
+ return (await fs_extra_1.default.stat(blogSourceAbsolute)).birthtime;
104
+ }
105
+ const date = await getDate();
106
+ const formattedDate = formatBlogPostDate(i18n.currentLocale, date);
107
+ const title = (_b = (_a = frontMatter.title) !== null && _a !== void 0 ? _a : contentTitle) !== null && _b !== void 0 ? _b : parsedBlogFileName.text;
108
+ const description = (_d = (_c = frontMatter.description) !== null && _c !== void 0 ? _c : excerpt) !== null && _d !== void 0 ? _d : '';
109
+ const slug = frontMatter.slug || parsedBlogFileName.slug;
110
+ const permalink = (0, utils_1.normalizeUrl)([baseUrl, routeBasePath, slug]);
111
+ function getBlogEditUrl() {
112
+ const blogPathRelative = path_1.default.relative(blogDirPath, path_1.default.resolve(blogSourceAbsolute));
113
+ if (typeof editUrl === 'function') {
114
+ return editUrl({
115
+ blogDirPath: (0, utils_1.posixPath)(path_1.default.relative(siteDir, blogDirPath)),
116
+ blogPath: (0, utils_1.posixPath)(blogPathRelative),
162
117
  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
- });
118
+ locale: i18n.currentLocale,
119
+ });
120
+ }
121
+ else if (typeof editUrl === 'string') {
122
+ const isLocalized = blogDirPath === contentPaths.contentPathLocalized;
123
+ const fileContentPath = isLocalized && options.editLocalizedFiles
124
+ ? contentPaths.contentPathLocalized
125
+ : contentPaths.contentPath;
126
+ const contentPathEditUrl = (0, utils_1.normalizeUrl)([
127
+ editUrl,
128
+ (0, utils_1.posixPath)(path_1.default.relative(siteDir, fileContentPath)),
129
+ ]);
130
+ return (0, utils_1.getEditUrl)(blogPathRelative, contentPathEditUrl);
131
+ }
132
+ return undefined;
133
+ }
134
+ const tagsBasePath = (0, utils_1.normalizeUrl)([
135
+ baseUrl,
136
+ routeBasePath,
137
+ tagsRouteBasePath,
138
+ ]);
139
+ const authors = (0, authors_1.getBlogPostAuthors)({ authorsMap, frontMatter });
140
+ return {
141
+ id: slug,
142
+ metadata: {
143
+ permalink,
144
+ editUrl: getBlogEditUrl(),
145
+ source: aliasedSource,
146
+ title,
147
+ description,
148
+ date,
149
+ formattedDate,
150
+ tags: (0, utils_1.normalizeFrontMatterTags)(tagsBasePath, frontMatter.tags),
151
+ readingTime: showReadingTime
152
+ ? options.readingTime({
153
+ content,
154
+ frontMatter,
155
+ defaultReadingTime,
156
+ })
157
+ : undefined,
158
+ truncated: (truncateMarker === null || truncateMarker === void 0 ? void 0 : truncateMarker.test(content)) || false,
159
+ authors,
160
+ },
161
+ content,
162
+ };
163
+ }
164
+ async function generateBlogPosts(contentPaths, context, options) {
165
+ const { include, exclude } = options;
166
+ if (!fs_extra_1.default.existsSync(contentPaths.contentPath)) {
167
+ return [];
174
168
  }
175
- await Promise.all(blogSourceFiles.map(async (blogSourceFile) => {
169
+ const blogSourceFiles = await (0, utils_1.Globby)(include, {
170
+ cwd: contentPaths.contentPath,
171
+ ignore: exclude,
172
+ });
173
+ const authorsMap = await (0, authors_1.getAuthorsMap)({
174
+ contentPaths,
175
+ authorsMapPath: options.authorsMapPath,
176
+ });
177
+ const blogPosts = (await Promise.all(blogSourceFiles.map(async (blogSourceFile) => {
176
178
  try {
177
- return await processBlogSourceFile(blogSourceFile);
179
+ return await processBlogSourceFile(blogSourceFile, contentPaths, context, options, authorsMap);
178
180
  }
179
181
  catch (e) {
180
182
  console.error(chalk_1.default.red(`Processing of blog source file failed for path "${blogSourceFile}"`));
181
183
  throw e;
182
184
  }
183
- }));
185
+ }))).filter(Boolean);
184
186
  blogPosts.sort((a, b) => b.metadata.date.getTime() - a.metadata.date.getTime());
187
+ if (options.sortPosts === 'ascending') {
188
+ return blogPosts.reverse();
189
+ }
185
190
  return blogPosts;
186
191
  }
187
192
  exports.generateBlogPosts = generateBlogPosts;
188
193
  function linkify({ filePath, contentPaths, fileString, siteDir, sourceToPermalink, onBrokenMarkdownLink, }) {
189
- const { newContent, brokenMarkdownLinks } = utils_1.replaceMarkdownLinks({
194
+ const { newContent, brokenMarkdownLinks } = (0, utils_1.replaceMarkdownLinks)({
190
195
  siteDir,
191
196
  fileString,
192
197
  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 (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;
package/lib/index.d.ts CHANGED
@@ -6,5 +6,5 @@
6
6
  */
7
7
  import { PluginOptions, BlogContent } from './types';
8
8
  import { LoadContext, Plugin, OptionValidationContext, ValidationResult } from '@docusaurus/types';
9
- export default function pluginContentBlog(context: LoadContext, options: PluginOptions): Plugin<BlogContent | null>;
9
+ export default function pluginContentBlog(context: LoadContext, options: PluginOptions): Plugin<BlogContent>;
10
10
  export declare function validateOptions({ validate, options, }: OptionValidationContext<PluginOptions>): ValidationResult<PluginOptions>;