@docusaurus/plugin-content-docs 2.0.0-beta.16 → 2.0.0-beta.19

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 (93) hide show
  1. package/lib/categoryGeneratedIndex.d.ts +1 -1
  2. package/lib/categoryGeneratedIndex.js +5 -7
  3. package/lib/cli.d.ts +3 -2
  4. package/lib/cli.js +49 -41
  5. package/lib/client/docsClientUtils.d.ts +8 -5
  6. package/lib/client/docsClientUtils.js +13 -15
  7. package/lib/client/index.d.ts +12 -9
  8. package/lib/client/index.js +30 -33
  9. package/lib/constants.d.ts +4 -0
  10. package/lib/constants.js +4 -1
  11. package/lib/docs.d.ts +8 -15
  12. package/lib/docs.js +34 -39
  13. package/lib/{docFrontMatter.d.ts → frontMatter.d.ts} +4 -2
  14. package/lib/{docFrontMatter.js → frontMatter.js} +3 -0
  15. package/lib/globalData.d.ts +3 -7
  16. package/lib/globalData.js +9 -13
  17. package/lib/index.d.ts +1 -2
  18. package/lib/index.js +33 -26
  19. package/lib/lastUpdate.d.ts +4 -6
  20. package/lib/lastUpdate.js +14 -5
  21. package/lib/markdown/index.js +1 -1
  22. package/lib/markdown/linkify.js +5 -2
  23. package/lib/numberPrefix.js +16 -22
  24. package/lib/options.d.ts +3 -5
  25. package/lib/options.js +6 -5
  26. package/lib/props.d.ts +3 -3
  27. package/lib/props.js +10 -10
  28. package/lib/routes.d.ts +5 -4
  29. package/lib/routes.js +10 -24
  30. package/lib/server-export.d.ts +2 -1
  31. package/lib/server-export.js +3 -4
  32. package/lib/sidebars/generator.js +63 -44
  33. package/lib/sidebars/index.js +20 -16
  34. package/lib/sidebars/normalization.js +3 -3
  35. package/lib/sidebars/postProcessor.js +18 -25
  36. package/lib/sidebars/processor.d.ts +3 -1
  37. package/lib/sidebars/processor.js +17 -6
  38. package/lib/sidebars/types.d.ts +31 -19
  39. package/lib/sidebars/utils.d.ts +17 -6
  40. package/lib/sidebars/utils.js +27 -37
  41. package/lib/sidebars/validation.d.ts +3 -1
  42. package/lib/sidebars/validation.js +1 -0
  43. package/lib/slug.d.ts +1 -2
  44. package/lib/slug.js +4 -5
  45. package/lib/tags.d.ts +2 -1
  46. package/lib/tags.js +2 -2
  47. package/lib/translations.d.ts +3 -3
  48. package/lib/translations.js +28 -81
  49. package/lib/types.d.ts +10 -95
  50. package/lib/versions/files.d.ts +44 -0
  51. package/lib/versions/files.js +142 -0
  52. package/lib/versions/index.d.ts +36 -0
  53. package/lib/versions/index.js +155 -0
  54. package/lib/versions/validation.d.ts +17 -0
  55. package/lib/versions/validation.js +71 -0
  56. package/package.json +14 -12
  57. package/src/categoryGeneratedIndex.ts +10 -9
  58. package/src/cli.ts +64 -69
  59. package/src/client/docsClientUtils.ts +14 -16
  60. package/src/client/index.ts +42 -43
  61. package/src/constants.ts +4 -2
  62. package/src/deps.d.ts +1 -1
  63. package/src/docs.ts +48 -51
  64. package/src/{docFrontMatter.ts → frontMatter.ts} +9 -6
  65. package/src/globalData.ts +15 -16
  66. package/src/index.ts +45 -40
  67. package/src/lastUpdate.ts +20 -8
  68. package/src/markdown/index.ts +1 -3
  69. package/src/markdown/linkify.ts +6 -3
  70. package/src/numberPrefix.ts +18 -28
  71. package/src/options.ts +6 -8
  72. package/src/plugin-content-docs.d.ts +457 -116
  73. package/src/props.ts +12 -9
  74. package/src/routes.ts +13 -39
  75. package/src/server-export.ts +1 -3
  76. package/src/sidebars/generator.ts +88 -59
  77. package/src/sidebars/index.ts +20 -15
  78. package/src/sidebars/normalization.ts +1 -1
  79. package/src/sidebars/postProcessor.ts +6 -11
  80. package/src/sidebars/processor.ts +27 -14
  81. package/src/sidebars/types.ts +25 -23
  82. package/src/sidebars/utils.ts +45 -46
  83. package/src/sidebars/validation.ts +4 -3
  84. package/src/slug.ts +7 -6
  85. package/src/tags.ts +3 -2
  86. package/src/translations.ts +32 -84
  87. package/src/types.ts +15 -107
  88. package/src/versions/files.ts +220 -0
  89. package/src/versions/index.ts +247 -0
  90. package/src/versions/validation.ts +113 -0
  91. package/lib/versions.d.ts +0 -41
  92. package/lib/versions.js +0 -329
  93. package/src/versions.ts +0 -606
package/lib/options.js CHANGED
@@ -6,12 +6,12 @@
6
6
  * LICENSE file in the root directory of this source tree.
7
7
  */
8
8
  Object.defineProperty(exports, "__esModule", { value: true });
9
- exports.validateOptions = exports.OptionsSchema = exports.DEFAULT_OPTIONS = void 0;
9
+ exports.validateOptions = exports.DEFAULT_OPTIONS = void 0;
10
10
  const tslib_1 = require("tslib");
11
11
  const utils_validation_1 = require("@docusaurus/utils-validation");
12
12
  const utils_1 = require("@docusaurus/utils");
13
- const logger_1 = (0, tslib_1.__importDefault)(require("@docusaurus/logger"));
14
- const remark_admonitions_1 = (0, tslib_1.__importDefault)(require("remark-admonitions"));
13
+ const logger_1 = tslib_1.__importDefault(require("@docusaurus/logger"));
14
+ const remark_admonitions_1 = tslib_1.__importDefault(require("remark-admonitions"));
15
15
  const generator_1 = require("./sidebars/generator");
16
16
  const numberPrefix_1 = require("./numberPrefix");
17
17
  exports.DEFAULT_OPTIONS = {
@@ -54,7 +54,7 @@ const VersionOptionsSchema = utils_validation_1.Joi.object({
54
54
  const VersionsOptionsSchema = utils_validation_1.Joi.object()
55
55
  .pattern(utils_validation_1.Joi.string().required(), VersionOptionsSchema)
56
56
  .default(exports.DEFAULT_OPTIONS.versions);
57
- exports.OptionsSchema = utils_validation_1.Joi.object({
57
+ const OptionsSchema = utils_validation_1.Joi.object({
58
58
  path: utils_validation_1.Joi.string().default(exports.DEFAULT_OPTIONS.path),
59
59
  editUrl: utils_validation_1.Joi.alternatives().try(utils_validation_1.URISchema, utils_validation_1.Joi.function()),
60
60
  editCurrentVersion: utils_validation_1.Joi.boolean().default(exports.DEFAULT_OPTIONS.editCurrentVersion),
@@ -64,6 +64,7 @@ exports.OptionsSchema = utils_validation_1.Joi.object({
64
64
  // .allow('') ""
65
65
  .default(exports.DEFAULT_OPTIONS.routeBasePath),
66
66
  tagsBasePath: utils_validation_1.Joi.string().default(exports.DEFAULT_OPTIONS.tagsBasePath),
67
+ // @ts-expect-error: deprecated
67
68
  homePageId: utils_validation_1.Joi.any().forbidden().messages({
68
69
  'any.unknown': 'The docs plugin option homePageId is not supported anymore. To make a doc the "home", please add "slug: /" in its front matter. See: https://docusaurus.io/docs/next/docs-introduction#home-page-docs',
69
70
  }),
@@ -121,7 +122,7 @@ function validateOptions({ validate, options: userOptions, }) {
121
122
  };
122
123
  }
123
124
  }
124
- const normalizedOptions = validate(exports.OptionsSchema, options);
125
+ const normalizedOptions = validate(OptionsSchema, options);
125
126
  if (normalizedOptions.admonitions) {
126
127
  normalizedOptions.remarkPlugins = normalizedOptions.remarkPlugins.concat([
127
128
  [remark_admonitions_1.default, normalizedOptions.admonitions],
package/lib/props.d.ts CHANGED
@@ -4,12 +4,12 @@
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 type { LoadedVersion, VersionTag, DocMetadata } from './types';
8
- import type { PropSidebars, PropVersionMetadata, PropTagDocList } from '@docusaurus/plugin-content-docs';
7
+ import type { VersionTag } from './types';
8
+ import type { PropSidebars, PropVersionMetadata, PropTagDocList, DocMetadata, LoadedVersion } from '@docusaurus/plugin-content-docs';
9
9
  export declare function toSidebarsProp(loadedVersion: LoadedVersion): PropSidebars;
10
10
  export declare function toVersionMetadataProp(pluginId: string, loadedVersion: LoadedVersion): PropVersionMetadata;
11
11
  export declare function toTagDocListProp({ allTagsPath, tag, docs, }: {
12
12
  allTagsPath: string;
13
13
  tag: VersionTag;
14
- docs: Pick<DocMetadata, 'id' | 'title' | 'description' | 'permalink'>[];
14
+ docs: DocMetadata[];
15
15
  }): PropTagDocList;
package/lib/props.js CHANGED
@@ -8,7 +8,7 @@
8
8
  Object.defineProperty(exports, "__esModule", { value: true });
9
9
  exports.toTagDocListProp = exports.toVersionMetadataProp = exports.toSidebarsProp = void 0;
10
10
  const tslib_1 = require("tslib");
11
- const lodash_1 = (0, tslib_1.__importDefault)(require("lodash"));
11
+ const lodash_1 = tslib_1.__importDefault(require("lodash"));
12
12
  const docs_1 = require("./docs");
13
13
  function toSidebarsProp(loadedVersion) {
14
14
  const docsById = (0, docs_1.createDocsByIdIndex)(loadedVersion.docs);
@@ -22,7 +22,6 @@ Available document ids are:
22
22
  return docMetadata;
23
23
  }
24
24
  const convertDocLink = (item) => {
25
- var _a;
26
25
  const docMetadata = getDocById(item.id);
27
26
  const { title, permalink, frontMatter: { sidebar_label: sidebarLabel }, } = docMetadata;
28
27
  return {
@@ -30,12 +29,12 @@ Available document ids are:
30
29
  label: sidebarLabel || item.label || title,
31
30
  href: permalink,
32
31
  className: item.className,
33
- customProps: (_a = item.customProps) !== null && _a !== void 0 ? _a : docMetadata.frontMatter.sidebar_custom_props,
32
+ customProps: item.customProps ?? docMetadata.frontMatter.sidebar_custom_props,
34
33
  docId: docMetadata.unversionedId,
35
34
  };
36
35
  };
37
36
  function getCategoryLinkHref(link) {
38
- switch (link === null || link === void 0 ? void 0 : link.type) {
37
+ switch (link?.type) {
39
38
  case 'doc':
40
39
  return getDocById(link.id).permalink;
41
40
  case 'generated-index':
@@ -82,10 +81,10 @@ function toVersionMetadataProp(pluginId, loadedVersion) {
82
81
  return {
83
82
  pluginId,
84
83
  version: loadedVersion.versionName,
85
- label: loadedVersion.versionLabel,
86
- banner: loadedVersion.versionBanner,
87
- badge: loadedVersion.versionBadge,
88
- className: loadedVersion.versionClassName,
84
+ label: loadedVersion.label,
85
+ banner: loadedVersion.banner,
86
+ badge: loadedVersion.badge,
87
+ className: loadedVersion.className,
89
88
  isLast: loadedVersion.isLast,
90
89
  docsSidebars: toSidebarsProp(loadedVersion),
91
90
  docs: toVersionDocsProp(loadedVersion),
@@ -105,10 +104,11 @@ function toTagDocListProp({ allTagsPath, tag, docs, }) {
105
104
  }));
106
105
  }
107
106
  return {
108
- name: tag.name,
107
+ label: tag.label,
109
108
  permalink: tag.permalink,
110
- docs: toDocListProp(),
111
109
  allTagsPath,
110
+ count: tag.docIds.length,
111
+ items: toDocListProp(),
112
112
  };
113
113
  }
114
114
  exports.toTagDocListProp = toTagDocListProp;
package/lib/routes.d.ts CHANGED
@@ -5,9 +5,10 @@
5
5
  * LICENSE file in the root directory of this source tree.
6
6
  */
7
7
  import type { PluginContentLoadedActions, RouteConfig } from '@docusaurus/types';
8
- import type { DocMetadata, LoadedVersion } from './types';
8
+ import type { FullVersion } from './types';
9
+ import type { DocMetadata } from '@docusaurus/plugin-content-docs';
9
10
  export declare function createCategoryGeneratedIndexRoutes({ version, actions, docCategoryGeneratedIndexComponent, aliasedSource, }: {
10
- version: LoadedVersion;
11
+ version: FullVersion;
11
12
  actions: PluginContentLoadedActions;
12
13
  docCategoryGeneratedIndexComponent: string;
13
14
  aliasedSource: (str: string) => string;
@@ -17,8 +18,8 @@ export declare function createDocRoutes({ docs, actions, docItemComponent, }: {
17
18
  actions: PluginContentLoadedActions;
18
19
  docItemComponent: string;
19
20
  }): Promise<RouteConfig[]>;
20
- export declare function createVersionRoutes({ loadedVersion, actions, docItemComponent, docLayoutComponent, docCategoryGeneratedIndexComponent, pluginId, aliasedSource, }: {
21
- loadedVersion: LoadedVersion;
21
+ export declare function createVersionRoutes({ version, actions, docItemComponent, docLayoutComponent, docCategoryGeneratedIndexComponent, pluginId, aliasedSource, }: {
22
+ version: FullVersion;
22
23
  actions: PluginContentLoadedActions;
23
24
  docLayoutComponent: string;
24
25
  docItemComponent: string;
package/lib/routes.js CHANGED
@@ -10,27 +10,15 @@ exports.createVersionRoutes = exports.createDocRoutes = exports.createCategoryGe
10
10
  const tslib_1 = require("tslib");
11
11
  const utils_1 = require("@docusaurus/utils");
12
12
  const props_1 = require("./props");
13
- const logger_1 = (0, tslib_1.__importDefault)(require("@docusaurus/logger"));
13
+ const logger_1 = tslib_1.__importDefault(require("@docusaurus/logger"));
14
14
  async function createCategoryGeneratedIndexRoutes({ version, actions, docCategoryGeneratedIndexComponent, aliasedSource, }) {
15
15
  const slugs = (0, utils_1.createSlugger)();
16
16
  async function createCategoryGeneratedIndexRoute(categoryGeneratedIndex) {
17
- const { sidebar, title, description, slug, permalink, previous, next, image, keywords, } = categoryGeneratedIndex;
18
- const propFileName = slugs.slug(`${version.versionPath}-${categoryGeneratedIndex.sidebar}-category-${categoryGeneratedIndex.title}`);
19
- const prop = {
20
- title,
21
- description,
22
- slug,
23
- permalink,
24
- image,
25
- keywords,
26
- navigation: {
27
- previous,
28
- next,
29
- },
30
- };
17
+ const { sidebar, ...prop } = categoryGeneratedIndex;
18
+ const propFileName = slugs.slug(`${version.path}-${categoryGeneratedIndex.sidebar}-category-${categoryGeneratedIndex.title}`);
31
19
  const propData = await actions.createData(`${(0, utils_1.docuHash)(`category/${propFileName}`)}.json`, JSON.stringify(prop, null, 2));
32
20
  return {
33
- path: permalink,
21
+ path: categoryGeneratedIndex.permalink,
34
22
  component: docCategoryGeneratedIndexComponent,
35
23
  exact: true,
36
24
  modules: {
@@ -68,8 +56,8 @@ async function createDocRoutes({ docs, actions, docItemComponent, }) {
68
56
  }));
69
57
  }
70
58
  exports.createDocRoutes = createDocRoutes;
71
- async function createVersionRoutes({ loadedVersion, actions, docItemComponent, docLayoutComponent, docCategoryGeneratedIndexComponent, pluginId, aliasedSource, }) {
72
- async function doCreateVersionRoutes(version) {
59
+ async function createVersionRoutes({ version, actions, docItemComponent, docLayoutComponent, docCategoryGeneratedIndexComponent, pluginId, aliasedSource, }) {
60
+ async function doCreateVersionRoutes() {
73
61
  const versionMetadata = (0, props_1.toVersionMetadataProp)(pluginId, version);
74
62
  const versionMetadataPropPath = await actions.createData(`${(0, utils_1.docuHash)(`version-${version.versionName}-metadata-prop`)}.json`, JSON.stringify(versionMetadata, null, 2));
75
63
  async function createVersionSubRoutes() {
@@ -86,12 +74,10 @@ async function createVersionRoutes({ loadedVersion, actions, docItemComponent, d
86
74
  return routes.sort((a, b) => a.path.localeCompare(b.path));
87
75
  }
88
76
  actions.addRoute({
89
- path: version.versionPath,
90
- // allow matching /docs/* as well
77
+ path: version.path,
78
+ // Allow matching /docs/* since this is the wrapping route
91
79
  exact: false,
92
- // main docs component (DocPage)
93
80
  component: docLayoutComponent,
94
- // sub-routes for each doc
95
81
  routes: await createVersionSubRoutes(),
96
82
  modules: {
97
83
  versionMetadata: aliasedSource(versionMetadataPropPath),
@@ -100,10 +86,10 @@ async function createVersionRoutes({ loadedVersion, actions, docItemComponent, d
100
86
  });
101
87
  }
102
88
  try {
103
- return await doCreateVersionRoutes(loadedVersion);
89
+ return await doCreateVersionRoutes();
104
90
  }
105
91
  catch (err) {
106
- logger_1.default.error `Can't create version routes for version name=${loadedVersion.versionName}`;
92
+ logger_1.default.error `Can't create version routes for version name=${version.versionName}`;
107
93
  throw err;
108
94
  }
109
95
  }
@@ -5,4 +5,5 @@
5
5
  * LICENSE file in the root directory of this source tree.
6
6
  */
7
7
  export { CURRENT_VERSION_NAME, VERSIONED_DOCS_DIR, VERSIONED_SIDEBARS_DIR, VERSIONS_JSON_FILE, } from './constants';
8
- export { filterVersions, getDefaultVersionBanner, getVersionBadge, getVersionBanner, getVersionsFilePath, readVersionsFile, readVersionNames, } from './versions';
8
+ export { filterVersions, getDefaultVersionBanner, getVersionBadge, getVersionBanner, } from './versions';
9
+ export { readVersionNames } from './versions/files';
@@ -6,7 +6,7 @@
6
6
  * LICENSE file in the root directory of this source tree.
7
7
  */
8
8
  Object.defineProperty(exports, "__esModule", { value: true });
9
- exports.readVersionNames = exports.readVersionsFile = exports.getVersionsFilePath = exports.getVersionBanner = exports.getVersionBadge = exports.getDefaultVersionBanner = exports.filterVersions = exports.VERSIONS_JSON_FILE = exports.VERSIONED_SIDEBARS_DIR = exports.VERSIONED_DOCS_DIR = exports.CURRENT_VERSION_NAME = void 0;
9
+ exports.readVersionNames = exports.getVersionBanner = exports.getVersionBadge = exports.getDefaultVersionBanner = exports.filterVersions = exports.VERSIONS_JSON_FILE = exports.VERSIONED_SIDEBARS_DIR = exports.VERSIONED_DOCS_DIR = exports.CURRENT_VERSION_NAME = void 0;
10
10
  // APIs available to Node.js
11
11
  var constants_1 = require("./constants");
12
12
  Object.defineProperty(exports, "CURRENT_VERSION_NAME", { enumerable: true, get: function () { return constants_1.CURRENT_VERSION_NAME; } });
@@ -18,6 +18,5 @@ Object.defineProperty(exports, "filterVersions", { enumerable: true, get: functi
18
18
  Object.defineProperty(exports, "getDefaultVersionBanner", { enumerable: true, get: function () { return versions_1.getDefaultVersionBanner; } });
19
19
  Object.defineProperty(exports, "getVersionBadge", { enumerable: true, get: function () { return versions_1.getVersionBadge; } });
20
20
  Object.defineProperty(exports, "getVersionBanner", { enumerable: true, get: function () { return versions_1.getVersionBanner; } });
21
- Object.defineProperty(exports, "getVersionsFilePath", { enumerable: true, get: function () { return versions_1.getVersionsFilePath; } });
22
- Object.defineProperty(exports, "readVersionsFile", { enumerable: true, get: function () { return versions_1.readVersionsFile; } });
23
- Object.defineProperty(exports, "readVersionNames", { enumerable: true, get: function () { return versions_1.readVersionNames; } });
21
+ var files_1 = require("./versions/files");
22
+ Object.defineProperty(exports, "readVersionNames", { enumerable: true, get: function () { return files_1.readVersionNames; } });
@@ -8,14 +8,12 @@
8
8
  Object.defineProperty(exports, "__esModule", { value: true });
9
9
  exports.DefaultSidebarItemsGenerator = exports.CategoryMetadataFilenamePattern = exports.CategoryMetadataFilenameBase = void 0;
10
10
  const tslib_1 = require("tslib");
11
- const lodash_1 = (0, tslib_1.__importDefault)(require("lodash"));
11
+ const lodash_1 = tslib_1.__importDefault(require("lodash"));
12
12
  const utils_1 = require("@docusaurus/utils");
13
- const logger_1 = (0, tslib_1.__importDefault)(require("@docusaurus/logger"));
14
- const path_1 = (0, tslib_1.__importDefault)(require("path"));
13
+ const logger_1 = tslib_1.__importDefault(require("@docusaurus/logger"));
14
+ const path_1 = tslib_1.__importDefault(require("path"));
15
15
  const docs_1 = require("../docs");
16
16
  const BreadcrumbSeparator = '/';
17
- // To avoid possible name clashes with a folder of the same name as the ID
18
- const docIdPrefix = '$doc$/';
19
17
  // Just an alias to the make code more explicit
20
18
  function getLocalDocId(docId) {
21
19
  return lodash_1.default.last(docId.split('/'));
@@ -29,7 +27,9 @@ const DefaultSidebarItemsGenerator = async ({ numberPrefixParser, isCategoryInde
29
27
  const getDoc = (docId) => {
30
28
  const doc = findDoc(docId);
31
29
  if (!doc) {
32
- throw new Error(`Can't find any doc with id=${docId}.\nAvailable doc ids:\n- ${Object.keys(docsById).join('\n- ')}`);
30
+ throw new Error(`Can't find any doc with ID ${docId}.
31
+ Available doc IDs:
32
+ - ${Object.keys(docsById).join('\n- ')}`);
33
33
  }
34
34
  return doc;
35
35
  };
@@ -41,9 +41,9 @@ const DefaultSidebarItemsGenerator = async ({ numberPrefixParser, isCategoryInde
41
41
  return (
42
42
  // Doc at the root of the autogenerated sidebar dir
43
43
  doc.sourceDirName === autogenDir ||
44
- // autogen dir is . and doc is in subfolder
44
+ // Autogen dir is . and doc is in subfolder
45
45
  autogenDir === '.' ||
46
- // autogen dir is not . and doc is in subfolder
46
+ // Autogen dir is not . and doc is in subfolder
47
47
  // "api/myDoc" startsWith "api/" (note "api2/myDoc" is not included)
48
48
  doc.sourceDirName.startsWith((0, utils_1.addTrailingSlash)(autogenDir)));
49
49
  }
@@ -72,14 +72,16 @@ const DefaultSidebarItemsGenerator = async ({ numberPrefixParser, isCategoryInde
72
72
  const treeRoot = {};
73
73
  docs.forEach((doc) => {
74
74
  const breadcrumb = getRelativeBreadcrumb(doc);
75
- let currentDir = treeRoot; // We walk down the file's path to generate the fs structure
75
+ // We walk down the file's path to generate the fs structure
76
+ let currentDir = treeRoot;
76
77
  breadcrumb.forEach((dir) => {
77
78
  if (typeof currentDir[dir] === 'undefined') {
78
79
  currentDir[dir] = {}; // Create new folder.
79
80
  }
80
81
  currentDir = currentDir[dir]; // Go into the subdirectory.
81
82
  });
82
- currentDir[`${docIdPrefix}${doc.id}`] = null; // We've walked through the file path. Register the file in this directory.
83
+ // We've walked through the path. Register the file in this directory.
84
+ currentDir[path_1.default.basename(doc.source)] = doc.id;
83
85
  });
84
86
  return treeRoot;
85
87
  }
@@ -88,24 +90,22 @@ const DefaultSidebarItemsGenerator = async ({ numberPrefixParser, isCategoryInde
88
90
  * (From a record to an array of items, akin to normalizing shorthand)
89
91
  */
90
92
  function generateSidebar(fsModel) {
91
- function createDocItem(id) {
93
+ function createDocItem(id, fullPath, fileName) {
92
94
  const { sidebarPosition: position, frontMatter: { sidebar_label: label, sidebar_class_name: className }, } = getDoc(id);
93
95
  return {
94
96
  type: 'doc',
95
97
  id,
96
98
  position,
99
+ source: fileName,
97
100
  // We don't want these fields to magically appear in the generated
98
101
  // sidebar
99
102
  ...(label !== undefined && { label }),
100
103
  ...(className !== undefined && { className }),
101
104
  };
102
105
  }
103
- async function createCategoryItem(dir, fullPath, folderName) {
104
- var _a, _b;
105
- const categoryMetadata = categoriesMetadata[(0, utils_1.posixPath)(path_1.default.join(autogenDir, fullPath))];
106
- const className = categoryMetadata === null || categoryMetadata === void 0 ? void 0 : categoryMetadata.className;
107
- const { filename, numberPrefix } = numberPrefixParser(folderName);
108
- const allItems = await Promise.all(Object.entries(dir).map(([key, content]) => dirToItem(content, key, `${fullPath}/${key}`)));
106
+ function createCategoryItem(dir, fullPath, folderName) {
107
+ const categoryMetadata = categoriesMetadata[path_1.default.posix.join(autogenDir, fullPath)];
108
+ const allItems = Object.entries(dir).map(([key, content]) => dirToItem(content, key, `${fullPath}/${key}`));
109
109
  // Try to match a doc inside the category folder,
110
110
  // using the "local id" (myDoc) or "qualified id" (dirName/myDoc)
111
111
  function findDocByLocalId(localId) {
@@ -120,48 +120,64 @@ const DefaultSidebarItemsGenerator = async ({ numberPrefixParser, isCategoryInde
120
120
  return isCategoryIndex((0, docs_1.toCategoryIndexMatcherParam)(doc));
121
121
  });
122
122
  }
123
- function getCategoryLinkedDocId() {
124
- var _a, _b;
125
- const link = categoryMetadata === null || categoryMetadata === void 0 ? void 0 : categoryMetadata.link;
126
- if (link !== undefined) {
127
- if (link && link.type === 'doc') {
128
- return ((_a = findDocByLocalId(link.id)) === null || _a === void 0 ? void 0 : _a.id) || getDoc(link.id).id;
129
- }
123
+ // In addition to the ID, this function also retrieves metadata of the
124
+ // linked doc that could be used as fallback values for category metadata
125
+ function getCategoryLinkedDocMetadata() {
126
+ const link = categoryMetadata?.link;
127
+ if (link !== undefined && link?.type !== 'doc') {
130
128
  // If a link is explicitly specified, we won't apply conventions
131
129
  return undefined;
132
130
  }
133
- // Apply default convention to pick index.md, README.md or
134
- // <categoryName>.md as the category doc
135
- return (_b = findConventionalCategoryDocLink()) === null || _b === void 0 ? void 0 : _b.id;
131
+ const id = link
132
+ ? findDocByLocalId(link.id)?.id ?? getDoc(link.id).id
133
+ : findConventionalCategoryDocLink()?.id;
134
+ if (!id) {
135
+ return undefined;
136
+ }
137
+ const doc = getDoc(id);
138
+ return {
139
+ id,
140
+ position: doc.sidebarPosition,
141
+ label: doc.frontMatter.sidebar_label ?? doc.title,
142
+ customProps: doc.frontMatter.sidebar_custom_props,
143
+ className: doc.frontMatter.sidebar_class_name,
144
+ };
136
145
  }
137
- const categoryLinkedDocId = getCategoryLinkedDocId();
138
- const link = categoryLinkedDocId
146
+ const categoryLinkedDoc = getCategoryLinkedDocMetadata();
147
+ const link = categoryLinkedDoc
139
148
  ? {
140
149
  type: 'doc',
141
- id: categoryLinkedDocId, // We "remap" a potentially "local id" to a "qualified id"
150
+ id: categoryLinkedDoc.id, // We "remap" a potentially "local id" to a "qualified id"
142
151
  }
143
- : categoryMetadata === null || categoryMetadata === void 0 ? void 0 : categoryMetadata.link;
152
+ : categoryMetadata?.link;
144
153
  // If a doc is linked, remove it from the category subItems
145
- const items = allItems.filter((item) => !(item.type === 'doc' && item.id === categoryLinkedDocId));
154
+ const items = allItems.filter((item) => !(item.type === 'doc' && item.id === categoryLinkedDoc?.id));
155
+ const className = categoryMetadata?.className ?? categoryLinkedDoc?.className;
156
+ const customProps = categoryMetadata?.customProps ?? categoryLinkedDoc?.customProps;
157
+ const { filename, numberPrefix } = numberPrefixParser(folderName);
146
158
  return {
147
159
  type: 'category',
148
- label: (_a = categoryMetadata === null || categoryMetadata === void 0 ? void 0 : categoryMetadata.label) !== null && _a !== void 0 ? _a : filename,
149
- collapsible: categoryMetadata === null || categoryMetadata === void 0 ? void 0 : categoryMetadata.collapsible,
150
- collapsed: categoryMetadata === null || categoryMetadata === void 0 ? void 0 : categoryMetadata.collapsed,
151
- position: (_b = categoryMetadata === null || categoryMetadata === void 0 ? void 0 : categoryMetadata.position) !== null && _b !== void 0 ? _b : numberPrefix,
160
+ label: categoryMetadata?.label ?? categoryLinkedDoc?.label ?? filename,
161
+ collapsible: categoryMetadata?.collapsible,
162
+ collapsed: categoryMetadata?.collapsed,
163
+ position: categoryMetadata?.position ??
164
+ categoryLinkedDoc?.position ??
165
+ numberPrefix,
166
+ source: folderName,
167
+ ...(customProps !== undefined && { customProps }),
152
168
  ...(className !== undefined && { className }),
153
169
  items,
154
170
  ...(link && { link }),
155
171
  };
156
172
  }
157
- async function dirToItem(dir, // The directory item to be transformed.
158
- itemKey, // For docs, it's the doc ID; for categories, it's used to generate the next `relativePath`.
173
+ function dirToItem(dir, // The directory item to be transformed.
174
+ itemKey, // File/folder name; for categories, it's used to generate the next `relativePath`.
159
175
  fullPath) {
160
- return dir
176
+ return typeof dir === 'object'
161
177
  ? createCategoryItem(dir, fullPath, itemKey)
162
- : createDocItem(itemKey.substring(docIdPrefix.length));
178
+ : createDocItem(dir, fullPath, itemKey);
163
179
  }
164
- return Promise.all(Object.entries(fsModel).map(([key, content]) => dirToItem(content, key, key)));
180
+ return Object.entries(fsModel).map(([key, content]) => dirToItem(content, key, key));
165
181
  }
166
182
  /**
167
183
  * Step 4. Recursively sort the categories/docs + remove the "position"
@@ -177,13 +193,16 @@ const DefaultSidebarItemsGenerator = async ({ numberPrefixParser, isCategoryInde
177
193
  }
178
194
  return item;
179
195
  });
180
- const sortedSidebarItems = lodash_1.default.sortBy(processedSidebarItems, (item) => item.position);
181
- return sortedSidebarItems.map(({ position, ...item }) => item);
196
+ const sortedSidebarItems = lodash_1.default.sortBy(processedSidebarItems, [
197
+ 'position',
198
+ 'source',
199
+ ]);
200
+ return sortedSidebarItems.map(({ position, source, ...item }) => item);
182
201
  }
183
202
  // TODO: the whole code is designed for pipeline operator
184
203
  const docs = getAutogenDocs();
185
204
  const fsModel = treeify(docs);
186
- const sidebarWithPosition = await generateSidebar(fsModel);
205
+ const sidebarWithPosition = generateSidebar(fsModel);
187
206
  const sortedSidebar = sortItems(sidebarWithPosition);
188
207
  return sortedSidebar;
189
208
  };
@@ -8,18 +8,18 @@
8
8
  Object.defineProperty(exports, "__esModule", { value: true });
9
9
  exports.loadSidebars = exports.loadSidebarsFileUnsafe = exports.resolveSidebarPathOption = exports.DisabledSidebars = exports.DefaultSidebars = void 0;
10
10
  const tslib_1 = require("tslib");
11
- const fs_extra_1 = (0, tslib_1.__importDefault)(require("fs-extra"));
12
- const import_fresh_1 = (0, tslib_1.__importDefault)(require("import-fresh"));
11
+ const fs_extra_1 = tslib_1.__importDefault(require("fs-extra"));
12
+ const import_fresh_1 = tslib_1.__importDefault(require("import-fresh"));
13
13
  const validation_1 = require("./validation");
14
14
  const normalization_1 = require("./normalization");
15
15
  const processor_1 = require("./processor");
16
16
  const postProcessor_1 = require("./postProcessor");
17
- const path_1 = (0, tslib_1.__importDefault)(require("path"));
17
+ const path_1 = tslib_1.__importDefault(require("path"));
18
18
  const utils_1 = require("@docusaurus/utils");
19
- const logger_1 = (0, tslib_1.__importDefault)(require("@docusaurus/logger"));
20
- const js_yaml_1 = (0, tslib_1.__importDefault)(require("js-yaml"));
21
- const lodash_1 = (0, tslib_1.__importDefault)(require("lodash"));
22
- const combine_promises_1 = (0, tslib_1.__importDefault)(require("combine-promises"));
19
+ const logger_1 = tslib_1.__importDefault(require("@docusaurus/logger"));
20
+ const js_yaml_1 = tslib_1.__importDefault(require("js-yaml"));
21
+ const lodash_1 = tslib_1.__importDefault(require("lodash"));
22
+ const combine_promises_1 = tslib_1.__importDefault(require("combine-promises"));
23
23
  exports.DefaultSidebars = {
24
24
  defaultSidebar: [
25
25
  {
@@ -30,7 +30,6 @@ exports.DefaultSidebars = {
30
30
  };
31
31
  exports.DisabledSidebars = {};
32
32
  // If a path is provided, make it absolute
33
- // use this before loadSidebars()
34
33
  function resolveSidebarPathOption(siteDir, sidebarPathOption) {
35
34
  return sidebarPathOption
36
35
  ? path_1.default.resolve(siteDir, sidebarPathOption)
@@ -43,7 +42,7 @@ async function readCategoriesMetadata(contentPath) {
43
42
  });
44
43
  const categoryToFile = lodash_1.default.groupBy(categoryFiles, path_1.default.dirname);
45
44
  return (0, combine_promises_1.default)(lodash_1.default.mapValues(categoryToFile, async (files, folder) => {
46
- const [filePath] = files;
45
+ const filePath = files[0];
47
46
  if (files.length > 1) {
48
47
  logger_1.default.warn `There are more than one category metadata files for path=${folder}: ${files.join(', ')}. The behavior is undetermined.`;
49
48
  }
@@ -76,13 +75,18 @@ async function loadSidebarsFileUnsafe(sidebarFilePath) {
76
75
  return (0, import_fresh_1.default)(sidebarFilePath);
77
76
  }
78
77
  exports.loadSidebarsFileUnsafe = loadSidebarsFileUnsafe;
79
- // Note: sidebarFilePath must be absolute, use resolveSidebarPathOption
80
78
  async function loadSidebars(sidebarFilePath, options) {
81
- const sidebarsConfig = await loadSidebarsFileUnsafe(sidebarFilePath);
82
- const normalizedSidebars = (0, normalization_1.normalizeSidebars)(sidebarsConfig);
83
- (0, validation_1.validateSidebars)(normalizedSidebars);
84
- const categoriesMetadata = await readCategoriesMetadata(options.version.contentPath);
85
- const processedSidebars = await (0, processor_1.processSidebars)(normalizedSidebars, categoriesMetadata, options);
86
- return (0, postProcessor_1.postProcessSidebars)(processedSidebars, options);
79
+ try {
80
+ const sidebarsConfig = await loadSidebarsFileUnsafe(sidebarFilePath);
81
+ const normalizedSidebars = (0, normalization_1.normalizeSidebars)(sidebarsConfig);
82
+ (0, validation_1.validateSidebars)(normalizedSidebars);
83
+ const categoriesMetadata = await readCategoriesMetadata(options.version.contentPath);
84
+ const processedSidebars = await (0, processor_1.processSidebars)(normalizedSidebars, categoriesMetadata, options);
85
+ return (0, postProcessor_1.postProcessSidebars)(processedSidebars, options);
86
+ }
87
+ catch (err) {
88
+ logger_1.default.error `Sidebars file at path=${sidebarFilePath} failed to be loaded.`;
89
+ throw err;
90
+ }
87
91
  }
88
92
  exports.loadSidebars = loadSidebars;
@@ -9,8 +9,8 @@ Object.defineProperty(exports, "__esModule", { value: true });
9
9
  exports.normalizeSidebars = exports.normalizeItem = void 0;
10
10
  const tslib_1 = require("tslib");
11
11
  const utils_1 = require("./utils");
12
- const lodash_1 = (0, tslib_1.__importDefault)(require("lodash"));
13
- const logger_1 = (0, tslib_1.__importDefault)(require("@docusaurus/logger"));
12
+ const lodash_1 = tslib_1.__importDefault(require("lodash"));
13
+ const logger_1 = tslib_1.__importDefault(require("@docusaurus/logger"));
14
14
  function normalizeCategoriesShorthand(sidebar) {
15
15
  return Object.entries(sidebar).map(([label, items]) => ({
16
16
  type: 'category',
@@ -42,7 +42,7 @@ function normalizeItem(item) {
42
42
  exports.normalizeItem = normalizeItem;
43
43
  function normalizeSidebar(sidebar, place) {
44
44
  if (!Array.isArray(sidebar) && !(0, utils_1.isCategoriesShorthand)(sidebar)) {
45
- throw new Error(logger_1.default.interpolate `Invalid sidebar items collection code=${JSON.stringify(sidebar)} in ${place}: it must either be an array of sidebar items or a shorthand notation (which doesn't contain a code=${'type'} property). See path=${'https://docusaurus.io/docs/sidebar/items'} for all valid syntaxes.`);
45
+ throw new Error(logger_1.default.interpolate `Invalid sidebar items collection code=${JSON.stringify(sidebar)} in ${place}: it must either be an array of sidebar items or a shorthand notation (which doesn't contain a code=${'type'} property). See url=${'https://docusaurus.io/docs/sidebar/items'} for all valid syntaxes.`);
46
46
  }
47
47
  const normalizedSidebar = Array.isArray(sidebar)
48
48
  ? sidebar
@@ -9,14 +9,13 @@ Object.defineProperty(exports, "__esModule", { value: true });
9
9
  exports.postProcessSidebars = void 0;
10
10
  const tslib_1 = require("tslib");
11
11
  const utils_1 = require("@docusaurus/utils");
12
- const lodash_1 = (0, tslib_1.__importDefault)(require("lodash"));
12
+ const lodash_1 = tslib_1.__importDefault(require("lodash"));
13
13
  function normalizeCategoryLink(category, params) {
14
- var _a, _b;
15
- if (((_a = category.link) === null || _a === void 0 ? void 0 : _a.type) === 'generated-index') {
16
- // default slug logic can be improved
14
+ if (category.link?.type === 'generated-index') {
15
+ // Default slug logic can be improved
17
16
  const getDefaultSlug = () => `/category/${params.categoryLabelSlugger.slug(category.label)}`;
18
- const slug = (_b = category.link.slug) !== null && _b !== void 0 ? _b : getDefaultSlug();
19
- const permalink = (0, utils_1.normalizeUrl)([params.version.versionPath, slug]);
17
+ const slug = category.link.slug ?? getDefaultSlug();
18
+ const permalink = (0, utils_1.normalizeUrl)([params.version.path, slug]);
20
19
  return {
21
20
  ...category.link,
22
21
  slug,
@@ -26,12 +25,11 @@ function normalizeCategoryLink(category, params) {
26
25
  return category.link;
27
26
  }
28
27
  function postProcessSidebarItem(item, params) {
29
- var _a, _b;
30
28
  if (item.type === 'category') {
31
29
  const category = {
32
30
  ...item,
33
- collapsed: (_a = item.collapsed) !== null && _a !== void 0 ? _a : params.sidebarOptions.sidebarCollapsed,
34
- collapsible: (_b = item.collapsible) !== null && _b !== void 0 ? _b : params.sidebarOptions.sidebarCollapsible,
31
+ collapsed: item.collapsed ?? params.sidebarOptions.sidebarCollapsed,
32
+ collapsible: item.collapsible ?? params.sidebarOptions.sidebarCollapsible,
35
33
  link: normalizeCategoryLink(item, params),
36
34
  items: item.items.map((subItem) => postProcessSidebarItem(subItem, params)),
37
35
  };
@@ -41,22 +39,17 @@ function postProcessSidebarItem(item, params) {
41
39
  if (!category.link) {
42
40
  throw new Error(`Sidebar category ${item.label} has neither any subitem nor a link. This makes this item not able to link to anything.`);
43
41
  }
44
- switch (category.link.type) {
45
- case 'doc':
46
- return {
47
- type: 'doc',
48
- label: category.label,
49
- id: category.link.id,
50
- };
51
- case 'generated-index':
52
- return {
53
- type: 'link',
54
- label: category.label,
55
- href: category.link.permalink,
56
- };
57
- default:
58
- throw new Error('Unexpected sidebar category link type');
59
- }
42
+ return category.link.type === 'doc'
43
+ ? {
44
+ type: 'doc',
45
+ label: category.label,
46
+ id: category.link.id,
47
+ }
48
+ : {
49
+ type: 'link',
50
+ label: category.label,
51
+ href: category.link.permalink,
52
+ };
60
53
  }
61
54
  // A non-collapsible category can't be collapsed!
62
55
  if (category.collapsible === false) {
@@ -5,4 +5,6 @@
5
5
  * LICENSE file in the root directory of this source tree.
6
6
  */
7
7
  import type { NormalizedSidebars, ProcessedSidebars, SidebarProcessorParams, CategoryMetadataFile } from './types';
8
- export declare function processSidebars(unprocessedSidebars: NormalizedSidebars, categoriesMetadata: Record<string, CategoryMetadataFile>, params: SidebarProcessorParams): Promise<ProcessedSidebars>;
8
+ export declare function processSidebars(unprocessedSidebars: NormalizedSidebars, categoriesMetadata: {
9
+ [filePath: string]: CategoryMetadataFile;
10
+ }, params: SidebarProcessorParams): Promise<ProcessedSidebars>;