/
index.js
237 lines (210 loc) · 7.19 KB
/
index.js
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
229
230
231
232
233
234
235
236
237
/**
* @typedef {import('esbuild').Plugin} Plugin
* @typedef {import('esbuild').PluginBuild} PluginBuild
* @typedef {import('esbuild').OnLoadArgs} OnLoadArgs
* @typedef {import('esbuild').OnLoadResult} OnLoadResult
* @typedef {import('esbuild').OnResolveArgs} OnResolveArgs
* @typedef {import('esbuild').Message} Message
* @typedef {import('vfile').VFileValue} VFileValue
* @typedef {import('vfile-message').VFileMessage} VFileMessage
* @typedef {import('unist').Point} Point
* @typedef {import('@mdx-js/mdx/lib/core.js').ProcessorOptions} ProcessorOptions
*
* @typedef {ProcessorOptions & {allowDangerousRemoteMdx?: boolean}} Options
*/
import assert from 'node:assert'
import {promises as fs} from 'node:fs'
import path from 'node:path'
import process from 'node:process'
import fetch from 'node-fetch'
import {VFile} from 'vfile'
import {createFormatAwareProcessors} from '@mdx-js/mdx/lib/util/create-format-aware-processors.js'
import {extnamesToRegex} from '@mdx-js/mdx/lib/util/extnames-to-regex.js'
const eol = /\r\n|\r|\n|\u2028|\u2029/g
/** @type Map<string, string> */
const cache = new Map()
const p = process
/**
* Compile MDX w/ esbuild.
*
* @param {Options} [options]
* @return {Plugin}
*/
export function esbuild(options = {}) {
const {allowDangerousRemoteMdx, ...rest} = options
const name = '@mdx-js/esbuild'
const remoteNamespace = name + '-remote'
const {extnames, process} = createFormatAwareProcessors(rest)
return {name, setup}
/**
* @param {PluginBuild} build
*/
function setup(build) {
const filter = extnamesToRegex(extnames)
/* eslint-disable-next-line security/detect-non-literal-regexp */
const filterHttp = new RegExp('^https?:\\/{2}.+' + filter.source)
const http = /^https?:\/{2}/
const filterHttpOrRelative = /^(https?:\/{2}|.{1,2}\/).*/
if (allowDangerousRemoteMdx) {
// Intercept import paths starting with "http:" and "https:" so
// esbuild doesn't attempt to map them to a file system location.
// Tag them with the "http-url" namespace to associate them with
// this plugin.
build.onResolve(
{filter: filterHttp, namespace: 'file'},
resolveRemoteInLocal
)
build.onResolve(
{filter: filterHttpOrRelative, namespace: remoteNamespace},
resolveInRemote
)
}
build.onLoad({filter: /.*/, namespace: remoteNamespace}, onloadremote)
build.onLoad({filter}, onload)
/** @param {OnResolveArgs} args */
function resolveRemoteInLocal(args) {
return {path: args.path, namespace: remoteNamespace}
}
// Intercept all import paths inside downloaded files and resolve them against
// the original URL. All of these
// files will be in the "http-url" namespace. Make sure to keep
// the newly resolved URL in the "http-url" namespace so imports
// inside it will also be resolved as URLs recursively.
/** @param {OnResolveArgs} args */
function resolveInRemote(args) {
return {
path: String(new URL(args.path, args.importer)),
namespace: remoteNamespace
}
}
/**
* @param {OnLoadArgs} data
* @returns {Promise<OnLoadResult>}
*/
async function onloadremote(data) {
const href = data.path
console.log('%s: downloading `%s`', remoteNamespace, href)
/** @type {string} */
let contents
const cachedContents = cache.get(href)
if (cachedContents) {
contents = cachedContents
} else {
contents = await (await fetch(href)).text()
cache.set(href, contents)
}
return filter.test(href)
? onload({
suffix: '',
// Clean search and hash from URL.
path: Object.assign(new URL(href), {search: '', hash: ''}).href,
namespace: 'file',
pluginData: {contents}
})
: // V8 on Erbium.
/* c8 ignore next 2 */
{contents, loader: 'js', resolveDir: p.cwd()}
}
/**
* @param {Omit<OnLoadArgs, 'pluginData'> & {pluginData?: {contents?: string|Buffer}}} data
* @returns {Promise<OnLoadResult>}
*/
async function onload(data) {
/** @type {string} */
const doc = String(
data.pluginData && data.pluginData.contents !== undefined
? data.pluginData.contents
: /* eslint-disable-next-line security/detect-non-literal-fs-filename */
await fs.readFile(data.path)
)
let file = new VFile({value: doc, path: data.path})
/** @type {VFileValue|undefined} */
let value
/** @type {Array<VFileMessage|Error>} */
let messages = []
/** @type {Array<Message>} */
const errors = []
/** @type {Array<Message>} */
const warnings = []
try {
file = await process(file)
value = file.value
messages = file.messages
} catch (error_) {
const error = /** @type {VFileMessage|Error} */ (error_)
if ('fatal' in error) error.fatal = true
messages.push(error)
}
for (const message of messages) {
const location = 'position' in message ? message.position : undefined
const start = location ? location.start : undefined
const end = location ? location.end : undefined
let length = 0
let lineStart = 0
let line = 0
let column = 0
if (
start &&
start.line !== null &&
start.line !== undefined &&
start.column !== undefined &&
start.column !== null &&
start.offset !== undefined &&
start.offset !== null
) {
line = start.line
column = start.column - 1
lineStart = start.offset - column
length = 1
if (
end &&
end.line !== null &&
end.line !== undefined &&
end.column !== undefined &&
end.column !== null &&
end.offset !== undefined &&
end.offset !== null
) {
length = end.offset - start.offset
}
}
eol.lastIndex = lineStart
const match = eol.exec(doc)
const lineEnd = match ? match.index : doc.length
;(!('fatal' in message) || message.fatal ? errors : warnings).push({
pluginName: name,
id: '',
text:
'reason' in message
? message.reason
: /* Extra fallback to make sure weird values are definitely strings */
/* c8 ignore next */
message.stack || String(message),
notes: [],
location: {
namespace: 'file',
suggestion: '',
file: data.path,
line,
column,
length: Math.min(length, lineEnd),
lineText: doc.slice(lineStart, lineEnd)
},
detail: message
})
}
// Safety check: the file has a path, so there has to be a `dirname`.
assert(file.dirname, 'expected `dirname` to be defined')
// V8 on Erbium.
/* c8 ignore next 9 */
return {
contents: value,
errors,
warnings,
resolveDir: http.test(file.path)
? p.cwd()
: path.resolve(file.cwd, file.dirname)
}
}
}
}