@docusaurus/utils 2.0.0-beta.15d451942 → 2.0.0-beta.18

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 (106) hide show
  1. package/README.md +1 -1
  2. package/lib/constants.d.ts +68 -0
  3. package/lib/constants.d.ts.map +1 -0
  4. package/lib/constants.js +71 -0
  5. package/lib/constants.js.map +1 -0
  6. package/lib/dataFileUtils.d.ts +60 -0
  7. package/lib/dataFileUtils.d.ts.map +1 -0
  8. package/lib/dataFileUtils.js +91 -0
  9. package/lib/dataFileUtils.js.map +1 -0
  10. package/lib/emitUtils.d.ts +35 -0
  11. package/lib/emitUtils.d.ts.map +1 -0
  12. package/lib/emitUtils.js +107 -0
  13. package/lib/emitUtils.js.map +1 -0
  14. package/lib/gitUtils.d.ts +66 -0
  15. package/lib/gitUtils.d.ts.map +1 -0
  16. package/lib/gitUtils.js +66 -0
  17. package/lib/gitUtils.js.map +1 -0
  18. package/lib/globUtils.d.ts +39 -0
  19. package/lib/globUtils.d.ts.map +1 -0
  20. package/lib/globUtils.js +66 -0
  21. package/lib/globUtils.js.map +1 -0
  22. package/lib/hashUtils.d.ts +17 -0
  23. package/lib/hashUtils.d.ts.map +1 -0
  24. package/lib/hashUtils.js +42 -0
  25. package/lib/hashUtils.js.map +1 -0
  26. package/lib/i18nUtils.d.ts +28 -0
  27. package/lib/i18nUtils.d.ts.map +1 -0
  28. package/lib/i18nUtils.js +49 -0
  29. package/lib/i18nUtils.js.map +1 -0
  30. package/lib/index.d.ts +16 -82
  31. package/lib/index.d.ts.map +1 -0
  32. package/lib/index.js +89 -411
  33. package/lib/index.js.map +1 -0
  34. package/lib/jsUtils.d.ts +45 -0
  35. package/lib/jsUtils.d.ts.map +1 -0
  36. package/lib/jsUtils.js +94 -0
  37. package/lib/jsUtils.js.map +1 -0
  38. package/lib/markdownLinks.d.ts +49 -5
  39. package/lib/markdownLinks.d.ts.map +1 -0
  40. package/lib/markdownLinks.js +48 -13
  41. package/lib/markdownLinks.js.map +1 -0
  42. package/lib/markdownUtils.d.ts +112 -0
  43. package/lib/markdownUtils.d.ts.map +1 -0
  44. package/lib/markdownUtils.js +271 -0
  45. package/lib/markdownUtils.js.map +1 -0
  46. package/lib/pathUtils.d.ts +52 -0
  47. package/lib/pathUtils.d.ts.map +1 -0
  48. package/lib/pathUtils.js +113 -0
  49. package/lib/pathUtils.js.map +1 -0
  50. package/lib/slugger.d.ts +24 -0
  51. package/lib/slugger.d.ts.map +1 -0
  52. package/lib/slugger.js +23 -0
  53. package/lib/slugger.js.map +1 -0
  54. package/lib/tags.d.ts +48 -0
  55. package/lib/tags.d.ts.map +1 -0
  56. package/lib/tags.js +91 -0
  57. package/lib/tags.js.map +1 -0
  58. package/lib/urlUtils.d.ts +66 -0
  59. package/lib/urlUtils.d.ts.map +1 -0
  60. package/lib/urlUtils.js +208 -0
  61. package/lib/urlUtils.js.map +1 -0
  62. package/lib/webpackUtils.d.ts +35 -0
  63. package/lib/webpackUtils.d.ts.map +1 -0
  64. package/lib/webpackUtils.js +116 -0
  65. package/lib/webpackUtils.js.map +1 -0
  66. package/package.json +20 -10
  67. package/src/constants.ts +90 -0
  68. package/src/dataFileUtils.ts +122 -0
  69. package/src/deps.d.ts +10 -0
  70. package/src/emitUtils.ts +130 -0
  71. package/src/gitUtils.ts +153 -0
  72. package/src/globUtils.ts +80 -0
  73. package/src/hashUtils.ts +38 -0
  74. package/src/i18nUtils.ts +67 -0
  75. package/src/index.ts +94 -521
  76. package/src/jsUtils.ts +102 -0
  77. package/src/markdownLinks.ts +89 -30
  78. package/src/markdownUtils.ts +354 -0
  79. package/src/pathUtils.ts +121 -0
  80. package/src/slugger.ts +36 -0
  81. package/src/tags.ts +117 -0
  82. package/src/urlUtils.ts +235 -0
  83. package/src/webpackUtils.ts +154 -0
  84. package/lib/.tsbuildinfo +0 -3972
  85. package/lib/codeTranslationsUtils.d.ts +0 -11
  86. package/lib/codeTranslationsUtils.js +0 -50
  87. package/lib/escapePath.d.ts +0 -17
  88. package/lib/escapePath.js +0 -25
  89. package/lib/markdownParser.d.ts +0 -28
  90. package/lib/markdownParser.js +0 -132
  91. package/lib/posixPath.d.ts +0 -14
  92. package/lib/posixPath.js +0 -28
  93. package/src/__tests__/__fixtures__/defaultCodeTranslations/en.json +0 -4
  94. package/src/__tests__/__fixtures__/defaultCodeTranslations/fr-FR.json +0 -5
  95. package/src/__tests__/__fixtures__/defaultCodeTranslations/fr.json +0 -4
  96. package/src/__tests__/__snapshots__/index.test.ts.snap +0 -8
  97. package/src/__tests__/codeTranslationsUtils.test.ts +0 -112
  98. package/src/__tests__/escapePath.test.ts +0 -25
  99. package/src/__tests__/index.test.ts +0 -681
  100. package/src/__tests__/markdownParser.test.ts +0 -772
  101. package/src/__tests__/posixPath.test.ts +0 -25
  102. package/src/codeTranslationsUtils.ts +0 -56
  103. package/src/escapePath.ts +0 -23
  104. package/src/markdownParser.ts +0 -177
  105. package/src/posixPath.ts +0 -27
  106. package/tsconfig.json +0 -9
package/lib/jsUtils.js ADDED
@@ -0,0 +1,94 @@
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.reportMessage = exports.findAsyncSequential = exports.mapAsyncSequential = exports.removePrefix = exports.removeSuffix = void 0;
10
+ const tslib_1 = require("tslib");
11
+ const logger_1 = tslib_1.__importDefault(require("@docusaurus/logger"));
12
+ /** Removes a given string suffix from `str`. */
13
+ function removeSuffix(str, suffix) {
14
+ if (suffix === '') {
15
+ // str.slice(0, 0) is ""
16
+ return str;
17
+ }
18
+ return str.endsWith(suffix) ? str.slice(0, -suffix.length) : str;
19
+ }
20
+ exports.removeSuffix = removeSuffix;
21
+ /** Removes a given string prefix from `str`. */
22
+ function removePrefix(str, prefix) {
23
+ return str.startsWith(prefix) ? str.slice(prefix.length) : str;
24
+ }
25
+ exports.removePrefix = removePrefix;
26
+ /**
27
+ * `Array#map` for async operations where order matters.
28
+ * @param array The array to traverse.
29
+ * @param action An async action to be performed on every array item. Will be
30
+ * awaited before working on the next.
31
+ * @returns The list of results returned from every `action(item)`
32
+ */
33
+ async function mapAsyncSequential(array, action) {
34
+ const results = [];
35
+ for (const t of array) {
36
+ const result = await action(t);
37
+ results.push(result);
38
+ }
39
+ return results;
40
+ }
41
+ exports.mapAsyncSequential = mapAsyncSequential;
42
+ /**
43
+ * `Array#find` for async operations where order matters.
44
+ * @param array The array to traverse.
45
+ * @param predicate An async predicate to be called on every array item. Should
46
+ * return a boolean indicating whether the currently element should be returned.
47
+ * @returns The function immediately returns the first item on which `predicate`
48
+ * returns `true`, or `undefined` if none matches the predicate.
49
+ */
50
+ async function findAsyncSequential(array, predicate) {
51
+ for (const t of array) {
52
+ if (await predicate(t)) {
53
+ return t;
54
+ }
55
+ }
56
+ return undefined;
57
+ }
58
+ exports.findAsyncSequential = findAsyncSequential;
59
+ /**
60
+ * Takes a message and reports it according to the severity that the user wants.
61
+ *
62
+ * - `ignore`: completely no-op
63
+ * - `log`: uses the `INFO` log level
64
+ * - `warn`: uses the `WARN` log level
65
+ * - `error`: uses the `ERROR` log level
66
+ * - `throw`: aborts the process, throws the error.
67
+ *
68
+ * Since the logger doesn't have logging level filters yet, these severities
69
+ * mostly just differ by their colors.
70
+ *
71
+ * @throws In addition to throwing when `reportingSeverity === "throw"`, this
72
+ * function also throws if `reportingSeverity` is not one of the above.
73
+ */
74
+ function reportMessage(message, reportingSeverity) {
75
+ switch (reportingSeverity) {
76
+ case 'ignore':
77
+ break;
78
+ case 'log':
79
+ logger_1.default.info(message);
80
+ break;
81
+ case 'warn':
82
+ logger_1.default.warn(message);
83
+ break;
84
+ case 'error':
85
+ logger_1.default.error(message);
86
+ break;
87
+ case 'throw':
88
+ throw new Error(message);
89
+ default:
90
+ throw new Error(`Unexpected "reportingSeverity" value: ${reportingSeverity}.`);
91
+ }
92
+ }
93
+ exports.reportMessage = reportMessage;
94
+ //# sourceMappingURL=jsUtils.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"jsUtils.js","sourceRoot":"","sources":["../src/jsUtils.ts"],"names":[],"mappings":";AAAA;;;;;GAKG;;;;AAGH,wEAAwC;AAExC,gDAAgD;AAChD,SAAgB,YAAY,CAAC,GAAW,EAAE,MAAc;IACtD,IAAI,MAAM,KAAK,EAAE,EAAE;QACjB,wBAAwB;QACxB,OAAO,GAAG,CAAC;KACZ;IACD,OAAO,GAAG,CAAC,QAAQ,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC,GAAG,CAAC,KAAK,CAAC,CAAC,EAAE,CAAC,MAAM,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC,GAAG,CAAC;AACnE,CAAC;AAND,oCAMC;AAED,gDAAgD;AAChD,SAAgB,YAAY,CAAC,GAAW,EAAE,MAAc;IACtD,OAAO,GAAG,CAAC,UAAU,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC,GAAG,CAAC,KAAK,CAAC,MAAM,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC,GAAG,CAAC;AACjE,CAAC;AAFD,oCAEC;AAED;;;;;;GAMG;AACI,KAAK,UAAU,kBAAkB,CACtC,KAAU,EACV,MAA4B;IAE5B,MAAM,OAAO,GAAQ,EAAE,CAAC;IACxB,KAAK,MAAM,CAAC,IAAI,KAAK,EAAE;QACrB,MAAM,MAAM,GAAG,MAAM,MAAM,CAAC,CAAC,CAAC,CAAC;QAC/B,OAAO,CAAC,IAAI,CAAC,MAAM,CAAC,CAAC;KACtB;IACD,OAAO,OAAO,CAAC;AACjB,CAAC;AAVD,gDAUC;AAED;;;;;;;GAOG;AACI,KAAK,UAAU,mBAAmB,CACvC,KAAU,EACV,SAAqC;IAErC,KAAK,MAAM,CAAC,IAAI,KAAK,EAAE;QACrB,IAAI,MAAM,SAAS,CAAC,CAAC,CAAC,EAAE;YACtB,OAAO,CAAC,CAAC;SACV;KACF;IACD,OAAO,SAAS,CAAC;AACnB,CAAC;AAVD,kDAUC;AAED;;;;;;;;;;;;;;GAcG;AACH,SAAgB,aAAa,CAC3B,OAAe,EACf,iBAAoC;IAEpC,QAAQ,iBAAiB,EAAE;QACzB,KAAK,QAAQ;YACX,MAAM;QACR,KAAK,KAAK;YACR,gBAAM,CAAC,IAAI,CAAC,OAAO,CAAC,CAAC;YACrB,MAAM;QACR,KAAK,MAAM;YACT,gBAAM,CAAC,IAAI,CAAC,OAAO,CAAC,CAAC;YACrB,MAAM;QACR,KAAK,OAAO;YACV,gBAAM,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC;YACtB,MAAM;QACR,KAAK,OAAO;YACV,MAAM,IAAI,KAAK,CAAC,OAAO,CAAC,CAAC;QAC3B;YACE,MAAM,IAAI,KAAK,CACb,yCAAyC,iBAAiB,GAAG,CAC9D,CAAC;KACL;AACH,CAAC;AAvBD,sCAuBC"}
@@ -4,24 +4,68 @@
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
+ /**
8
+ * Content plugins have a base path and a localized path to source content from.
9
+ * We will look into the localized path in priority.
10
+ */
7
11
  export declare type ContentPaths = {
12
+ /**
13
+ * The absolute path to the base content directory, like `"<siteDir>/docs"`.
14
+ */
8
15
  contentPath: string;
16
+ /**
17
+ * The absolute path to the localized content directory, like
18
+ * `"<siteDir>/i18n/zh-Hans/plugin-content-docs"`.
19
+ */
9
20
  contentPathLocalized: string;
10
21
  };
22
+ /** Data structure representing each broken Markdown link to be reported. */
11
23
  export declare type BrokenMarkdownLink<T extends ContentPaths> = {
24
+ /** Absolute path to the file containing this link. */
12
25
  filePath: string;
26
+ /**
27
+ * This is generic because it may contain extra metadata like version name,
28
+ * which the reporter can provide for context.
29
+ */
13
30
  contentPaths: T;
31
+ /**
32
+ * The content of the link, like `"./brokenFile.md"`
33
+ */
14
34
  link: string;
15
35
  };
16
- export declare type ReplaceMarkdownLinksParams<T extends ContentPaths> = {
36
+ /**
37
+ * Takes a Markdown file and replaces relative file references with their URL
38
+ * counterparts, e.g. `[link](./intro.md)` => `[link](/docs/intro)`, preserving
39
+ * everything else.
40
+ *
41
+ * This method uses best effort to find a matching file. The file reference can
42
+ * be relative to the directory of the current file (most likely) or any of the
43
+ * content paths (so `/tutorials/intro.md` can be resolved as
44
+ * `<siteDir>/docs/tutorials/intro.md`). Links that contain the `http(s):` or
45
+ * `@site/` prefix will always be ignored.
46
+ */
47
+ export declare function replaceMarkdownLinks<T extends ContentPaths>({ siteDir, fileString, filePath, contentPaths, sourceToPermalink, }: {
48
+ /** Absolute path to the site directory, used to resolve aliased paths. */
17
49
  siteDir: string;
50
+ /** The Markdown file content to be processed. */
18
51
  fileString: string;
52
+ /** Absolute path to the current file containing `fileString`. */
19
53
  filePath: string;
54
+ /** The content paths which the file reference may live in. */
20
55
  contentPaths: T;
21
- sourceToPermalink: Record<string, string>;
22
- };
23
- export declare type ReplaceMarkdownLinksReturn<T extends ContentPaths> = {
56
+ /**
57
+ * A map from source paths to their URLs. Source paths are `@site` aliased.
58
+ */
59
+ sourceToPermalink: {
60
+ [aliasedPath: string]: string;
61
+ };
62
+ }): {
63
+ /**
64
+ * The content with all Markdown file references replaced with their URLs.
65
+ * Unresolved links are left as-is.
66
+ */
24
67
  newContent: string;
68
+ /** The list of broken links, */
25
69
  brokenMarkdownLinks: BrokenMarkdownLink<T>[];
26
70
  };
27
- export declare function replaceMarkdownLinks<T extends ContentPaths>({ siteDir, fileString, filePath, contentPaths, sourceToPermalink, }: ReplaceMarkdownLinksParams<T>): ReplaceMarkdownLinksReturn<T>;
71
+ //# sourceMappingURL=markdownLinks.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"markdownLinks.d.ts","sourceRoot":"","sources":["../src/markdownLinks.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AAMH;;;GAGG;AACH,oBAAY,YAAY,GAAG;IACzB;;OAEG;IACH,WAAW,EAAE,MAAM,CAAC;IACpB;;;OAGG;IACH,oBAAoB,EAAE,MAAM,CAAC;CAC9B,CAAC;AAEF,4EAA4E;AAC5E,oBAAY,kBAAkB,CAAC,CAAC,SAAS,YAAY,IAAI;IACvD,sDAAsD;IACtD,QAAQ,EAAE,MAAM,CAAC;IACjB;;;OAGG;IACH,YAAY,EAAE,CAAC,CAAC;IAChB;;OAEG;IACH,IAAI,EAAE,MAAM,CAAC;CACd,CAAC;AAEF;;;;;;;;;;GAUG;AACH,wBAAgB,oBAAoB,CAAC,CAAC,SAAS,YAAY,EAAE,EAC3D,OAAO,EACP,UAAU,EACV,QAAQ,EACR,YAAY,EACZ,iBAAiB,GAClB,EAAE;IACD,0EAA0E;IAC1E,OAAO,EAAE,MAAM,CAAC;IAChB,iDAAiD;IACjD,UAAU,EAAE,MAAM,CAAC;IACnB,iEAAiE;IACjE,QAAQ,EAAE,MAAM,CAAC;IACjB,8DAA8D;IAC9D,YAAY,EAAE,CAAC,CAAC;IAChB;;OAEG;IACH,iBAAiB,EAAE;QAAC,CAAC,WAAW,EAAE,MAAM,GAAG,MAAM,CAAA;KAAC,CAAC;CACpD,GAAG;IACF;;;OAGG;IACH,UAAU,EAAE,MAAM,CAAC;IACnB,iCAAiC;IACjC,mBAAmB,EAAE,kBAAkB,CAAC,CAAC,CAAC,EAAE,CAAC;CAC9C,CAuEA"}
@@ -7,35 +7,69 @@
7
7
  */
8
8
  Object.defineProperty(exports, "__esModule", { value: true });
9
9
  exports.replaceMarkdownLinks = void 0;
10
- const url_1 = require("url");
11
- const index_1 = require("./index");
10
+ const tslib_1 = require("tslib");
11
+ const path_1 = tslib_1.__importDefault(require("path"));
12
+ const dataFileUtils_1 = require("./dataFileUtils");
13
+ const pathUtils_1 = require("./pathUtils");
14
+ /**
15
+ * Takes a Markdown file and replaces relative file references with their URL
16
+ * counterparts, e.g. `[link](./intro.md)` => `[link](/docs/intro)`, preserving
17
+ * everything else.
18
+ *
19
+ * This method uses best effort to find a matching file. The file reference can
20
+ * be relative to the directory of the current file (most likely) or any of the
21
+ * content paths (so `/tutorials/intro.md` can be resolved as
22
+ * `<siteDir>/docs/tutorials/intro.md`). Links that contain the `http(s):` or
23
+ * `@site/` prefix will always be ignored.
24
+ */
12
25
  function replaceMarkdownLinks({ siteDir, fileString, filePath, contentPaths, sourceToPermalink, }) {
13
- const { contentPath, contentPathLocalized } = contentPaths;
14
26
  const brokenMarkdownLinks = [];
15
27
  // Replace internal markdown linking (except in fenced blocks).
16
28
  let fencedBlock = false;
29
+ let lastCodeFence = '';
17
30
  const lines = fileString.split('\n').map((line) => {
18
31
  if (line.trim().startsWith('```')) {
19
- fencedBlock = !fencedBlock;
32
+ const codeFence = line.trim().match(/^`+/)[0];
33
+ if (!fencedBlock) {
34
+ fencedBlock = true;
35
+ lastCodeFence = codeFence;
36
+ // If we are in a ````-fenced block, all ``` would be plain text instead
37
+ // of fences
38
+ }
39
+ else if (codeFence.length >= lastCodeFence.length) {
40
+ fencedBlock = false;
41
+ }
20
42
  }
21
43
  if (fencedBlock) {
22
44
  return line;
23
45
  }
24
46
  let modifiedLine = line;
25
47
  // Replace inline-style links or reference-style links e.g:
26
- // This is [Document 1](doc1.md) -> we replace this doc1.md with correct link
27
- // [doc1]: doc1.md -> we replace this doc1.md with correct link
28
- const mdRegex = /(?:(?:\]\()|(?:\]:\s?))(?!https)([^'")\]\s>]+\.mdx?)/g;
48
+ // This is [Document 1](doc1.md)
49
+ // [doc1]: doc1.md
50
+ const mdRegex = /(?:\]\(|\]:\s*)(?!https?:\/\/|@site\/)(?<filename>[^'")\]\s>]+\.mdx?)/g;
29
51
  let mdMatch = mdRegex.exec(modifiedLine);
30
52
  while (mdMatch !== null) {
31
53
  // Replace it to correct html link.
32
- const mdLink = mdMatch[1];
33
- const aliasedSource = (source) => index_1.aliasedSitePath(source, siteDir);
34
- const permalink = sourceToPermalink[aliasedSource(url_1.resolve(filePath, mdLink))] ||
35
- sourceToPermalink[aliasedSource(`${contentPathLocalized}/${mdLink}`)] ||
36
- sourceToPermalink[aliasedSource(`${contentPath}/${mdLink}`)];
54
+ const mdLink = mdMatch.groups.filename;
55
+ const sourcesToTry = [
56
+ path_1.default.dirname(filePath),
57
+ ...(0, dataFileUtils_1.getContentPathList)(contentPaths),
58
+ ].map((p) => path_1.default.join(p, decodeURIComponent(mdLink)));
59
+ const aliasedSourceMatch = sourcesToTry
60
+ .map((source) => (0, pathUtils_1.aliasedSitePath)(source, siteDir))
61
+ .find((source) => sourceToPermalink[source]);
62
+ const permalink = aliasedSourceMatch
63
+ ? sourceToPermalink[aliasedSourceMatch]
64
+ : undefined;
37
65
  if (permalink) {
38
- modifiedLine = modifiedLine.replace(mdLink, permalink);
66
+ // MDX won't be happy if the permalink contains a space, we need to
67
+ // convert it to %20
68
+ const encodedPermalink = permalink
69
+ .split('/')
70
+ .map((part) => part.replace(/\s/g, '%20'))
71
+ .join('/');
72
+ modifiedLine = modifiedLine.replace(mdLink, encodedPermalink);
39
73
  }
40
74
  else {
41
75
  const brokenMarkdownLink = {
@@ -53,3 +87,4 @@ function replaceMarkdownLinks({ siteDir, fileString, filePath, contentPaths, sou
53
87
  return { newContent, brokenMarkdownLinks };
54
88
  }
55
89
  exports.replaceMarkdownLinks = replaceMarkdownLinks;
90
+ //# sourceMappingURL=markdownLinks.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"markdownLinks.js","sourceRoot":"","sources":["../src/markdownLinks.ts"],"names":[],"mappings":"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"}
@@ -0,0 +1,112 @@
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 { type SluggerOptions } from './slugger';
8
+ /**
9
+ * Parses custom ID from a heading. The ID must be composed of letters,
10
+ * underscores, and dashes only.
11
+ *
12
+ * @param heading e.g. `## Some heading {#some-heading}` where the last
13
+ * character must be `}` for the ID to be recognized
14
+ */
15
+ export declare function parseMarkdownHeadingId(heading: string): {
16
+ /**
17
+ * The heading content sans the ID part, right-trimmed. e.g. `## Some heading`
18
+ */
19
+ text: string;
20
+ /** The heading ID. e.g. `some-heading` */
21
+ id?: string;
22
+ };
23
+ /**
24
+ * Creates an excerpt of a Markdown file. This function will:
25
+ *
26
+ * - Ignore h1 headings (setext or atx)
27
+ * - Ignore import/export
28
+ * - Ignore code blocks
29
+ *
30
+ * And for the first contentful line, it will strip away most Markdown
31
+ * syntax, including HTML tags, emphasis, links (keeping the text), etc.
32
+ */
33
+ export declare function createExcerpt(fileString: string): string | undefined;
34
+ /**
35
+ * Takes a raw Markdown file content, and parses the front matter using
36
+ * gray-matter. Worth noting that gray-matter accepts TOML and other markup
37
+ * languages as well.
38
+ *
39
+ * @throws Throws when gray-matter throws. e.g.:
40
+ * ```md
41
+ * ---
42
+ * foo: : bar
43
+ * ---
44
+ * ```
45
+ */
46
+ export declare function parseFrontMatter(markdownFileContent: string): {
47
+ /** Front matter as parsed by gray-matter. */
48
+ frontMatter: {
49
+ [key: string]: unknown;
50
+ };
51
+ /** The remaining content, trimmed. */
52
+ content: string;
53
+ };
54
+ declare type ParseMarkdownContentTitleOptions = {
55
+ /**
56
+ * If `true`, the matching title will be removed from the returned content.
57
+ * We can promise that at least one empty line will be left between the
58
+ * content before and after, but you shouldn't make too much assumption
59
+ * about what's left.
60
+ */
61
+ removeContentTitle?: boolean;
62
+ };
63
+ /**
64
+ * Takes the raw Markdown content, without front matter, and tries to find an h1
65
+ * title (setext or atx) to be used as metadata.
66
+ *
67
+ * It only searches until the first contentful paragraph, ignoring import/export
68
+ * declarations.
69
+ *
70
+ * It will try to convert markdown to reasonable text, but won't be best effort,
71
+ * since it's only used as a fallback when `frontMatter.title` is not provided.
72
+ * For now, we just unwrap inline code (``# `config.js` `` => `config.js`).
73
+ */
74
+ export declare function parseMarkdownContentTitle(contentUntrimmed: string, options?: ParseMarkdownContentTitleOptions): {
75
+ /** The content, optionally without the content title. */
76
+ content: string;
77
+ /** The title, trimmed and without the `#`. */
78
+ contentTitle: string | undefined;
79
+ };
80
+ /**
81
+ * Makes a full-round parse.
82
+ *
83
+ * @throws Throws when `parseFrontMatter` throws, usually because of invalid
84
+ * syntax.
85
+ */
86
+ export declare function parseMarkdownString(markdownFileContent: string, options?: ParseMarkdownContentTitleOptions): {
87
+ /** @see {@link parseFrontMatter} */
88
+ frontMatter: {
89
+ [key: string]: unknown;
90
+ };
91
+ /** @see {@link parseMarkdownContentTitle} */
92
+ contentTitle: string | undefined;
93
+ /** @see {@link createExcerpt} */
94
+ excerpt: string | undefined;
95
+ /**
96
+ * Content without front matter and (optionally) without title, depending on
97
+ * the `removeContentTitle` option.
98
+ */
99
+ content: string;
100
+ };
101
+ export declare type WriteHeadingIDOptions = SluggerOptions & {
102
+ /** Overwrite existing heading IDs. */
103
+ overwrite?: boolean;
104
+ };
105
+ /**
106
+ * Takes Markdown content, returns new content with heading IDs written.
107
+ * Respects existing IDs (unless `overwrite=true`) and never generates colliding
108
+ * IDs (through the slugger).
109
+ */
110
+ export declare function writeMarkdownHeadingId(content: string, options?: WriteHeadingIDOptions): string;
111
+ export {};
112
+ //# sourceMappingURL=markdownUtils.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"markdownUtils.d.ts","sourceRoot":"","sources":["../src/markdownUtils.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AAIH,OAAO,EAA8B,KAAK,cAAc,EAAC,MAAM,WAAW,CAAC;AAM3E;;;;;;GAMG;AACH,wBAAgB,sBAAsB,CAAC,OAAO,EAAE,MAAM,GAAG;IACvD;;OAEG;IACH,IAAI,EAAE,MAAM,CAAC;IACb,0CAA0C;IAC1C,EAAE,CAAC,EAAE,MAAM,CAAC;CACb,CAUA;AAID;;;;;;;;;GASG;AACH,wBAAgB,aAAa,CAAC,UAAU,EAAE,MAAM,GAAG,MAAM,GAAG,SAAS,CA4EpE;AAED;;;;;;;;;;;GAWG;AACH,wBAAgB,gBAAgB,CAAC,mBAAmB,EAAE,MAAM,GAAG;IAC7D,6CAA6C;IAC7C,WAAW,EAAE;QAAC,CAAC,GAAG,EAAE,MAAM,GAAG,OAAO,CAAA;KAAC,CAAC;IACtC,sCAAsC;IACtC,OAAO,EAAE,MAAM,CAAC;CACjB,CAMA;AASD,aAAK,gCAAgC,GAAG;IACtC;;;;;OAKG;IACH,kBAAkB,CAAC,EAAE,OAAO,CAAC;CAC9B,CAAC;AAEF;;;;;;;;;;GAUG;AACH,wBAAgB,yBAAyB,CACvC,gBAAgB,EAAE,MAAM,EACxB,OAAO,CAAC,EAAE,gCAAgC,GACzC;IACD,yDAAyD;IACzD,OAAO,EAAE,MAAM,CAAC;IAChB,8CAA8C;IAC9C,YAAY,EAAE,MAAM,GAAG,SAAS,CAAC;CAClC,CAyCA;AAED;;;;;GAKG;AACH,wBAAgB,mBAAmB,CACjC,mBAAmB,EAAE,MAAM,EAC3B,OAAO,CAAC,EAAE,gCAAgC,GACzC;IACD,oCAAoC;IACpC,WAAW,EAAE;QAAC,CAAC,GAAG,EAAE,MAAM,GAAG,OAAO,CAAA;KAAC,CAAC;IACtC,6CAA6C;IAC7C,YAAY,EAAE,MAAM,GAAG,SAAS,CAAC;IACjC,iCAAiC;IACjC,OAAO,EAAE,MAAM,GAAG,SAAS,CAAC;IAC5B;;;OAGG;IACH,OAAO,EAAE,MAAM,CAAC;CACjB,CAuBA;AAyBD,oBAAY,qBAAqB,GAAG,cAAc,GAAG;IACnD,sCAAsC;IACtC,SAAS,CAAC,EAAE,OAAO,CAAC;CACrB,CAAC;AAEF;;;;GAIG;AACH,wBAAgB,sBAAsB,CACpC,OAAO,EAAE,MAAM,EACf,OAAO,GAAE,qBAA+D,GACvE,MAAM,CAoCR"}
@@ -0,0 +1,271 @@
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.writeMarkdownHeadingId = exports.parseMarkdownString = exports.parseMarkdownContentTitle = exports.parseFrontMatter = exports.createExcerpt = exports.parseMarkdownHeadingId = void 0;
10
+ const tslib_1 = require("tslib");
11
+ const logger_1 = tslib_1.__importDefault(require("@docusaurus/logger"));
12
+ const gray_matter_1 = tslib_1.__importDefault(require("gray-matter"));
13
+ const slugger_1 = require("./slugger");
14
+ // Some utilities for parsing Markdown content. These things are only used on
15
+ // server-side when we infer metadata like `title` and `description` from the
16
+ // content. Most parsing is still done in MDX through the mdx-loader.
17
+ /**
18
+ * Parses custom ID from a heading. The ID must be composed of letters,
19
+ * underscores, and dashes only.
20
+ *
21
+ * @param heading e.g. `## Some heading {#some-heading}` where the last
22
+ * character must be `}` for the ID to be recognized
23
+ */
24
+ function parseMarkdownHeadingId(heading) {
25
+ const customHeadingIdRegex = /\s*\{#(?<id>[\w-]+)\}$/;
26
+ const matches = customHeadingIdRegex.exec(heading);
27
+ if (matches) {
28
+ return {
29
+ text: heading.replace(matches[0], ''),
30
+ id: matches.groups.id,
31
+ };
32
+ }
33
+ return { text: heading, id: undefined };
34
+ }
35
+ exports.parseMarkdownHeadingId = parseMarkdownHeadingId;
36
+ // TODO: Find a better way to do so, possibly by compiling the Markdown content,
37
+ // stripping out HTML tags and obtaining the first line.
38
+ /**
39
+ * Creates an excerpt of a Markdown file. This function will:
40
+ *
41
+ * - Ignore h1 headings (setext or atx)
42
+ * - Ignore import/export
43
+ * - Ignore code blocks
44
+ *
45
+ * And for the first contentful line, it will strip away most Markdown
46
+ * syntax, including HTML tags, emphasis, links (keeping the text), etc.
47
+ */
48
+ function createExcerpt(fileString) {
49
+ const fileLines = fileString
50
+ .trimStart()
51
+ // Remove Markdown alternate title
52
+ .replace(/^[^\n]*\n[=]+/g, '')
53
+ .split('\n');
54
+ let inCode = false;
55
+ let inImport = false;
56
+ let lastCodeFence = '';
57
+ for (const fileLine of fileLines) {
58
+ if (fileLine === '' && inImport) {
59
+ inImport = false;
60
+ }
61
+ // Skip empty line.
62
+ if (!fileLine.trim()) {
63
+ continue;
64
+ }
65
+ // Skip import/export declaration.
66
+ if ((/^(?:import|export)\s.*/.test(fileLine) || inImport) && !inCode) {
67
+ inImport = true;
68
+ continue;
69
+ }
70
+ // Skip code block line.
71
+ if (fileLine.trim().startsWith('```')) {
72
+ const codeFence = fileLine.trim().match(/^`+/)[0];
73
+ if (!inCode) {
74
+ inCode = true;
75
+ lastCodeFence = codeFence;
76
+ // If we are in a ````-fenced block, all ``` would be plain text instead
77
+ // of fences
78
+ }
79
+ else if (codeFence.length >= lastCodeFence.length) {
80
+ inCode = false;
81
+ }
82
+ continue;
83
+ }
84
+ else if (inCode) {
85
+ continue;
86
+ }
87
+ const cleanedLine = fileLine
88
+ // Remove HTML tags.
89
+ .replace(/<[^>]*>/g, '')
90
+ // Remove Title headers
91
+ .replace(/^#[^#]+#?/gm, '')
92
+ // Remove Markdown + ATX-style headers
93
+ .replace(/^#{1,6}\s*(?<text>[^#]*)\s*#{0,6}/gm, '$1')
94
+ // Remove emphasis.
95
+ .replace(/(?<opening>[*_]{1,3})(?<text>.*?)\1/g, '$2')
96
+ // Remove strikethroughs.
97
+ .replace(/~~(?<text>\S.*\S)~~/g, '$1')
98
+ // Remove images.
99
+ .replace(/!\[(?<alt>.*?)\][[(].*?[\])]/g, '$1')
100
+ // Remove footnotes.
101
+ .replace(/\[\^.+?\](?:: .*$)?/g, '')
102
+ // Remove inline links.
103
+ .replace(/\[(?<alt>.*?)\][[(].*?[\])]/g, '$1')
104
+ // Remove inline code.
105
+ .replace(/`(?<text>.+?)`/g, '$1')
106
+ // Remove blockquotes.
107
+ .replace(/^\s{0,3}>\s?/g, '')
108
+ // Remove admonition definition.
109
+ .replace(/:::.*/, '')
110
+ // Remove Emoji names within colons include preceding whitespace.
111
+ .replace(/\s?:(?:::|[^:\n])+:/g, '')
112
+ // Remove custom Markdown heading id.
113
+ .replace(/\{#*[\w-]+\}/, '')
114
+ .trim();
115
+ if (cleanedLine) {
116
+ return cleanedLine;
117
+ }
118
+ }
119
+ return undefined;
120
+ }
121
+ exports.createExcerpt = createExcerpt;
122
+ /**
123
+ * Takes a raw Markdown file content, and parses the front matter using
124
+ * gray-matter. Worth noting that gray-matter accepts TOML and other markup
125
+ * languages as well.
126
+ *
127
+ * @throws Throws when gray-matter throws. e.g.:
128
+ * ```md
129
+ * ---
130
+ * foo: : bar
131
+ * ---
132
+ * ```
133
+ */
134
+ function parseFrontMatter(markdownFileContent) {
135
+ const { data, content } = (0, gray_matter_1.default)(markdownFileContent);
136
+ return {
137
+ frontMatter: data,
138
+ content: content.trim(),
139
+ };
140
+ }
141
+ exports.parseFrontMatter = parseFrontMatter;
142
+ function toTextContentTitle(contentTitle) {
143
+ if (contentTitle.startsWith('`') && contentTitle.endsWith('`')) {
144
+ return contentTitle.substring(1, contentTitle.length - 1);
145
+ }
146
+ return contentTitle;
147
+ }
148
+ /**
149
+ * Takes the raw Markdown content, without front matter, and tries to find an h1
150
+ * title (setext or atx) to be used as metadata.
151
+ *
152
+ * It only searches until the first contentful paragraph, ignoring import/export
153
+ * declarations.
154
+ *
155
+ * It will try to convert markdown to reasonable text, but won't be best effort,
156
+ * since it's only used as a fallback when `frontMatter.title` is not provided.
157
+ * For now, we just unwrap inline code (``# `config.js` `` => `config.js`).
158
+ */
159
+ function parseMarkdownContentTitle(contentUntrimmed, options) {
160
+ const removeContentTitleOption = options?.removeContentTitle ?? false;
161
+ const content = contentUntrimmed.trim();
162
+ // We only need to detect import statements that will be parsed by MDX as
163
+ // `import` nodes, as broken syntax can't render anyways. That means any block
164
+ // that has `import` at the very beginning and surrounded by empty lines.
165
+ const contentWithoutImport = content
166
+ .replace(/^(?:import\s(?:.|\n(?!\n))*\n{2,})*/, '')
167
+ .trim();
168
+ const regularTitleMatch = /^#[ \t]+(?<title>[^ \t].*)(?:\n|$)/.exec(contentWithoutImport);
169
+ const alternateTitleMatch = /^(?<title>.*)\n=+(?:\n|$)/.exec(contentWithoutImport);
170
+ const titleMatch = regularTitleMatch ?? alternateTitleMatch;
171
+ if (!titleMatch) {
172
+ return { content, contentTitle: undefined };
173
+ }
174
+ const newContent = removeContentTitleOption
175
+ ? content.replace(titleMatch[0], '')
176
+ : content;
177
+ if (regularTitleMatch) {
178
+ return {
179
+ content: newContent.trim(),
180
+ contentTitle: toTextContentTitle(regularTitleMatch
181
+ .groups.title.trim()
182
+ .replace(/\s*(?:\{#*[\w-]+\}|#+)$/, '')).trim(),
183
+ };
184
+ }
185
+ return {
186
+ content: newContent.trim(),
187
+ contentTitle: toTextContentTitle(alternateTitleMatch.groups.title.trim().replace(/\s*=+$/, '')).trim(),
188
+ };
189
+ }
190
+ exports.parseMarkdownContentTitle = parseMarkdownContentTitle;
191
+ /**
192
+ * Makes a full-round parse.
193
+ *
194
+ * @throws Throws when `parseFrontMatter` throws, usually because of invalid
195
+ * syntax.
196
+ */
197
+ function parseMarkdownString(markdownFileContent, options) {
198
+ try {
199
+ const { frontMatter, content: contentWithoutFrontMatter } = parseFrontMatter(markdownFileContent);
200
+ const { content, contentTitle } = parseMarkdownContentTitle(contentWithoutFrontMatter, options);
201
+ const excerpt = createExcerpt(content);
202
+ return {
203
+ frontMatter,
204
+ content,
205
+ contentTitle,
206
+ excerpt,
207
+ };
208
+ }
209
+ catch (err) {
210
+ logger_1.default.error(`Error while parsing Markdown front matter.
211
+ This can happen if you use special characters in front matter values (try using double quotes around that value).`);
212
+ throw err;
213
+ }
214
+ }
215
+ exports.parseMarkdownString = parseMarkdownString;
216
+ function unwrapMarkdownLinks(line) {
217
+ return line.replace(/\[(?<alt>[^\]]+)\]\([^)]+\)/g, (match, p1) => p1);
218
+ }
219
+ function addHeadingId(line, slugger, maintainCase) {
220
+ let headingLevel = 0;
221
+ while (line.charAt(headingLevel) === '#') {
222
+ headingLevel += 1;
223
+ }
224
+ const headingText = line.slice(headingLevel).trimEnd();
225
+ const headingHashes = line.slice(0, headingLevel);
226
+ const slug = slugger.slug(unwrapMarkdownLinks(headingText).trim(), {
227
+ maintainCase,
228
+ });
229
+ return `${headingHashes}${headingText} {#${slug}}`;
230
+ }
231
+ /**
232
+ * Takes Markdown content, returns new content with heading IDs written.
233
+ * Respects existing IDs (unless `overwrite=true`) and never generates colliding
234
+ * IDs (through the slugger).
235
+ */
236
+ function writeMarkdownHeadingId(content, options = { maintainCase: false, overwrite: false }) {
237
+ const { maintainCase = false, overwrite = false } = options;
238
+ const lines = content.split('\n');
239
+ const slugger = (0, slugger_1.createSlugger)();
240
+ // If we can't overwrite existing slugs, make sure other headings don't
241
+ // generate colliding slugs by first marking these slugs as occupied
242
+ if (!overwrite) {
243
+ lines.forEach((line) => {
244
+ const parsedHeading = parseMarkdownHeadingId(line);
245
+ if (parsedHeading.id) {
246
+ slugger.slug(parsedHeading.id);
247
+ }
248
+ });
249
+ }
250
+ let inCode = false;
251
+ return lines
252
+ .map((line) => {
253
+ if (line.startsWith('```')) {
254
+ inCode = !inCode;
255
+ return line;
256
+ }
257
+ // Ignore h1 headings, as we don't create anchor links for those
258
+ if (inCode || !line.startsWith('##')) {
259
+ return line;
260
+ }
261
+ const parsedHeading = parseMarkdownHeadingId(line);
262
+ // Do not process if id is already there
263
+ if (parsedHeading.id && !overwrite) {
264
+ return line;
265
+ }
266
+ return addHeadingId(parsedHeading.text, slugger, maintainCase);
267
+ })
268
+ .join('\n');
269
+ }
270
+ exports.writeMarkdownHeadingId = writeMarkdownHeadingId;
271
+ //# sourceMappingURL=markdownUtils.js.map