-
Notifications
You must be signed in to change notification settings - Fork 750
Expand file tree
/
Copy pathdeno.ts
More file actions
496 lines (432 loc) · 14.1 KB
/
deno.ts
File metadata and controls
496 lines (432 loc) · 14.1 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
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
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
import type { Plugin } from "vite";
import {
type Loader,
MediaType,
RequestedModuleType,
ResolutionMode,
Workspace,
} from "@deno/loader";
import * as path from "@std/path";
import * as babel from "@babel/core";
import { httpAbsolute } from "./patches/http_absolute.ts";
import { JSX_REG } from "../utils.ts";
import { builtinModules } from "node:module";
// @ts-ignore Workaround for https://github.com/denoland/deno/issues/30850
const { default: babelReact } = await import("@babel/preset-react");
const BUILTINS = new Set(builtinModules);
export function deno(): Plugin {
let ssrLoader: Loader;
let browserLoader: Loader;
let isDev = false;
// Cache for package.json "type" field lookups. Per Node.js semantics,
// .js files in node_modules are CJS unless the nearest package.json
// has "type": "module".
const pkgTypeCache = new Map<string, boolean>();
async function isEsmPackage(filePath: string): Promise<boolean> {
let dir = path.dirname(filePath);
while (true) {
const cached = pkgTypeCache.get(dir);
if (cached !== undefined) return cached;
try {
const text = await Deno.readTextFile(path.join(dir, "package.json"));
const isEsm = JSON.parse(text).type === "module";
pkgTypeCache.set(dir, isEsm);
return isEsm;
} catch {
const parent = path.dirname(dir);
if (parent === dir) break;
dir = parent;
}
}
return false;
}
// Detect actual ESM export/import statements at the statement level.
// More robust than code.includes("export ") which matches comments
// and strings (e.g. "// Remove export in next version" would trick it).
// Handles both formatted and minified ESM (e.g. "import{" with no space).
const ESM_STMT_RE =
/(?:^|[\n;])\s*(?:export\s*[{*]|export\s+(?:default|const|let|var|function|class|async)\b|import\s*[{*"']|import\s+[a-zA-Z_$])/;
return {
name: "deno",
sharedDuringBuild: true,
// We must be first to be able to resolve before the
// Vite's own`vite:resolve` plugin. It always treats bare
// specifiers as external during SSR.
enforce: "pre",
config(_, env) {
isDev = env.command === "serve";
},
async configResolved() {
// TODO: Pass conditions
ssrLoader = await new Workspace({
platform: "node",
cachedOnly: true,
}).createLoader();
browserLoader = await new Workspace({
platform: "browser",
preserveJsx: true,
cachedOnly: true,
})
.createLoader();
},
applyToEnvironment() {
return true;
},
async resolveId(id, importer, options) {
if (BUILTINS.has(id)) {
// `node:` prefix is not included in builtins list.
if (!id.startsWith("node:")) {
id = `node:${id}`;
}
return {
id,
external: true,
};
}
const loader = this.environment.config.consumer === "server"
? ssrLoader
: browserLoader;
const original = id;
let isHttp = false;
if (id.startsWith("deno-http::")) {
isHttp = true;
id = id.slice("deno-http::".length);
}
importer = isDenoSpecifier(importer)
? parseDenoSpecifier(importer).specifier
: importer;
if (id.startsWith("/") && importer && /^https?:\/\//g.test(importer)) {
const url = new URL(importer);
id = `${url.origin}${id}`;
}
// Apply resolve.alias before Deno resolution so that
// react -> preact/compat works even in externalized packages.
// Vite normalizes alias config to { find, replacement }[] format.
const aliases = this.environment?.config?.resolve?.alias;
if (aliases) {
const list = Array.isArray(aliases) ? aliases : [];
for (const alias of list) {
const find = alias.find;
if (typeof find === "string" ? find === id : find?.test?.(id)) {
id = typeof alias.replacement === "string" ? alias.replacement : id;
break;
}
}
}
// We still want to allow other plugins to participate in
// resolution, with us being in front due to `enforce: "pre"`.
// But we still want to ignore everything `vite:resolve` does
// because we're kinda replacing that plugin here.
const tmp = await this.resolve(id, importer, options);
if (tmp && tmp.resolvedBy !== "vite:resolve") {
if (tmp.external && !/^https?:\/\//.test(tmp.id)) {
return tmp;
}
// A plugin namespaced it, we should not attempt to resolve it.
if (tmp.id.startsWith("\0")) {
return tmp;
}
id = tmp.id;
}
// Plugins may return lower cased drive letters on windows
if (!isHttp && path.isAbsolute(id)) {
id = path.toFileUrl(path.normalize(id))
.href;
}
try {
// Ensure we're passing a valid importer that Deno understands
const denoImporter = importer && !importer.startsWith("\0")
? importer
: undefined;
// For bare specifiers from non-deno importers, try resolving
// with the importer's file URL so workspace import maps work
let denoImporterUrl = denoImporter;
if (
denoImporter && !denoImporter.startsWith("file://") &&
!denoImporter.startsWith("http") &&
path.isAbsolute(denoImporter)
) {
denoImporterUrl = path.toFileUrl(denoImporter).href;
}
let resolved = await loader.resolve(
id,
denoImporterUrl,
ResolutionMode.Import,
);
if (resolved.startsWith("node:")) {
return {
id: resolved,
external: true,
};
}
if (original === resolved) {
return null;
}
const type = getDenoType(id, options.attributes.type ?? "default");
if (
type !== RequestedModuleType.Default ||
/^(https?|jsr|npm):/.test(resolved)
) {
return toDenoSpecifier(resolved, type);
}
if (resolved.startsWith("file://")) {
resolved = path.fromFileUrl(resolved);
}
// For file:// resolved modules (npm packages in node_modules,
// local files), let Vite handle loading natively. This allows
// Vite to externalize CJS packages in SSR mode (Node.js handles
// them with native require()) and avoids needing a custom CJS
// transform. Only \0deno:: virtual modules (jsr:, non-default
// types) need Fresh's custom load hook.
return { id: resolved };
} catch {
// ignore
}
},
async load(id) {
const loader = this.environment.config.consumer === "server"
? ssrLoader
: browserLoader;
// In dev mode, CJS files need to be wrapped in an ESM shim:
// - SSR: module runner evaluates as ESM, needs module/exports/require
// - Client: browser evaluates as ESM, needs module/exports
// In build mode, Rollup's @rollup/plugin-commonjs handles CJS.
//
// CJS detection uses Node.js semantics (package.json "type" field)
// instead of content heuristics, which can be fooled by comments
// or strings containing "export"/"import".
if (
isDev &&
!id.startsWith("\0") &&
id.includes("node_modules") &&
/\.(c?js|cjs)$/.test(id)
) {
// .cjs is always CJS. For .js files, check the nearest
// package.json "type" field first (Node.js semantics), then
// fall back to content-based detection for dual CJS/ESM
// packages that ship ESM in .js without "type": "module".
if (id.endsWith(".cjs") || !(await isEsmPackage(id))) {
try {
const code = await Deno.readTextFile(id);
// Skip if the file contains actual ESM syntax. Some packages
// (e.g. @opentelemetry/api) ship both CJS and ESM as .js
// without "type": "module" in package.json.
if (!ESM_STMT_RE.test(code)) {
const isServer = this.environment.config.consumer === "server";
if (isServer) {
// SSR: use Node.js createRequire for full CJS compat
const wrapped = `
import { createRequire as __cjs_createRequire } from "node:module";
import { fileURLToPath as __cjs_fileURLToPath } from "node:url";
import { dirname as __cjs_dirname } from "node:path";
var __filename = __cjs_fileURLToPath(import.meta.url);
var __dirname = __cjs_dirname(__filename);
var require = __cjs_createRequire(import.meta.url);
var module = { exports: {} };
var exports = module.exports;
${code}
export default module.exports;
`;
return { code: wrapped };
}
// Client: convert require() calls to ESM imports so
// browsers can load them. Hoist static require() calls
// to import statements at the top.
const imports: string[] = [];
let idx = 0;
const transformed = code.replace(
/\brequire\(["']([^"']+)["']\)/g,
(_match: string, spec: string) => {
const varName = `__cjs_import_${idx++}`;
imports.push(
`import ${varName} from ${JSON.stringify(spec)};`,
);
return `(${varName}.default ?? ${varName})`;
},
);
const wrapped = `${imports.join("\n")}
var module = { exports: {} };
var exports = module.exports;
var __filename = "";
var __dirname = "";
${transformed}
export default module.exports;
`;
return { code: wrapped };
}
} catch {
// Fall through to default loading
}
}
}
if (isDenoSpecifier(id)) {
const { type, specifier } = parseDenoSpecifier(id);
const result = await loader.load(specifier, type);
if (result.kind === "external") {
return null;
}
const code = new TextDecoder().decode(result.code);
const maybeJsx = babelTransform({
ssr: this.environment.config.consumer === "server",
media: result.mediaType,
code,
id: specifier,
isDev,
});
if (maybeJsx !== null) {
return maybeJsx;
}
return {
code,
};
}
},
transform: {
filter: {
id: JSX_REG,
},
async handler(_, id) {
// This transform is a hack to be able to re-use Deno's precompile
// jsx transform.
if (this.environment.name === "client") {
return;
}
let actualId = id;
if (isDenoSpecifier(id)) {
const { specifier } = parseDenoSpecifier(id);
actualId = specifier;
}
actualId = actualId.replace("?commonjs-es-import", "");
if (actualId.startsWith("\0")) {
actualId = actualId.slice(1);
}
if (path.isAbsolute(actualId)) {
actualId = path.toFileUrl(actualId).href;
}
const resolved = await ssrLoader.resolve(
actualId,
undefined,
ResolutionMode.Import,
);
const result = await ssrLoader.load(
resolved,
RequestedModuleType.Default,
);
if (result.kind === "external") {
return;
}
const code = new TextDecoder().decode(result.code);
return {
code,
};
},
},
};
}
function isJsMediaType(media: MediaType): boolean {
switch (media) {
case MediaType.JavaScript:
case MediaType.Jsx:
case MediaType.Mjs:
case MediaType.Cjs:
case MediaType.TypeScript:
case MediaType.Mts:
case MediaType.Cts:
case MediaType.Tsx:
return true;
case MediaType.Dts:
case MediaType.Dmts:
case MediaType.Dcts:
case MediaType.Css:
case MediaType.Json:
case MediaType.Html:
case MediaType.Sql:
case MediaType.Wasm:
case MediaType.SourceMap:
case MediaType.Unknown:
return false;
}
return false;
}
export type DenoSpecifier = string & { __deno: string };
function isDenoSpecifier(str: unknown): str is DenoSpecifier {
return typeof str === "string" && str.startsWith("\0deno::");
}
function toDenoSpecifier(spec: string, type: RequestedModuleType) {
return `\0deno::${type}::${spec}`;
}
function parseDenoSpecifier(
spec: DenoSpecifier,
): { type: RequestedModuleType; specifier: string } {
const match = spec.match(/^\0deno::([^:]+)::(.*)$/)!;
let specifier = match[2];
const specMatch = specifier.match(/^(\w+):\/([^/].*)$/);
if (specMatch !== null) {
const protocol = specMatch[1];
let rest = specMatch[2];
if (protocol === "file") {
rest = "/" + rest;
}
specifier = `${protocol}://${rest}`;
}
if (path.isAbsolute(specifier)) {
specifier = path.toFileUrl(specifier).href;
}
return { type: +match[1], specifier };
}
function getDenoType(id: string, type: string): RequestedModuleType {
switch (type) {
case "json":
return RequestedModuleType.Json;
case "bytes":
return RequestedModuleType.Bytes;
case "text":
return RequestedModuleType.Text;
default:
if (id.endsWith(".json")) {
return RequestedModuleType.Json;
}
return RequestedModuleType.Default;
}
}
function babelTransform(
options: {
media: MediaType;
ssr: boolean;
code: string;
id: string;
isDev: boolean;
},
) {
if (!isJsMediaType(options.media)) {
return null;
}
const { ssr, code, id, isDev } = options;
const presets: babel.PluginItem[] = [];
if (
!ssr && (id.endsWith(".tsx") || id.endsWith(".jsx"))
) {
presets.push([babelReact, {
runtime: "automatic",
importSource: "preact",
development: isDev,
throwIfNamespace: false,
}]);
}
const url = URL.canParse(id) ? new URL(id) : null;
const result = babel.transformSync(code, {
filename: id,
babelrc: false,
sourceMaps: "both",
presets: presets,
plugins: [httpAbsolute(url)],
compact: false,
});
if (result !== null && result.code) {
return {
code: result.code,
map: result.map,
};
}
return null;
}