@jsenv/core 40.0.1 → 40.0.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/js/build.js +17639 -0
- package/dist/js/directory_listing.js +4 -4
- package/dist/js/main.js +994 -0
- package/dist/js/new_stylesheet.js +1 -1
- package/dist/js/process_teardown_events.js +1848 -0
- package/dist/js/regenerator_runtime.js +1 -1
- package/dist/js/server_events_client.js +0 -1
- package/dist/js/start_build_server.js +206 -0
- package/dist/js/start_dev_server.js +846 -0
- package/dist/jsenv_core.js +2 -21359
- package/package.json +18 -14
- package/src/build/build_specifier_manager.js +2 -1
- package/src/main.js +13 -3
- package/src/plugins/resolution_node_esm/node_esm_resolver.js +17 -1
|
@@ -0,0 +1,846 @@
|
|
|
1
|
+
import { assertAndNormalizeDirectoryUrl, createLogger, createTaskLog } from "./process_teardown_events.js";
|
|
2
|
+
import { ServerEvents, jsenvServiceCORS, jsenvAccessControlAllowedHeaders, composeTwoResponses, serveDirectory, jsenvServiceErrorHandler, startServer } from "@jsenv/server";
|
|
3
|
+
import { convertFileSystemErrorToResponseProperties } from "@jsenv/server/src/internal/convertFileSystemErrorToResponseProperties.js";
|
|
4
|
+
import { URL_META } from "./main.js";
|
|
5
|
+
import { existsSync, readFileSync } from "node:fs";
|
|
6
|
+
import { moveUrl, urlIsInsideOf, ensureWindowsDriveLetter, urlToRelativeUrl, lookupPackageDirectory, createEventEmitter, watchSourceFiles, createPluginStore, getCorePlugins, defaultRuntimeCompat, createKitchen, bufferToEtag, createPluginController } from "./build.js";
|
|
7
|
+
import { parseHtml, injectJsenvScript, stringifyHtmlAst } from "@jsenv/ast";
|
|
8
|
+
import { createRequire } from "node:module";
|
|
9
|
+
import "node:process";
|
|
10
|
+
import "node:os";
|
|
11
|
+
import "node:tty";
|
|
12
|
+
import "string-width";
|
|
13
|
+
import "node:url";
|
|
14
|
+
import "@jsenv/sourcemap";
|
|
15
|
+
import "@jsenv/runtime-compat";
|
|
16
|
+
import "node:path";
|
|
17
|
+
import "node:crypto";
|
|
18
|
+
import "node:perf_hooks";
|
|
19
|
+
import "@jsenv/plugin-supervisor";
|
|
20
|
+
import "@jsenv/js-module-fallback";
|
|
21
|
+
|
|
22
|
+
const WEB_URL_CONVERTER = {
|
|
23
|
+
asWebUrl: (fileUrl, webServer) => {
|
|
24
|
+
if (urlIsInsideOf(fileUrl, webServer.rootDirectoryUrl)) {
|
|
25
|
+
return moveUrl({
|
|
26
|
+
url: fileUrl,
|
|
27
|
+
from: webServer.rootDirectoryUrl,
|
|
28
|
+
to: `${webServer.origin}/`,
|
|
29
|
+
});
|
|
30
|
+
}
|
|
31
|
+
const fsRootUrl = ensureWindowsDriveLetter("file:///", fileUrl);
|
|
32
|
+
return `${webServer.origin}/@fs/${fileUrl.slice(fsRootUrl.length)}`;
|
|
33
|
+
},
|
|
34
|
+
asFileUrl: (webUrl, webServer) => {
|
|
35
|
+
const { pathname, search } = new URL(webUrl);
|
|
36
|
+
if (pathname.startsWith("/@fs/")) {
|
|
37
|
+
const fsRootRelativeUrl = pathname.slice("/@fs/".length);
|
|
38
|
+
return `file:///${fsRootRelativeUrl}${search}`;
|
|
39
|
+
}
|
|
40
|
+
return moveUrl({
|
|
41
|
+
url: webUrl,
|
|
42
|
+
from: `${webServer.origin}/`,
|
|
43
|
+
to: webServer.rootDirectoryUrl,
|
|
44
|
+
});
|
|
45
|
+
},
|
|
46
|
+
};
|
|
47
|
+
|
|
48
|
+
/*
|
|
49
|
+
* This plugin is very special because it is here
|
|
50
|
+
* to provide "serverEvents" used by other plugins
|
|
51
|
+
*/
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
const serverEventsClientFileUrl = new URL(
|
|
55
|
+
"./server_events_client.js",
|
|
56
|
+
import.meta.url,
|
|
57
|
+
).href;
|
|
58
|
+
|
|
59
|
+
const jsenvPluginServerEvents = ({ clientAutoreload }) => {
|
|
60
|
+
let serverEvents = new ServerEvents({
|
|
61
|
+
actionOnClientLimitReached: "kick-oldest",
|
|
62
|
+
});
|
|
63
|
+
const { clientServerEventsConfig } = clientAutoreload;
|
|
64
|
+
const { logs = true } = clientServerEventsConfig;
|
|
65
|
+
|
|
66
|
+
return {
|
|
67
|
+
name: "jsenv:server_events",
|
|
68
|
+
appliesDuring: "dev",
|
|
69
|
+
effect: ({ kitchenContext, otherPlugins }) => {
|
|
70
|
+
const allServerEvents = {};
|
|
71
|
+
for (const otherPlugin of otherPlugins) {
|
|
72
|
+
const { serverEvents } = otherPlugin;
|
|
73
|
+
if (!serverEvents) {
|
|
74
|
+
continue;
|
|
75
|
+
}
|
|
76
|
+
for (const serverEventName of Object.keys(serverEvents)) {
|
|
77
|
+
// we could throw on serverEvent name conflict
|
|
78
|
+
// we could throw if serverEvents[serverEventName] is not a function
|
|
79
|
+
allServerEvents[serverEventName] = serverEvents[serverEventName];
|
|
80
|
+
}
|
|
81
|
+
}
|
|
82
|
+
const serverEventNames = Object.keys(allServerEvents);
|
|
83
|
+
if (serverEventNames.length === 0) {
|
|
84
|
+
return false;
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
const onabort = () => {
|
|
88
|
+
serverEvents.close();
|
|
89
|
+
};
|
|
90
|
+
kitchenContext.signal.addEventListener("abort", onabort);
|
|
91
|
+
for (const serverEventName of Object.keys(allServerEvents)) {
|
|
92
|
+
const serverEventInfo = {
|
|
93
|
+
...kitchenContext,
|
|
94
|
+
// serverEventsDispatcher variable is safe, we can disable esling warning
|
|
95
|
+
// eslint-disable-next-line no-loop-func
|
|
96
|
+
sendServerEvent: (data) => {
|
|
97
|
+
if (!serverEvents) {
|
|
98
|
+
// this can happen if a plugin wants to send a server event but
|
|
99
|
+
// server is closing or the plugin got destroyed but still wants to do things
|
|
100
|
+
// if plugin code is correctly written it is never supposed to happen
|
|
101
|
+
// because it means a plugin is still trying to do stuff after being destroyed
|
|
102
|
+
return;
|
|
103
|
+
}
|
|
104
|
+
serverEvents.sendEventToAllClients({
|
|
105
|
+
type: serverEventName,
|
|
106
|
+
data,
|
|
107
|
+
});
|
|
108
|
+
},
|
|
109
|
+
};
|
|
110
|
+
const serverEventInit = allServerEvents[serverEventName];
|
|
111
|
+
serverEventInit(serverEventInfo);
|
|
112
|
+
}
|
|
113
|
+
return () => {
|
|
114
|
+
kitchenContext.signal.removeEventListener("abort", onabort);
|
|
115
|
+
serverEvents.close();
|
|
116
|
+
serverEvents = undefined;
|
|
117
|
+
};
|
|
118
|
+
},
|
|
119
|
+
transformUrlContent: {
|
|
120
|
+
html: (urlInfo) => {
|
|
121
|
+
const htmlAst = parseHtml({
|
|
122
|
+
html: urlInfo.content,
|
|
123
|
+
url: urlInfo.url,
|
|
124
|
+
});
|
|
125
|
+
injectJsenvScript(htmlAst, {
|
|
126
|
+
src: serverEventsClientFileUrl,
|
|
127
|
+
initCall: {
|
|
128
|
+
callee: "window.__server_events__.setup",
|
|
129
|
+
params: {
|
|
130
|
+
logs,
|
|
131
|
+
},
|
|
132
|
+
},
|
|
133
|
+
pluginName: "jsenv:server_events",
|
|
134
|
+
});
|
|
135
|
+
return stringifyHtmlAst(htmlAst);
|
|
136
|
+
},
|
|
137
|
+
},
|
|
138
|
+
devServerRoutes: [
|
|
139
|
+
{
|
|
140
|
+
endpoint: "GET /.internal/events.websocket",
|
|
141
|
+
description: `Jsenv dev server emit server events on this endpoint. When a file is saved the "reload" event is sent here.`,
|
|
142
|
+
fetch: serverEvents.fetch,
|
|
143
|
+
declarationSource: import.meta.url,
|
|
144
|
+
},
|
|
145
|
+
],
|
|
146
|
+
};
|
|
147
|
+
};
|
|
148
|
+
|
|
149
|
+
const memoizeByFirstArgument = (compute) => {
|
|
150
|
+
const urlCache = new Map();
|
|
151
|
+
|
|
152
|
+
const fnWithMemoization = (url, ...args) => {
|
|
153
|
+
const valueFromCache = urlCache.get(url);
|
|
154
|
+
if (valueFromCache) {
|
|
155
|
+
return valueFromCache;
|
|
156
|
+
}
|
|
157
|
+
const value = compute(url, ...args);
|
|
158
|
+
urlCache.set(url, value);
|
|
159
|
+
return value;
|
|
160
|
+
};
|
|
161
|
+
|
|
162
|
+
fnWithMemoization.forget = () => {
|
|
163
|
+
urlCache.clear();
|
|
164
|
+
};
|
|
165
|
+
|
|
166
|
+
return fnWithMemoization;
|
|
167
|
+
};
|
|
168
|
+
|
|
169
|
+
const requireFromJsenv = createRequire(import.meta.url);
|
|
170
|
+
|
|
171
|
+
const parseUserAgentHeader = memoizeByFirstArgument((userAgent) => {
|
|
172
|
+
if (userAgent.includes("node-fetch/")) {
|
|
173
|
+
// it's not really node and conceptually we can't assume the node version
|
|
174
|
+
// but good enough for now
|
|
175
|
+
return {
|
|
176
|
+
runtimeName: "node",
|
|
177
|
+
runtimeVersion: process.version.slice(1),
|
|
178
|
+
};
|
|
179
|
+
}
|
|
180
|
+
const UA = requireFromJsenv("@financial-times/polyfill-useragent-normaliser");
|
|
181
|
+
const { ua } = new UA(userAgent);
|
|
182
|
+
const { family, major, minor, patch } = ua;
|
|
183
|
+
return {
|
|
184
|
+
runtimeName: family.toLowerCase(),
|
|
185
|
+
runtimeVersion:
|
|
186
|
+
family === "Other" ? "unknown" : `${major}.${minor}${patch}`,
|
|
187
|
+
};
|
|
188
|
+
});
|
|
189
|
+
|
|
190
|
+
const EXECUTED_BY_TEST_PLAN = process.argv.includes("--jsenv-test");
|
|
191
|
+
|
|
192
|
+
/**
|
|
193
|
+
* Start a server for source files:
|
|
194
|
+
* - cook source files according to jsenv plugins
|
|
195
|
+
* - inject code to autoreload the browser when a file is modified
|
|
196
|
+
* @param {Object} devServerParameters
|
|
197
|
+
* @param {string|url} devServerParameters.sourceDirectoryUrl Root directory of the project
|
|
198
|
+
* @return {Object} A dev server object
|
|
199
|
+
*/
|
|
200
|
+
const startDevServer = async ({
|
|
201
|
+
sourceDirectoryUrl,
|
|
202
|
+
sourceMainFilePath = "./index.html",
|
|
203
|
+
ignore,
|
|
204
|
+
port = 3456,
|
|
205
|
+
hostname,
|
|
206
|
+
acceptAnyIp,
|
|
207
|
+
https,
|
|
208
|
+
// it's better to use http1 by default because it allows to get statusText in devtools
|
|
209
|
+
// which gives valuable information when there is errors
|
|
210
|
+
http2 = false,
|
|
211
|
+
logLevel = EXECUTED_BY_TEST_PLAN ? "warn" : "info",
|
|
212
|
+
serverLogLevel = "warn",
|
|
213
|
+
services = [],
|
|
214
|
+
|
|
215
|
+
signal = new AbortController().signal,
|
|
216
|
+
handleSIGINT = true,
|
|
217
|
+
keepProcessAlive = true,
|
|
218
|
+
onStop = () => {},
|
|
219
|
+
|
|
220
|
+
sourceFilesConfig = {},
|
|
221
|
+
clientAutoreload = true,
|
|
222
|
+
|
|
223
|
+
// runtimeCompat is the runtimeCompat for the build
|
|
224
|
+
// when specified, dev server use it to warn in case
|
|
225
|
+
// code would be supported during dev but not after build
|
|
226
|
+
runtimeCompat = defaultRuntimeCompat,
|
|
227
|
+
plugins = [],
|
|
228
|
+
referenceAnalysis = {},
|
|
229
|
+
nodeEsmResolution,
|
|
230
|
+
supervisor = true,
|
|
231
|
+
magicExtensions,
|
|
232
|
+
magicDirectoryIndex,
|
|
233
|
+
directoryListing,
|
|
234
|
+
injections,
|
|
235
|
+
transpilation,
|
|
236
|
+
cacheControl = true,
|
|
237
|
+
ribbon = true,
|
|
238
|
+
// toolbar = false,
|
|
239
|
+
onKitchenCreated = () => {},
|
|
240
|
+
|
|
241
|
+
sourcemaps = "inline",
|
|
242
|
+
sourcemapsSourcesContent,
|
|
243
|
+
outDirectoryUrl,
|
|
244
|
+
...rest
|
|
245
|
+
}) => {
|
|
246
|
+
// params type checking
|
|
247
|
+
{
|
|
248
|
+
const unexpectedParamNames = Object.keys(rest);
|
|
249
|
+
if (unexpectedParamNames.length > 0) {
|
|
250
|
+
throw new TypeError(
|
|
251
|
+
`${unexpectedParamNames.join(",")}: there is no such param`,
|
|
252
|
+
);
|
|
253
|
+
}
|
|
254
|
+
sourceDirectoryUrl = assertAndNormalizeDirectoryUrl(
|
|
255
|
+
sourceDirectoryUrl,
|
|
256
|
+
"sourceDirectoryUrl",
|
|
257
|
+
);
|
|
258
|
+
if (!existsSync(new URL(sourceDirectoryUrl))) {
|
|
259
|
+
throw new Error(`ENOENT on sourceDirectoryUrl at ${sourceDirectoryUrl}`);
|
|
260
|
+
}
|
|
261
|
+
if (typeof sourceMainFilePath !== "string") {
|
|
262
|
+
throw new TypeError(
|
|
263
|
+
`sourceMainFilePath must be a string, got ${sourceMainFilePath}`,
|
|
264
|
+
);
|
|
265
|
+
}
|
|
266
|
+
sourceMainFilePath = urlToRelativeUrl(
|
|
267
|
+
new URL(sourceMainFilePath, sourceDirectoryUrl),
|
|
268
|
+
sourceDirectoryUrl,
|
|
269
|
+
);
|
|
270
|
+
if (outDirectoryUrl === undefined) {
|
|
271
|
+
if (
|
|
272
|
+
process.env.CAPTURING_SIDE_EFFECTS ||
|
|
273
|
+
(false)
|
|
274
|
+
) {
|
|
275
|
+
outDirectoryUrl = new URL("../.jsenv/", sourceDirectoryUrl);
|
|
276
|
+
} else {
|
|
277
|
+
const packageDirectoryUrl = lookupPackageDirectory(sourceDirectoryUrl);
|
|
278
|
+
if (packageDirectoryUrl) {
|
|
279
|
+
outDirectoryUrl = `${packageDirectoryUrl}.jsenv/`;
|
|
280
|
+
}
|
|
281
|
+
}
|
|
282
|
+
} else if (outDirectoryUrl !== null && outDirectoryUrl !== false) {
|
|
283
|
+
outDirectoryUrl = assertAndNormalizeDirectoryUrl(
|
|
284
|
+
outDirectoryUrl,
|
|
285
|
+
"outDirectoryUrl",
|
|
286
|
+
);
|
|
287
|
+
}
|
|
288
|
+
}
|
|
289
|
+
|
|
290
|
+
// params normalization
|
|
291
|
+
{
|
|
292
|
+
if (clientAutoreload === true) {
|
|
293
|
+
clientAutoreload = {};
|
|
294
|
+
}
|
|
295
|
+
if (clientAutoreload === false) {
|
|
296
|
+
clientAutoreload = { enabled: false };
|
|
297
|
+
}
|
|
298
|
+
}
|
|
299
|
+
|
|
300
|
+
const logger = createLogger({ logLevel });
|
|
301
|
+
const startDevServerTask = createTaskLog("start dev server", {
|
|
302
|
+
disabled: !logger.levels.info,
|
|
303
|
+
});
|
|
304
|
+
|
|
305
|
+
const serverStopCallbackSet = new Set();
|
|
306
|
+
const serverStopAbortController = new AbortController();
|
|
307
|
+
serverStopCallbackSet.add(() => {
|
|
308
|
+
serverStopAbortController.abort();
|
|
309
|
+
});
|
|
310
|
+
const serverStopAbortSignal = serverStopAbortController.signal;
|
|
311
|
+
const kitchenCache = new Map();
|
|
312
|
+
|
|
313
|
+
const finalServices = [];
|
|
314
|
+
// x-server-inspect service
|
|
315
|
+
{
|
|
316
|
+
finalServices.push({
|
|
317
|
+
name: "jsenv:server_header",
|
|
318
|
+
routes: [
|
|
319
|
+
{
|
|
320
|
+
endpoint: "GET /.internal/server.json",
|
|
321
|
+
description: "Get information about jsenv dev server",
|
|
322
|
+
availableMediaTypes: ["application/json"],
|
|
323
|
+
declarationSource: import.meta.url,
|
|
324
|
+
fetch: () =>
|
|
325
|
+
Response.json({
|
|
326
|
+
server: "jsenv_dev_server/1",
|
|
327
|
+
sourceDirectoryUrl,
|
|
328
|
+
}),
|
|
329
|
+
},
|
|
330
|
+
],
|
|
331
|
+
injectResponseProperties: () => {
|
|
332
|
+
return {
|
|
333
|
+
headers: {
|
|
334
|
+
server: "jsenv_dev_server/1",
|
|
335
|
+
},
|
|
336
|
+
};
|
|
337
|
+
},
|
|
338
|
+
});
|
|
339
|
+
}
|
|
340
|
+
// cors service
|
|
341
|
+
{
|
|
342
|
+
finalServices.push(
|
|
343
|
+
jsenvServiceCORS({
|
|
344
|
+
accessControlAllowRequestOrigin: true,
|
|
345
|
+
accessControlAllowRequestMethod: true,
|
|
346
|
+
accessControlAllowRequestHeaders: true,
|
|
347
|
+
accessControlAllowedRequestHeaders: [
|
|
348
|
+
...jsenvAccessControlAllowedHeaders,
|
|
349
|
+
"x-jsenv-execution-id",
|
|
350
|
+
],
|
|
351
|
+
accessControlAllowCredentials: true,
|
|
352
|
+
timingAllowOrigin: true,
|
|
353
|
+
}),
|
|
354
|
+
);
|
|
355
|
+
}
|
|
356
|
+
// custom services
|
|
357
|
+
{
|
|
358
|
+
finalServices.push(...services);
|
|
359
|
+
}
|
|
360
|
+
// file_service
|
|
361
|
+
{
|
|
362
|
+
const clientFileChangeEventEmitter = createEventEmitter();
|
|
363
|
+
const clientFileDereferencedEventEmitter = createEventEmitter();
|
|
364
|
+
clientAutoreload = {
|
|
365
|
+
enabled: true,
|
|
366
|
+
clientServerEventsConfig: {},
|
|
367
|
+
clientFileChangeEventEmitter,
|
|
368
|
+
clientFileDereferencedEventEmitter,
|
|
369
|
+
...clientAutoreload,
|
|
370
|
+
};
|
|
371
|
+
const stopWatchingSourceFiles = watchSourceFiles(
|
|
372
|
+
sourceDirectoryUrl,
|
|
373
|
+
(fileInfo) => {
|
|
374
|
+
clientFileChangeEventEmitter.emit(fileInfo);
|
|
375
|
+
},
|
|
376
|
+
{
|
|
377
|
+
sourceFilesConfig,
|
|
378
|
+
keepProcessAlive: false,
|
|
379
|
+
cooldownBetweenFileEvents: clientAutoreload.cooldownBetweenFileEvents,
|
|
380
|
+
},
|
|
381
|
+
);
|
|
382
|
+
serverStopCallbackSet.add(stopWatchingSourceFiles);
|
|
383
|
+
|
|
384
|
+
const devServerPluginStore = createPluginStore([
|
|
385
|
+
jsenvPluginServerEvents({ clientAutoreload }),
|
|
386
|
+
...plugins,
|
|
387
|
+
...getCorePlugins({
|
|
388
|
+
rootDirectoryUrl: sourceDirectoryUrl,
|
|
389
|
+
mainFilePath: sourceMainFilePath,
|
|
390
|
+
runtimeCompat,
|
|
391
|
+
sourceFilesConfig,
|
|
392
|
+
|
|
393
|
+
referenceAnalysis,
|
|
394
|
+
nodeEsmResolution,
|
|
395
|
+
magicExtensions,
|
|
396
|
+
magicDirectoryIndex,
|
|
397
|
+
directoryListing,
|
|
398
|
+
supervisor,
|
|
399
|
+
injections,
|
|
400
|
+
transpilation,
|
|
401
|
+
|
|
402
|
+
clientAutoreload,
|
|
403
|
+
cacheControl,
|
|
404
|
+
ribbon,
|
|
405
|
+
}),
|
|
406
|
+
]);
|
|
407
|
+
const getOrCreateKitchen = (request) => {
|
|
408
|
+
const { runtimeName, runtimeVersion } = parseUserAgentHeader(
|
|
409
|
+
request.headers["user-agent"] || "",
|
|
410
|
+
);
|
|
411
|
+
const runtimeId = `${runtimeName}@${runtimeVersion}`;
|
|
412
|
+
const existing = kitchenCache.get(runtimeId);
|
|
413
|
+
if (existing) {
|
|
414
|
+
return existing;
|
|
415
|
+
}
|
|
416
|
+
const watchAssociations = URL_META.resolveAssociations(
|
|
417
|
+
{ watch: stopWatchingSourceFiles.watchPatterns },
|
|
418
|
+
sourceDirectoryUrl,
|
|
419
|
+
);
|
|
420
|
+
let kitchen;
|
|
421
|
+
clientFileChangeEventEmitter.on(({ url, event }) => {
|
|
422
|
+
const urlInfo = kitchen.graph.getUrlInfo(url);
|
|
423
|
+
if (urlInfo) {
|
|
424
|
+
if (event === "removed") {
|
|
425
|
+
urlInfo.onRemoved();
|
|
426
|
+
} else {
|
|
427
|
+
urlInfo.onModified();
|
|
428
|
+
}
|
|
429
|
+
}
|
|
430
|
+
});
|
|
431
|
+
const clientRuntimeCompat = { [runtimeName]: runtimeVersion };
|
|
432
|
+
|
|
433
|
+
kitchen = createKitchen({
|
|
434
|
+
name: runtimeId,
|
|
435
|
+
signal: serverStopAbortSignal,
|
|
436
|
+
logLevel,
|
|
437
|
+
rootDirectoryUrl: sourceDirectoryUrl,
|
|
438
|
+
mainFilePath: sourceMainFilePath,
|
|
439
|
+
ignore,
|
|
440
|
+
dev: true,
|
|
441
|
+
runtimeCompat,
|
|
442
|
+
clientRuntimeCompat,
|
|
443
|
+
supervisor,
|
|
444
|
+
sourcemaps,
|
|
445
|
+
sourcemapsSourcesContent,
|
|
446
|
+
outDirectoryUrl: outDirectoryUrl
|
|
447
|
+
? new URL(`${runtimeName}@${runtimeVersion}/`, outDirectoryUrl)
|
|
448
|
+
: undefined,
|
|
449
|
+
});
|
|
450
|
+
kitchen.graph.urlInfoCreatedEventEmitter.on((urlInfoCreated) => {
|
|
451
|
+
const { watch } = URL_META.applyAssociations({
|
|
452
|
+
url: urlInfoCreated.url,
|
|
453
|
+
associations: watchAssociations,
|
|
454
|
+
});
|
|
455
|
+
urlInfoCreated.isWatched = watch;
|
|
456
|
+
// when an url depends on many others, we check all these (like package.json)
|
|
457
|
+
urlInfoCreated.isValid = () => {
|
|
458
|
+
if (!urlInfoCreated.url.startsWith("file:")) {
|
|
459
|
+
return false;
|
|
460
|
+
}
|
|
461
|
+
if (urlInfoCreated.content === undefined) {
|
|
462
|
+
// urlInfo content is undefined when:
|
|
463
|
+
// - url info content never fetched
|
|
464
|
+
// - it is considered as modified because undelying file is watched and got saved
|
|
465
|
+
// - it is considered as modified because underlying file content
|
|
466
|
+
// was compared using etag and it has changed
|
|
467
|
+
return false;
|
|
468
|
+
}
|
|
469
|
+
if (!watch) {
|
|
470
|
+
// file is not watched, check the filesystem
|
|
471
|
+
let fileContentAsBuffer;
|
|
472
|
+
try {
|
|
473
|
+
fileContentAsBuffer = readFileSync(new URL(urlInfoCreated.url));
|
|
474
|
+
} catch (e) {
|
|
475
|
+
if (e.code === "ENOENT") {
|
|
476
|
+
urlInfoCreated.onModified();
|
|
477
|
+
return false;
|
|
478
|
+
}
|
|
479
|
+
return false;
|
|
480
|
+
}
|
|
481
|
+
const fileContentEtag = bufferToEtag(fileContentAsBuffer);
|
|
482
|
+
if (fileContentEtag !== urlInfoCreated.originalContentEtag) {
|
|
483
|
+
urlInfoCreated.onModified();
|
|
484
|
+
// restore content to be able to compare it again later
|
|
485
|
+
urlInfoCreated.kitchen.urlInfoTransformer.setContent(
|
|
486
|
+
urlInfoCreated,
|
|
487
|
+
String(fileContentAsBuffer),
|
|
488
|
+
{
|
|
489
|
+
contentEtag: fileContentEtag,
|
|
490
|
+
},
|
|
491
|
+
);
|
|
492
|
+
return false;
|
|
493
|
+
}
|
|
494
|
+
}
|
|
495
|
+
for (const implicitUrl of urlInfoCreated.implicitUrlSet) {
|
|
496
|
+
const implicitUrlInfo =
|
|
497
|
+
urlInfoCreated.graph.getUrlInfo(implicitUrl);
|
|
498
|
+
if (!implicitUrlInfo) {
|
|
499
|
+
continue;
|
|
500
|
+
}
|
|
501
|
+
if (implicitUrlInfo.content === undefined) {
|
|
502
|
+
// happens when we explicitely load an url with a search param
|
|
503
|
+
// - it creates an implicit url info to the url without params
|
|
504
|
+
// - we never explicitely request the url without search param so it has no content
|
|
505
|
+
// in that case the underlying urlInfo cannot be invalidate by the implicit
|
|
506
|
+
// we use modifiedTimestamp to detect if the url was loaded once
|
|
507
|
+
// or is just here to be used later
|
|
508
|
+
if (implicitUrlInfo.modifiedTimestamp) {
|
|
509
|
+
return false;
|
|
510
|
+
}
|
|
511
|
+
continue;
|
|
512
|
+
}
|
|
513
|
+
if (!implicitUrlInfo.isValid()) {
|
|
514
|
+
return false;
|
|
515
|
+
}
|
|
516
|
+
}
|
|
517
|
+
return true;
|
|
518
|
+
};
|
|
519
|
+
});
|
|
520
|
+
kitchen.graph.urlInfoDereferencedEventEmitter.on(
|
|
521
|
+
(urlInfoDereferenced, lastReferenceFromOther) => {
|
|
522
|
+
clientFileDereferencedEventEmitter.emit(
|
|
523
|
+
urlInfoDereferenced,
|
|
524
|
+
lastReferenceFromOther,
|
|
525
|
+
);
|
|
526
|
+
},
|
|
527
|
+
);
|
|
528
|
+
const devServerPluginController = createPluginController(
|
|
529
|
+
devServerPluginStore,
|
|
530
|
+
kitchen,
|
|
531
|
+
);
|
|
532
|
+
kitchen.setPluginController(devServerPluginController);
|
|
533
|
+
|
|
534
|
+
serverStopCallbackSet.add(() => {
|
|
535
|
+
devServerPluginController.callHooks("destroy", kitchen.context);
|
|
536
|
+
});
|
|
537
|
+
kitchenCache.set(runtimeId, kitchen);
|
|
538
|
+
onKitchenCreated(kitchen);
|
|
539
|
+
return kitchen;
|
|
540
|
+
};
|
|
541
|
+
|
|
542
|
+
finalServices.push({
|
|
543
|
+
name: "jsenv:dev_server_routes",
|
|
544
|
+
augmentRouteFetchSecondArg: (request) => {
|
|
545
|
+
const kitchen = getOrCreateKitchen(request);
|
|
546
|
+
return { kitchen };
|
|
547
|
+
},
|
|
548
|
+
routes: [
|
|
549
|
+
...devServerPluginStore.allDevServerRoutes,
|
|
550
|
+
{
|
|
551
|
+
endpoint: "GET *",
|
|
552
|
+
description: "Serve project files.",
|
|
553
|
+
declarationSource: import.meta.url,
|
|
554
|
+
fetch: async (request, { kitchen }) => {
|
|
555
|
+
const { rootDirectoryUrl, mainFilePath } = kitchen.context;
|
|
556
|
+
let requestResource = request.resource;
|
|
557
|
+
let requestedUrl;
|
|
558
|
+
if (requestResource.startsWith("/@fs/")) {
|
|
559
|
+
const fsRootRelativeUrl = requestResource.slice("/@fs/".length);
|
|
560
|
+
requestedUrl = `file:///${fsRootRelativeUrl}`;
|
|
561
|
+
} else {
|
|
562
|
+
const requestedUrlObject = new URL(
|
|
563
|
+
requestResource === "/"
|
|
564
|
+
? mainFilePath
|
|
565
|
+
: requestResource.slice(1),
|
|
566
|
+
rootDirectoryUrl,
|
|
567
|
+
);
|
|
568
|
+
requestedUrlObject.searchParams.delete("hot");
|
|
569
|
+
requestedUrl = requestedUrlObject.href;
|
|
570
|
+
}
|
|
571
|
+
const { referer } = request.headers;
|
|
572
|
+
const parentUrl = referer
|
|
573
|
+
? WEB_URL_CONVERTER.asFileUrl(referer, {
|
|
574
|
+
origin: request.origin,
|
|
575
|
+
rootDirectoryUrl: sourceDirectoryUrl,
|
|
576
|
+
})
|
|
577
|
+
: sourceDirectoryUrl;
|
|
578
|
+
let reference = kitchen.graph.inferReference(
|
|
579
|
+
request.resource,
|
|
580
|
+
parentUrl,
|
|
581
|
+
);
|
|
582
|
+
if (reference) {
|
|
583
|
+
reference.urlInfo.context.request = request;
|
|
584
|
+
reference.urlInfo.context.requestedUrl = requestedUrl;
|
|
585
|
+
} else {
|
|
586
|
+
const rootUrlInfo = kitchen.graph.rootUrlInfo;
|
|
587
|
+
rootUrlInfo.context.request = request;
|
|
588
|
+
rootUrlInfo.context.requestedUrl = requestedUrl;
|
|
589
|
+
reference = rootUrlInfo.dependencies.createResolveAndFinalize({
|
|
590
|
+
trace: { message: parentUrl },
|
|
591
|
+
type: "http_request",
|
|
592
|
+
specifier: request.resource,
|
|
593
|
+
});
|
|
594
|
+
rootUrlInfo.context.request = null;
|
|
595
|
+
rootUrlInfo.context.requestedUrl = null;
|
|
596
|
+
}
|
|
597
|
+
const urlInfo = reference.urlInfo;
|
|
598
|
+
const ifNoneMatch = request.headers["if-none-match"];
|
|
599
|
+
const urlInfoTargetedByCache =
|
|
600
|
+
urlInfo.findParentIfInline() || urlInfo;
|
|
601
|
+
|
|
602
|
+
try {
|
|
603
|
+
if (!urlInfo.error && ifNoneMatch) {
|
|
604
|
+
const [clientOriginalContentEtag, clientContentEtag] =
|
|
605
|
+
ifNoneMatch.split("_");
|
|
606
|
+
if (
|
|
607
|
+
urlInfoTargetedByCache.originalContentEtag ===
|
|
608
|
+
clientOriginalContentEtag &&
|
|
609
|
+
urlInfoTargetedByCache.contentEtag === clientContentEtag &&
|
|
610
|
+
urlInfoTargetedByCache.isValid()
|
|
611
|
+
) {
|
|
612
|
+
const headers = {
|
|
613
|
+
"cache-control": `private,max-age=0,must-revalidate`,
|
|
614
|
+
};
|
|
615
|
+
Object.keys(urlInfo.headers).forEach((key) => {
|
|
616
|
+
if (key !== "content-length") {
|
|
617
|
+
headers[key] = urlInfo.headers[key];
|
|
618
|
+
}
|
|
619
|
+
});
|
|
620
|
+
return {
|
|
621
|
+
status: 304,
|
|
622
|
+
headers,
|
|
623
|
+
};
|
|
624
|
+
}
|
|
625
|
+
}
|
|
626
|
+
await urlInfo.cook({ request, reference });
|
|
627
|
+
let { response } = urlInfo;
|
|
628
|
+
if (response) {
|
|
629
|
+
return response;
|
|
630
|
+
}
|
|
631
|
+
response = {
|
|
632
|
+
url: reference.url,
|
|
633
|
+
status: 200,
|
|
634
|
+
headers: {
|
|
635
|
+
// when we send eTag to the client the next request to the server
|
|
636
|
+
// will send etag in request headers.
|
|
637
|
+
// If they match jsenv bypass cooking and returns 304
|
|
638
|
+
// This must not happen when a plugin uses "no-store" or "no-cache" as it means
|
|
639
|
+
// plugin logic wants to happens for every request to this url
|
|
640
|
+
...(cacheIsDisabledInResponseHeader(urlInfoTargetedByCache)
|
|
641
|
+
? {
|
|
642
|
+
"cache-control": "no-store", // for inline file we force no-store when parent is no-store
|
|
643
|
+
}
|
|
644
|
+
: {
|
|
645
|
+
"cache-control": `private,max-age=0,must-revalidate`,
|
|
646
|
+
// it's safe to use "_" separator because etag is encoded with base64 (see https://stackoverflow.com/a/13195197)
|
|
647
|
+
"eTag": `${urlInfoTargetedByCache.originalContentEtag}_${urlInfoTargetedByCache.contentEtag}`,
|
|
648
|
+
}),
|
|
649
|
+
...urlInfo.headers,
|
|
650
|
+
"content-type": urlInfo.contentType,
|
|
651
|
+
"content-length": urlInfo.contentLength,
|
|
652
|
+
},
|
|
653
|
+
body: urlInfo.content,
|
|
654
|
+
timing: urlInfo.timing, // TODO: use something else
|
|
655
|
+
};
|
|
656
|
+
const augmentResponseInfo = {
|
|
657
|
+
...kitchen.context,
|
|
658
|
+
reference,
|
|
659
|
+
urlInfo,
|
|
660
|
+
};
|
|
661
|
+
kitchen.pluginController.callHooks(
|
|
662
|
+
"augmentResponse",
|
|
663
|
+
augmentResponseInfo,
|
|
664
|
+
(returnValue) => {
|
|
665
|
+
response = composeTwoResponses(response, returnValue);
|
|
666
|
+
},
|
|
667
|
+
);
|
|
668
|
+
return response;
|
|
669
|
+
} catch (error) {
|
|
670
|
+
const originalError = error ? error.cause || error : error;
|
|
671
|
+
if (originalError.asResponse) {
|
|
672
|
+
return originalError.asResponse();
|
|
673
|
+
}
|
|
674
|
+
const code = originalError.code;
|
|
675
|
+
if (code === "PARSE_ERROR") {
|
|
676
|
+
// when possible let browser re-throw the syntax error
|
|
677
|
+
// it's not possible to do that when url info content is not available
|
|
678
|
+
// (happens for js_module_fallback for instance)
|
|
679
|
+
if (urlInfo.content !== undefined) {
|
|
680
|
+
kitchen.context.logger
|
|
681
|
+
.error(`Error while handling ${request.url}:
|
|
682
|
+
${originalError.reasonCode || originalError.code}
|
|
683
|
+
${error.trace?.message}`);
|
|
684
|
+
return {
|
|
685
|
+
url: reference.url,
|
|
686
|
+
status: 200,
|
|
687
|
+
// reason becomes the http response statusText, it must not contain invalid chars
|
|
688
|
+
// https://github.com/nodejs/node/blob/0c27ca4bc9782d658afeaebcec85ec7b28f1cc35/lib/_http_common.js#L221
|
|
689
|
+
statusText: error.reason,
|
|
690
|
+
statusMessage: originalError.message,
|
|
691
|
+
headers: {
|
|
692
|
+
"content-type": urlInfo.contentType,
|
|
693
|
+
"content-length": urlInfo.contentLength,
|
|
694
|
+
"cache-control": "no-store",
|
|
695
|
+
},
|
|
696
|
+
body: urlInfo.content,
|
|
697
|
+
};
|
|
698
|
+
}
|
|
699
|
+
return {
|
|
700
|
+
url: reference.url,
|
|
701
|
+
status: 500,
|
|
702
|
+
statusText: error.reason,
|
|
703
|
+
statusMessage: originalError.message,
|
|
704
|
+
headers: {
|
|
705
|
+
"cache-control": "no-store",
|
|
706
|
+
},
|
|
707
|
+
body: urlInfo.content,
|
|
708
|
+
};
|
|
709
|
+
}
|
|
710
|
+
if (code === "DIRECTORY_REFERENCE_NOT_ALLOWED") {
|
|
711
|
+
return serveDirectory(reference.url, {
|
|
712
|
+
headers: {
|
|
713
|
+
accept: "text/html",
|
|
714
|
+
},
|
|
715
|
+
canReadDirectory: true,
|
|
716
|
+
rootDirectoryUrl: sourceDirectoryUrl,
|
|
717
|
+
});
|
|
718
|
+
}
|
|
719
|
+
if (code === "NOT_ALLOWED") {
|
|
720
|
+
return {
|
|
721
|
+
url: reference.url,
|
|
722
|
+
status: 403,
|
|
723
|
+
statusText: originalError.reason,
|
|
724
|
+
};
|
|
725
|
+
}
|
|
726
|
+
if (code === "NOT_FOUND") {
|
|
727
|
+
return {
|
|
728
|
+
url: reference.url,
|
|
729
|
+
status: 404,
|
|
730
|
+
statusText: originalError.reason,
|
|
731
|
+
statusMessage: originalError.message,
|
|
732
|
+
};
|
|
733
|
+
}
|
|
734
|
+
return {
|
|
735
|
+
url: reference.url,
|
|
736
|
+
status: 500,
|
|
737
|
+
statusText: error.reason,
|
|
738
|
+
statusMessage: error.stack,
|
|
739
|
+
headers: {
|
|
740
|
+
"cache-control": "no-store",
|
|
741
|
+
},
|
|
742
|
+
};
|
|
743
|
+
}
|
|
744
|
+
},
|
|
745
|
+
},
|
|
746
|
+
],
|
|
747
|
+
});
|
|
748
|
+
}
|
|
749
|
+
// jsenv error handler service
|
|
750
|
+
{
|
|
751
|
+
finalServices.push({
|
|
752
|
+
name: "jsenv:omega_error_handler",
|
|
753
|
+
handleError: (error) => {
|
|
754
|
+
const getResponseForError = () => {
|
|
755
|
+
if (error && error.asResponse) {
|
|
756
|
+
return error.asResponse();
|
|
757
|
+
}
|
|
758
|
+
if (error && error.statusText === "Unexpected directory operation") {
|
|
759
|
+
return {
|
|
760
|
+
status: 403,
|
|
761
|
+
};
|
|
762
|
+
}
|
|
763
|
+
return convertFileSystemErrorToResponseProperties(error);
|
|
764
|
+
};
|
|
765
|
+
const response = getResponseForError();
|
|
766
|
+
if (!response) {
|
|
767
|
+
return null;
|
|
768
|
+
}
|
|
769
|
+
const body = JSON.stringify({
|
|
770
|
+
status: response.status,
|
|
771
|
+
statusText: response.statusText,
|
|
772
|
+
headers: response.headers,
|
|
773
|
+
body: response.body,
|
|
774
|
+
});
|
|
775
|
+
return {
|
|
776
|
+
status: 200,
|
|
777
|
+
headers: {
|
|
778
|
+
"content-type": "application/json",
|
|
779
|
+
"content-length": Buffer.byteLength(body),
|
|
780
|
+
},
|
|
781
|
+
body,
|
|
782
|
+
};
|
|
783
|
+
},
|
|
784
|
+
});
|
|
785
|
+
}
|
|
786
|
+
// default error handler
|
|
787
|
+
{
|
|
788
|
+
finalServices.push(
|
|
789
|
+
jsenvServiceErrorHandler({
|
|
790
|
+
sendErrorDetails: true,
|
|
791
|
+
}),
|
|
792
|
+
);
|
|
793
|
+
}
|
|
794
|
+
|
|
795
|
+
const server = await startServer({
|
|
796
|
+
signal,
|
|
797
|
+
stopOnExit: false,
|
|
798
|
+
stopOnSIGINT: handleSIGINT,
|
|
799
|
+
stopOnInternalError: false,
|
|
800
|
+
keepProcessAlive,
|
|
801
|
+
logLevel: serverLogLevel,
|
|
802
|
+
startLog: false,
|
|
803
|
+
|
|
804
|
+
https,
|
|
805
|
+
http2,
|
|
806
|
+
acceptAnyIp,
|
|
807
|
+
hostname,
|
|
808
|
+
port,
|
|
809
|
+
requestWaitingMs: 60_000,
|
|
810
|
+
services: finalServices,
|
|
811
|
+
});
|
|
812
|
+
server.stoppedPromise.then((reason) => {
|
|
813
|
+
onStop();
|
|
814
|
+
for (const serverStopCallback of serverStopCallbackSet) {
|
|
815
|
+
serverStopCallback(reason);
|
|
816
|
+
}
|
|
817
|
+
serverStopCallbackSet.clear();
|
|
818
|
+
});
|
|
819
|
+
startDevServerTask.done();
|
|
820
|
+
if (hostname) {
|
|
821
|
+
delete server.origins.localip;
|
|
822
|
+
delete server.origins.externalip;
|
|
823
|
+
}
|
|
824
|
+
logger.info(``);
|
|
825
|
+
Object.keys(server.origins).forEach((key) => {
|
|
826
|
+
logger.info(`- ${server.origins[key]}`);
|
|
827
|
+
});
|
|
828
|
+
logger.info(``);
|
|
829
|
+
return {
|
|
830
|
+
origin: server.origin,
|
|
831
|
+
sourceDirectoryUrl,
|
|
832
|
+
stop: () => {
|
|
833
|
+
server.stop();
|
|
834
|
+
},
|
|
835
|
+
kitchenCache,
|
|
836
|
+
};
|
|
837
|
+
};
|
|
838
|
+
|
|
839
|
+
const cacheIsDisabledInResponseHeader = (urlInfo) => {
|
|
840
|
+
return (
|
|
841
|
+
urlInfo.headers["cache-control"] === "no-store" ||
|
|
842
|
+
urlInfo.headers["cache-control"] === "no-cache"
|
|
843
|
+
);
|
|
844
|
+
};
|
|
845
|
+
|
|
846
|
+
export { startDevServer };
|