-
Notifications
You must be signed in to change notification settings - Fork 922
/
build-import-proxy.ts
280 lines (258 loc) · 7.94 KB
/
build-import-proxy.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
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
import path from 'path';
import postCss from 'postcss';
import postCssModules from 'postcss-modules';
import {logger} from '../logger';
import {SnowpackConfig} from '../types';
import {appendHtmlToHead, hasExtension, HMR_CLIENT_CODE, HMR_OVERLAY_CODE} from '../util';
import {generateSRI} from './import-sri';
export const SRI_CLIENT_HMR_SNOWPACK = generateSRI(Buffer.from(HMR_CLIENT_CODE));
export const SRI_ERROR_HMR_SNOWPACK = generateSRI(Buffer.from(HMR_OVERLAY_CODE));
const importMetaRegex = /import\s*\.\s*meta/;
export function getMetaUrlPath(urlPath: string, config: SnowpackConfig): string {
return path.posix.normalize(path.posix.join('/', config.buildOptions.metaUrlPath, urlPath));
}
export function wrapImportMeta({
code,
hmr,
env,
config,
}: {
code: string;
hmr: boolean;
env: boolean;
config: SnowpackConfig;
}) {
// Create Regex expressions here, since global regex has per-string state
const importMetaHotRegex = /import\s*\.\s*meta\s*\.\s*hot/g;
const importMetaEnvRegex = /import\s*\.\s*meta\s*\.\s*env/g;
// Optimize: replace direct references to `import.meta.hot` by inlining undefined.
// Do this first so that we can bail out in the next `import.meta` test.
if (!hmr) {
code = code.replace(importMetaHotRegex, 'undefined /* [snowpack] import.meta.hot */ ');
}
if (!importMetaRegex.test(code)) {
return code;
}
let hmrSnippet = ``;
if (hmr) {
hmrSnippet = `import * as __SNOWPACK_HMR__ from '${getMetaUrlPath(
'hmr-client.js',
config,
)}';\nimport.meta.hot = __SNOWPACK_HMR__.createHotContext(import.meta.url);\n`;
}
let envSnippet = ``;
if (env) {
envSnippet = `import * as __SNOWPACK_ENV__ from '${getMetaUrlPath('env.js', config)}';\n`;
// Optimize any direct references `import.meta.env` by inlining the ref
code = code.replace(importMetaEnvRegex, '__SNOWPACK_ENV__');
// If we still detect references to `import.meta`, assign `import.meta.env` to be safe
if (importMetaRegex.test(code)) {
envSnippet += `import.meta.env = __SNOWPACK_ENV__;\n`;
}
}
return hmrSnippet + envSnippet + '\n' + code;
}
export function wrapHtmlResponse({
code,
hmr,
hmrPort,
isDev,
config,
mode,
}: {
code: string;
hmr: boolean;
hmrPort?: number;
isDev: boolean;
config: SnowpackConfig;
mode: 'development' | 'production';
}) {
// replace %PUBLIC_URL% (along with surrounding slashes, if any)
code = code.replace(/\/?%PUBLIC_URL%\/?/g, isDev ? '/' : config.buildOptions.baseUrl);
// replace %MODE%
code = code.replace(/%MODE%/g, mode);
const snowpackPublicEnv = getSnowpackPublicEnvVariables();
code = code.replace(/%SNOWPACK_PUBLIC_.+?%/gi, (match: string) => {
const envVariableName = match.slice(1, -1);
if (envVariableName in snowpackPublicEnv) {
return snowpackPublicEnv[envVariableName] || '';
}
logger.warn(`Environment variable "${envVariableName}" is not set`);
return match;
});
// Full Page Transformations: Only full page responses should get these transformations.
// Any code not containing `<!DOCTYPE html>` is assumed to be an HTML fragment.
const isFullPage = code.trim().toLowerCase().startsWith('<!doctype html>');
if (hmr && !isFullPage && !config.buildOptions.htmlFragments) {
throw new Error(`HTML fragment found!
HTML fragments (files not starting with "<!doctype html>") are not transformed like full HTML pages.
Add the missing doctype, or set buildOptions.htmlFragments=true if HTML fragments are expected.`);
}
if (hmr && isFullPage) {
let hmrScript = ``;
if (hmrPort) {
hmrScript += `<script type="text/javascript">window.HMR_WEBSOCKET_PORT=${hmrPort}</script>\n`;
}
hmrScript += `<script type="module" integrity="${SRI_CLIENT_HMR_SNOWPACK}" src="${getMetaUrlPath(
'hmr-client.js',
config,
)}"></script>`;
if (config.devOptions.hmrErrorOverlay) {
hmrScript += `<script type="module" integrity="${SRI_ERROR_HMR_SNOWPACK}" src="${getMetaUrlPath(
'hmr-error-overlay.js',
config,
)}"></script>`;
}
code = appendHtmlToHead(code, hmrScript);
}
return code;
}
function generateJsonImportProxy({
code,
hmr,
config,
}: {
code: string;
hmr: boolean;
config: SnowpackConfig;
}) {
const jsonImportProxyCode = `let json = ${JSON.stringify(JSON.parse(code))};
export default json;`;
return wrapImportMeta({code: jsonImportProxyCode, hmr, env: false, config});
}
function generateCssImportProxy({
code,
hmr,
config,
}: {
code: string;
hmr: boolean;
config: SnowpackConfig;
}) {
const cssImportProxyCode = `// [snowpack] add styles to the page (skip if no document exists)
if (typeof document !== 'undefined') {${
hmr
? `
import.meta.hot.accept();
import.meta.hot.dispose(() => {
document.head.removeChild(styleEl);
});\n`
: ''
}
const code = ${JSON.stringify(code)};
const styleEl = document.createElement("style");
const codeEl = document.createTextNode(code);
styleEl.type = 'text/css';
styleEl.appendChild(codeEl);
document.head.appendChild(styleEl);
}`;
return wrapImportMeta({code: cssImportProxyCode, hmr, env: false, config});
}
async function generateCssModuleImportProxy({
url,
code,
hmr,
config,
}: {
url: string;
code: string;
hmr: boolean;
config: SnowpackConfig;
}) {
let moduleJson: string | undefined;
const processor = postCss([
postCssModules({
getJSON: (_, json) => {
moduleJson = json;
},
}),
]);
const result = await processor.process(code, {
from: url,
to: url + '.proxy.js',
});
// log any warnings that happened.
result
.warnings()
.forEach((element) => logger.warn(`${url} - ${element.text}`, {name: 'snowpack:cssmodules'}));
// return the JS+CSS proxy file.
return `
export let code = ${JSON.stringify(result.css)};
let json = ${JSON.stringify(moduleJson)};
export default json;
${
hmr
? `
import * as __SNOWPACK_HMR_API__ from '${getMetaUrlPath('hmr-client.js', config)}';
import.meta.hot = __SNOWPACK_HMR_API__.createHotContext(import.meta.url);\n`
: ``
}
// [snowpack] add styles to the page (skip if no document exists)
if (typeof document !== 'undefined') {${
hmr
? `
import.meta.hot.dispose(() => {
document && document.head.removeChild(styleEl);
});\n`
: ``
}
const styleEl = document.createElement("style");
const codeEl = document.createTextNode(code);
styleEl.type = 'text/css';
styleEl.appendChild(codeEl);
document.head.appendChild(styleEl);
}`;
}
function generateDefaultImportProxy(url: string) {
return `export default ${JSON.stringify(url)};`;
}
export async function wrapImportProxy({
url,
code,
hmr,
config,
}: {
url: string;
code: string | Buffer;
hmr: boolean;
config: SnowpackConfig;
}) {
if (hasExtension(url, '.json')) {
return generateJsonImportProxy({code: code.toString(), hmr, config});
}
if (hasExtension(url, '.css')) {
// if proxying a CSS file, remove its source map (the path no longer applies)
const sanitized = code.toString().replace(/\/\*#\s*sourceMappingURL=[^/]+\//gm, '');
return hasExtension(url, '.module.css')
? generateCssModuleImportProxy({url, code: sanitized, hmr, config})
: generateCssImportProxy({code: sanitized, hmr, config});
}
return generateDefaultImportProxy(url);
}
export function generateEnvModule({
mode,
isSSR,
}: {
mode: 'development' | 'production';
isSSR: boolean;
}) {
const envObject: Record<string, string | boolean | undefined> = getSnowpackPublicEnvVariables();
envObject.MODE = mode;
envObject.NODE_ENV = mode;
envObject.SSR = isSSR;
return Object.entries(envObject)
.map(([key, val]) => {
return `export const ${key} = ${JSON.stringify(val)};`;
})
.join('\n');
}
const PUBLIC_ENV_REGEX = /^SNOWPACK_PUBLIC_.+/;
function getSnowpackPublicEnvVariables() {
const envObject = {...process.env};
for (const env of Object.keys(envObject)) {
if (!PUBLIC_ENV_REGEX.test(env)) {
delete envObject[env];
}
}
return envObject;
}