@docusaurus/utils 2.0.0-beta.15a2b59f9 → 2.0.0-beta.17

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 (104) hide show
  1. package/lib/constants.d.ts +20 -0
  2. package/lib/constants.d.ts.map +1 -0
  3. package/lib/constants.js +26 -0
  4. package/lib/constants.js.map +1 -0
  5. package/lib/dataFileUtils.d.ts +24 -0
  6. package/lib/dataFileUtils.d.ts.map +1 -0
  7. package/lib/dataFileUtils.js +65 -0
  8. package/lib/dataFileUtils.js.map +1 -0
  9. package/lib/emitUtils.d.ts +23 -0
  10. package/lib/emitUtils.d.ts.map +1 -0
  11. package/lib/emitUtils.js +90 -0
  12. package/lib/emitUtils.js.map +1 -0
  13. package/lib/gitUtils.d.ts +17 -0
  14. package/lib/gitUtils.d.ts.map +1 -0
  15. package/lib/gitUtils.js +63 -0
  16. package/lib/gitUtils.js.map +1 -0
  17. package/lib/globUtils.d.ts +12 -0
  18. package/lib/globUtils.d.ts.map +1 -0
  19. package/lib/globUtils.js +48 -0
  20. package/lib/globUtils.js.map +1 -0
  21. package/lib/hashUtils.d.ts +1 -0
  22. package/lib/hashUtils.d.ts.map +1 -0
  23. package/lib/hashUtils.js +7 -5
  24. package/lib/hashUtils.js.map +1 -0
  25. package/lib/i18nUtils.d.ts +17 -0
  26. package/lib/i18nUtils.d.ts.map +1 -0
  27. package/lib/i18nUtils.js +40 -0
  28. package/lib/i18nUtils.js.map +1 -0
  29. package/lib/index.d.ts +15 -75
  30. package/lib/index.d.ts.map +1 -0
  31. package/lib/index.js +84 -395
  32. package/lib/index.js.map +1 -0
  33. package/lib/jsUtils.d.ts +17 -0
  34. package/lib/jsUtils.d.ts.map +1 -0
  35. package/lib/jsUtils.js +72 -0
  36. package/lib/jsUtils.js.map +1 -0
  37. package/lib/markdownLinks.d.ts +1 -0
  38. package/lib/markdownLinks.d.ts.map +1 -0
  39. package/lib/markdownLinks.js +36 -11
  40. package/lib/markdownLinks.js.map +1 -0
  41. package/lib/markdownParser.d.ts +5 -3
  42. package/lib/markdownParser.d.ts.map +1 -0
  43. package/lib/markdownParser.js +72 -52
  44. package/lib/markdownParser.js.map +1 -0
  45. package/lib/pathUtils.d.ts +44 -0
  46. package/lib/pathUtils.d.ts.map +1 -0
  47. package/lib/pathUtils.js +88 -10
  48. package/lib/pathUtils.js.map +1 -0
  49. package/lib/slugger.d.ts +14 -0
  50. package/lib/slugger.d.ts.map +1 -0
  51. package/lib/slugger.js +19 -0
  52. package/lib/slugger.js.map +1 -0
  53. package/lib/tags.d.ts +27 -0
  54. package/lib/tags.d.ts.map +1 -0
  55. package/lib/tags.js +76 -0
  56. package/lib/tags.js.map +1 -0
  57. package/lib/urlUtils.d.ts +20 -0
  58. package/lib/urlUtils.d.ts.map +1 -0
  59. package/lib/urlUtils.js +136 -0
  60. package/lib/urlUtils.js.map +1 -0
  61. package/lib/webpackUtils.d.ts +30 -0
  62. package/lib/webpackUtils.d.ts.map +1 -0
  63. package/lib/webpackUtils.js +112 -0
  64. package/lib/webpackUtils.js.map +1 -0
  65. package/package.json +20 -10
  66. package/src/constants.ts +38 -0
  67. package/src/dataFileUtils.ts +90 -0
  68. package/src/deps.d.ts +10 -0
  69. package/src/emitUtils.ts +113 -0
  70. package/src/gitUtils.ts +93 -0
  71. package/src/globUtils.ts +64 -0
  72. package/src/hashUtils.ts +3 -3
  73. package/src/i18nUtils.ts +58 -0
  74. package/src/index.ts +87 -502
  75. package/src/jsUtils.ts +88 -0
  76. package/src/markdownLinks.ts +35 -13
  77. package/src/markdownParser.ts +76 -57
  78. package/src/pathUtils.ts +87 -8
  79. package/src/slugger.ts +24 -0
  80. package/src/tags.ts +105 -0
  81. package/src/urlUtils.ts +149 -0
  82. package/src/webpackUtils.ts +146 -0
  83. package/lib/.tsbuildinfo +0 -1
  84. package/lib/codeTranslationsUtils.d.ts +0 -11
  85. package/lib/codeTranslationsUtils.js +0 -50
  86. package/lib/escapePath.d.ts +0 -17
  87. package/lib/escapePath.js +0 -25
  88. package/lib/posixPath.d.ts +0 -14
  89. package/lib/posixPath.js +0 -28
  90. package/src/__tests__/__fixtures__/defaultCodeTranslations/en.json +0 -4
  91. package/src/__tests__/__fixtures__/defaultCodeTranslations/fr-FR.json +0 -5
  92. package/src/__tests__/__fixtures__/defaultCodeTranslations/fr.json +0 -4
  93. package/src/__tests__/__snapshots__/index.test.ts.snap +0 -8
  94. package/src/__tests__/codeTranslationsUtils.test.ts +0 -112
  95. package/src/__tests__/escapePath.test.ts +0 -25
  96. package/src/__tests__/hashUtils.test.ts +0 -51
  97. package/src/__tests__/index.test.ts +0 -631
  98. package/src/__tests__/markdownParser.test.ts +0 -817
  99. package/src/__tests__/pathUtils.test.ts +0 -63
  100. package/src/__tests__/posixPath.test.ts +0 -25
  101. package/src/codeTranslationsUtils.ts +0 -56
  102. package/src/escapePath.ts +0 -23
  103. package/src/posixPath.ts +0 -27
  104. package/tsconfig.json +0 -9
package/lib/jsUtils.js ADDED
@@ -0,0 +1,72 @@
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.getElementsAround = exports.removePrefix = exports.removeSuffix = void 0;
10
+ const tslib_1 = require("tslib");
11
+ const logger_1 = tslib_1.__importDefault(require("@docusaurus/logger"));
12
+ function removeSuffix(str, suffix) {
13
+ if (suffix === '') {
14
+ return str; // always returns "" otherwise!
15
+ }
16
+ return str.endsWith(suffix) ? str.slice(0, -suffix.length) : str;
17
+ }
18
+ exports.removeSuffix = removeSuffix;
19
+ function removePrefix(str, prefix) {
20
+ return str.startsWith(prefix) ? str.slice(prefix.length) : str;
21
+ }
22
+ exports.removePrefix = removePrefix;
23
+ function getElementsAround(array, aroundIndex) {
24
+ const min = 0;
25
+ const max = array.length - 1;
26
+ if (aroundIndex < min || aroundIndex > max) {
27
+ throw new Error(`Valid "aroundIndex" for array (of size ${array.length}) are between ${min} and ${max}, but you provided ${aroundIndex}.`);
28
+ }
29
+ const previous = aroundIndex === min ? undefined : array[aroundIndex - 1];
30
+ const next = aroundIndex === max ? undefined : array[aroundIndex + 1];
31
+ return { previous, next };
32
+ }
33
+ exports.getElementsAround = getElementsAround;
34
+ async function mapAsyncSequential(array, action) {
35
+ const results = [];
36
+ for (const t of array) {
37
+ const result = await action(t);
38
+ results.push(result);
39
+ }
40
+ return results;
41
+ }
42
+ exports.mapAsyncSequential = mapAsyncSequential;
43
+ async function findAsyncSequential(array, predicate) {
44
+ for (const t of array) {
45
+ if (await predicate(t)) {
46
+ return t;
47
+ }
48
+ }
49
+ return undefined;
50
+ }
51
+ exports.findAsyncSequential = findAsyncSequential;
52
+ function reportMessage(message, reportingSeverity) {
53
+ switch (reportingSeverity) {
54
+ case 'ignore':
55
+ break;
56
+ case 'log':
57
+ logger_1.default.info(message);
58
+ break;
59
+ case 'warn':
60
+ logger_1.default.warn(message);
61
+ break;
62
+ case 'error':
63
+ logger_1.default.error(message);
64
+ break;
65
+ case 'throw':
66
+ throw new Error(message);
67
+ default:
68
+ throw new Error(`Unexpected "reportingSeverity" value: ${reportingSeverity}.`);
69
+ }
70
+ }
71
+ exports.reportMessage = reportMessage;
72
+ //# 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,SAAgB,YAAY,CAAC,GAAW,EAAE,MAAc;IACtD,IAAI,MAAM,KAAK,EAAE,EAAE;QACjB,OAAO,GAAG,CAAC,CAAC,+BAA+B;KAC5C;IACD,OAAO,GAAG,CAAC,QAAQ,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC,GAAG,CAAC,KAAK,C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O,CAAC;AACjB,CAAC;AAVD,gDAUC;AAEM,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,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"}
@@ -25,3 +25,4 @@ export declare type ReplaceMarkdownLinksReturn<T extends ContentPaths> = {
25
25
  brokenMarkdownLinks: BrokenMarkdownLink<T>[];
26
26
  };
27
27
  export declare function replaceMarkdownLinks<T extends ContentPaths>({ siteDir, fileString, filePath, contentPaths, sourceToPermalink, }: ReplaceMarkdownLinksParams<T>): ReplaceMarkdownLinksReturn<T>;
28
+ //# sourceMappingURL=markdownLinks.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"markdownLinks.d.ts","sourceRoot":"","sources":["../src/markdownLinks.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AAKH,oBAAY,YAAY,GAAG;IACzB,WAAW,EAAE,MAAM,CAAC;IACpB,oBAAoB,EAAE,MAAM,CAAC;CAC9B,CAAC;AAEF,oBAAY,kBAAkB,CAAC,CAAC,SAAS,YAAY,IAAI;IACvD,QAAQ,EAAE,MAAM,CAAC;IACjB,YAAY,EAAE,CAAC,CAAC;IAChB,IAAI,EAAE,MAAM,CAAC;CACd,CAAC;AAEF,oBAAY,0BAA0B,CAAC,CAAC,SAAS,YAAY,IAAI;IAC/D,OAAO,EAAE,MAAM,CAAC;IAChB,UAAU,EAAE,MAAM,CAAC;IACnB,QAAQ,EAAE,MAAM,CAAC;IACjB,YAAY,EAAE,CAAC,CAAC;IAChB,iBAAiB,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;CAC3C,CAAC;AAEF,oBAAY,0BAA0B,CAAC,CAAC,SAAS,YAAY,IAAI;IAC/D,UAAU,EAAE,MAAM,CAAC;IACnB,mBAAmB,EAAE,kBAAkB,CAAC,CAAC,CAAC,EAAE,CAAC;CAC9C,CAAC;AAEF,wBAAgB,oBAAoB,CAAC,CAAC,SAAS,YAAY,EAAE,EAC3D,OAAO,EACP,UAAU,EACV,QAAQ,EACR,YAAY,EACZ,iBAAiB,GAClB,EAAE,0BAA0B,CAAC,CAAC,CAAC,GAAG,0BAA0B,CAAC,CAAC,CAAC,CA0E/D"}
@@ -7,35 +7,59 @@
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 pathUtils_1 = require("./pathUtils");
12
13
  function replaceMarkdownLinks({ siteDir, fileString, filePath, contentPaths, sourceToPermalink, }) {
13
14
  const { contentPath, contentPathLocalized } = contentPaths;
14
15
  const brokenMarkdownLinks = [];
15
16
  // Replace internal markdown linking (except in fenced blocks).
16
17
  let fencedBlock = false;
18
+ let lastCodeFence = '';
17
19
  const lines = fileString.split('\n').map((line) => {
18
20
  if (line.trim().startsWith('```')) {
19
- fencedBlock = !fencedBlock;
21
+ if (!fencedBlock) {
22
+ fencedBlock = true;
23
+ [lastCodeFence] = line.trim().match(/^`+/);
24
+ // If we are in a ````-fenced block, all ``` would be plain text instead
25
+ // of fences
26
+ }
27
+ else if (line.trim().match(/^`+/)[0].length >= lastCodeFence.length) {
28
+ fencedBlock = false;
29
+ }
20
30
  }
21
31
  if (fencedBlock) {
22
32
  return line;
23
33
  }
24
34
  let modifiedLine = line;
25
35
  // 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
36
+ // This is [Document 1](doc1.md) -> we replace this doc1.md with correct
37
+ // ink
27
38
  // [doc1]: doc1.md -> we replace this doc1.md with correct link
28
- const mdRegex = /(?:(?:\]\()|(?:\]:\s?))(?!https)([^'")\]\s>]+\.mdx?)/g;
39
+ const mdRegex = /(?:(?:\]\()|(?:\]:\s*))(?!https?:\/\/|@site\/)(?<filename>[^'")\]\s>]+\.mdx?)/g;
29
40
  let mdMatch = mdRegex.exec(modifiedLine);
30
41
  while (mdMatch !== null) {
31
42
  // 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}`)];
43
+ const mdLink = mdMatch.groups.filename;
44
+ const sourcesToTry = [
45
+ path_1.default.resolve(path_1.default.dirname(filePath), decodeURIComponent(mdLink)),
46
+ `${contentPathLocalized}/${decodeURIComponent(mdLink)}`,
47
+ `${contentPath}/${decodeURIComponent(mdLink)}`,
48
+ ];
49
+ const aliasedSourceMatch = sourcesToTry
50
+ .map((source) => (0, pathUtils_1.aliasedSitePath)(source, siteDir))
51
+ .find((source) => sourceToPermalink[source]);
52
+ const permalink = aliasedSourceMatch
53
+ ? sourceToPermalink[aliasedSourceMatch]
54
+ : undefined;
37
55
  if (permalink) {
38
- modifiedLine = modifiedLine.replace(mdLink, permalink);
56
+ // MDX won't be happy if the permalink contains a space, we need to
57
+ // convert it to %20
58
+ const encodedPermalink = permalink
59
+ .split('/')
60
+ .map((part) => part.replace(/\s/g, '%20'))
61
+ .join('/');
62
+ modifiedLine = modifiedLine.replace(mdLink, encodedPermalink);
39
63
  }
40
64
  else {
41
65
  const brokenMarkdownLink = {
@@ -53,3 +77,4 @@ function replaceMarkdownLinks({ siteDir, fileString, filePath, contentPaths, sou
53
77
  return { newContent, brokenMarkdownLinks };
54
78
  }
55
79
  exports.replaceMarkdownLinks = replaceMarkdownLinks;
80
+ //# sourceMappingURL=markdownLinks.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"markdownLinks.js","sourceRoot":"","sources":["../src/markdownLinks.ts"],"names":[],"mappings":";AAAA;;;;;GAKG;;;;AAEH,wDAAwB;AACxB,2CAA4C;AA0B5C,SAAgB,oBAAoB,CAAyB,EAC3D,OAAO,EACP,UAAU,EACV,QAAQ,EACR,YAAY,EACZ,iBAAiB,GACa;IAC9B,MAAM,EAAC,WAAW,EAAE,oBAAoB,EAAC,GAAG,YAAY,CAAC;IAEzD,MAAM,mBAAmB,GAA4B,EAAE,CAAC;IAExD,+DAA+D;IAC/D,IAAI,WAAW,GAAG,KAAK,CAAC;IACxB,IAAI,aAAa,GAAG,EAAE,CAAC;IACvB,MAAM,KAAK,GAAG,UAAU,CAAC,KAAK,CAAC,IAAI,CAAC,CAAC,GAAG,CAAC,CAAC,IAAI,EAAE,EAAE;QAChD,IAAI,IAAI,CAAC,IAAI,EAAE,CAAC,UAAU,CAAC,KAAK,CAAC,EAAE;YACjC,IAAI,CAAC,WAAW,EAAE;gBAChB,WAAW,GAAG,IAAI,CAAC;gBACnB,CAAC,aAAa,CAAC,GAAG,IAAI,CAAC,IAAI,EAAE,CAAC,KAAK,CAAC,KAAK,CAAE,CAAC;gBAC5C,wEAAwE;gBACxE,YA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,CAAC,GAAG,CAAC;qBACV,GAAG,CAAC,CAAC,IAAI,EAAE,EAAE,CAAC,IAAI,CAAC,OAAO,CAAC,KAAK,EAAE,KAAK,CAAC,CAAC;qBACzC,IAAI,CAAC,GAAG,CAAC,CAAC;gBACb,YAAY,GAAG,YAAY,CAAC,OAAO,CAAC,MAAM,EAAE,gBAAgB,CAAC,CAAC;aAC/D;iBAAM;gBACL,MAAM,kBAAkB,GAA0B;oBAChD,YAAY;oBACZ,QAAQ;oBACR,IAAI,EAAE,MAAM;iBACb,CAAC;gBAEF,mBAAmB,CAAC,IAAI,CAAC,kBAAkB,CAAC,CAAC;aAC9C;YACD,OAAO,GAAG,OAAO,CAAC,IAAI,CAAC,YAAY,CAAC,CAAC;SACtC;QACD,OAAO,YAAY,CAAC;IACtB,CAAC,CAAC,CAAC;IAEH,MAAM,UAAU,GAAG,KAAK,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;IAEpC,OAAO,EAAC,UAAU,EAAE,mBAAmB,EAAC,CAAC;AAC3C,CAAC;AAhFD,oDAgFC"}
@@ -4,6 +4,10 @@
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
+ export declare function parseMarkdownHeadingId(heading: string): {
8
+ text: string;
9
+ id?: string;
10
+ };
7
11
  export declare function createExcerpt(fileString: string): string | undefined;
8
12
  export declare function parseFrontMatter(markdownFileContent: string): {
9
13
  frontMatter: Record<string, unknown>;
@@ -24,7 +28,5 @@ declare type ParsedMarkdown = {
24
28
  export declare function parseMarkdownString(markdownFileContent: string, options?: {
25
29
  removeContentTitle?: boolean;
26
30
  }): ParsedMarkdown;
27
- export declare function parseMarkdownFile(source: string, options?: {
28
- removeContentTitle?: boolean;
29
- }): Promise<ParsedMarkdown>;
30
31
  export {};
32
+ //# sourceMappingURL=markdownParser.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"markdownParser.d.ts","sourceRoot":"","sources":["../src/markdownParser.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AAOH,wBAAgB,sBAAsB,CAAC,OAAO,EAAE,MAAM,GAAG;IACvD,IAAI,EAAE,MAAM,CAAC;IACb,EAAE,CAAC,EAAE,MAAM,CAAC;CACb,CAUA;AAKD,wBAAgB,aAAa,CAAC,UAAU,EAAE,MAAM,GAAG,MAAM,GAAG,SAAS,CAyEpE;AAED,wBAAgB,gBAAgB,CAAC,mBAAmB,EAAE,MAAM,GAAG;IAC7D,WAAW,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;IACrC,OAAO,EAAE,MAAM,CAAC;CACjB,CAMA;AAcD,wBAAgB,yBAAyB,CACvC,gBAAgB,EAAE,MAAM,EACxB,OAAO,CAAC,EAAE;IAAC,kBAAkB,CAAC,EAAE,OAAO,CAAA;CAAC,GACvC;IAAC,OAAO,EAAE,MAAM,CAAC;IAAC,YAAY,EAAE,MAAM,GAAG,SAAS,CAAA;CAAC,CAkCrD;AAED,aAAK,cAAc,GAAG;IACpB,WAAW,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;IACrC,OAAO,EAAE,MAAM,CAAC;IAChB,YAAY,EAAE,MAAM,GAAG,SAAS,CAAC;IACjC,OAAO,EAAE,MAAM,GAAG,SAAS,CAAC;CAC7B,CAAC;AAEF,wBAAgB,mBAAmB,CACjC,mBAAmB,EAAE,MAAM,EAC3B,OAAO,CAAC,EAAE;IAAC,kBAAkB,CAAC,EAAE,OAAO,CAAA;CAAC,GACvC,cAAc,CAuBhB"}
@@ -6,11 +6,24 @@
6
6
  * LICENSE file in the root directory of this source tree.
7
7
  */
8
8
  Object.defineProperty(exports, "__esModule", { value: true });
9
- exports.parseMarkdownFile = exports.parseMarkdownString = exports.parseMarkdownContentTitle = exports.parseFrontMatter = exports.createExcerpt = void 0;
9
+ exports.parseMarkdownString = exports.parseMarkdownContentTitle = exports.parseFrontMatter = exports.createExcerpt = exports.parseMarkdownHeadingId = void 0;
10
10
  const tslib_1 = require("tslib");
11
- const chalk_1 = tslib_1.__importDefault(require("chalk"));
12
- const fs_extra_1 = tslib_1.__importDefault(require("fs-extra"));
11
+ const logger_1 = tslib_1.__importDefault(require("@docusaurus/logger"));
13
12
  const gray_matter_1 = tslib_1.__importDefault(require("gray-matter"));
13
+ // Input: ## Some heading {#some-heading}
14
+ // Output: {text: "## Some heading", id: "some-heading"}
15
+ function parseMarkdownHeadingId(heading) {
16
+ const customHeadingIdRegex = /^(?<text>.*?)\s*\{#(?<id>[\w-]+)\}$/;
17
+ const matches = customHeadingIdRegex.exec(heading);
18
+ if (matches) {
19
+ return {
20
+ text: matches.groups.text,
21
+ id: matches.groups.id,
22
+ };
23
+ }
24
+ return { text: heading, id: undefined };
25
+ }
26
+ exports.parseMarkdownHeadingId = parseMarkdownHeadingId;
14
27
  // Hacky way of stripping out import statements from the excerpt
15
28
  // TODO: Find a better way to do so, possibly by compiling the Markdown content,
16
29
  // stripping out HTML tags and obtaining the first line.
@@ -20,40 +33,59 @@ function createExcerpt(fileString) {
20
33
  // Remove Markdown alternate title
21
34
  .replace(/^[^\n]*\n[=]+/g, '')
22
35
  .split('\n');
36
+ let inCode = false;
37
+ let lastCodeFence = '';
23
38
  /* eslint-disable no-continue */
24
- // eslint-disable-next-line no-restricted-syntax
25
39
  for (const fileLine of fileLines) {
26
40
  // Skip empty line.
27
41
  if (!fileLine.trim()) {
28
42
  continue;
29
43
  }
30
44
  // Skip import/export declaration.
31
- if (/^\s*?import\s.*(from.*)?;?|export\s.*{.*};?/.test(fileLine)) {
45
+ if (/^(?:import|export)\s.*/.test(fileLine)) {
46
+ continue;
47
+ }
48
+ // Skip code block line.
49
+ if (fileLine.trim().startsWith('```')) {
50
+ if (!inCode) {
51
+ inCode = true;
52
+ [lastCodeFence] = fileLine.trim().match(/^`+/);
53
+ // If we are in a ````-fenced block, all ``` would be plain text instead
54
+ // of fences
55
+ }
56
+ else if (fileLine.trim().match(/^`+/)[0].length >= lastCodeFence.length) {
57
+ inCode = false;
58
+ }
59
+ continue;
60
+ }
61
+ else if (inCode) {
32
62
  continue;
33
63
  }
34
64
  const cleanedLine = fileLine
35
65
  // Remove HTML tags.
36
66
  .replace(/<[^>]*>/g, '')
37
67
  // Remove Title headers
38
- .replace(/^#\s*([^#]*)\s*#?/gm, '')
68
+ .replace(/^#\s*[^#]*\s*#?/gm, '')
39
69
  // Remove Markdown + ATX-style headers
40
- .replace(/^#{1,6}\s*([^#]*)\s*(#{1,6})?/gm, '$1')
41
- // Remove emphasis and strikethroughs.
42
- .replace(/([*_~]{1,3})(\S.*?\S{0,1})\1/g, '$2')
70
+ .replace(/^#{1,6}\s*(?<text>[^#]*)\s*(?:#{1,6})?/gm, '$1')
71
+ // Remove emphasis.
72
+ .replace(/(?<opening>[*_]{1,3})(?<text>.*?)\1/g, '$2')
73
+ // Remove strikethroughs.
74
+ .replace(/~~(?<text>\S.*\S)~~/g, '$1')
43
75
  // Remove images.
44
- .replace(/!\[(.*?)\][[(].*?[\])]/g, '$1')
76
+ .replace(/!\[(?<alt>.*?)\][[(].*?[\])]/g, '$1')
45
77
  // Remove footnotes.
46
- .replace(/\[\^.+?\](: .*?$)?/g, '')
78
+ .replace(/\[\^.+?\](?:: .*?$)?/g, '')
47
79
  // Remove inline links.
48
- .replace(/\[(.*?)\][[(].*?[\])]/g, '$1')
80
+ .replace(/\[(?<alt>.*?)\][[(].*?[\])]/g, '$1')
49
81
  // Remove inline code.
50
- .replace(/`(.+?)`/g, '$1')
82
+ .replace(/`(?<text>.+?)`/g, '$1')
51
83
  // Remove blockquotes.
52
84
  .replace(/^\s{0,3}>\s?/g, '')
53
85
  // Remove admonition definition.
54
- .replace(/(:{3}.*)/, '')
86
+ .replace(/:::.*/, '')
55
87
  // Remove Emoji names within colons include preceding whitespace.
56
- .replace(/\s?(:(::|[^:\n])+:)/g, '')
88
+ .replace(/\s?:(?:::|[^:\n])+:/g, '')
57
89
  // Remove custom Markdown heading id.
58
90
  .replace(/{#*[\w-]+}/, '')
59
91
  .trim();
@@ -65,17 +97,18 @@ function createExcerpt(fileString) {
65
97
  }
66
98
  exports.createExcerpt = createExcerpt;
67
99
  function parseFrontMatter(markdownFileContent) {
68
- var _a;
69
- const { data, content } = gray_matter_1.default(markdownFileContent);
100
+ const { data, content } = (0, gray_matter_1.default)(markdownFileContent);
70
101
  return {
71
- frontMatter: data !== null && data !== void 0 ? data : {},
72
- content: (_a = content === null || content === void 0 ? void 0 : content.trim()) !== null && _a !== void 0 ? _a : '',
102
+ frontMatter: data,
103
+ content: content.trim(),
73
104
  };
74
105
  }
75
106
  exports.parseFrontMatter = parseFrontMatter;
76
- // Try to convert markdown heading as text
77
- // Does not need to be perfect, it is only used as a fallback when frontMatter.title is not provided
78
- // For now, we just unwrap possible inline code blocks (# `config.js`)
107
+ /**
108
+ * Try to convert markdown heading to text. Does not need to be perfect, it is
109
+ * only used as a fallback when frontMatter.title is not provided. For now, we
110
+ * just unwrap possible inline code blocks (# `config.js`)
111
+ */
79
112
  function toTextContentTitle(contentTitle) {
80
113
  if (contentTitle.startsWith('`') && contentTitle.endsWith('`')) {
81
114
  return contentTitle.substring(1, contentTitle.length - 1);
@@ -83,30 +116,26 @@ function toTextContentTitle(contentTitle) {
83
116
  return contentTitle;
84
117
  }
85
118
  function parseMarkdownContentTitle(contentUntrimmed, options) {
86
- var _a, _b;
87
- const removeContentTitleOption = (_a = options === null || options === void 0 ? void 0 : options.removeContentTitle) !== null && _a !== void 0 ? _a : false;
119
+ const removeContentTitleOption = options?.removeContentTitle ?? false;
88
120
  const content = contentUntrimmed.trim();
89
- const IMPORT_STATEMENT = /import\s+(([\w*{}\s\n,]+)from\s+)?["'\s]([@\w/_.-]+)["'\s];?|\n/
90
- .source;
91
- const REGULAR_TITLE = /(?<pattern>#\s*(?<title>[^#\n{]*)+[ \t]*(?<suffix>({#*[\w-]+})|#)?\n*?)/
121
+ const IMPORT_STATEMENT = /import\s+(?:[\w*{}\s\n,]+from\s+)?["'\s][@\w/_.-]+["'\s];?|\n/.source;
122
+ const REGULAR_TITLE = /(?<pattern>#\s*(?<title>[^#\n{]*)+[ \t]*(?<suffix>(?:{#*[\w-]+})|#)?\n*?)/
92
123
  .source;
93
124
  const ALTERNATE_TITLE = /(?<pattern>\s*(?<title>[^\n]*)\s*\n[=]+)/.source;
94
125
  const regularTitleMatch = new RegExp(`^(?:${IMPORT_STATEMENT})*?${REGULAR_TITLE}`, 'g').exec(content);
95
126
  const alternateTitleMatch = new RegExp(`^(?:${IMPORT_STATEMENT})*?${ALTERNATE_TITLE}`, 'g').exec(content);
96
- const titleMatch = regularTitleMatch !== null && regularTitleMatch !== void 0 ? regularTitleMatch : alternateTitleMatch;
97
- const { pattern, title } = (_b = titleMatch === null || titleMatch === void 0 ? void 0 : titleMatch.groups) !== null && _b !== void 0 ? _b : {};
127
+ const titleMatch = regularTitleMatch ?? alternateTitleMatch;
128
+ const { pattern, title } = titleMatch?.groups ?? {};
98
129
  if (!pattern || !title) {
99
130
  return { content, contentTitle: undefined };
100
131
  }
101
- else {
102
- const newContent = removeContentTitleOption
103
- ? content.replace(pattern, '')
104
- : content;
105
- return {
106
- content: newContent.trim(),
107
- contentTitle: toTextContentTitle(title.trim()).trim(),
108
- };
109
- }
132
+ const newContent = removeContentTitleOption
133
+ ? content.replace(pattern, '')
134
+ : content;
135
+ return {
136
+ content: newContent.trim(),
137
+ contentTitle: toTextContentTitle(title.trim()).trim(),
138
+ };
110
139
  }
111
140
  exports.parseMarkdownContentTitle = parseMarkdownContentTitle;
112
141
  function parseMarkdownString(markdownFileContent, options) {
@@ -121,20 +150,11 @@ function parseMarkdownString(markdownFileContent, options) {
121
150
  excerpt,
122
151
  };
123
152
  }
124
- catch (e) {
125
- console.error(chalk_1.default.red(`Error while parsing Markdown frontmatter.
126
- This can happen if you use special characters in frontmatter values (try using double quotes around that value).`));
127
- throw e;
153
+ catch (err) {
154
+ logger_1.default.error(`Error while parsing Markdown front matter.
155
+ This can happen if you use special characters in front matter values (try using double quotes around that value).`);
156
+ throw err;
128
157
  }
129
158
  }
130
159
  exports.parseMarkdownString = parseMarkdownString;
131
- async function parseMarkdownFile(source, options) {
132
- const markdownString = await fs_extra_1.default.readFile(source, 'utf-8');
133
- try {
134
- return parseMarkdownString(markdownString, options);
135
- }
136
- catch (e) {
137
- throw new Error(`Error while parsing Markdown file ${source}: "${e.message}".`);
138
- }
139
- }
140
- exports.parseMarkdownFile = parseMarkdownFile;
160
+ //# sourceMappingURL=markdownParser.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"markdownParser.js","sourceRoot":"","sources":["../src/markdownParser.ts"],"names":[],"mappings":";AAAA;;;;;GAKG;;;;AAEH,wEAAwC;AACxC,sEAAiC;AAEjC,yCAAyC;AACzC,wDAAwD;AACxD,SAAgB,sBAAsB,CAAC,OAAe;IAIpD,MAAM,oBAAoB,GAAG,qCAAqC,CAAC;IACnE,MAAM,OAAO,GAAG,oBAAoB,CAAC,IAAI,CAAC,OAAO,CAAC,CAAC;IACnD,IAAI,OAAO,EAAE;QACX,OAAO;YACL,IAAI,EAAE,OAAO,CAAC,MAAO,CAAC,IAAI;YAC1B,EAAE,EAAE,OAAO,CAAC,MAAO,CAAC,EAAE;SACvB,CAAC;KACH;IACD,OAAO,EAAC,IAAI,EAAE,OAAO,EAAE,EAAE,EAAE,SAAS,EAAC,CAAC;AACxC,CAAC;AAbD,wDAaC;AAED,gEAAgE;AAChE,gFAAgF;AAChF,wDAAwD;AACxD,SAAgB,aAAa,CAAC,UAAkB;IAC9C,MAAM,SAAS,GAAG,UAAU;SACzB,QAAQ,EAAE;QACX,kCAAkC;SACjC,OAAO,CAAC,gBAAgB,EAAE,EAAE,CAAC;SAC7B,KAAK,CAAC,IAAI,CAAC,CAAC;IACf,IAAI,MAAM,GAAG,KAAK,CAAC;IACnB,IAAI,aAAa,GAAG,EAAE,CAAC;IAEvB,gCAAgC;IAChC,KAAK,MAAM,QAAQ,IAAI,SAAS,EAAE;QAChC,mBAAmB;QACnB,IAAI,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CAAC;KACX;AACH,CAAC;AA1BD,kDA0BC"}
@@ -6,3 +6,47 @@
6
6
  */
7
7
  export declare const isNameTooLong: (str: string) => boolean;
8
8
  export declare const shortName: (str: string) => string;
9
+ /**
10
+ * Convert Windows backslash paths to posix style paths.
11
+ * E.g: endi\lie -> endi/lie
12
+ *
13
+ * Returns original path if the posix counterpart is not valid Windows path.
14
+ * This makes the legacy code that uses posixPath safe; but also makes it less
15
+ * useful when you actually want a path with forward slashes (e.g. for URL)
16
+ *
17
+ * Adopted from https://github.com/sindresorhus/slash/blob/main/index.js
18
+ */
19
+ export declare function posixPath(str: string): string;
20
+ /**
21
+ * When you want to display a path in a message/warning/error, it's more
22
+ * convenient to:
23
+ *
24
+ * - make it relative to `cwd()`
25
+ * - convert to posix (ie not using windows \ path separator)
26
+ *
27
+ * This way, Jest tests can run more reliably on any computer/CI on both
28
+ * Unix/Windows
29
+ * For Windows users this is not perfect (as they see / instead of \) but it's
30
+ * probably good enough
31
+ */
32
+ export declare function toMessageRelativeFilePath(filePath: string): string;
33
+ /**
34
+ * Alias filepath relative to site directory, very useful so that we
35
+ * don't expose user's site structure.
36
+ * Example: some/path/to/website/docs/foo.md -> @site/docs/foo.md
37
+ */
38
+ export declare function aliasedSitePath(filePath: string, siteDir: string): string;
39
+ /**
40
+ * When you have a path like C:\X\Y
41
+ * It is not safe to use directly when generating code
42
+ * For example, this would fail due to unescaped \:
43
+ * `<img src={require('${filePath}')} />`
44
+ * But this would work: `<img src={require('${escapePath(filePath)}')} />`
45
+ *
46
+ * posixPath can't be used in all cases, because forward slashes are only valid
47
+ * Windows paths when they don't contain non-ascii characters, and posixPath
48
+ * doesn't escape those that fail to be converted.
49
+ */
50
+ export declare function escapePath(str: string): string;
51
+ export declare function addTrailingPathSeparator(str: string): string;
52
+ //# sourceMappingURL=pathUtils.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"pathUtils.d.ts","sourceRoot":"","sources":["../src/pathUtils.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AAeH,eAAO,MAAM,aAAa,QAAS,MAAM,KAAG,OAIgC,CAAC;AAE7E,eAAO,MAAM,SAAS,QAAS,MAAM,KAAG,MAiBvC,CAAC;AAEF;;;;;;;;;GASG;AACH,wBAAgB,SAAS,CAAC,GAAG,EAAE,MAAM,GAAG,MAAM,CAY7C;AAED;;;;;;;;;;;GAWG;AACH,wBAAgB,yBAAyB,CAAC,QAAQ,EAAE,MAAM,GAAG,MAAM,CAElE;AAED;;;;GAIG;AACH,wBAAgB,eAAe,CAAC,QAAQ,EAAE,MAAM,EAAE,OAAO,EAAE,MAAM,GAAG,MAAM,CAKzE;AAED;;;;;;;;;;GAUG;AACH,wBAAgB,UAAU,CAAC,GAAG,EAAE,MAAM,GAAG,MAAM,CAK9C;AAED,wBAAgB,wBAAwB,CAAC,GAAG,EAAE,MAAM,GAAG,MAAM,CAK5D"}
package/lib/pathUtils.js CHANGED
@@ -6,23 +6,26 @@
6
6
  * LICENSE file in the root directory of this source tree.
7
7
  */
8
8
  Object.defineProperty(exports, "__esModule", { value: true });
9
- exports.shortName = exports.isNameTooLong = void 0;
9
+ exports.addTrailingPathSeparator = exports.escapePath = exports.aliasedSitePath = exports.toMessageRelativeFilePath = exports.posixPath = exports.shortName = exports.isNameTooLong = void 0;
10
+ const tslib_1 = require("tslib");
11
+ const path_1 = tslib_1.__importDefault(require("path"));
10
12
  // Based on https://github.com/gatsbyjs/gatsby/pull/21518/files
11
- // MacOS (APFS) and Windows (NTFS) filename length limit = 255 chars, Others = 255 bytes
13
+ // MacOS (APFS) and Windows (NTFS) filename length limit = 255 chars,
14
+ // Others = 255 bytes
12
15
  const MAX_PATH_SEGMENT_CHARS = 255;
13
16
  const MAX_PATH_SEGMENT_BYTES = 255;
14
17
  // Space for appending things to the string like file extensions and so on
15
18
  const SPACE_FOR_APPENDING = 10;
16
- const isMacOs = process.platform === `darwin`;
17
- const isWindows = process.platform === `win32`;
18
- const isNameTooLong = (str) => {
19
- return isMacOs || isWindows
20
- ? str.length + SPACE_FOR_APPENDING > MAX_PATH_SEGMENT_CHARS // MacOS (APFS) and Windows (NTFS) filename length limit (255 chars)
21
- : Buffer.from(str).length + SPACE_FOR_APPENDING > MAX_PATH_SEGMENT_BYTES; // Other (255 bytes)
22
- };
19
+ const isMacOs = () => process.platform === 'darwin';
20
+ const isWindows = () => process.platform === 'win32';
21
+ const isNameTooLong = (str) =>
22
+ // Not entirely correct: we can't assume FS from OS. But good enough?
23
+ isMacOs() || isWindows()
24
+ ? str.length + SPACE_FOR_APPENDING > MAX_PATH_SEGMENT_CHARS // MacOS (APFS) and Windows (NTFS) filename length limit (255 chars)
25
+ : Buffer.from(str).length + SPACE_FOR_APPENDING > MAX_PATH_SEGMENT_BYTES; // Other (255 bytes)
23
26
  exports.isNameTooLong = isNameTooLong;
24
27
  const shortName = (str) => {
25
- if (isMacOs || isWindows) {
28
+ if (isMacOs() || isWindows()) {
26
29
  const overflowingChars = str.length - MAX_PATH_SEGMENT_CHARS;
27
30
  return str.slice(0, str.length - overflowingChars - SPACE_FOR_APPENDING - 1);
28
31
  }
@@ -33,3 +36,78 @@ const shortName = (str) => {
33
36
  .toString();
34
37
  };
35
38
  exports.shortName = shortName;
39
+ /**
40
+ * Convert Windows backslash paths to posix style paths.
41
+ * E.g: endi\lie -> endi/lie
42
+ *
43
+ * Returns original path if the posix counterpart is not valid Windows path.
44
+ * This makes the legacy code that uses posixPath safe; but also makes it less
45
+ * useful when you actually want a path with forward slashes (e.g. for URL)
46
+ *
47
+ * Adopted from https://github.com/sindresorhus/slash/blob/main/index.js
48
+ */
49
+ function posixPath(str) {
50
+ const isExtendedLengthPath = /^\\\\\?\\/.test(str);
51
+ // Forward slashes are only valid Windows paths when they don't contain non-
52
+ // ascii characters.
53
+ // eslint-disable-next-line no-control-regex
54
+ const hasNonAscii = /[^\u0000-\u0080]+/.test(str);
55
+ if (isExtendedLengthPath || hasNonAscii) {
56
+ return str;
57
+ }
58
+ return str.replace(/\\/g, '/');
59
+ }
60
+ exports.posixPath = posixPath;
61
+ /**
62
+ * When you want to display a path in a message/warning/error, it's more
63
+ * convenient to:
64
+ *
65
+ * - make it relative to `cwd()`
66
+ * - convert to posix (ie not using windows \ path separator)
67
+ *
68
+ * This way, Jest tests can run more reliably on any computer/CI on both
69
+ * Unix/Windows
70
+ * For Windows users this is not perfect (as they see / instead of \) but it's
71
+ * probably good enough
72
+ */
73
+ function toMessageRelativeFilePath(filePath) {
74
+ return posixPath(path_1.default.relative(process.cwd(), filePath));
75
+ }
76
+ exports.toMessageRelativeFilePath = toMessageRelativeFilePath;
77
+ /**
78
+ * Alias filepath relative to site directory, very useful so that we
79
+ * don't expose user's site structure.
80
+ * Example: some/path/to/website/docs/foo.md -> @site/docs/foo.md
81
+ */
82
+ function aliasedSitePath(filePath, siteDir) {
83
+ const relativePath = posixPath(path_1.default.relative(siteDir, filePath));
84
+ // Cannot use path.join() as it resolves '../' and removes
85
+ // the '@site'. Let webpack loader resolve it.
86
+ return `@site/${relativePath}`;
87
+ }
88
+ exports.aliasedSitePath = aliasedSitePath;
89
+ /**
90
+ * When you have a path like C:\X\Y
91
+ * It is not safe to use directly when generating code
92
+ * For example, this would fail due to unescaped \:
93
+ * `<img src={require('${filePath}')} />`
94
+ * But this would work: `<img src={require('${escapePath(filePath)}')} />`
95
+ *
96
+ * posixPath can't be used in all cases, because forward slashes are only valid
97
+ * Windows paths when they don't contain non-ascii characters, and posixPath
98
+ * doesn't escape those that fail to be converted.
99
+ */
100
+ function escapePath(str) {
101
+ const escaped = JSON.stringify(str);
102
+ // Remove the " around the json string;
103
+ return escaped.substring(1, escaped.length - 1);
104
+ }
105
+ exports.escapePath = escapePath;
106
+ function addTrailingPathSeparator(str) {
107
+ return str.endsWith(path_1.default.sep)
108
+ ? str
109
+ : // If this is Windows, we need to change the forward slash to backward
110
+ `${str.replace(/\/$/, '')}${path_1.default.sep}`;
111
+ }
112
+ exports.addTrailingPathSeparator = addTrailingPathSeparator;
113
+ //#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AAM,GAAG,CAAC,CAAC,CAAC;AAClD,CAAC;AALD,gCAKC;AAED,SAAgB,wBAAwB,CAAC,GAAW;IAClD,OAAO,GAAG,CAAC,QAAQ,CAAC,cAAI,CAAC,GAAG,CAAC;QAC3B,CAAC,CAAC,GAAG;QACL,CAAC,CAAC,sEAAsE;YACtE,GAAG,GAAG,CAAC,OAAO,CAAC,KAAK,EAAE,EAAE,CAAC,GAAG,cAAI,CAAC,GAAG,EAAE,CAAC;AAC7C,CAAC;AALD,4DAKC"}
@@ -0,0 +1,14 @@
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
+ export declare type SluggerOptions = {
8
+ maintainCase?: boolean;
9
+ };
10
+ export declare type Slugger = {
11
+ slug: (value: string, options?: SluggerOptions) => string;
12
+ };
13
+ export declare function createSlugger(): Slugger;
14
+ //# sourceMappingURL=slugger.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"slugger.d.ts","sourceRoot":"","sources":["../src/slugger.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AAOH,oBAAY,cAAc,GAAG;IAAC,YAAY,CAAC,EAAE,OAAO,CAAA;CAAC,CAAC;AAEtD,oBAAY,OAAO,GAAG;IACpB,IAAI,EAAE,CAAC,KAAK,EAAE,MAAM,EAAE,OAAO,CAAC,EAAE,cAAc,KAAK,MAAM,CAAC;CAC3D,CAAC;AAEF,wBAAgB,aAAa,IAAI,OAAO,CAKvC"}
package/lib/slugger.js ADDED
@@ -0,0 +1,19 @@
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.createSlugger = void 0;
10
+ const tslib_1 = require("tslib");
11
+ const github_slugger_1 = tslib_1.__importDefault(require("github-slugger"));
12
+ function createSlugger() {
13
+ const githubSlugger = new github_slugger_1.default();
14
+ return {
15
+ slug: (value, options) => githubSlugger.slug(value, options?.maintainCase),
16
+ };
17
+ }
18
+ exports.createSlugger = createSlugger;
19
+ //# sourceMappingURL=slugger.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"slugger.js","sourceRoot":"","sources":["../src/slugger.ts"],"names":[],"mappings":";AAAA;;;;;GAKG;;;;AAEH,4EAA2C;AAW3C,SAAgB,aAAa;IAC3B,MAAM,aAAa,GAAG,IAAI,wBAAa,EAAE,CAAC;IAC1C,OAAO;QACL,IAAI,EAAE,CAAC,KAAK,EAAE,OAAO,EAAE,EAAE,CAAC,aAAa,CAAC,IAAI,CAAC,KAAK,EAAE,OAAO,EAAE,YAAY,CAAC;KAC3E,CAAC;AACJ,CAAC;AALD,sCAKC"}