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

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 (88) hide show
  1. package/README.md +1 -1
  2. package/lib/constants.d.ts +20 -0
  3. package/lib/constants.d.ts.map +1 -0
  4. package/lib/constants.js +27 -0
  5. package/lib/constants.js.map +1 -0
  6. package/lib/dataFileUtils.d.ts +24 -0
  7. package/lib/dataFileUtils.d.ts.map +1 -0
  8. package/lib/dataFileUtils.js +65 -0
  9. package/lib/dataFileUtils.js.map +1 -0
  10. package/lib/gitUtils.d.ts +17 -0
  11. package/lib/gitUtils.d.ts.map +1 -0
  12. package/lib/gitUtils.js +63 -0
  13. package/lib/gitUtils.js.map +1 -0
  14. package/lib/globUtils.d.ts +12 -0
  15. package/lib/globUtils.d.ts.map +1 -0
  16. package/lib/globUtils.js +48 -0
  17. package/lib/globUtils.js.map +1 -0
  18. package/lib/hashUtils.d.ts +16 -0
  19. package/lib/hashUtils.d.ts.map +1 -0
  20. package/lib/hashUtils.js +41 -0
  21. package/lib/hashUtils.js.map +1 -0
  22. package/lib/index.d.ts +30 -52
  23. package/lib/index.d.ts.map +1 -0
  24. package/lib/index.js +126 -247
  25. package/lib/index.js.map +1 -0
  26. package/lib/markdownLinks.d.ts +1 -0
  27. package/lib/markdownLinks.d.ts.map +1 -0
  28. package/lib/markdownLinks.js +36 -11
  29. package/lib/markdownLinks.js.map +1 -0
  30. package/lib/markdownParser.d.ts +7 -3
  31. package/lib/markdownParser.d.ts.map +1 -0
  32. package/lib/markdownParser.js +77 -48
  33. package/lib/markdownParser.js.map +1 -0
  34. package/lib/pathUtils.d.ts +51 -0
  35. package/lib/pathUtils.d.ts.map +1 -0
  36. package/lib/pathUtils.js +106 -0
  37. package/lib/pathUtils.js.map +1 -0
  38. package/lib/slugger.d.ts +14 -0
  39. package/lib/slugger.d.ts.map +1 -0
  40. package/lib/slugger.js +19 -0
  41. package/lib/slugger.js.map +1 -0
  42. package/lib/tags.d.ts +27 -0
  43. package/lib/tags.d.ts.map +1 -0
  44. package/lib/tags.js +77 -0
  45. package/lib/tags.js.map +1 -0
  46. package/lib/urlUtils.d.ts +9 -0
  47. package/lib/urlUtils.d.ts.map +1 -0
  48. package/lib/urlUtils.js +81 -0
  49. package/lib/urlUtils.js.map +1 -0
  50. package/lib/webpackUtils.d.ts +30 -0
  51. package/lib/webpackUtils.d.ts.map +1 -0
  52. package/lib/webpackUtils.js +112 -0
  53. package/lib/webpackUtils.js.map +1 -0
  54. package/package.json +20 -10
  55. package/src/constants.ts +38 -0
  56. package/src/dataFileUtils.ts +90 -0
  57. package/src/deps.d.ts +10 -0
  58. package/src/gitUtils.ts +93 -0
  59. package/src/globUtils.ts +64 -0
  60. package/src/hashUtils.ts +37 -0
  61. package/src/index.ts +135 -294
  62. package/src/markdownLinks.ts +35 -13
  63. package/src/markdownParser.ts +86 -62
  64. package/src/pathUtils.ts +115 -0
  65. package/src/slugger.ts +24 -0
  66. package/src/tags.ts +105 -0
  67. package/src/urlUtils.ts +96 -0
  68. package/src/webpackUtils.ts +146 -0
  69. package/lib/.tsbuildinfo +0 -3972
  70. package/lib/codeTranslationsUtils.d.ts +0 -11
  71. package/lib/codeTranslationsUtils.js +0 -50
  72. package/lib/escapePath.d.ts +0 -17
  73. package/lib/escapePath.js +0 -25
  74. package/lib/posixPath.d.ts +0 -14
  75. package/lib/posixPath.js +0 -28
  76. package/src/__tests__/__fixtures__/defaultCodeTranslations/en.json +0 -4
  77. package/src/__tests__/__fixtures__/defaultCodeTranslations/fr-FR.json +0 -5
  78. package/src/__tests__/__fixtures__/defaultCodeTranslations/fr.json +0 -4
  79. package/src/__tests__/__snapshots__/index.test.ts.snap +0 -8
  80. package/src/__tests__/codeTranslationsUtils.test.ts +0 -112
  81. package/src/__tests__/escapePath.test.ts +0 -25
  82. package/src/__tests__/index.test.ts +0 -681
  83. package/src/__tests__/markdownParser.test.ts +0 -772
  84. package/src/__tests__/posixPath.test.ts +0 -25
  85. package/src/codeTranslationsUtils.ts +0 -56
  86. package/src/escapePath.ts +0 -23
  87. package/src/posixPath.ts +0 -27
  88. package/tsconfig.json +0 -9
package/lib/index.js CHANGED
@@ -6,23 +6,76 @@
6
6
  * LICENSE file in the root directory of this source tree.
7
7
  */
8
8
  Object.defineProperty(exports, "__esModule", { value: true });
9
- exports.parseMarkdownHeadingId = exports.updateTranslationFileMessages = exports.getSwizzledComponent = exports.mergeTranslations = exports.reportMessage = exports.getFolderContainingFile = exports.findFolderContainingFile = exports.findAsyncSequential = exports.mapAsyncSequencial = exports.getPluginI18nPath = exports.getElementsAround = exports.getFilePathForRoutePath = exports.removePrefix = exports.removeSuffix = exports.removeTrailingSlash = exports.addTrailingPathSeparator = exports.addTrailingSlash = exports.addLeadingSlash = exports.resolvePathname = exports.isValidPathname = exports.getEditUrl = exports.aliasedSitePath = exports.normalizeUrl = exports.getSubFolder = exports.idx = exports.genChunkName = exports.toMessageRelativeFilePath = exports.genComponentName = exports.upperFirst = exports.docuHash = exports.simpleHash = exports.encodePath = exports.fileToPath = exports.objectWithKeySorted = exports.generate = exports.posixPath = void 0;
9
+ exports.genChunkName = exports.encodePath = exports.fileToPath = exports.generate = exports.getFolderContainingFile = exports.findFolderContainingFile = exports.getContentPathList = exports.getDataFileData = exports.getDataFilePath = exports.getFileLoaderUtils = exports.createAbsoluteFilePathMatcher = exports.createMatcher = exports.GlobExcludeDefault = exports.Globby = exports.docuHash = exports.simpleHash = exports.md5Hash = exports.escapePath = exports.aliasedSitePath = exports.toMessageRelativeFilePath = exports.posixPath = exports.shortName = exports.isNameTooLong = exports.createSlugger = exports.replaceMarkdownLinks = exports.parseMarkdownString = exports.parseMarkdownContentTitle = exports.parseFrontMatter = exports.createExcerpt = exports.parseMarkdownHeadingId = exports.groupTaggedItems = exports.normalizeFrontMatterTags = exports.normalizeFrontMatterTag = exports.getEditUrl = exports.normalizeUrl = exports.GitNotFoundError = exports.getFileCommitDate = exports.WEBPACK_URL_LOADER_LIMIT = exports.DEFAULT_PLUGIN_ID = exports.DEFAULT_PORT = exports.THEME_PATH = exports.OUTPUT_STATIC_ASSETS_DIR_NAME = exports.STATIC_DIR_NAME = exports.SRC_DIR_NAME = exports.GENERATED_FILES_DIR_NAME = exports.BABEL_CONFIG_FILE_NAME = exports.DEFAULT_CONFIG_FILE_NAME = exports.DEFAULT_BUILD_DIR_NAME = exports.NODE_MINOR_VERSION = exports.NODE_MAJOR_VERSION = void 0;
10
+ exports.updateTranslationFileMessages = exports.mergeTranslations = exports.reportMessage = exports.findAsyncSequential = exports.mapAsyncSequential = exports.readOutputHTMLFile = exports.getPluginI18nPath = exports.getElementsAround = exports.removePrefix = exports.removeSuffix = exports.removeTrailingSlash = exports.addTrailingSlash = exports.addTrailingPathSeparator = exports.addLeadingSlash = exports.resolvePathname = exports.isValidPathname = void 0;
10
11
  const tslib_1 = require("tslib");
11
- const chalk_1 = tslib_1.__importDefault(require("chalk"));
12
- const path_1 = tslib_1.__importDefault(require("path"));
12
+ const logger_1 = (0, tslib_1.__importDefault)(require("@docusaurus/logger"));
13
+ const path_1 = (0, tslib_1.__importDefault)(require("path"));
13
14
  const crypto_1 = require("crypto");
14
- const lodash_1 = require("lodash");
15
- const escape_string_regexp_1 = tslib_1.__importDefault(require("escape-string-regexp"));
16
- const fs_extra_1 = tslib_1.__importDefault(require("fs-extra"));
15
+ const lodash_1 = (0, tslib_1.__importDefault)(require("lodash"));
16
+ const fs_extra_1 = (0, tslib_1.__importDefault)(require("fs-extra"));
17
17
  const url_1 = require("url");
18
- // @ts-expect-error: no typedefs :s
19
- const resolve_pathname_1 = tslib_1.__importDefault(require("resolve-pathname"));
20
- const posixPath_1 = require("./posixPath");
21
- exports.posixPath = posixPath_1.posixPath;
22
- tslib_1.__exportStar(require("./codeTranslationsUtils"), exports);
23
- tslib_1.__exportStar(require("./markdownParser"), exports);
24
- tslib_1.__exportStar(require("./markdownLinks"), exports);
25
- tslib_1.__exportStar(require("./escapePath"), exports);
18
+ const resolve_pathname_1 = (0, tslib_1.__importDefault)(require("resolve-pathname"));
19
+ const hashUtils_1 = require("./hashUtils");
20
+ const constants_1 = require("./constants");
21
+ var constants_2 = require("./constants");
22
+ Object.defineProperty(exports, "NODE_MAJOR_VERSION", { enumerable: true, get: function () { return constants_2.NODE_MAJOR_VERSION; } });
23
+ Object.defineProperty(exports, "NODE_MINOR_VERSION", { enumerable: true, get: function () { return constants_2.NODE_MINOR_VERSION; } });
24
+ Object.defineProperty(exports, "DEFAULT_BUILD_DIR_NAME", { enumerable: true, get: function () { return constants_2.DEFAULT_BUILD_DIR_NAME; } });
25
+ Object.defineProperty(exports, "DEFAULT_CONFIG_FILE_NAME", { enumerable: true, get: function () { return constants_2.DEFAULT_CONFIG_FILE_NAME; } });
26
+ Object.defineProperty(exports, "BABEL_CONFIG_FILE_NAME", { enumerable: true, get: function () { return constants_2.BABEL_CONFIG_FILE_NAME; } });
27
+ Object.defineProperty(exports, "GENERATED_FILES_DIR_NAME", { enumerable: true, get: function () { return constants_2.GENERATED_FILES_DIR_NAME; } });
28
+ Object.defineProperty(exports, "SRC_DIR_NAME", { enumerable: true, get: function () { return constants_2.SRC_DIR_NAME; } });
29
+ Object.defineProperty(exports, "STATIC_DIR_NAME", { enumerable: true, get: function () { return constants_2.STATIC_DIR_NAME; } });
30
+ Object.defineProperty(exports, "OUTPUT_STATIC_ASSETS_DIR_NAME", { enumerable: true, get: function () { return constants_2.OUTPUT_STATIC_ASSETS_DIR_NAME; } });
31
+ Object.defineProperty(exports, "THEME_PATH", { enumerable: true, get: function () { return constants_2.THEME_PATH; } });
32
+ Object.defineProperty(exports, "DEFAULT_PORT", { enumerable: true, get: function () { return constants_2.DEFAULT_PORT; } });
33
+ Object.defineProperty(exports, "DEFAULT_PLUGIN_ID", { enumerable: true, get: function () { return constants_2.DEFAULT_PLUGIN_ID; } });
34
+ Object.defineProperty(exports, "WEBPACK_URL_LOADER_LIMIT", { enumerable: true, get: function () { return constants_2.WEBPACK_URL_LOADER_LIMIT; } });
35
+ var gitUtils_1 = require("./gitUtils");
36
+ Object.defineProperty(exports, "getFileCommitDate", { enumerable: true, get: function () { return gitUtils_1.getFileCommitDate; } });
37
+ Object.defineProperty(exports, "GitNotFoundError", { enumerable: true, get: function () { return gitUtils_1.GitNotFoundError; } });
38
+ var urlUtils_1 = require("./urlUtils");
39
+ Object.defineProperty(exports, "normalizeUrl", { enumerable: true, get: function () { return urlUtils_1.normalizeUrl; } });
40
+ Object.defineProperty(exports, "getEditUrl", { enumerable: true, get: function () { return urlUtils_1.getEditUrl; } });
41
+ var tags_1 = require("./tags");
42
+ Object.defineProperty(exports, "normalizeFrontMatterTag", { enumerable: true, get: function () { return tags_1.normalizeFrontMatterTag; } });
43
+ Object.defineProperty(exports, "normalizeFrontMatterTags", { enumerable: true, get: function () { return tags_1.normalizeFrontMatterTags; } });
44
+ Object.defineProperty(exports, "groupTaggedItems", { enumerable: true, get: function () { return tags_1.groupTaggedItems; } });
45
+ var markdownParser_1 = require("./markdownParser");
46
+ Object.defineProperty(exports, "parseMarkdownHeadingId", { enumerable: true, get: function () { return markdownParser_1.parseMarkdownHeadingId; } });
47
+ Object.defineProperty(exports, "createExcerpt", { enumerable: true, get: function () { return markdownParser_1.createExcerpt; } });
48
+ Object.defineProperty(exports, "parseFrontMatter", { enumerable: true, get: function () { return markdownParser_1.parseFrontMatter; } });
49
+ Object.defineProperty(exports, "parseMarkdownContentTitle", { enumerable: true, get: function () { return markdownParser_1.parseMarkdownContentTitle; } });
50
+ Object.defineProperty(exports, "parseMarkdownString", { enumerable: true, get: function () { return markdownParser_1.parseMarkdownString; } });
51
+ var markdownLinks_1 = require("./markdownLinks");
52
+ Object.defineProperty(exports, "replaceMarkdownLinks", { enumerable: true, get: function () { return markdownLinks_1.replaceMarkdownLinks; } });
53
+ var slugger_1 = require("./slugger");
54
+ Object.defineProperty(exports, "createSlugger", { enumerable: true, get: function () { return slugger_1.createSlugger; } });
55
+ var pathUtils_1 = require("./pathUtils");
56
+ Object.defineProperty(exports, "isNameTooLong", { enumerable: true, get: function () { return pathUtils_1.isNameTooLong; } });
57
+ Object.defineProperty(exports, "shortName", { enumerable: true, get: function () { return pathUtils_1.shortName; } });
58
+ Object.defineProperty(exports, "posixPath", { enumerable: true, get: function () { return pathUtils_1.posixPath; } });
59
+ Object.defineProperty(exports, "toMessageRelativeFilePath", { enumerable: true, get: function () { return pathUtils_1.toMessageRelativeFilePath; } });
60
+ Object.defineProperty(exports, "aliasedSitePath", { enumerable: true, get: function () { return pathUtils_1.aliasedSitePath; } });
61
+ Object.defineProperty(exports, "escapePath", { enumerable: true, get: function () { return pathUtils_1.escapePath; } });
62
+ var hashUtils_2 = require("./hashUtils");
63
+ Object.defineProperty(exports, "md5Hash", { enumerable: true, get: function () { return hashUtils_2.md5Hash; } });
64
+ Object.defineProperty(exports, "simpleHash", { enumerable: true, get: function () { return hashUtils_2.simpleHash; } });
65
+ Object.defineProperty(exports, "docuHash", { enumerable: true, get: function () { return hashUtils_2.docuHash; } });
66
+ var globUtils_1 = require("./globUtils");
67
+ Object.defineProperty(exports, "Globby", { enumerable: true, get: function () { return globUtils_1.Globby; } });
68
+ Object.defineProperty(exports, "GlobExcludeDefault", { enumerable: true, get: function () { return globUtils_1.GlobExcludeDefault; } });
69
+ Object.defineProperty(exports, "createMatcher", { enumerable: true, get: function () { return globUtils_1.createMatcher; } });
70
+ Object.defineProperty(exports, "createAbsoluteFilePathMatcher", { enumerable: true, get: function () { return globUtils_1.createAbsoluteFilePathMatcher; } });
71
+ var webpackUtils_1 = require("./webpackUtils");
72
+ Object.defineProperty(exports, "getFileLoaderUtils", { enumerable: true, get: function () { return webpackUtils_1.getFileLoaderUtils; } });
73
+ var dataFileUtils_1 = require("./dataFileUtils");
74
+ Object.defineProperty(exports, "getDataFilePath", { enumerable: true, get: function () { return dataFileUtils_1.getDataFilePath; } });
75
+ Object.defineProperty(exports, "getDataFileData", { enumerable: true, get: function () { return dataFileUtils_1.getDataFileData; } });
76
+ Object.defineProperty(exports, "getContentPathList", { enumerable: true, get: function () { return dataFileUtils_1.getContentPathList; } });
77
+ Object.defineProperty(exports, "findFolderContainingFile", { enumerable: true, get: function () { return dataFileUtils_1.findFolderContainingFile; } });
78
+ Object.defineProperty(exports, "getFolderContainingFile", { enumerable: true, get: function () { return dataFileUtils_1.getFolderContainingFile; } });
26
79
  const fileHash = new Map();
27
80
  async function generate(generatedFilesDir, file, content, skipCache = process.env.NODE_ENV === 'production') {
28
81
  const filepath = path_1.default.join(generatedFilesDir, file);
@@ -35,12 +88,12 @@ async function generate(generatedFilesDir, file, content, skipCache = process.en
35
88
  // If file already exists but its not in runtime cache yet,
36
89
  // we try to calculate the content hash and then compare
37
90
  // This is to avoid unnecessary overwriting and we can reuse old file.
38
- if (!lastHash && fs_extra_1.default.existsSync(filepath)) {
91
+ if (!lastHash && (await fs_extra_1.default.pathExists(filepath))) {
39
92
  const lastContent = await fs_extra_1.default.readFile(filepath, 'utf8');
40
- lastHash = crypto_1.createHash('md5').update(lastContent).digest('hex');
93
+ lastHash = (0, crypto_1.createHash)('md5').update(lastContent).digest('hex');
41
94
  fileHash.set(filepath, lastHash);
42
95
  }
43
- const currentHash = crypto_1.createHash('md5').update(content).digest('hex');
96
+ const currentHash = (0, crypto_1.createHash)('md5').update(content).digest('hex');
44
97
  if (lastHash !== currentHash) {
45
98
  await fs_extra_1.default.ensureDir(path_1.default.dirname(filepath));
46
99
  await fs_extra_1.default.writeFile(filepath, content);
@@ -48,18 +101,8 @@ async function generate(generatedFilesDir, file, content, skipCache = process.en
48
101
  }
49
102
  }
50
103
  exports.generate = generate;
51
- function objectWithKeySorted(obj) {
52
- // https://github.com/lodash/lodash/issues/1459#issuecomment-460941233
53
- return Object.keys(obj)
54
- .sort()
55
- .reduce((acc, key) => {
56
- acc[key] = obj[key];
57
- return acc;
58
- }, {});
59
- }
60
- exports.objectWithKeySorted = objectWithKeySorted;
61
- const indexRE = /(^|.*\/)index\.(md|mdx|js|jsx|ts|tsx)$/i;
62
- const extRE = /\.(md|mdx|js|jsx|ts|tsx)$/;
104
+ const indexRE = /(?<dirname>^|.*\/)index\.(?:mdx?|jsx?|tsx?)$/i;
105
+ const extRE = /\.(?:mdx?|jsx?|tsx?)$/;
63
106
  /**
64
107
  * Convert filepath to url path.
65
108
  * Example: 'index.md' -> '/', 'foo/bar.js' -> '/foo/bar',
@@ -71,60 +114,13 @@ function fileToPath(file) {
71
114
  return `/${file.replace(extRE, '').replace(/\\/g, '/')}`;
72
115
  }
73
116
  exports.fileToPath = fileToPath;
74
- function encodePath(userpath) {
75
- return userpath
117
+ function encodePath(userPath) {
118
+ return userPath
76
119
  .split('/')
77
120
  .map((item) => encodeURIComponent(item))
78
121
  .join('/');
79
122
  }
80
123
  exports.encodePath = encodePath;
81
- function simpleHash(str, length) {
82
- return crypto_1.createHash('md5').update(str).digest('hex').substr(0, length);
83
- }
84
- exports.simpleHash = simpleHash;
85
- /**
86
- * Given an input string, convert to kebab-case and append a hash.
87
- * Avoid str collision.
88
- */
89
- function docuHash(str) {
90
- if (str === '/') {
91
- return 'index';
92
- }
93
- const shortHash = simpleHash(str, 3);
94
- return `${lodash_1.kebabCase(str)}-${shortHash}`;
95
- }
96
- exports.docuHash = docuHash;
97
- /**
98
- * Convert first string character to the upper case.
99
- * E.g: docusaurus -> Docusaurus
100
- */
101
- function upperFirst(str) {
102
- return str ? str.charAt(0).toUpperCase() + str.slice(1) : '';
103
- }
104
- exports.upperFirst = upperFirst;
105
- /**
106
- * Generate unique React Component Name.
107
- * E.g: /foo-bar -> FooBar096
108
- */
109
- function genComponentName(pagePath) {
110
- if (pagePath === '/') {
111
- return 'index';
112
- }
113
- const pageHash = docuHash(pagePath);
114
- return upperFirst(lodash_1.camelCase(pageHash));
115
- }
116
- exports.genComponentName = genComponentName;
117
- // When you want to display a path in a message/warning/error,
118
- // it's more convenient to:
119
- // - make it relative to cwd()
120
- // - convert to posix (ie not using windows \ path separator)
121
- // This way, Jest tests can run more reliably on any computer/CI
122
- // on both Unix/Windows
123
- // For Windows users this is not perfect (as they see / instead of \) but it's probably good enough
124
- function toMessageRelativeFilePath(filePath) {
125
- return exports.posixPath(path_1.default.relative(process.cwd(), filePath));
126
- }
127
- exports.toMessageRelativeFilePath = toMessageRelativeFilePath;
128
124
  const chunkNameCache = new Map();
129
125
  /**
130
126
  * Generate unique chunk name given a module path.
@@ -133,15 +129,15 @@ function genChunkName(modulePath, prefix, preferredName, shortId = process.env.N
133
129
  let chunkName = chunkNameCache.get(modulePath);
134
130
  if (!chunkName) {
135
131
  if (shortId) {
136
- chunkName = simpleHash(modulePath, 8);
132
+ chunkName = (0, hashUtils_1.simpleHash)(modulePath, 8);
137
133
  }
138
134
  else {
139
135
  let str = modulePath;
140
136
  if (preferredName) {
141
- const shortHash = simpleHash(modulePath, 3);
137
+ const shortHash = (0, hashUtils_1.simpleHash)(modulePath, 3);
142
138
  str = `${preferredName}${shortHash}`;
143
139
  }
144
- const name = str === '/' ? 'index' : docuHash(str);
140
+ const name = str === '/' ? 'index' : (0, hashUtils_1.docuHash)(str);
145
141
  chunkName = prefix ? `${prefix}---${name}` : name;
146
142
  }
147
143
  chunkNameCache.set(modulePath, chunkName);
@@ -149,102 +145,6 @@ function genChunkName(modulePath, prefix, preferredName, shortId = process.env.N
149
145
  return chunkName;
150
146
  }
151
147
  exports.genChunkName = genChunkName;
152
- // Too dynamic
153
- // eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types, @typescript-eslint/no-explicit-any
154
- function idx(target, keyPaths) {
155
- return (target &&
156
- keyPaths &&
157
- (Array.isArray(keyPaths)
158
- ? keyPaths.reduce((obj, key) => obj && obj[key], target)
159
- : target[keyPaths]));
160
- }
161
- exports.idx = idx;
162
- /**
163
- * Given a filepath and dirpath, get the first directory.
164
- */
165
- function getSubFolder(file, refDir) {
166
- const separator = escape_string_regexp_1.default(path_1.default.sep);
167
- const baseDir = escape_string_regexp_1.default(path_1.default.basename(refDir));
168
- const regexSubFolder = new RegExp(`${baseDir}${separator}(.*?)${separator}.*`);
169
- const match = regexSubFolder.exec(file);
170
- return match && match[1];
171
- }
172
- exports.getSubFolder = getSubFolder;
173
- function normalizeUrl(rawUrls) {
174
- const urls = [...rawUrls];
175
- const resultArray = [];
176
- let hasStartingSlash = false;
177
- let hasEndingSlash = false;
178
- // If the first part is a plain protocol, we combine it with the next part.
179
- if (urls[0].match(/^[^/:]+:\/*$/) && urls.length > 1) {
180
- const first = urls.shift();
181
- urls[0] = first + urls[0];
182
- }
183
- // There must be two or three slashes in the file protocol,
184
- // two slashes in anything else.
185
- const replacement = urls[0].match(/^file:\/\/\//) ? '$1:///' : '$1://';
186
- urls[0] = urls[0].replace(/^([^/:]+):\/*/, replacement);
187
- // eslint-disable-next-line
188
- for (let i = 0; i < urls.length; i++) {
189
- let component = urls[i];
190
- if (typeof component !== 'string') {
191
- throw new TypeError(`Url must be a string. Received ${typeof component}`);
192
- }
193
- if (component === '') {
194
- if (i === urls.length - 1 && hasEndingSlash) {
195
- resultArray.push('/');
196
- }
197
- // eslint-disable-next-line
198
- continue;
199
- }
200
- if (component !== '/') {
201
- if (i > 0) {
202
- // Removing the starting slashes for each component but the first.
203
- component = component.replace(/^[/]+/,
204
- // Special case where the first element of rawUrls is empty ["", "/hello"] => /hello
205
- component[0] === '/' && !hasStartingSlash ? '/' : '');
206
- }
207
- hasEndingSlash = component[component.length - 1] === '/';
208
- // Removing the ending slashes for each component but the last.
209
- // For the last component we will combine multiple slashes to a single one.
210
- component = component.replace(/[/]+$/, i < urls.length - 1 ? '' : '/');
211
- }
212
- hasStartingSlash = true;
213
- resultArray.push(component);
214
- }
215
- let str = resultArray.join('/');
216
- // Each input component is now separated by a single slash
217
- // except the possible first plain protocol part.
218
- // Remove trailing slash before parameters or hash.
219
- str = str.replace(/\/(\?|&|#[^!])/g, '$1');
220
- // Replace ? in parameters with &.
221
- const parts = str.split('?');
222
- str = parts.shift() + (parts.length > 0 ? '?' : '') + parts.join('&');
223
- // Dedupe forward slashes in the entire path, avoiding protocol slashes.
224
- str = str.replace(/([^:]\/)\/+/g, '$1');
225
- // Dedupe forward slashes at the beginning of the path.
226
- str = str.replace(/^\/+/g, '/');
227
- return str;
228
- }
229
- exports.normalizeUrl = normalizeUrl;
230
- /**
231
- * Alias filepath relative to site directory, very useful so that we
232
- * don't expose user's site structure.
233
- * Example: some/path/to/website/docs/foo.md -> @site/docs/foo.md
234
- */
235
- function aliasedSitePath(filePath, siteDir) {
236
- const relativePath = exports.posixPath(path_1.default.relative(siteDir, filePath));
237
- // Cannot use path.join() as it resolves '../' and removes
238
- // the '@site'. Let webpack loader resolve it.
239
- return `@site/${relativePath}`;
240
- }
241
- exports.aliasedSitePath = aliasedSitePath;
242
- function getEditUrl(fileRelativePath, editUrl) {
243
- return editUrl
244
- ? normalizeUrl([editUrl, exports.posixPath(fileRelativePath)])
245
- : undefined;
246
- }
247
- exports.getEditUrl = getEditUrl;
248
148
  function isValidPathname(str) {
249
149
  if (!str.startsWith('/')) {
250
150
  return false;
@@ -254,28 +154,32 @@ function isValidPathname(str) {
254
154
  const parsedPathname = new url_1.URL(str, 'https://domain.com').pathname;
255
155
  return parsedPathname === str || parsedPathname === encodeURI(str);
256
156
  }
257
- catch (e) {
157
+ catch {
258
158
  return false;
259
159
  }
260
160
  }
261
161
  exports.isValidPathname = isValidPathname;
262
162
  // resolve pathname and fail fast if resolution fails
263
163
  function resolvePathname(to, from) {
264
- return resolve_pathname_1.default(to, from);
164
+ return (0, resolve_pathname_1.default)(to, from);
265
165
  }
266
166
  exports.resolvePathname = resolvePathname;
267
167
  function addLeadingSlash(str) {
268
168
  return str.startsWith('/') ? str : `/${str}`;
269
169
  }
270
170
  exports.addLeadingSlash = addLeadingSlash;
171
+ function addTrailingPathSeparator(str) {
172
+ return str.endsWith(path_1.default.sep)
173
+ ? str
174
+ : // If this is Windows, we need to change the forward slash to backward
175
+ `${str.replace(/\/$/, '')}${path_1.default.sep}`;
176
+ }
177
+ exports.addTrailingPathSeparator = addTrailingPathSeparator;
178
+ // TODO deduplicate: also present in @docusaurus/utils-common
271
179
  function addTrailingSlash(str) {
272
180
  return str.endsWith('/') ? str : `${str}/`;
273
181
  }
274
182
  exports.addTrailingSlash = addTrailingSlash;
275
- function addTrailingPathSeparator(str) {
276
- return str.endsWith(path_1.default.sep) ? str : `${str}${path_1.default.sep}`;
277
- }
278
- exports.addTrailingPathSeparator = addTrailingPathSeparator;
279
183
  function removeTrailingSlash(str) {
280
184
  return removeSuffix(str, '/');
281
185
  }
@@ -291,50 +195,63 @@ function removePrefix(str, prefix) {
291
195
  return str.startsWith(prefix) ? str.slice(prefix.length) : str;
292
196
  }
293
197
  exports.removePrefix = removePrefix;
294
- function getFilePathForRoutePath(routePath) {
295
- const fileName = path_1.default.basename(routePath);
296
- const filePath = path_1.default.dirname(routePath);
297
- return path_1.default.join(filePath, `${fileName}/index.html`);
298
- }
299
- exports.getFilePathForRoutePath = getFilePathForRoutePath;
300
198
  function getElementsAround(array, aroundIndex) {
301
199
  const min = 0;
302
200
  const max = array.length - 1;
303
201
  if (aroundIndex < min || aroundIndex > max) {
304
- throw new Error(`Valid aroundIndex for array (of size ${array.length}) are between ${min} and ${max}, but you provided aroundIndex=${aroundIndex}`);
202
+ throw new Error(`Valid "aroundIndex" for array (of size ${array.length}) are between ${min} and ${max}, but you provided ${aroundIndex}.`);
305
203
  }
306
204
  const previous = aroundIndex === min ? undefined : array[aroundIndex - 1];
307
205
  const next = aroundIndex === max ? undefined : array[aroundIndex + 1];
308
206
  return { previous, next };
309
207
  }
310
208
  exports.getElementsAround = getElementsAround;
311
- function getPluginI18nPath({ siteDir, locale, pluginName, pluginId = 'default', // TODO duplicated constant
312
- subPaths = [], }) {
209
+ function getPluginI18nPath({ siteDir, locale, pluginName, pluginId = constants_1.DEFAULT_PLUGIN_ID, subPaths = [], }) {
313
210
  return path_1.default.join(siteDir, 'i18n',
314
- // namespace first by locale: convenient to work in a single folder for a translator
211
+ // namespace first by locale: convenient to work in a single folder for a
212
+ // translator
315
213
  locale,
316
214
  // Make it convenient to use for single-instance
317
215
  // ie: return "docs", not "docs-default" nor "docs/default"
318
- `${pluginName}${
319
- // TODO duplicate constant :(
320
- pluginId === 'default' ? '' : `-${pluginId}`}`, ...subPaths);
216
+ `${pluginName}${pluginId === constants_1.DEFAULT_PLUGIN_ID ? '' : `-${pluginId}`}`, ...subPaths);
321
217
  }
322
218
  exports.getPluginI18nPath = getPluginI18nPath;
323
- async function mapAsyncSequencial(array, action) {
219
+ /**
220
+ * @param permalink The URL that the HTML file corresponds to, without base URL
221
+ * @param outDir Full path to the output directory
222
+ * @param trailingSlash The site config option. If provided, only one path will
223
+ * be read.
224
+ * @returns This returns a buffer, which you have to decode string yourself if
225
+ * needed. (Not always necessary since the output isn't for human consumption
226
+ * anyways, and most HTML manipulation libs accept buffers)
227
+ */
228
+ async function readOutputHTMLFile(permalink, outDir, trailingSlash) {
229
+ const withTrailingSlashPath = path_1.default.join(outDir, permalink, 'index.html');
230
+ const withoutTrailingSlashPath = path_1.default.join(outDir, `${permalink.replace(/\/$/, '')}.html`);
231
+ if (trailingSlash) {
232
+ return fs_extra_1.default.readFile(withTrailingSlashPath);
233
+ }
234
+ else if (trailingSlash === false) {
235
+ return fs_extra_1.default.readFile(withoutTrailingSlashPath);
236
+ }
237
+ const HTMLPath = await findAsyncSequential([withTrailingSlashPath, withoutTrailingSlashPath], fs_extra_1.default.pathExists);
238
+ if (!HTMLPath) {
239
+ throw new Error(`Expected output HTML file to be found at ${withTrailingSlashPath}`);
240
+ }
241
+ return fs_extra_1.default.readFile(HTMLPath);
242
+ }
243
+ exports.readOutputHTMLFile = readOutputHTMLFile;
244
+ async function mapAsyncSequential(array, action) {
324
245
  const results = [];
325
- // eslint-disable-next-line no-restricted-syntax
326
246
  for (const t of array) {
327
- // eslint-disable-next-line no-await-in-loop
328
247
  const result = await action(t);
329
248
  results.push(result);
330
249
  }
331
250
  return results;
332
251
  }
333
- exports.mapAsyncSequencial = mapAsyncSequencial;
252
+ exports.mapAsyncSequential = mapAsyncSequential;
334
253
  async function findAsyncSequential(array, predicate) {
335
- // eslint-disable-next-line no-restricted-syntax
336
254
  for (const t of array) {
337
- // eslint-disable-next-line no-await-in-loop
338
255
  if (await predicate(t)) {
339
256
  return t;
340
257
  }
@@ -342,78 +259,40 @@ async function findAsyncSequential(array, predicate) {
342
259
  return undefined;
343
260
  }
344
261
  exports.findAsyncSequential = findAsyncSequential;
345
- // return the first folder path in which the file exists in
346
- async function findFolderContainingFile(folderPaths, relativeFilePath) {
347
- return findAsyncSequential(folderPaths, (folderPath) => fs_extra_1.default.pathExists(path_1.default.join(folderPath, relativeFilePath)));
348
- }
349
- exports.findFolderContainingFile = findFolderContainingFile;
350
- async function getFolderContainingFile(folderPaths, relativeFilePath) {
351
- const maybeFolderPath = await findFolderContainingFile(folderPaths, relativeFilePath);
352
- // should never happen, as the source was read from the FS anyway...
353
- if (!maybeFolderPath) {
354
- throw new Error(`relativeFilePath=[${relativeFilePath}] does not exist in any of these folders: \n- ${folderPaths.join('\n- ')}]`);
355
- }
356
- return maybeFolderPath;
357
- }
358
- exports.getFolderContainingFile = getFolderContainingFile;
359
262
  function reportMessage(message, reportingSeverity) {
360
263
  switch (reportingSeverity) {
361
264
  case 'ignore':
362
265
  break;
363
266
  case 'log':
364
- console.log(chalk_1.default.bold.blue('info ') + chalk_1.default.blue(message));
267
+ logger_1.default.info(message);
365
268
  break;
366
269
  case 'warn':
367
- console.warn(chalk_1.default.bold.yellow('warn ') + chalk_1.default.yellow(message));
270
+ logger_1.default.warn(message);
368
271
  break;
369
272
  case 'error':
370
- console.error(chalk_1.default.bold.red('error ') + chalk_1.default.red(message));
273
+ logger_1.default.error(message);
371
274
  break;
372
275
  case 'throw':
373
276
  throw new Error(message);
374
277
  default:
375
- throw new Error(`unexpected reportingSeverity value: ${reportingSeverity}`);
278
+ throw new Error(`Unexpected "reportingSeverity" value: ${reportingSeverity}.`);
376
279
  }
377
280
  }
378
281
  exports.reportMessage = reportMessage;
379
282
  function mergeTranslations(contents) {
380
- return contents.reduce((acc, content) => {
381
- return { ...acc, ...content };
382
- }, {});
283
+ return contents.reduce((acc, content) => ({ ...acc, ...content }), {});
383
284
  }
384
285
  exports.mergeTranslations = mergeTranslations;
385
- function getSwizzledComponent(componentPath) {
386
- const swizzledComponentPath = path_1.default.resolve(process.cwd(), 'src', componentPath);
387
- return fs_extra_1.default.existsSync(swizzledComponentPath)
388
- ? swizzledComponentPath
389
- : undefined;
390
- }
391
- exports.getSwizzledComponent = getSwizzledComponent;
392
286
  // Useful to update all the messages of a translation file
393
287
  // Used in tests to simulate translations
394
288
  function updateTranslationFileMessages(translationFile, updateMessage) {
395
289
  return {
396
290
  ...translationFile,
397
- content: lodash_1.mapValues(translationFile.content, (translation) => ({
291
+ content: lodash_1.default.mapValues(translationFile.content, (translation) => ({
398
292
  ...translation,
399
293
  message: updateMessage(translation.message),
400
294
  })),
401
295
  };
402
296
  }
403
297
  exports.updateTranslationFileMessages = updateTranslationFileMessages;
404
- // Input: ## Some heading {#some-heading}
405
- // Output: {text: "## Some heading", id: "some-heading"}
406
- function parseMarkdownHeadingId(heading) {
407
- const customHeadingIdRegex = /^(.*?)\s*\{#([\w-]+)\}$/;
408
- const matches = customHeadingIdRegex.exec(heading);
409
- if (matches) {
410
- return {
411
- text: matches[1],
412
- id: matches[2],
413
- };
414
- }
415
- else {
416
- return { text: heading, id: undefined };
417
- }
418
- }
419
- exports.parseMarkdownHeadingId = parseMarkdownHeadingId;
298
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":";AAAA;;;;;GAKG;;;;;AAEH,6EAAwC;AACxC,6DAAwB;AACxB,mCAAkC;AAClC,iEAAuB;AACvB,qEAA0B;AAC1B,6BAAwB;AAOxB,qFAAqD;AAErD,2CAAiD;AACjD,2CAA8C;AAE9C,yCA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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;AAED,SAAgB,iBAAiB,CAC/B,QAAkC;IAElC,OAAO,QAAQ,CAAC,MAAM,CAAC,CAAC,GAAG,EAAE,OAAO,EAAE,EAAE,CAAC,CAAC,EAAC,GAAG,GAAG,EAAE,GAAG,OAAO,EAAC,CAAC,EAAE,EAAE,CAAC,CAAC;AACvE,CAAC;AAJD,8CAIC;AAED,0DAA0D;AAC1D,yCAAyC;AACzC,SAAgB,6BAA6B,CAC3C,eAAgC,EAChC,aAA0C;IAE1C,OAAO;QACL,GAAG,eAAe;QAClB,OAAO,EAAE,gBAAC,CAAC,SAAS,CAAC,eAAe,CAAC,OAAO,EAAE,CAAC,WAAW,EAAE,EAAE,CAAC,CAAC;YAC9D,GAAG,WAAW;YACd,OAAO,EAAE,aAAa,CAAC,WAAW,CAAC,OAAO,CAAC;SAC5C,CAAC,CAAC;KACJ,CAAC;AACJ,CAAC;AAXD,sEAWC"}
@@ -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 = (0, 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,6DAAwB;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;gB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