-
-
Notifications
You must be signed in to change notification settings - Fork 9.9k
Expand file tree
/
Copy pathindex.ts
More file actions
228 lines (205 loc) · 6.17 KB
/
index.ts
File metadata and controls
228 lines (205 loc) · 6.17 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
/**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
import path from 'path';
import url from 'url';
import fs from 'fs-extra';
import {
toMessageRelativeFilePath,
posixPath,
escapePath,
findAsyncSequential,
getFileLoaderUtils,
parseURLOrPath,
} from '@docusaurus/utils';
import escapeHtml from 'escape-html';
import {assetRequireAttributeValue, transformNode} from '../utils';
import type {Plugin, Transformer} from 'unified';
import type {MdxJsxTextElement} from 'mdast-util-mdx';
import type {Parent} from 'unist';
import type {Link, Literal, Root} from 'mdast';
type PluginOptions = {
staticDirs: string[];
siteDir: string;
};
type Context = PluginOptions & {
filePath: string;
inlineMarkdownLinkFileLoader: string;
};
type Target = [node: Link, index: number, parent: Parent];
/**
* Transforms the link node to a JSX `<a>` element with a `require()` call.
*/
async function toAssetRequireNode(
[node]: Target,
assetPath: string,
context: Context,
) {
// MdxJsxTextElement => see https://github.com/facebook/docusaurus/pull/8288#discussion_r1125871405
const jsxNode = node as unknown as MdxJsxTextElement;
const attributes: MdxJsxTextElement['attributes'] = [];
// require("assets/file.pdf") means requiring from a package called assets
const relativeAssetPath = `./${posixPath(
path.relative(path.dirname(context.filePath), assetPath),
)}`;
const parsedUrl = parseURLOrPath(node.url);
const hash = parsedUrl.hash ?? '';
const search = parsedUrl.search ?? '';
const requireString = `${
// A hack to stop Webpack from using its built-in loader to parse JSON
path.extname(relativeAssetPath) === '.json'
? `${relativeAssetPath.replace('.json', '.raw')}!=`
: ''
}${context.inlineMarkdownLinkFileLoader}${
escapePath(relativeAssetPath) + search
}`;
attributes.push({
type: 'mdxJsxAttribute',
name: 'target',
value: '_blank',
});
// Assets are not routes, and are required by Webpack already
// They should not trigger the broken link checker
attributes.push({
type: 'mdxJsxAttribute',
name: 'data-noBrokenLinkCheck',
value: {
type: 'mdxJsxAttributeValueExpression',
value: 'true',
data: {
estree: {
type: 'Program',
body: [
{
type: 'ExpressionStatement',
expression: {
type: 'Literal',
value: true,
raw: 'true',
},
},
],
sourceType: 'module',
comments: [],
},
},
},
});
attributes.push({
type: 'mdxJsxAttribute',
name: 'href',
value: assetRequireAttributeValue(requireString, hash),
});
if (node.title) {
attributes.push({
type: 'mdxJsxAttribute',
name: 'title',
value: escapeHtml(node.title),
});
}
const {children} = node;
transformNode(jsxNode, {
type: 'mdxJsxTextElement',
name: 'a',
attributes,
children,
});
}
async function ensureAssetFileExist(assetPath: string, sourceFilePath: string) {
const assetExists = await fs.pathExists(assetPath);
if (!assetExists) {
throw new Error(
`Asset ${toMessageRelativeFilePath(
assetPath,
)} used in ${toMessageRelativeFilePath(sourceFilePath)} not found.`,
);
}
}
async function getAssetAbsolutePath(
assetPath: string,
{siteDir, filePath, staticDirs}: Context,
) {
if (assetPath.startsWith('@site/')) {
const assetFilePath = path.join(siteDir, assetPath.replace('@site/', ''));
// The @site alias is the only way to believe that the user wants an asset.
// Everything else can just be a link URL
await ensureAssetFileExist(assetFilePath, filePath);
return assetFilePath;
} else if (path.isAbsolute(assetPath)) {
const assetFilePath = await findAsyncSequential(
staticDirs.map((dir) => path.join(dir, assetPath)),
fs.pathExists,
);
if (assetFilePath) {
return assetFilePath;
}
} else {
const assetFilePath = path.join(path.dirname(filePath), assetPath);
if (await fs.pathExists(assetFilePath)) {
return assetFilePath;
}
}
return null;
}
async function processLinkNode(target: Target, context: Context) {
const [node] = target;
if (!node.url) {
// Try to improve error feedback
// see https://github.com/facebook/docusaurus/issues/3309#issuecomment-690371675
const title =
node.title ?? (node.children[0] as Literal | undefined)?.value ?? '?';
const line = node.position?.start.line ?? '?';
throw new Error(
`Markdown link URL is mandatory in "${toMessageRelativeFilePath(
context.filePath,
)}" file (title: ${title}, line: ${line}).`,
);
}
const parsedUrl = url.parse(node.url);
if (parsedUrl.protocol || !parsedUrl.pathname) {
// Don't process pathname:// here, it's used by the <Link> component
return;
}
const hasSiteAlias = parsedUrl.pathname.startsWith('@site/');
const hasAssetLikeExtension =
path.extname(parsedUrl.pathname) &&
!parsedUrl.pathname.match(/\.(?:mdx?|html)(?:#|$)/);
if (!hasSiteAlias && !hasAssetLikeExtension) {
return;
}
const assetPath = await getAssetAbsolutePath(
decodeURIComponent(parsedUrl.pathname),
context,
);
if (assetPath) {
await toAssetRequireNode(target, assetPath, context);
}
}
const plugin: Plugin<PluginOptions[], Root> = function plugin(
options,
): Transformer<Root> {
return async (root, vfile) => {
const {visit} = await import('unist-util-visit');
const fileLoaderUtils = getFileLoaderUtils(
vfile.data.compilerName === 'server',
);
const context: Context = {
...options,
filePath: vfile.path!,
inlineMarkdownLinkFileLoader:
fileLoaderUtils.loaders.inlineMarkdownLinkFileLoader,
};
const promises: Promise<void>[] = [];
visit(root, 'link', (node, index, parent) => {
if (!parent || index === undefined) {
return;
}
promises.push(processLinkNode([node, index, parent], context));
});
await Promise.all(promises);
};
};
export default plugin;