-
-
Notifications
You must be signed in to change notification settings - Fork 1.1k
/
index.js
274 lines (245 loc) · 7.55 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
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
/**
* @typedef {import('@mdx-js/mdx').ProcessorOptions} ProcessorOptions
* @typedef {import('esbuild').Message} Message
* @typedef {import('esbuild').OnLoadArgs} OnLoadArgs
* @typedef {import('esbuild').OnLoadResult} OnLoadResult
* @typedef {import('esbuild').OnResolveArgs} OnResolveArgs
* @typedef {import('esbuild').Plugin} Plugin
* @typedef {import('esbuild').PluginBuild} PluginBuild
* @typedef {import('vfile').Value} Value
* @typedef {import('vfile-message').VFileMessage} VFileMessage
*/
/**
* @typedef EsbuildOptions
* Extra options.
* @property {boolean | null | undefined} [allowDangerousRemoteMdx=false]
* Allow remote MDX (default: `false`).
*
* @typedef {Omit<OnLoadArgs, 'pluginData'> & LoadDataFields} LoadData
* Data passed to `onload`.
*
* @typedef LoadDataFields
* Extra fields given in `data` to `onload`.
* @property {PluginData | null | undefined} [pluginData]
* Plugin data.
*
* @typedef {EsbuildOptions & ProcessorOptions} Options
* Configuration.
*
* @typedef PluginData
* Extra data passed.
* @property {Buffer | string | null | undefined} [contents]
* File contents.
*
* @typedef State
* Info passed around.
* @property {string} doc
* File value.
* @property {string} name
* Plugin name.
* @property {string} path
* File path.
*/
import assert from 'node:assert'
import fs from 'node:fs/promises'
import path from 'node:path'
import process from 'node:process'
import {createFormatAwareProcessors} from '@mdx-js/mdx/internal-create-format-aware-processors'
import {extnamesToRegex} from '@mdx-js/mdx/internal-extnames-to-regex'
import {fetch} from 'undici'
import {VFile} from 'vfile'
const eol = /\r\n|\r|\n|\u2028|\u2029/g
/** @type {Map<string, string>} */
const cache = new Map()
const name = '@mdx-js/esbuild'
const p = process
const remoteNamespace = name + '-remote'
/**
* Compile MDX w/ esbuild.
*
* @param {Readonly<Options> | null | undefined} [options]
* Configuration (optional).
* @return {Plugin}
* Plugin.
*/
export function esbuild(options) {
const {allowDangerousRemoteMdx, ...rest} = options || {}
const {extnames, process} = createFormatAwareProcessors(rest)
return {name, setup}
/**
* @param {PluginBuild} build
* Build.
* @returns {undefined}
* Nothing.
*/
function setup(build) {
const filter = extnamesToRegex(extnames)
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 {namespace: remoteNamespace, path: args.path}
}
// 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 {
namespace: remoteNamespace,
path: String(new URL(args.path, args.importer))
}
}
/**
* @param {OnLoadArgs} data
* Data.
* @returns {Promise<OnLoadResult>}
* Result.
*/
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 {
const response = await fetch(href)
contents = await response.text()
cache.set(href, contents)
}
if (filter.test(href)) {
// Clean search and hash from URL.
const url = new URL(href)
url.hash = ''
url.search = ''
return onload({
namespace: 'file',
path: url.href,
pluginData: {contents},
suffix: ''
})
}
return {contents, loader: 'js', resolveDir: p.cwd()}
}
/**
* @param {LoadData} data
* Data.
* @returns {Promise<OnLoadResult>}
* Result.
*/
async function onload(data) {
const doc = String(
data.pluginData &&
data.pluginData.contents !== null &&
data.pluginData.contents !== undefined
? data.pluginData.contents
: await fs.readFile(data.path)
)
/** @type {State} */
const state = {doc, name, path: data.path}
let file = new VFile({path: data.path, value: doc})
/** @type {Value | undefined} */
let value
/** @type {Array<Error | VFileMessage>} */
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 {Error | VFileMessage} */ (error_)
if ('fatal' in error) error.fatal = true
messages.push(error)
}
for (const message of messages) {
const list = !('fatal' in message) || message.fatal ? errors : warnings
list.push(vfileMessageToEsbuild(state, message))
}
// Safety check: the file has a path, so there has to be a `dirname`.
assert(file.dirname, 'expected `dirname` to be defined')
return {
contents: value || '',
errors,
resolveDir: http.test(file.path)
? p.cwd()
: path.resolve(file.cwd, file.dirname),
warnings
}
}
}
}
/**
* @param {Readonly<State>} state
* Info passed around.
* @param {Readonly<Error | VFileMessage>} message
* VFile message or error.
* @returns {Message}
* ESBuild message.
*/
function vfileMessageToEsbuild(state, message) {
const place = 'place' in message ? message.place : undefined
const start = place ? ('start' in place ? place.start : place) : undefined
const end = place && 'end' in place ? place.end : undefined
let length = 0
let lineStart = 0
let line = 0
let column = 0
if (start && start.offset !== undefined) {
line = start.line
column = start.column - 1
lineStart = start.offset - column
length = 1
if (end && end.offset !== undefined) {
length = end.offset - start.offset
}
}
eol.lastIndex = lineStart
const match = eol.exec(state.doc)
const lineEnd = match ? match.index : state.doc.length
return {
detail: message,
id: '',
location: {
column,
file: state.path,
length: Math.min(length, lineEnd),
line,
lineText: state.doc.slice(lineStart, lineEnd),
namespace: 'file',
suggestion: ''
},
notes: [],
pluginName: state.name,
text: String(
('reason' in message ? message.reason : undefined) ||
/* c8 ignore next 2 - errors should have stacks */
message.stack ||
message
)
}
}