-
Notifications
You must be signed in to change notification settings - Fork 170
/
transformer.ts
186 lines (179 loc) · 7.08 KB
/
transformer.ts
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
import MagicString from "https://esm.sh/magic-string@0.26.2";
import { parseDeps, transform } from "https://deno.land/x/aleph_compiler@0.6.1/mod.ts";
import type { TransformOptions, TransformResult } from "https://deno.land/x/aleph_compiler@0.6.1/types.ts";
import { TransformError } from "../framework/core/error.ts";
import { readCode } from "../lib/fs.ts";
import log from "../lib/log.ts";
import util from "../lib/util.ts";
import { bundleCSS } from "./bundle_css.ts";
import {
builtinModuleExts,
getAlephPkgUri,
getDeploymentId,
getUnoGenerator,
regFullVersion,
restoreUrl,
toLocalPath,
} from "./helpers.ts";
import { isRouteFile } from "./routing.ts";
import { DependencyGraph } from "./graph.ts";
import type { ImportMap, JSXConfig, ModuleLoader } from "./types.ts";
export type TransformerOptions = {
buildTarget?: TransformOptions["target"];
importMap: ImportMap;
isDev: boolean;
jsxConfig?: JSXConfig;
loader?: ModuleLoader;
};
export default {
test: (pathname: string) => {
return pathname.startsWith("/-/") ||
(builtinModuleExts.find((ext) => pathname.endsWith(`.${ext}`)) && !pathname.endsWith(".d.ts")) ||
pathname.endsWith(".css");
},
fetch: async (req: Request, options: TransformerOptions): Promise<Response> => {
const { isDev, loader } = options;
const { pathname, searchParams, search } = new URL(req.url);
const specifier = pathname.startsWith("/-/") ? restoreUrl(pathname + search) : `.${pathname}`;
const clientDependencyGraph: DependencyGraph | undefined = Reflect.get(globalThis, "__ALEPH_CLIENT_DEP_GRAPH");
const deployId = getDeploymentId();
const etag = deployId ? `W/${deployId}` : null;
if (etag && req.headers.get("If-None-Match") === etag) {
return new Response(null, { status: 304 });
}
let resBody = "";
let resType = "application/javascript";
let [sourceCode, codeType] = await readCode(specifier);
try {
let lang: string | undefined;
let inlineCSS: string | undefined;
let isCSS: boolean;
let uno: boolean;
if (loader) {
const loaded = await loader.load(specifier, sourceCode, { importMap: options.importMap, isDev });
sourceCode = loaded.code;
lang = loaded.lang;
inlineCSS = loaded.inlineCSS;
isCSS = loaded.lang === "css";
uno = Boolean(loaded.isTemplateLanguage || loaded.lang === "jsx" || loaded.lang === "tsx");
} else {
isCSS = codeType.startsWith("text/css");
uno = pathname.endsWith(".jsx") || pathname.endsWith(".tsx");
}
if (isCSS) {
const asJsModule = searchParams.has("module");
const { code, deps } = await bundleCSS(specifier, sourceCode, {
// todo: support borwserslist
targets: {
android: 95,
chrome: 95,
edge: 95,
firefox: 90,
safari: 14,
},
minify: !isDev,
cssModules: asJsModule && pathname.endsWith(".module.css"),
asJsModule,
hmr: isDev,
});
clientDependencyGraph?.mark(specifier, { deps: deps?.map((specifier) => ({ specifier })) });
resBody = code;
if (!asJsModule) {
resType = "text/css";
}
} else {
const alephPkgUri = getAlephPkgUri();
const { jsxConfig, importMap, buildTarget } = options;
let ret: TransformResult;
if (/^https?:\/\/((cdn\.)?esm\.sh|unpkg\.com)\//.test(specifier)) {
// don't transform modules imported from esm.sh
const deps = await parseDeps(specifier, sourceCode, { importMap: JSON.stringify(importMap) });
if (deps.length > 0) {
const s = new MagicString(sourceCode);
deps.forEach((dep) => {
const { importUrl, loc } = dep;
if (loc) {
s.overwrite(loc.start - 1, loc.end - 1, `"${toLocalPath(importUrl)}"`);
}
});
ret = { code: s.toString(), deps };
} else {
ret = { code: sourceCode, deps };
}
} else {
const graphVersions = clientDependencyGraph?.modules.filter((mod) =>
!util.isLikelyHttpURL(specifier) && !util.isLikelyHttpURL(mod.specifier) && mod.specifier !== specifier
).reduce((acc, { specifier, version }) => {
acc[specifier] = version.toString(16);
return acc;
}, {} as Record<string, string>);
ret = await transform(specifier, sourceCode, {
...jsxConfig,
lang: lang as TransformOptions["lang"],
stripDataExport: isRouteFile(specifier),
target: buildTarget ?? (isDev ? "es2022" : "es2020"),
alephPkgUri,
importMap: JSON.stringify(importMap),
graphVersions,
globalVersion: clientDependencyGraph?.globalVersion.toString(16),
isDev,
});
}
let { code, map, deps } = ret;
let hasInlineCSS = false;
if (uno) {
try {
const unoGenerator = getUnoGenerator();
if (unoGenerator) {
const { css } = await unoGenerator.generate(sourceCode, { id: specifier, minify: !isDev });
if (css) {
code += `\nimport { applyUnoCSS as __applyUnoCSS } from "${
toLocalPath(alephPkgUri)
}/framework/core/style.ts";\n__applyUnoCSS(${JSON.stringify(specifier)}, ${JSON.stringify(css)});\n`;
hasInlineCSS = true;
}
}
} catch (e) {
log.warn("[UnoCSS]", e);
}
}
if (inlineCSS) {
code += `\nimport { applyCSS as __applyCSS } from "${
toLocalPath(alephPkgUri)
}/framework/core/style.ts";\n__applyCSS(${JSON.stringify(specifier)}, ${JSON.stringify(inlineCSS)});\n`;
hasInlineCSS = true;
}
if (hasInlineCSS) {
deps = [...(deps || []), { specifier: alephPkgUri + "/framework/core/style.ts" }] as typeof deps;
}
clientDependencyGraph?.mark(specifier, { deps });
if (map) {
try {
const m = JSON.parse(map);
if (!util.isLikelyHttpURL(specifier)) {
m.sources = [`file://source/${util.trimPrefix(specifier, ".")}`];
}
m.sourcesContent = [sourceCode];
resBody = code +
`\n//# sourceMappingURL=data:application/json;charset=utf-8;base64,${btoa(JSON.stringify(m))}\n`;
} catch (e) {
log.debug(`[dev] Failed to add source map for '${specifier}'`, e);
resBody = code;
}
} else {
resBody = code;
}
}
} catch (error) {
throw new TransformError(specifier, sourceCode, error.message, error.stack);
}
const headers = new Headers([["Content-Type", `${resType}; charset=utf-8`]]);
if (etag) {
headers.set("ETag", etag);
}
if (searchParams.get("v") || (pathname.startsWith("/-/") && regFullVersion.test(pathname))) {
headers.append("Cache-Control", "public, max-age=31536000, immutable");
}
return new Response(resBody, { headers });
},
};