achieve-http-server 0.0.0-stage → 3.1.5

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/achieve.js ADDED
@@ -0,0 +1,3412 @@
1
+
2
+ /*
3
+ * Achieve - Web server for Node.js
4
+ * Copyright (c) 2018-2026 Roger F. Gay
5
+ * SPDX-License-Identifier: MIT
6
+ */
7
+
8
+ // Essential modules. Always load.
9
+ const fs = require('fs');
10
+ const path = require('path');
11
+ const querystring = require('querystring');
12
+ const { createRequire } = require('node:module');
13
+ const { pathToFileURL } = require('node:url');
14
+ // Optional modules. Load only when used.
15
+
16
+ let http;
17
+ let https;
18
+ let http2;
19
+ let zlib;
20
+ let streamPipeline;
21
+ let compressionJobs = new Set();
22
+ let compressionTempSequence = 0;
23
+ // const avmine = require("./avmine");
24
+ // const dt = require('./datetime');
25
+ // let flatted = require('flatted');
26
+
27
+ if (process.env.NODE_ENV === undefined) process.env.NODE_ENV = 'production';
28
+
29
+ let moduleLoadTimes = {};
30
+ let productionHelperCache = new Map();
31
+ const esmLoadContext = Symbol("esmLoadContext");
32
+ let servletResolutionCache = new Map();
33
+ let servletResolutionAliases = new Map();
34
+ let registeredMethods = new Map();
35
+ let routeMap;
36
+ let pathMap;
37
+
38
+ let mode = "development";
39
+ let logging = {
40
+ server: false,
41
+ access: false
42
+ };
43
+ let loggingConfigurationLocked = false;
44
+ let serverEntryPath = getServerEntryPath();
45
+ let serverInstallationPath = path.dirname(serverEntryPath);
46
+ let applicationRequire = createRequire(serverEntryPath);
47
+ let logRoot = path.join(serverInstallationPath,"logs");
48
+ let serverLogSink;
49
+ let accessLogSink;
50
+
51
+ let corsPolicies = new Map();
52
+ let bufferedInputLimit = 1024 * 1024; // default 1 MiB
53
+
54
+ function getServerEntryPath() {
55
+ if (require.main && typeof require.main.filename === "string" && require.main.filename.length > 0) {
56
+ return path.resolve(require.main.filename);
57
+ }
58
+ if (typeof process.argv[1] === "string" && process.argv[1].length > 0) {
59
+ return path.resolve(process.argv[1]);
60
+ }
61
+ return path.join(path.resolve(process.cwd()),"achieve-entry.js");
62
+ }
63
+
64
+ function ensureLoggingConfigurable(functionName) {
65
+ if (loggingConfigurationLocked) {
66
+ throw new Error(functionName + "() must be called before listen().");
67
+ }
68
+ }
69
+
70
+ exports.setMode = function (newMode) {
71
+ ensureLoggingConfigurable("setMode");
72
+ if (newMode !== "development" && newMode !== "production") {
73
+ throw new TypeError('setMode() requires "development" or "production".');
74
+ }
75
+ mode = newMode;
76
+ productionHelperCache.clear();
77
+ };
78
+
79
+ exports.setLogging = function (...selections) {
80
+ ensureLoggingConfigurable("setLogging");
81
+ if (selections.length === 0) {
82
+ throw new TypeError("setLogging() requires at least one argument.");
83
+ }
84
+
85
+ if (selections.length === 1 && typeof selections[0] === "boolean") {
86
+ let enabled = selections[0];
87
+ logging = {
88
+ server: enabled,
89
+ access: enabled
90
+ };
91
+ return;
92
+ }
93
+
94
+ if (selections.some(selection => typeof selection !== "string")) {
95
+ throw new TypeError("setLogging() accepts one boolean or persistent logging selection names.");
96
+ }
97
+
98
+ let selected = {
99
+ server: false,
100
+ access: false
101
+ };
102
+ for (let selection of selections) {
103
+ if (!Object.prototype.hasOwnProperty.call(selected,selection)) {
104
+ throw new RangeError("Unknown logging selection: " + selection);
105
+ }
106
+ selected[selection] = true;
107
+ }
108
+ logging = selected;
109
+ };
110
+ // Configure buffered input during startup, before listen(), for predictable request handling.
111
+ exports.setBufferedInputLimit = function(limit) {
112
+ if (!Number.isSafeInteger(limit) || limit < 1) {
113
+ throw new RangeError("Buffered input limit must be a positive integer.");
114
+ }
115
+ const v8 = require("node:v8");
116
+ let maxLimit = Math.floor(v8.getHeapStatistics().heap_size_limit * 0.01);
117
+
118
+ if (limit > maxLimit) {
119
+ throw new RangeError("Buffered input limit exceeds Achieve's safe maximum of " + maxLimit + " bytes.");
120
+ }
121
+ bufferedInputLimit = limit;
122
+ }
123
+ exports.setLogPath = function (newLogRoot) {
124
+ ensureLoggingConfigurable("setLogPath");
125
+ if (typeof newLogRoot !== "string" || newLogRoot.trim().length === 0) {
126
+ throw new TypeError("setLogPath() requires a non-empty path string.");
127
+ }
128
+ let candidate = newLogRoot.trim();
129
+ logRoot = path.isAbsolute(candidate)
130
+ ? path.normalize(candidate)
131
+ : path.resolve(serverInstallationPath,candidate);
132
+ };
133
+
134
+ function padNumber(value,width = 2) {
135
+ return String(value).padStart(width,"0");
136
+ }
137
+
138
+ function localDateKey(date = new Date()) {
139
+ return date.getFullYear() + "-" +
140
+ padNumber(date.getMonth() + 1) + "-" +
141
+ padNumber(date.getDate());
142
+ }
143
+
144
+ function localTimestamp(date = new Date()) {
145
+ let offsetMinutes = -date.getTimezoneOffset();
146
+ let sign = offsetMinutes >= 0 ? "+" : "-";
147
+ let absoluteOffset = Math.abs(offsetMinutes);
148
+ return localDateKey(date) + "T" +
149
+ padNumber(date.getHours()) + ":" +
150
+ padNumber(date.getMinutes()) + ":" +
151
+ padNumber(date.getSeconds()) + "." +
152
+ padNumber(date.getMilliseconds(),3) +
153
+ sign +
154
+ padNumber(Math.floor(absoluteOffset / 60)) + ":" +
155
+ padNumber(absoluteOffset % 60);
156
+ }
157
+
158
+ function createLogSink(category) {
159
+ let stream;
160
+ let streams = new Set();
161
+ let dateKey;
162
+ let failed = false;
163
+ let ended = false;
164
+ let failureError;
165
+ let errorReported = false;
166
+
167
+ function reportFailure(err) {
168
+ if (errorReported) return;
169
+ errorReported = true;
170
+ console.error(
171
+ "Achieve " + category + " logging failed: " +
172
+ (err && err.message ? err.message : String(err))
173
+ );
174
+ }
175
+
176
+ function disable(err) {
177
+ failed = true;
178
+ if (!failureError) failureError = err;
179
+ reportFailure(err);
180
+ for (let ownedStream of streams) {
181
+ if (!ownedStream.destroyed) ownedStream.destroy();
182
+ }
183
+ stream = undefined;
184
+ dateKey = undefined;
185
+ }
186
+
187
+ function openStream(nextDateKey) {
188
+ let categoryPath = path.join(logRoot,category);
189
+ let filePath = path.join(categoryPath,nextDateKey + ".log");
190
+ fs.mkdirSync(categoryPath,{recursive:true});
191
+ let fileDescriptor = fs.openSync(filePath,"a");
192
+ let nextStream;
193
+ try {
194
+ nextStream = fs.createWriteStream(filePath,{
195
+ fd:fileDescriptor,
196
+ flags:"a",
197
+ autoClose:true
198
+ });
199
+ } catch (err) {
200
+ fs.closeSync(fileDescriptor);
201
+ throw err;
202
+ }
203
+ streams.add(nextStream);
204
+ nextStream.once("close",function () {
205
+ streams.delete(nextStream);
206
+ });
207
+ nextStream.on("error",function (err) {
208
+ disable(err);
209
+ });
210
+ return nextStream;
211
+ }
212
+
213
+ function initialize() {
214
+ if (failed || ended) return false;
215
+ if (stream) return true;
216
+ try {
217
+ dateKey = localDateKey();
218
+ stream = openStream(dateKey);
219
+ return true;
220
+ } catch (err) {
221
+ disable(err);
222
+ return false;
223
+ }
224
+ }
225
+
226
+ function write(record) {
227
+ if (failed || ended) return false;
228
+ if (!stream && !initialize()) return false;
229
+ let now = new Date();
230
+ let nextDateKey = localDateKey(now);
231
+ if (nextDateKey !== dateKey) {
232
+ let nextStream;
233
+ try {
234
+ nextStream = openStream(nextDateKey);
235
+ } catch (err) {
236
+ disable(err);
237
+ return false;
238
+ }
239
+ let previousStream = stream;
240
+ stream = nextStream;
241
+ dateKey = nextDateKey;
242
+ previousStream.end();
243
+ }
244
+ try {
245
+ stream.write(localTimestamp(now) + " " + record + "\n");
246
+ return true;
247
+ } catch (err) {
248
+ disable(err);
249
+ return false;
250
+ }
251
+ }
252
+
253
+ function close() {
254
+ for (let ownedStream of streams) {
255
+ if (!ownedStream.destroyed) ownedStream.destroy();
256
+ }
257
+ stream = undefined;
258
+ dateKey = undefined;
259
+ }
260
+
261
+ function end(callback) {
262
+ callback = typeof callback === "function"
263
+ ? callback
264
+ : function () {};
265
+
266
+ if (failed || ended) {
267
+ process.nextTick(callback);
268
+ return;
269
+ }
270
+
271
+ ended = true;
272
+
273
+ let openStreams = Array.from(streams).filter(function (ownedStream) {
274
+ return !ownedStream.destroyed;
275
+ });
276
+
277
+ stream = undefined;
278
+ dateKey = undefined;
279
+
280
+ if (openStreams.length === 0) {
281
+ process.nextTick(callback);
282
+ return;
283
+ }
284
+
285
+ let remaining = openStreams.length;
286
+
287
+ function streamClosed() {
288
+ remaining--;
289
+ if (remaining === 0) {
290
+ callback(failed ? failureError : undefined);
291
+ }
292
+ }
293
+
294
+ for (let ownedStream of openStreams) {
295
+ ownedStream.once("close",streamClosed);
296
+ if (!ownedStream.writableEnded) ownedStream.end();
297
+ }
298
+ }
299
+
300
+ return {
301
+ initialize:initialize,
302
+ write:write,
303
+ close:close,
304
+ end:end,
305
+ hasFailed:function () { return failed; }
306
+ };
307
+ }
308
+
309
+ function developmentLog(...values) {
310
+ if (mode === "development") console.log(...values);
311
+ }
312
+
313
+ function serverEvent(event,message,err) {
314
+ if (logging.server && serverLogSink) {
315
+ serverLogSink.write(
316
+ event + " " +
317
+ (err && err.stack ? message + "\n" + err.stack : message)
318
+ );
319
+ }
320
+ }
321
+
322
+ function serverWarning(message) {
323
+ if (!loggingConfigurationLocked || mode === "development") console.log(message);
324
+ serverEvent("WARN",message);
325
+ }
326
+
327
+ function serverError(message,err) {
328
+ if (!loggingConfigurationLocked || mode === "development") console.error(message);
329
+ serverEvent("ERROR",message,err);
330
+ }
331
+
332
+ function startupWarning(message) {
333
+ console.log(message);
334
+ serverEvent("WARN",message);
335
+ }
336
+
337
+ function startupError(message,err) {
338
+ console.error(message);
339
+ serverEvent("ERROR",message,err);
340
+ }
341
+
342
+ function accessLogValue(value) {
343
+ return '"' +
344
+ String(value)
345
+ .replace(/\\/g,"\\\\")
346
+ .replace(/"/g,'\\"')
347
+ .replace(/[\x00-\x1F\x7F]/g,function (character) {
348
+ return "\\u" +
349
+ character.charCodeAt(0).toString(16).padStart(4,"0");
350
+ }) +
351
+ '"';
352
+ }
353
+
354
+ function createAccessRecorder(req) {
355
+ if (
356
+ !logging.access ||
357
+ !accessLogSink ||
358
+ accessLogSink.hasFailed()
359
+ ) return;
360
+
361
+ let started = process.hrtime.bigint();
362
+ let recorded = false;
363
+ let method = req.method || "";
364
+ let requestTarget = req.url || "";
365
+ let remoteAddress =
366
+ req.socket && req.socket.remoteAddress
367
+ ? req.socket.remoteAddress
368
+ : "-";
369
+
370
+ return function recordAccess(statusCode,completionState) {
371
+ if (recorded) return;
372
+ recorded = true;
373
+
374
+ let elapsedNanoseconds = process.hrtime.bigint() - started;
375
+ let elapsedMilliseconds = Number(elapsedNanoseconds) / 1e6;
376
+
377
+ accessLogSink.write(
378
+ "remote=" + accessLogValue(remoteAddress) +
379
+ " method=" + accessLogValue(method) +
380
+ " target=" + accessLogValue(requestTarget) +
381
+ " status=" + statusCode +
382
+ " elapsed=" + elapsedMilliseconds.toFixed(3) + "ms" +
383
+ " state=" + completionState
384
+ );
385
+ };
386
+ }
387
+
388
+ function attachAccessLogging(req,res) {
389
+ let recordAccess = createAccessRecorder(req);
390
+ if (!recordAccess) return;
391
+
392
+ res.once("finish",function () {
393
+ recordAccess(res.statusCode,"complete");
394
+ });
395
+
396
+ res.once("close",function () {
397
+ recordAccess(res.statusCode,"aborted");
398
+ });
399
+ }
400
+
401
+ function initializeLogging() {
402
+ if (loggingConfigurationLocked) {
403
+ return (
404
+ (!logging.server || (serverLogSink && !serverLogSink.hasFailed())) &&
405
+ (!logging.access || (accessLogSink && !accessLogSink.hasFailed()))
406
+ );
407
+ }
408
+ loggingConfigurationLocked = true;
409
+
410
+ if (logging.server) {
411
+ serverLogSink = createLogSink("server");
412
+ if (!serverLogSink.initialize()) {
413
+ console.error("Achieve listener was not started because server logging could not be initialized.");
414
+ return false;
415
+ }
416
+ }
417
+
418
+ if (logging.access) {
419
+ accessLogSink = createLogSink("access");
420
+ if (!accessLogSink.initialize()) {
421
+ if (serverLogSink) serverLogSink.close();
422
+ console.error("Achieve listener was not started because access logging could not be initialized.");
423
+ return false;
424
+ }
425
+ }
426
+
427
+ return true;
428
+ }
429
+
430
+ let reqCount = 0;
431
+ // basePath is the explicitly configured root directory for applications.
432
+ let basePath;
433
+ let physicalBasePath;
434
+ let bCaching=false, bCachingCheck=false, compress=false, showMimes=false;
435
+ let corsdomains=[];
436
+ let shortVersion = require('./package.json').version;
437
+ let version = "HLL Achieve v" + shortVersion;
438
+ let nv = nodeVersion();
439
+ let etagString = nv + shortVersion;
440
+ let defaultCharSet="utf-8";
441
+ exports.showMimeTypes = function () {
442
+ showMimes=true;
443
+ };
444
+ exports.setCompress = function (on) {
445
+ if (typeof on == "boolean") {
446
+ compress=on;
447
+ if (compress) {
448
+ zlib = require('node:zlib');
449
+ streamPipeline = require('node:stream').pipeline;
450
+ }
451
+ } else {
452
+ serverError("ERROR: setCompress(true) requires a boolean argument. (default: false)");
453
+ }
454
+ };
455
+ exports.setNodeEnv = function (env) {
456
+ process.env.NODE_ENV=env;
457
+ serverEvent("CONFIG","NODE_ENV set to " + env);
458
+ };
459
+ exports.setRootDir = function () {
460
+ serverError("ERROR: setRootDir() is no longer supported. Use setAppPath() instead.");
461
+ };
462
+ exports.setAppPath = function (bp) {
463
+ let newPath=path.resolve(bp);
464
+ validateApplicationPath(newPath,"setAppPath() application path");
465
+ let newPhysicalPath=fs.realpathSync.native(newPath);
466
+ productionHelperCache.clear();
467
+ servletResolutionCache.clear();
468
+ servletResolutionAliases.clear();
469
+ basePath=newPath;
470
+ physicalBasePath=newPhysicalPath;
471
+ };
472
+ function validateApplicationPath(applicationPath,description="Application path") {
473
+ let stats;
474
+ try {
475
+ stats=fs.statSync(applicationPath);
476
+ } catch (err) {
477
+ throw new Error(description + " does not exist: " + applicationPath,{cause:err});
478
+ }
479
+ if (!stats.isDirectory()) {
480
+ throw new Error(description + " is not a directory: " + applicationPath);
481
+ }
482
+ }
483
+ function applicationPathReady() {
484
+ if (basePath === undefined) {
485
+ startupError("ERROR: Application space has not been configured. Use setAppPath() before starting the server.");
486
+ return false;
487
+ }
488
+ validateApplicationPath(basePath,"Configured application path");
489
+ physicalBasePath=fs.realpathSync.native(basePath);
490
+ return true;
491
+ }
492
+ function validRoutePath(value) {
493
+ if (typeof value !== "string" || value.length === 0 || value.charAt(0) !== "/") return false;
494
+ if (value.indexOf("?") !== -1 || value.indexOf("#") !== -1 || value.indexOf("\\") !== -1 || value.indexOf("\0") !== -1) return false;
495
+ if (path.posix.normalize(value) !== value) return false;
496
+ return !value.split("/").some(part => part === "." || part === "..");
497
+ }
498
+ exports.setRouteMap = function (configured) {
499
+ if (configured === null || typeof configured !== "object" ||
500
+ (Object.getPrototypeOf(configured) !== Object.prototype && Object.getPrototypeOf(configured) !== null)) {
501
+ throw new TypeError("setRouteMap() requires a plain object.");
502
+ }
503
+ let entries=Object.entries(configured);
504
+ if (entries.length === 0) throw new TypeError("setRouteMap() requires at least one route.");
505
+ let validated=new Map();
506
+ for (let [publicPath,targetPath] of entries) {
507
+ if (!validRoutePath(publicPath)) throw new TypeError("setRouteMap() contains an invalid public route: " + publicPath);
508
+ if (!validRoutePath(targetPath)) throw new TypeError("setRouteMap() contains an invalid mapped target for: " + publicPath);
509
+ if (!containedRequestPath(basePath,targetPath)) throw new TypeError("setRouteMap() mapped targets must remain beneath the application path.");
510
+ validated.set(publicPath,targetPath);
511
+ }
512
+ if (routeMap === undefined) routeMap=new Map();
513
+ for (let [publicPath,targetPath] of validated) routeMap.set(publicPath,targetPath);
514
+ };
515
+ exports.setPathMap = function (configured) {
516
+ if (configured === null || typeof configured !== "object" ||
517
+ (Object.getPrototypeOf(configured) !== Object.prototype && Object.getPrototypeOf(configured) !== null)) {
518
+ throw new TypeError("setPathMap() requires a plain object.");
519
+ }
520
+ let entries=Object.entries(configured);
521
+ if (entries.length === 0) throw new TypeError("setPathMap() requires at least one path mapping.");
522
+ let validated=new Map();
523
+ for (let [publicPath,targetPath] of entries) {
524
+ if (!validRoutePath(publicPath) || publicPath === "/" || !publicPath.endsWith("/")) {
525
+ throw new TypeError("setPathMap() contains an invalid public path (a non-root directory path ending in / is required): " + publicPath);
526
+ }
527
+ if (!validRoutePath(targetPath) || !targetPath.endsWith("/")) {
528
+ throw new TypeError("setPathMap() contains an invalid mapped target (a directory path ending in / is required) for: " + publicPath);
529
+ }
530
+ if (!containedRequestPath(basePath,targetPath)) throw new TypeError("setPathMap() mapped targets must remain beneath the application path.");
531
+ validated.set(publicPath,targetPath);
532
+ }
533
+ if (pathMap === undefined) pathMap=new Map();
534
+ for (let [publicPath,targetPath] of validated) pathMap.set(publicPath,targetPath);
535
+ };
536
+ const achieveOwnedMethods = new Set(["GET","HEAD","POST","OPTIONS"]);
537
+ const advertisedBuiltInMethods = ["GET","HEAD","POST","OPTIONS"];
538
+ const httpTokenPattern = /^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/;
539
+ exports.registerMethod = function (method,servletPath) {
540
+ if (typeof method !== "string" || method.length === 0) throw new TypeError("registerMethod() requires a nonempty method string.");
541
+ if (!httpTokenPattern.test(method)) throw new TypeError("registerMethod() requires a valid HTTP method token.");
542
+ if (method.toUpperCase() === "CONNECT") {
543
+ throw new RangeError(
544
+ "CONNECT cannot be registered as a servlet method. " +
545
+ "Node.js handles CONNECT through a separate server event. " +
546
+ "Consider using achieve-proxy instead."
547
+ );
548
+ }
549
+ if (achieveOwnedMethods.has(method.toUpperCase())) throw new RangeError(method + " is implemented by Achieve and cannot be registered.");
550
+ if (registeredMethods.has(method)) throw new RangeError(method + " is already registered.");
551
+ if (typeof servletPath !== "string" || servletPath.length === 0) throw new TypeError("registerMethod() requires a nonempty servlet path string.");
552
+ if (servletPath.indexOf("?") !== -1 || servletPath.indexOf("#") !== -1 ||
553
+ path.posix.isAbsolute(servletPath) || path.win32.isAbsolute(servletPath) ||
554
+ !servletModuleType(servletPath)) {
555
+ throw new TypeError("registerMethod() requires a relative .jss, .jss.cjs, or .jss.mjs servlet path.");
556
+ }
557
+ let fullPath=containedRequestPath(basePath,servletPath);
558
+ if (!fullPath) throw new TypeError("registerMethod() servlet path must remain beneath the application path.");
559
+ registeredMethods.set(method,path.relative(basePath,fullPath));
560
+ };
561
+ exports.setCaching = function (b) {
562
+ bCaching=b; // boolean
563
+ bCachingCheck=true;
564
+ };
565
+ // CORS
566
+ function checkCorsPolicyPath(req,res,resourcePath) {
567
+ let origin=req.headers.origin;
568
+ let fetchSite=req.headers["sec-fetch-site"];
569
+
570
+ if (!origin) return true;
571
+ if (fetchSite === "same-origin") return true;
572
+
573
+ resourcePath=resourcePath.replace(/\\/g,"/");
574
+ let pos=resourcePath.lastIndexOf("/");
575
+ let requestPath=resourcePath.substring(0,pos+1);
576
+ let asset=resourcePath.substring(pos+1);
577
+
578
+ if (corsPolicyMatch(origin,requestPath,asset)) {
579
+ res.setHeader("Access-Control-Allow-Origin",origin);
580
+ res.appendHeader("Vary","Origin");
581
+ return true;
582
+ }
583
+
584
+ res.statusCode=403;
585
+ res.end();
586
+ return false;
587
+ }
588
+ function checkCorsPolicy(req,res,fileInfo) {
589
+ return checkCorsPolicyPath(req,res,fileInfo.path);
590
+ }
591
+ function checkCorsTarget(req,res,resourceTarget) {
592
+ let queryStart=resourceTarget.indexOf("?");
593
+ let resourcePath=queryStart === -1 ? resourceTarget : resourceTarget.substring(0,queryStart);
594
+ return checkCorsPolicyPath(req,res,resourcePath);
595
+ }
596
+ function normalizeCorsPath(path) {
597
+ path = path.trim();
598
+ if (!path || path === "*") return "*";
599
+ if (!path.startsWith("/")) path = "/" + path;
600
+ if (!path.endsWith("/")) path += "/";
601
+ return path;
602
+ }
603
+ exports.allowOrigins = function (origins, paths="*", assets="*") {
604
+ if (!Array.isArray(origins)) origins = [origins];
605
+ if (!Array.isArray(paths)) paths = [paths];
606
+ if (!Array.isArray(assets)) assets = [assets];
607
+
608
+ paths = paths.map(normalizeCorsPath);
609
+ let assetSet = new Set(assets);
610
+
611
+ for (let origin of origins) {
612
+ origin = origin.trim();
613
+ if (!corsPolicies.has(origin)) corsPolicies.set(origin, new Map());
614
+
615
+ let pathMap = corsPolicies.get(origin);
616
+ for (let path of paths) pathMap.set(path, {assets: assetSet});
617
+ }
618
+ developmentLog(corsPolicies);
619
+ };
620
+ function isAssetAllowed(policy, asset) {
621
+ if (policy.assets.has("*")) return true;
622
+ return policy.assets.has(asset);
623
+ }
624
+ function corsPolicyMatch(origin, path, asset) {
625
+ let pathMap = corsPolicies.get(origin);
626
+ if (!pathMap) pathMap = corsPolicies.get("*");
627
+ if (!pathMap) return;
628
+
629
+ let policy = findPathPolicy(pathMap, path);
630
+ if (!policy) return;
631
+
632
+ if (!isAssetAllowed(policy, asset)) return;
633
+
634
+ return policy;
635
+ }
636
+ function findPathPolicy(pathMap, requestPath) {
637
+ if (pathMap.has(requestPath)) return pathMap.get(requestPath);
638
+
639
+ let path = requestPath;
640
+
641
+ while (path.length > 1) {
642
+ let pos = path.lastIndexOf("/", path.length - 2);
643
+ if (pos < 0) break;
644
+
645
+ path = path.substring(0, pos + 1);
646
+ if (pathMap.has(path)) return pathMap.get(path);
647
+ }
648
+
649
+ return pathMap.get("*");
650
+ }
651
+ function methodNotSupportedMessage(req) {
652
+ return (
653
+ req.method +
654
+ " request method is not yet supported on the server: " +
655
+ version
656
+ );
657
+ }
658
+
659
+ function methodNotSupported(req, res) {
660
+ let message = methodNotSupportedMessage(req);
661
+
662
+ res.statusCode = 501;
663
+ res.setHeader("Content-Type", "text/plain; charset=utf-8");
664
+ if (mode === "development") developmentLog(message);
665
+ res.end(message);
666
+ }
667
+
668
+ function completeServletResolution(req,res,fileInfo,sendBody,servletCacheKey,accountInfo) {
669
+ if (accountInfo.code == 200) {
670
+ if (mode === "production") {
671
+ let servletIdentity=servletPhysicalIdentity(fileInfo.fullPath);
672
+ servletResolutionCache.set(servletIdentity,{
673
+ basePath:fileInfo.basePath,
674
+ path:fileInfo.path,
675
+ fullPath:fileInfo.fullPath,
676
+ dirPath:fileInfo.dirPath,
677
+ suffix:fileInfo.suffix,
678
+ contentType:fileInfo.contentType,
679
+ account:accountInfo.account
680
+ });
681
+ servletResolutionAliases.set(
682
+ servletRequestIdentity(fileInfo.basePath,servletCacheKey),
683
+ servletIdentity
684
+ );
685
+ }
686
+ if (res.destroyed || res.writableEnded) return;
687
+ return handlePreparedServlet(req,res,fileInfo,accountInfo.account,sendBody);
688
+ }
689
+ if (res.destroyed || res.writableEnded) return;
690
+ reportError(res,accountInfo.account,accountInfo.code,accountInfo.reason,sendBody);
691
+ }
692
+
693
+ function handleResolvedResource(req, res, fileInfo, sendBody = true, servletCacheKey) {
694
+ // display(fileInfo);
695
+ // If request is a directory, it must have a trailing slash (otherwise resources such as css and js won't be loaded).
696
+ if (fileInfo.redirect) {
697
+ var queryStart = fileInfo.path.indexOf("?");
698
+ var redirectPath = queryStart === -1 ? fileInfo.path : fileInfo.path.substring(0,queryStart);
699
+ var newUrl = path.posix.join(redirectPath.replace(/\\/g,"/"), "/");
700
+ if (queryStart !== -1) newUrl += fileInfo.path.substring(queryStart);
701
+ res.statusCode = 301;
702
+ res.setHeader('Content-Type', 'text/plain');
703
+ res.setHeader('Location', newUrl);
704
+ if (sendBody) {
705
+ res.end('Redirecting to ' + newUrl);
706
+ } else {
707
+ res.end();
708
+ }
709
+ } else if (fileInfo.contentType === undefined) {
710
+ res.statusCode = 415;
711
+ res.setHeader('Content-Type', 'text/plain');
712
+ if (sendBody) {
713
+ res.end('Media type is not supported. Use server.addMimeType() in your application.'); // currently, defaults to text/plain
714
+ } else {
715
+ res.end();
716
+ }
717
+ // Files are served using the serveFile object in this application.
718
+ } else if (fileInfo.notAcceptable) {
719
+ reportError(res,fileInfo.fullPath,406,"No acceptable representation is available.",sendBody);
720
+ } else if (fileInfo.openError) {
721
+ let statusCode=fileInfo.openError.code === "ENOENT" ? 404 : 500;
722
+ let reason=statusCode === 404
723
+ ? "File not found: " + safeSourceIdentity(fileInfo.fullPath)
724
+ : "Error attempting to open " + safeSourceIdentity(fileInfo.fullPath) + ": " + rtErrorMsg(fileInfo.openError);
725
+ reportError(res,fileInfo.fullPath,statusCode,reason,sendBody);
726
+ } else if (fileInfo.serveFile) {
727
+ try {
728
+ let modified=staticModificationTime(res,fileInfo.stats);
729
+ if (evaluatePreconditions(req,res,true,fileInfo.etag,modified)) {
730
+ closeFileInfoDescriptor(fileInfo);
731
+ return;
732
+ }
733
+ setLastModified(res,modified);
734
+ new ServeFile(req,res,fileInfo,sendBody).init();
735
+ } catch (err) {
736
+ closeFileInfoDescriptor(fileInfo);
737
+ if (!res.headersSent) {
738
+ res.removeHeader('Content-Length');
739
+ res.removeHeader('Last-Modified');
740
+ }
741
+ reportError(res,fileInfo.fullPath,500,"Error attempting to serve " + safeSourceIdentity(fileInfo.fullPath),sendBody);
742
+ }
743
+ } else if (fileInfo.audioVisual) {
744
+ stream(req,res,fileInfo,sendBody);
745
+ // If file does not exist, return 404 File not found error.
746
+ } else if (fileInfo.noSuchFile) {
747
+ reportError(res,fileInfo.fullPath,404,"File not found: " + fileInfo.fullPath,sendBody);
748
+ // Otherwise, a JavaScript file should be loaded.
749
+ } else {
750
+ // Checks and adds JavaScript file.
751
+ if (servletModuleType(fileInfo.fullPath) == "module") {
752
+ getModuleAccount(fileInfo).then(function (accountInfo) {
753
+ completeServletResolution(req,res,fileInfo,sendBody,servletCacheKey,accountInfo);
754
+ });
755
+ return;
756
+ }
757
+ let accountInfo = getAccount(res,fileInfo);
758
+ return completeServletResolution(req,res,fileInfo,sendBody,servletCacheKey,accountInfo);
759
+ }
760
+ }
761
+
762
+ function servletResourcePath(resourceTarget) {
763
+ let queryStart=resourceTarget.indexOf("?");
764
+ return queryStart === -1
765
+ ? resourceTarget
766
+ : resourceTarget.substring(0,queryStart);
767
+ }
768
+
769
+ function servletPhysicalIdentity(fullPath) {
770
+ let identity=path.resolve(fullPath);
771
+ return process.platform === "win32" ? identity.toLowerCase() : identity;
772
+ }
773
+
774
+ function servletRequestIdentity(basePath,resourceTarget) {
775
+ let identity=containedRequestPath(basePath,servletResourcePath(resourceTarget));
776
+ if (!identity) return false;
777
+ return servletPhysicalIdentity(identity);
778
+ }
779
+
780
+ function cachedServletFileInfo(cached,req,resourceTarget) {
781
+ let queryStart=resourceTarget.indexOf("?");
782
+ return new FileInfo(
783
+ cached.basePath,
784
+ cached.path,
785
+ cached.fullPath,
786
+ cached.dirPath,
787
+ cached.suffix,
788
+ req.headers,
789
+ cached.contentType,
790
+ queryStart === -1 ? "" : resourceTarget.substring(queryStart+1),
791
+ false,
792
+ false,
793
+ false,
794
+ false,
795
+ "",
796
+ false
797
+ );
798
+ }
799
+ function handleUnexpectedRequestError(res,error,eventMessage,responseFailureMessage) {
800
+ serverError(eventMessage,error);
801
+ if (res.destroyed || res.writableEnded) return;
802
+ if (res.headersSent) {
803
+ try {
804
+ res.destroy();
805
+ } catch (destroyError) {
806
+ serverError("Failed to destroy incomplete response.",destroyError);
807
+ }
808
+ return;
809
+ }
810
+ try {
811
+ res.statusCode=500;
812
+ res.setHeader('Content-Type','text/plain;charset=utf-8');
813
+ res.end("Internal Server Error");
814
+ } catch (responseError) {
815
+ serverError(responseFailureMessage,responseError);
816
+ if (!res.destroyed) {
817
+ try {
818
+ res.destroy();
819
+ } catch (destroyError) {
820
+ serverError("Failed to destroy incomplete response.",destroyError);
821
+ }
822
+ }
823
+ }
824
+ }
825
+ function handlePreparedServlet(req,res,fileInfo,account,sendBody) {
826
+ if (evaluatePreconditions(req,res,true)) return;
827
+ try {
828
+ new startObject(req,res,fileInfo,account,sendBody).init();
829
+ } catch (err) {
830
+ handleUnexpectedRequestError(
831
+ res,
832
+ err,
833
+ "Unexpected error starting servlet.",
834
+ "Failed to send servlet startup error response."
835
+ );
836
+ }
837
+ }
838
+
839
+ function registeredHandlerFileInfo(req,basePath,servletPath) {
840
+ let fullPath=containedRequestPath(basePath,servletPath);
841
+ if (!fullPath || !servletModuleType(fullPath)) throw new Error("Invalid registered handler path: " + servletPath);
842
+ let stats=fs.statSync(fullPath);
843
+ if (!stats.isFile()) throw new Error("Registered handler is not a file: " + servletPath);
844
+ if (!containedPhysicalPath(fullPath)) throw new Error("Registered handler is outside the application path: " + servletPath);
845
+ let reload=moduleLoadTimes[fullPath] === undefined || moduleLoadTimes[fullPath] < stats.mtimeMs;
846
+ return new FileInfo(basePath,servletPath,fullPath,path.dirname(fullPath),"servlet",req.headers,
847
+ mimeList.servlet,"",false,false,false,reload,"",false);
848
+ }
849
+ function registeredHandlerFailure(req,res,servletPath,detail,error) {
850
+ serverError("Registered " + req.method + " handler " + servletPath + " failed: " + detail,error);
851
+ if (res.destroyed || res.writableEnded) return;
852
+ if (res.headersSent) return res.destroy();
853
+ reportError(res,null,500,"Registered method handler is unavailable.");
854
+ }
855
+ function invokeRegisteredServlet(req,res,fileInfo,account) {
856
+ res.setHeader('server',version);
857
+ res.setHeader('Content-Type','text/plain');
858
+ invokeServlet(req,res,fileInfo,account,{},true);
859
+ }
860
+ function completeRegisteredHandlerResolution(req,res,fileInfo,accountInfo) {
861
+ if (accountInfo.code != 200) return registeredHandlerFailure(req,res,fileInfo.path,accountInfo.reason);
862
+ if (mode === "production") {
863
+ servletResolutionCache.set(servletPhysicalIdentity(fileInfo.fullPath),{
864
+ basePath:fileInfo.basePath,path:fileInfo.path,fullPath:fileInfo.fullPath,
865
+ dirPath:fileInfo.dirPath,suffix:fileInfo.suffix,contentType:fileInfo.contentType,
866
+ account:accountInfo.account
867
+ });
868
+ }
869
+ if (!res.destroyed && !res.writableEnded) invokeRegisteredServlet(req,res,fileInfo,accountInfo.account);
870
+ }
871
+ function handleRegisteredMethod(req,res,basePath,resourceTarget) {
872
+ if (!checkCorsTarget(req,res,resourceTarget)) return;
873
+ let servletPath=registeredMethods.get(req.method);
874
+ let fileInfo;
875
+ try {
876
+ fileInfo=registeredHandlerFileInfo(req,basePath,servletPath);
877
+ } catch (err) {
878
+ return registeredHandlerFailure(req,res,servletPath,rtErrorMsg(err),err);
879
+ }
880
+ if (mode === "production") {
881
+ let cached=servletResolutionCache.get(servletPhysicalIdentity(fileInfo.fullPath));
882
+ if (cached) return invokeRegisteredServlet(req,res,fileInfo,cached.account);
883
+ }
884
+ if (servletModuleType(fileInfo.fullPath) == "module") {
885
+ getModuleAccount(fileInfo).then(function (accountInfo) {
886
+ completeRegisteredHandlerResolution(req,res,fileInfo,accountInfo);
887
+ });
888
+ return;
889
+ }
890
+ completeRegisteredHandlerResolution(req,res,fileInfo,getAccount(res,fileInfo));
891
+ }
892
+ function cachedServlet(basePath,resourceTarget) {
893
+ if (mode !== "production") return;
894
+ let servletIdentity=servletResolutionAliases.get(
895
+ servletRequestIdentity(basePath,resourceTarget)
896
+ );
897
+ if (!servletIdentity) return;
898
+ return servletResolutionCache.get(servletIdentity);
899
+ }
900
+
901
+ function mappedResourceTarget(resourceTarget) {
902
+ if (typeof resourceTarget !== "string") return;
903
+ let queryStart=resourceTarget.indexOf("?");
904
+ let publicPath=queryStart === -1 ? resourceTarget : resourceTarget.substring(0,queryStart);
905
+ let targetPath=routeMap === undefined ? undefined : routeMap.get(publicPath);
906
+ if (targetPath === undefined && pathMap !== undefined) {
907
+ let matchingSource;
908
+ for (let [sourcePath,mappedPath] of pathMap) {
909
+ if (publicPath.startsWith(sourcePath) &&
910
+ (matchingSource === undefined || sourcePath.length > matchingSource.length)) {
911
+ matchingSource=sourcePath;
912
+ targetPath=mappedPath + publicPath.substring(sourcePath.length);
913
+ }
914
+ }
915
+ }
916
+ if (targetPath === undefined) return;
917
+ return queryStart === -1 ? targetPath : targetPath + resourceTarget.substring(queryStart);
918
+ }
919
+ function protectedCompressionCacheTarget(basePath,resourceTarget) {
920
+ if (typeof resourceTarget !== "string") return false;
921
+ let queryStart=resourceTarget.indexOf("?");
922
+ let resourcePath=queryStart === -1 ? resourceTarget : resourceTarget.substring(0,queryStart);
923
+ let resolvedPath=containedRequestPath(basePath,resourcePath);
924
+ if (!resolvedPath) return false;
925
+ let cachePath=path.join(path.resolve(basePath),".compression-cache");
926
+ let relativePath=path.relative(cachePath,resolvedPath);
927
+ return relativePath === "" || (
928
+ relativePath !== ".." &&
929
+ !relativePath.startsWith(".." + path.sep) &&
930
+ !path.isAbsolute(relativePath)
931
+ );
932
+ }
933
+ function rejectProtectedCompressionCache(req,res,basePath,resourceTarget,sendBody = true) {
934
+ if (!protectedCompressionCacheTarget(basePath,resourceTarget)) return false;
935
+ reportError(res,resourceTarget,403,"Access to this resource is forbidden.",sendBody);
936
+ return true;
937
+ }
938
+ function checkResourceCors(req,res,fileInfo,publicTarget) {
939
+ let allowed;
940
+ try {
941
+ allowed=publicTarget === undefined
942
+ ? checkCorsPolicy(req,res,fileInfo)
943
+ : checkCorsTarget(req,res,publicTarget);
944
+ } catch (err) {
945
+ closeFileInfoDescriptor(fileInfo);
946
+ throw err;
947
+ }
948
+ if (!allowed) closeFileInfoDescriptor(fileInfo);
949
+ return allowed;
950
+ }
951
+ function handleGet(req, res, basePath, resourceTarget, publicTarget) {
952
+ let cached=cachedServlet(basePath,resourceTarget);
953
+ if (cached) {
954
+ let fileInfo=cachedServletFileInfo(cached,req,resourceTarget);
955
+ if (!checkResourceCors(req,res,fileInfo,publicTarget)) return;
956
+ handlePreparedServlet(req,res,fileInfo,cached.account,true);
957
+ return;
958
+ }
959
+ let fileInfo=setFileInfo(req,res,basePath,resourceTarget);
960
+ if (!checkResourceCors(req,res,fileInfo,publicTarget)) return;
961
+ handleResolvedResource(req,res,fileInfo,true,resourceTarget);
962
+ }
963
+
964
+ function handlePost (req, res, basePath, resourceTarget, publicTarget) {
965
+ let cached=cachedServlet(basePath,resourceTarget);
966
+ if (cached) {
967
+ let fileInfo=cachedServletFileInfo(cached,req,resourceTarget);
968
+ if (!checkResourceCors(req,res,fileInfo,publicTarget)) return;
969
+ handlePreparedServlet(req,res,fileInfo,cached.account,true);
970
+ return;
971
+ }
972
+ let fileInfo = setFileInfo(req, res, basePath, resourceTarget);
973
+ if (!checkResourceCors(req,res,fileInfo,publicTarget)) return;
974
+ handleResolvedResource(req, res, fileInfo, true, resourceTarget);
975
+ }
976
+
977
+ function handleHead (req, res, basePath, resourceTarget, publicTarget) {
978
+ let cached=cachedServlet(basePath,resourceTarget);
979
+ if (cached) {
980
+ let fileInfo=cachedServletFileInfo(cached,req,resourceTarget);
981
+ if (!checkResourceCors(req,res,fileInfo,publicTarget)) return;
982
+ handlePreparedServlet(req,res,fileInfo,cached.account,false);
983
+ return;
984
+ }
985
+ let fileInfo = setFileInfo(req, res, basePath, resourceTarget);
986
+ if (!checkResourceCors(req,res,fileInfo,publicTarget)) return;
987
+ handleResolvedResource(req, res, fileInfo, false, resourceTarget);
988
+ }
989
+ function advertisedMethods() {
990
+ return advertisedBuiltInMethods.concat(Array.from(registeredMethods.keys())).join(", ");
991
+ }
992
+ function handleOptions(req,res,basePath,resourceTarget,publicTarget) {
993
+ let allow=advertisedMethods();
994
+ if (req.url === "*") {
995
+ if (mode === "development") developmentLog("OPTIONS * REQUEST");
996
+ res.statusCode=204;
997
+ res.setHeader("Allow",allow);
998
+ res.setHeader("server",version);
999
+ res.end();
1000
+ return;
1001
+ }
1002
+
1003
+ let fileInfo=setFileInfo(req,res,basePath,resourceTarget);
1004
+ if (!checkResourceCors(req,res,fileInfo,publicTarget)) return;
1005
+ closeFileInfoDescriptor(fileInfo);
1006
+
1007
+ if (mode === "development") developmentLog("OPTIONS REQUEST: " + req);
1008
+ res.statusCode=204;
1009
+ if (req.headers.origin && req.headers["access-control-request-method"]) {
1010
+ res.setHeader("Access-Control-Allow-Methods",allow);
1011
+ res.setHeader("Access-Control-Allow-Headers","Content-Type");
1012
+ }
1013
+ res.setHeader("Allow",allow);
1014
+ res.setHeader("server",version);
1015
+ res.end();
1016
+ }
1017
+
1018
+ function dispatchMethod(req, res, basePath, resourceTarget) {
1019
+ let mappedTarget;
1020
+ switch (req.method) {
1021
+ case "GET":
1022
+ mappedTarget=mappedResourceTarget(resourceTarget);
1023
+ if (rejectProtectedCompressionCache(req,res,basePath,
1024
+ mappedTarget === undefined ? resourceTarget : mappedTarget)) return;
1025
+ handleGet(req,res,basePath,mappedTarget === undefined ? resourceTarget : mappedTarget,
1026
+ mappedTarget === undefined ? undefined : resourceTarget);
1027
+ break;
1028
+
1029
+ case "POST":
1030
+ mappedTarget=mappedResourceTarget(resourceTarget);
1031
+ if (rejectProtectedCompressionCache(req,res,basePath,
1032
+ mappedTarget === undefined ? resourceTarget : mappedTarget)) return;
1033
+ handlePost(req,res,basePath,mappedTarget === undefined ? resourceTarget : mappedTarget,
1034
+ mappedTarget === undefined ? undefined : resourceTarget);
1035
+ break;
1036
+
1037
+ case "HEAD":
1038
+ mappedTarget=mappedResourceTarget(resourceTarget);
1039
+ if (rejectProtectedCompressionCache(req,res,basePath,
1040
+ mappedTarget === undefined ? resourceTarget : mappedTarget,false)) return;
1041
+ handleHead(req,res,basePath,mappedTarget === undefined ? resourceTarget : mappedTarget,
1042
+ mappedTarget === undefined ? undefined : resourceTarget);
1043
+ break;
1044
+
1045
+ case "OPTIONS":
1046
+ mappedTarget=mappedResourceTarget(resourceTarget);
1047
+ if (rejectProtectedCompressionCache(req,res,basePath,
1048
+ mappedTarget === undefined ? resourceTarget : mappedTarget,false)) return;
1049
+ handleOptions(req,res,basePath,mappedTarget === undefined ? resourceTarget : mappedTarget,
1050
+ mappedTarget === undefined ? undefined : resourceTarget);
1051
+ break;
1052
+
1053
+ default:
1054
+ if (registeredMethods.has(req.method)) return handleRegisteredMethod(req,res,basePath,resourceTarget);
1055
+ return methodNotSupported(req, res);
1056
+ }
1057
+ }
1058
+
1059
+ function validAuthorityTarget(target) {
1060
+ if (typeof target !== "string") return false;
1061
+
1062
+ let host;
1063
+ let port;
1064
+ if (target.charAt(0) === "[") {
1065
+ let hostEnd = target.indexOf("]");
1066
+ if (hostEnd === -1 || target.charAt(hostEnd + 1) !== ":") return false;
1067
+ host = target.substring(0,hostEnd + 1);
1068
+ port = target.substring(hostEnd + 2);
1069
+ } else {
1070
+ let portStart = target.lastIndexOf(":");
1071
+ if (portStart <= 0 || target.indexOf(":") !== portStart) return false;
1072
+ host = target.substring(0,portStart);
1073
+ port = target.substring(portStart + 1);
1074
+ }
1075
+
1076
+ return (
1077
+ validHostValue(host) &&
1078
+ /^\d+$/.test(port) &&
1079
+ Number(port) <= 65535
1080
+ );
1081
+ }
1082
+
1083
+ function rawPathContainsBackslash(target) {
1084
+ let queryStart = target.indexOf("?");
1085
+ let pathname = queryStart === -1
1086
+ ? target
1087
+ : target.substring(0,queryStart);
1088
+ return pathname.indexOf("\\") !== -1;
1089
+ }
1090
+
1091
+ function absoluteAuthorityHost(authority) {
1092
+ if (authority.indexOf("@") !== -1) return false;
1093
+ let hostValue = authority;
1094
+
1095
+ if (!validHostValue(hostValue)) return false;
1096
+ if (hostValue.charAt(0) === "[") return hostValue;
1097
+
1098
+ let portStart = hostValue.lastIndexOf(":");
1099
+ let host = portStart === -1
1100
+ ? hostValue
1101
+ : hostValue.substring(0,portStart);
1102
+ return host.length > 0 ? hostValue : false;
1103
+ }
1104
+
1105
+ function requestTarget(req) {
1106
+ let rawTarget = req.url;
1107
+
1108
+ if (rawTarget.charAt(0) === "/") {
1109
+ if (req.method === "CONNECT") return false;
1110
+ if (rawPathContainsBackslash(rawTarget)) return false;
1111
+ return {form:"origin",resourceTarget:rawTarget};
1112
+ }
1113
+
1114
+ if (rawTarget === "*") {
1115
+ if (req.method !== "OPTIONS") return false;
1116
+ return {form:"asterisk"};
1117
+ }
1118
+
1119
+ if (req.method === "CONNECT") {
1120
+ if (!validAuthorityTarget(rawTarget)) return false;
1121
+ return {form:"authority",authority:rawTarget};
1122
+ }
1123
+
1124
+ if (rawPathContainsBackslash(rawTarget)) return false;
1125
+ let scheme = rawTarget.match(/^https?:\/\//i);
1126
+ if (!scheme || rawTarget.indexOf("#") !== -1) return false;
1127
+
1128
+ let authorityStart = scheme[0].length;
1129
+ let pathStart = rawTarget.indexOf("/",authorityStart);
1130
+ let queryStart = rawTarget.indexOf("?",authorityStart);
1131
+ let resourceStart;
1132
+ if (pathStart === -1) {
1133
+ resourceStart = queryStart;
1134
+ } else if (queryStart === -1) {
1135
+ resourceStart = pathStart;
1136
+ } else {
1137
+ resourceStart = Math.min(pathStart,queryStart);
1138
+ }
1139
+ let authorityEnd = resourceStart === -1
1140
+ ? rawTarget.length
1141
+ : resourceStart;
1142
+ let authority = absoluteAuthorityHost(
1143
+ rawTarget.substring(authorityStart,authorityEnd)
1144
+ );
1145
+ if (!authority) return false;
1146
+
1147
+ let resourceTarget = resourceStart === -1
1148
+ ? "/"
1149
+ : rawTarget.substring(resourceStart);
1150
+ if (resourceTarget.charAt(0) === "?") resourceTarget = "/" + resourceTarget;
1151
+ return {
1152
+ form:"absolute",
1153
+ authority:authority,
1154
+ resourceTarget:resourceTarget
1155
+ };
1156
+ }
1157
+
1158
+ function validHostValue(hostValue) {
1159
+ if (typeof hostValue !== "string") return false;
1160
+
1161
+ let bracketedHost = hostValue.match(/^\[([^\]]+)\](?::([0-9]*))?$/);
1162
+ if (bracketedHost) {
1163
+ let address = bracketedHost[1];
1164
+ return (
1165
+ require("net").isIP(address) === 6 ||
1166
+ /^v[0-9A-F]+\.[A-Za-z0-9._~!$&'()*+,;=:-]+$/i.test(address)
1167
+ );
1168
+ }
1169
+
1170
+ return /^(?:[A-Za-z0-9._~!$&'()*+,;=-]|%[0-9A-F]{2})*(?::[0-9]*)?$/i
1171
+ .test(hostValue);
1172
+ }
1173
+
1174
+ function normalizedHttp2Authority(authority,scheme) {
1175
+ if (
1176
+ typeof authority !== "string" ||
1177
+ authority.length === 0 ||
1178
+ !validHostValue(authority)
1179
+ ) return false;
1180
+
1181
+ let host = authority;
1182
+ let port;
1183
+ if (authority.charAt(0) === "[") {
1184
+ let hostEnd = authority.indexOf("]") + 1;
1185
+ host = authority.substring(0,hostEnd);
1186
+ if (authority.length > hostEnd) port = authority.substring(hostEnd + 1);
1187
+ } else {
1188
+ let portStart = authority.lastIndexOf(":");
1189
+ if (portStart !== -1) {
1190
+ host = authority.substring(0,portStart);
1191
+ port = authority.substring(portStart + 1);
1192
+ }
1193
+ }
1194
+ if (host.length === 0) return false;
1195
+
1196
+ if (
1197
+ host.charAt(0) === "[" &&
1198
+ require("net").isIP(host.substring(1,host.length - 1)) === 6
1199
+ ) {
1200
+ host = new URL("http://" + host).hostname;
1201
+ } else {
1202
+ host = host.replace(/%([0-9A-F]{2})/gi,function (encoding,hex) {
1203
+ let character = String.fromCharCode(parseInt(hex,16));
1204
+ return /^[A-Za-z0-9._~-]$/.test(character)
1205
+ ? character
1206
+ : "%" + hex.toUpperCase();
1207
+ }).toLowerCase();
1208
+ }
1209
+
1210
+ if (port !== undefined) {
1211
+ port = port.replace(/^0+(?=\d)/,"");
1212
+ let normalizedScheme = String(scheme).toLowerCase();
1213
+ let defaultPort = normalizedScheme === "http"
1214
+ ? "80"
1215
+ : normalizedScheme === "https" ? "443" : undefined;
1216
+ if (port === "" || defaultPort !== undefined && port === defaultPort) {
1217
+ port = undefined;
1218
+ }
1219
+ }
1220
+ return host + (port === undefined ? "" : ":" + port);
1221
+ }
1222
+
1223
+ function validRequestAuthority(req) {
1224
+ if (req.httpVersion === "2.0") {
1225
+ let authority = req.headers[":authority"];
1226
+ let host = req.headers.host;
1227
+ if (authority === undefined && host === undefined) return false;
1228
+
1229
+ let scheme = req.headers[":scheme"];
1230
+ let normalizedAuthority = authority === undefined
1231
+ ? undefined
1232
+ : normalizedHttp2Authority(authority,scheme);
1233
+ let normalizedHost = host === undefined
1234
+ ? undefined
1235
+ : normalizedHttp2Authority(host,scheme);
1236
+ if (
1237
+ normalizedAuthority === false ||
1238
+ normalizedHost === false
1239
+ ) return false;
1240
+ return (
1241
+ normalizedAuthority === undefined ||
1242
+ normalizedHost === undefined ||
1243
+ normalizedAuthority === normalizedHost
1244
+ );
1245
+ }
1246
+
1247
+ if (req.httpVersion !== "1.1") return true;
1248
+
1249
+ let hostCount = 0;
1250
+ let hostValue;
1251
+ for (let i = 0; i < req.rawHeaders.length; i += 2) {
1252
+ if (req.rawHeaders[i].toLowerCase() === "host") {
1253
+ hostCount++;
1254
+ if (hostCount > 1) return false;
1255
+ hostValue = req.rawHeaders[i+1];
1256
+ }
1257
+ }
1258
+
1259
+ return hostCount === 1 && validHostValue(hostValue);
1260
+ }
1261
+
1262
+ function connectResponseText(statusCode,statusMessage,contentType,body) {
1263
+ return (
1264
+ "HTTP/1.1 " + statusCode + " " + statusMessage + "\r\n" +
1265
+ "Content-Type: " + contentType + "\r\n" +
1266
+ "Content-Length: " + Buffer.byteLength(body,"utf8") + "\r\n" +
1267
+ "Connection: close\r\n" +
1268
+ "Date: " + new Date().toUTCString() + "\r\n" +
1269
+ "\r\n" +
1270
+ body
1271
+ );
1272
+ }
1273
+
1274
+ function handleConnectRequests(server) {
1275
+ server.on('connect',function(req,socket,head) {
1276
+ let recordAccess = createAccessRecorder(req);
1277
+ let responseStatus = 500;
1278
+ let responseStarted = false;
1279
+ let responseCompleted = false;
1280
+
1281
+ function recordAborted() {
1282
+ if (recordAccess) recordAccess(responseStatus,"aborted");
1283
+ }
1284
+
1285
+ socket.once("error",recordAborted);
1286
+ socket.once("close",function () {
1287
+ if (!responseCompleted) recordAborted();
1288
+ });
1289
+
1290
+ function endResponse(statusCode,statusMessage,contentType,body) {
1291
+ responseStatus = statusCode;
1292
+ if (!socket.writable) {
1293
+ recordAborted();
1294
+ socket.destroy();
1295
+ return;
1296
+ }
1297
+
1298
+ let responseText = connectResponseText(
1299
+ statusCode,
1300
+ statusMessage,
1301
+ contentType,
1302
+ body
1303
+ );
1304
+ responseStarted = true;
1305
+ socket.end(responseText,function () {
1306
+ responseCompleted = true;
1307
+ if (recordAccess) recordAccess(statusCode,"complete");
1308
+ });
1309
+ }
1310
+
1311
+ try {
1312
+ let targetInfo = requestTarget(req);
1313
+ if (!targetInfo || !validRequestAuthority(req)) {
1314
+ endResponse(
1315
+ 400,
1316
+ "Bad Request",
1317
+ "text/plain;charset=utf-8",
1318
+ "Bad Request"
1319
+ );
1320
+ return;
1321
+ }
1322
+
1323
+ let message = methodNotSupportedMessage(req);
1324
+ if (mode === "development") developmentLog(message);
1325
+ endResponse(
1326
+ 501,
1327
+ "Not Implemented",
1328
+ "text/plain; charset=utf-8",
1329
+ message
1330
+ );
1331
+ } catch (err) {
1332
+ serverError("Catchall error handling CONNECT.",err);
1333
+ if (responseStarted || !socket.writable) {
1334
+ recordAborted();
1335
+ if (!socket.destroyed) socket.destroy();
1336
+ return;
1337
+ }
1338
+
1339
+ try {
1340
+ endResponse(
1341
+ 500,
1342
+ "Internal Server Error",
1343
+ "text/plain;charset=utf-8",
1344
+ "Internal Server Error"
1345
+ );
1346
+ } catch (responseError) {
1347
+ serverError("Failed to send CONNECT catchall error response.",responseError);
1348
+ recordAborted();
1349
+ if (!socket.destroyed) socket.destroy();
1350
+ }
1351
+ }
1352
+ });
1353
+ }
1354
+
1355
+ function attachStartupLogging(server,protocol,port) {
1356
+ server.once("listening",function () {
1357
+ let serverName = protocol === "http"
1358
+ ? "HTTP"
1359
+ : protocol === "https"
1360
+ ? "HTTPS"
1361
+ : protocol === "http2.https"
1362
+ ? "HTTP2 (secure)"
1363
+ : "HTTP2 (insecure)";
1364
+ let corsRules=[];
1365
+ for (let [origin,pathMap] of corsPolicies) {
1366
+ for (let [corsPath,policy] of pathMap) {
1367
+ corsRules.push(origin + " " + corsPath + " [" + Array.from(policy.assets).join(", ") + "]");
1368
+ }
1369
+ }
1370
+ let routes=routeMap
1371
+ ? Array.from(routeMap,function ([publicPath,targetPath]) {
1372
+ return publicPath + " -> " + targetPath;
1373
+ })
1374
+ : [];
1375
+ let paths=pathMap
1376
+ ? Array.from(pathMap,function ([publicPath,targetPath]) {
1377
+ return publicPath + " -> " + targetPath;
1378
+ })
1379
+ : [];
1380
+ let methods=Array.from(registeredMethods,function ([method,servletPath]) {
1381
+ return method + " -> " + servletPath;
1382
+ });
1383
+ function startupDisplay(event,message) {
1384
+ console.log(message);
1385
+ serverEvent(event,message);
1386
+ }
1387
+ startupDisplay("START","\n" + version + " " + serverName + " is running on port " + port + ". (Node.js version " + process.version + ")");
1388
+ startupDisplay("CONFIG","Path to server entry: " + serverEntryPath);
1389
+ startupDisplay("CONFIG","Path to application base: " + basePath);
1390
+ startupDisplay("CONFIG","Mode: " + mode);
1391
+ startupDisplay("CONFIG","Node environment: " + process.env.NODE_ENV);
1392
+ startupDisplay("CONFIG","Browser caching: " + (bCaching ? "on" : "off"));
1393
+ startupDisplay("CONFIG","Static compression: " + (compress ? "on" : "off"));
1394
+ startupDisplay("CONFIG","Buffered input limit: " + bufferedInputLimit + " bytes");
1395
+ startupDisplay("CONFIG","Server logging: " + (logging.server ? "on" : "off"));
1396
+ startupDisplay("CONFIG","Access logging: " + (logging.access ? "on" : "off"));
1397
+ startupDisplay("CONFIG","Path to logs: " + logRoot);
1398
+ startupDisplay("CONFIG","MIME type listing: " + (showMimes ? "on" : "off"));
1399
+ startupDisplay("CONFIG","MIME types: " + Object.keys(mimeList).length + " configured");
1400
+ startupDisplay("CONFIG","Audiovisual MIME types: " + Object.keys(avMimeList).length + " configured");
1401
+ startupDisplay("CONFIG","Default character set: " + defaultCharSet);
1402
+ startupDisplay("CONFIG","CORS policies: " + (corsRules.length ? corsRules.join("; ") : "none"));
1403
+ startupDisplay("CONFIG","Route mappings: " + (routes.length ? routes.join("; ") : "none"));
1404
+ startupDisplay("CONFIG","Path mappings: " + (paths.length ? paths.join("; ") : "none"));
1405
+ startupDisplay("CONFIG","Registered methods: " + (methods.length ? methods.join(", ") : "none"));
1406
+ console.log("");
1407
+ });
1408
+ server.on("error",function (err) {
1409
+ if (server.listening) serverError(protocol + " listener error on port " + port + ": " + err.message,err);
1410
+ else startupError(protocol + " listener error on port " + port + ": " + err.message,err);
1411
+ });
1412
+ }
1413
+
1414
+ var achieveApp = function (req, res) {
1415
+ attachAccessLogging(req,res);
1416
+ if (mode === "development") developmentLog(req.method);
1417
+ try {
1418
+ // Get information about the requested file or application.
1419
+ // let urlParsed = url.parse(req.headers.referer, true);
1420
+ if (mode === "development") developmentLog("url: " + req.url + ", origin: " + req.socket.remoteAddress);
1421
+ if (/#|%(?![0-9A-Fa-f]{2})/.test(req.url)) {
1422
+ if (req.httpVersion === "2.0") {
1423
+ // A nonzero reset emits an expected stream error; it is not a server failure.
1424
+ req.stream.once("error",function () {});
1425
+ req.stream.close(http2.constants.NGHTTP2_PROTOCOL_ERROR);
1426
+ } else {
1427
+ res.statusCode=400;
1428
+ res.setHeader('Content-Type','text/plain;charset=utf-8');
1429
+ res.end("Bad Request");
1430
+ }
1431
+ return;
1432
+ }
1433
+ let targetInfo = requestTarget(req);
1434
+ if (!targetInfo || !validRequestAuthority(req)) {
1435
+ res.statusCode=400;
1436
+ res.setHeader('Content-Type','text/plain;charset=utf-8');
1437
+ res.end("Bad Request");
1438
+ return;
1439
+ }
1440
+ return dispatchMethod(req, res, basePath, targetInfo.resourceTarget);
1441
+ } catch (e) {
1442
+ handleUnexpectedRequestError(
1443
+ res,
1444
+ e,
1445
+ "Catchall error in achieveApp.",
1446
+ "Failed to send catchall error response."
1447
+ );
1448
+ }
1449
+ }
1450
+ function normalizedPort(port) {
1451
+ if (typeof port === "string") {
1452
+ let numericPort=port.trim();
1453
+ if (!/^\d+$/.test(numericPort)) return false;
1454
+ port=Number(numericPort);
1455
+ }
1456
+ if (typeof port !== "number" || !Number.isInteger(port)) return false;
1457
+ return port;
1458
+ }
1459
+ function displayMimeTypes() {
1460
+ if (!showMimes) return;
1461
+ console.log("\nMIME Types:");
1462
+ for (var type in mimeList) {
1463
+ console.log(" " + type + ": " + mimeList[type]);
1464
+ }
1465
+ console.log("\nAudioVisual MIME Types:");
1466
+ for (var atype in avMimeList) {
1467
+ console.log(" " + atype + ": " + avMimeList[atype]);
1468
+ }
1469
+ }
1470
+ exports.listen2 = function (ioptions) {
1471
+ http2 = require('http2');
1472
+
1473
+ let server;
1474
+ let ssl = false;
1475
+ let sport, portDefault;
1476
+
1477
+ try {
1478
+ if (typeof ioptions === "object") {
1479
+ if (ioptions.key === undefined || ioptions.cert === undefined) {
1480
+ startupError("FATAL ERROR: Security certification list is insufficient for SSL.");
1481
+ return;
1482
+ }
1483
+ ssl = true;
1484
+ portDefault = 443;
1485
+ sport = ioptions.http2Port;
1486
+ } else {
1487
+ portDefault = 80;
1488
+ sport = ioptions;
1489
+ }
1490
+
1491
+ if (sport === undefined) {
1492
+ sport=portDefault;
1493
+ } else if (normalizedPort(sport) === false) {
1494
+ startupWarning("http2 port " + sport + " is not a number. Setting port to default: " + portDefault + ".");
1495
+ sport=portDefault;
1496
+ } else {
1497
+ sport=normalizedPort(sport);
1498
+ }
1499
+ if ((sport<1024 && sport != portDefault) || sport>49151) {
1500
+ startupWarning("http2 port " + sport + " is outside acceptable range. (1024-49151) Setting port to default: " + portDefault + ".");
1501
+ sport=portDefault;
1502
+ }
1503
+ } catch (err) {
1504
+ startupWarning("Error setting port in listen2(). Setting port to default.")
1505
+ sport=portDefault;
1506
+ }
1507
+ if (!applicationPathReady()) return;
1508
+ if (!bCachingCheck) exports.setCaching(bCaching);
1509
+ if (!initializeLogging()) return;
1510
+
1511
+ if (ssl) {
1512
+ server = http2.createSecureServer(ioptions, achieveApp);
1513
+ } else {
1514
+ server = http2.createServer(achieveApp);
1515
+ }
1516
+ attachStartupLogging(server,ssl ? "http2.https" : "http2.http",sport);
1517
+ server.listen(sport);
1518
+ displayMimeTypes();
1519
+ return server;
1520
+
1521
+ };
1522
+ exports.slisten = function (ioptions) {
1523
+ https = require('https');
1524
+
1525
+ let server;
1526
+ let sport;
1527
+
1528
+ try {
1529
+ if (typeof ioptions !== "object") {
1530
+ startupError("FATAL ERROR: slisten() requires an options object as argument.");
1531
+ return;
1532
+ }
1533
+ if (ioptions.key === undefined || ioptions.cert === undefined) {
1534
+ startupError("FATAL ERROR: Security certification list is insufficient.");
1535
+ return;
1536
+ }
1537
+ sport = ioptions.httpsPort;
1538
+ if (sport === undefined) {
1539
+ sport=443;
1540
+ } else if (normalizedPort(sport) === false) {
1541
+ startupWarning("https port " + sport + " is not a number. Setting port to default.");
1542
+ sport=443;
1543
+ } else {
1544
+ sport=normalizedPort(sport);
1545
+ }
1546
+ if ((sport<1024 && sport!=443) || sport>49151) {
1547
+ startupWarning("https port " + sport + " is outside acceptable range. (1024-49151) Setting port to default.");
1548
+ sport=443;
1549
+ }
1550
+ } catch (err) {
1551
+ startupWarning("Error setting port in slisten(). Setting port to default.")
1552
+ sport=443;
1553
+ }
1554
+ if (!applicationPathReady()) return;
1555
+ if (!bCachingCheck) exports.setCaching(bCaching);
1556
+ if (!initializeLogging()) return;
1557
+
1558
+ server = https.createServer(ioptions, achieveApp);
1559
+ // Since 3.1.5, application-provided Node.js connect listeners handle HTTP/1.x CONNECT.
1560
+ attachStartupLogging(server,"https",sport);
1561
+ server.listen(sport);
1562
+ displayMimeTypes();
1563
+ return server;
1564
+
1565
+ };
1566
+ exports.listen = function (port) {
1567
+ http = require('http');
1568
+
1569
+ let server;
1570
+
1571
+ try {
1572
+
1573
+ if (port === undefined) {
1574
+ port=80;
1575
+ } else if (normalizedPort(port) === false) {
1576
+ startupWarning(port + " is not a number. Setting port to default.");
1577
+ port=80;
1578
+ } else {
1579
+ port=normalizedPort(port);
1580
+ }
1581
+ if ((port<1024 && port != 80) || port>49151) {
1582
+ startupWarning("Port " + port + " is outside acceptable range. (1024-49151) Setting port to default.");
1583
+ port=80;
1584
+ }
1585
+ } catch (err) {
1586
+ startupWarning("Error setting port in listen(). Setting port to default.")
1587
+ port=80;
1588
+ }
1589
+ if (!applicationPathReady()) return;
1590
+ if (!bCachingCheck) exports.setCaching(bCaching);
1591
+ if (!initializeLogging()) return;
1592
+
1593
+ server = http.createServer(achieveApp);
1594
+ // Since 3.1.5, application-provided Node.js connect listeners handle HTTP/1.x CONNECT.
1595
+ attachStartupLogging(server,"http",port);
1596
+ server.listen(port);
1597
+ displayMimeTypes();
1598
+ return server;
1599
+ };
1600
+ // Supported MIME types, based on file extensions
1601
+ // You may add new MIME types.
1602
+ exports.addMimeType = function (ext, mime) {
1603
+ try {
1604
+ ext=ext.trim(); mime=mime.trim();
1605
+ var extType=true, mimeType=true, extForm=true, mimeForm=true;
1606
+ if (typeof ext != "string") extType=false;
1607
+ if (typeof mime != "string") mimeType=false;
1608
+ if (extType && ext.indexOf('.') == 0) ext = ext.substring(1);
1609
+ if (extType && ext.indexOf('/') > -1) extForm=false;
1610
+ if (mimeType && mime.indexOf('/') < 1) mimeForm=false;
1611
+ if (extType && ext.toLowerCase() == "jss") {
1612
+ serverError(".jss is reserved for protected Achieve server-side source and cannot be registered as a public MIME type.");
1613
+ return;
1614
+ }
1615
+ if (extType && mimeType && extForm && mimeForm) {
1616
+ mimeList[ext]=mime;
1617
+ } else {
1618
+ if (!extType || !extForm) serverError("addMimeType(extension,mime) error: First argument must be a file suffix string such as 'html'");
1619
+ if (!mimeType || !mimeForm) serverError("addMimeType(extension,mime) error: Second argument must be a MIME type string such as 'text/html'");
1620
+ }
1621
+ } catch (err) {serverError("addMimeType() failed.",err);}
1622
+ };
1623
+ exports.addAVMimeType = function (ext, mime) {
1624
+ try {
1625
+ ext=ext.trim(); mime=mime.trim();
1626
+ var extType=true, mimeType=true, extForm=true, mimeForm=true;
1627
+ if (typeof ext != "string") extType=false;
1628
+ if (typeof mime != "string") mimeType=false;
1629
+ if (extType && ext.indexOf('.') == 0) ext = ext.substring(1);
1630
+ if (extType && ext.indexOf('/') > -1) extForm=false;
1631
+ if (mimeType && mime.indexOf('/') < 1) mimeForm=false;
1632
+ if (extType && mimeType && extForm && mimeForm) {
1633
+ avMimeList[ext]=mime;
1634
+ } else {
1635
+ if (!extType || !extForm) serverError("addAVMimeType(extension,mime) error: First argument must be a file suffix string such as 'html'");
1636
+ if (!mimeType || !mimeForm) serverError("addAVMimeType(extension,mime) error: Second argument must be a MIME type string such as 'text/html'");
1637
+ }
1638
+ } catch (err) {serverError("addAVMimeType() failed.",err);}
1639
+ };
1640
+ // "servlet" is not a file extension. It is used by this service to indicate running (not serving) js code.
1641
+ // "servlet" is required by this service. Default response MIME type for servlet is plain text, UTF-8
1642
+ let mimeList = {
1643
+ html: "text/html",
1644
+ htm: "text/html",
1645
+ css: "text/css",
1646
+ js: "application/javascript",
1647
+ mjs: "application/javascript",
1648
+ cjs: "application/javascript",
1649
+ xml: "application/xml",
1650
+ svg: "image/svg+xml",
1651
+ jpg: "image/jpeg",
1652
+ jpeg: "image/jpeg",
1653
+ png: "image/png",
1654
+ gif: "image/gif",
1655
+ json: "application/json",
1656
+ ico: "image/x-icon",
1657
+ xsl: "application/xslt+xml",
1658
+ pdf: "application/pdf",
1659
+ txt: "text/plain",
1660
+ servlet: "text/plain"
1661
+ };
1662
+ let avMimeList = {
1663
+ mp4: "video/mp4",
1664
+ m2v: "video/mpeg",
1665
+ ogv: "video/ogg",
1666
+ m2a: "audio/mpeg",
1667
+ mp3: "audio/mpeg3",
1668
+ oga: "audio/ogg"
1669
+ };
1670
+ function reportError (res,account,statusCode,reason,sendBody = true) {
1671
+ if (statusCode === undefined) statusCode = 500;
1672
+ if (statusCode >= 500) serverError(statusCode + ": " + reason);
1673
+ else if (mode === "development") developmentLog(statusCode + ": " + reason);
1674
+ res.statusCode=statusCode;
1675
+ res.setHeader('Content-Type','text/plain;charset=utf-8');
1676
+ if (sendBody) {
1677
+ res.end(reason);
1678
+ } else {
1679
+ res.end();
1680
+ }
1681
+ }
1682
+ function FileInfo (basePath,path,fullPath,dirPath,suffix,headers,contentType,queryString,serveFile,redirect,noSuchFile,reload,etag,audioVisual,notAcceptable = false,fileDescriptor,stats,openError) {
1683
+ this.basePath = basePath;
1684
+ this.path = path;
1685
+ this.fullPath = fullPath;
1686
+ this.dirPath = dirPath;
1687
+ this.suffix = suffix;
1688
+ this.headers = headers;
1689
+ this.contentType = contentType;
1690
+ this.queryString = queryString;
1691
+ this.serveFile = serveFile;
1692
+ this.redirect = redirect;
1693
+ this.noSuchFile = noSuchFile;
1694
+ this.reload = reload;
1695
+ this.etag = etag;
1696
+ this.audioVisual = audioVisual;
1697
+ this.notAcceptable = notAcceptable;
1698
+ this.fileDescriptor = fileDescriptor;
1699
+ this.stats = stats;
1700
+ this.openError = openError;
1701
+ }
1702
+ function closeFileInfoDescriptor (fileInfo) {
1703
+ if (fileInfo.fileDescriptor === undefined) return;
1704
+ let fileDescriptor=fileInfo.fileDescriptor;
1705
+ fileInfo.fileDescriptor=undefined;
1706
+ closeDescriptor(fileDescriptor,fileInfo.fullPath);
1707
+ }
1708
+ function hasEntityTagPrecondition (req) {
1709
+ return (
1710
+ req.headers['if-match'] !== undefined ||
1711
+ req.headers['if-none-match'] !== undefined
1712
+ );
1713
+ }
1714
+ function representationETag (stats,coding) {
1715
+ var rawVal = [
1716
+ stats.mtimeMs,
1717
+ stats.ctimeMs,
1718
+ stats.size,
1719
+ stats.dev,
1720
+ stats.ino,
1721
+ etagString
1722
+ ].join(":");
1723
+ return '"' + Buffer.from(rawVal).toString("base64url") + '-' + coding + '"';
1724
+ }
1725
+ function entityTagList (fieldValue) {
1726
+ let result=[];
1727
+ let member="";
1728
+ let quoted=false;
1729
+ for (let character of fieldValue) {
1730
+ if (character === '"') quoted=!quoted;
1731
+ if (character === "," && !quoted) {
1732
+ result.push(member.trim());
1733
+ member="";
1734
+ } else {
1735
+ member+=character;
1736
+ }
1737
+ }
1738
+ result.push(member.trim());
1739
+ return result;
1740
+ }
1741
+ function entityTag (value) {
1742
+ let tag=value;
1743
+ let weak=false;
1744
+ if (tag.indexOf("W/") === 0) {
1745
+ weak=true;
1746
+ tag=tag.substring(2);
1747
+ }
1748
+ if (
1749
+ tag.length < 2 ||
1750
+ tag.charAt(0) !== '"' ||
1751
+ tag.charAt(tag.length-1) !== '"' ||
1752
+ tag.substring(1,tag.length-1).indexOf('"') !== -1
1753
+ ) return false;
1754
+ return {weak:weak,tag:tag};
1755
+ }
1756
+ function entityTagFieldMatches (fieldValue,currentETag,weakComparison) {
1757
+ if (currentETag === undefined || currentETag === "") return false;
1758
+ let current=entityTag(currentETag);
1759
+ if (!current) return false;
1760
+ for (let member of entityTagList(fieldValue)) {
1761
+ let candidate=entityTag(member);
1762
+ if (!candidate) continue;
1763
+ if (weakComparison) {
1764
+ if (candidate.tag === current.tag) return true;
1765
+ } else if (!candidate.weak && !current.weak && candidate.tag === current.tag) {
1766
+ return true;
1767
+ }
1768
+ }
1769
+ return false;
1770
+ }
1771
+ // Use one origination time for Date, the future-mtime clamp, and comparisons.
1772
+ // The opened representation's original stats remain untouched (notably for ETags).
1773
+ function staticModificationTime (res,stats) {
1774
+ let now=Date.now();
1775
+ res.setHeader('Date',new Date(now).toUTCString());
1776
+ return Math.floor(Math.min(stats.mtimeMs,now)/1000);
1777
+ }
1778
+ function setLastModified (res,modified) {
1779
+ if (bCaching && modified !== undefined) {
1780
+ res.setHeader('Last-Modified',new Date(modified*1000).toUTCString());
1781
+ }
1782
+ }
1783
+ // Accept the three HTTP-date forms, not Date.parse's non-HTTP extensions/lists.
1784
+ function parseHTTPDate (value) {
1785
+ if (typeof value !== 'string') return undefined;
1786
+ let match=/^(Mon|Tue|Wed|Thu|Fri|Sat|Sun), (\d{2}) (Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec) (\d{4}) (\d{2}):(\d{2}):(\d{2}) GMT$/.exec(value);
1787
+ let obsolete=false;
1788
+ if (!match) {
1789
+ match=/^(Monday|Tuesday|Wednesday|Thursday|Friday|Saturday|Sunday), (\d{2})-(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)-(\d{2}) (\d{2}):(\d{2}):(\d{2}) GMT$/.exec(value);
1790
+ obsolete=!!match;
1791
+ }
1792
+ if (!match) {
1793
+ let asc=/^(Mon|Tue|Wed|Thu|Fri|Sat|Sun) (Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec) ( \d|\d{2}) (\d{2}):(\d{2}):(\d{2}) (\d{4})$/.exec(value);
1794
+ if (!asc) return undefined;
1795
+ match=[asc[0],asc[1],asc[3],asc[2],asc[7],asc[4],asc[5],asc[6]];
1796
+ }
1797
+ let day=Number(match[2]),month=['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec'].indexOf(match[3]);
1798
+ let year=Number(match[4]),hour=Number(match[5]),minute=Number(match[6]),second=Number(match[7]);
1799
+ if (hour>23 || minute>59 || second>60 || day<1) return undefined;
1800
+ let date=new Date(0);
1801
+ if (obsolete) year+=Math.floor(new Date(Date.now()).getUTCFullYear()/100)*100;
1802
+ date.setUTCFullYear(year,month,day);
1803
+ date.setUTCHours(hour,minute,Math.min(second,59),0);
1804
+ if (obsolete) {
1805
+ let limit=new Date(Date.now());
1806
+ limit.setUTCFullYear(limit.getUTCFullYear()+50);
1807
+ if (date>limit) { year-=100; date.setUTCFullYear(year); }
1808
+ }
1809
+ if (date.getUTCFullYear()!==year || date.getUTCMonth()!==month || date.getUTCDate()!==day) return undefined;
1810
+ return date.getTime()/1000+(second===60 ? 1 : 0);
1811
+ }
1812
+ function evaluatePreconditions (req,res,exists,currentETag,modified) {
1813
+ let ifMatch=req.headers['if-match'];
1814
+ if (ifMatch !== undefined) {
1815
+ let ifMatchResult = ifMatch.trim() === "*"
1816
+ ? exists
1817
+ : entityTagFieldMatches(ifMatch,currentETag,false);
1818
+ if (!ifMatchResult) {
1819
+ res.statusCode=412;
1820
+ res.end();
1821
+ return true;
1822
+ }
1823
+ } else if (modified !== undefined) {
1824
+ let unmodified=parseHTTPDate(req.headers['if-unmodified-since']);
1825
+ if (unmodified !== undefined && modified>unmodified) {
1826
+ res.statusCode=412;
1827
+ res.end();
1828
+ return true;
1829
+ }
1830
+ }
1831
+
1832
+ let ifNoneMatch=req.headers['if-none-match'];
1833
+ if (ifNoneMatch !== undefined) {
1834
+ let ifNoneMatchResult = ifNoneMatch.trim() === "*"
1835
+ ? exists
1836
+ : entityTagFieldMatches(ifNoneMatch,currentETag,true);
1837
+ if (ifNoneMatchResult) {
1838
+ if (req.method === "GET" || req.method === "HEAD") {
1839
+ if (currentETag) res.setHeader("ETag",currentETag);
1840
+ setLastModified(res,modified);
1841
+ res.statusCode=304;
1842
+ } else {
1843
+ res.statusCode=412;
1844
+ }
1845
+ res.end();
1846
+ return true;
1847
+ }
1848
+ } else if (modified !== undefined && (req.method === 'GET' || req.method === 'HEAD')) {
1849
+ let since=parseHTTPDate(req.headers['if-modified-since']);
1850
+ if (since !== undefined && modified<=since) {
1851
+ if (currentETag) res.setHeader('ETag',currentETag);
1852
+ setLastModified(res,modified);
1853
+ res.statusCode=304;
1854
+ res.end();
1855
+ return true;
1856
+ }
1857
+ }
1858
+ return false;
1859
+ }
1860
+ function Context (req,res,parms,dirPath,appPath,load) {
1861
+ let autoEnd=true;
1862
+ this.request = req;
1863
+ this.response = res;
1864
+ this.parms = parms; // deprecate
1865
+ this.params = parms;
1866
+ this.dirPath = dirPath;
1867
+ this.appPath = appPath;
1868
+ this.load = load;
1869
+ this.rtErrorMsg = rtErrorMsg;
1870
+ Object.defineProperties(this,{
1871
+ autoEnd:{
1872
+ enumerable:true,
1873
+ get:function () { return autoEnd; },
1874
+ set:function (value) { autoEnd=Boolean(value); }
1875
+ },
1876
+ allowAsync:{
1877
+ enumerable:true,
1878
+ get:function () { return !autoEnd; },
1879
+ set:function (value) { autoEnd=!Boolean(value); }
1880
+ }
1881
+ });
1882
+ }
1883
+ function PathInfo (filePath,reload,action,stats,resolution) {
1884
+ this.filePath = filePath;
1885
+ this.reload = reload;
1886
+ this.action = action;
1887
+ this.stats = stats;
1888
+ this.resolution = resolution;
1889
+ }
1890
+ function closeDescriptor (fileDescriptor,sourcePath) {
1891
+ try {
1892
+ fs.closeSync(fileDescriptor);
1893
+ } catch (err) {
1894
+ serverError("Error closing " + safeSourceIdentity(sourcePath) + ": " + rtErrorMsg(err),err);
1895
+ }
1896
+ }
1897
+ function containedRequestPath (boundaryPath,requestPath) {
1898
+ let boundary = path.resolve(boundaryPath);
1899
+ let candidate = path.join(boundary,requestPath);
1900
+ let relativeCandidate = path.relative(boundary,candidate);
1901
+
1902
+ if (
1903
+ relativeCandidate === ".." ||
1904
+ relativeCandidate.startsWith(".." + path.sep) ||
1905
+ path.isAbsolute(relativeCandidate)
1906
+ ) {
1907
+ return false;
1908
+ }
1909
+
1910
+ return candidate;
1911
+ }
1912
+ function containedPhysicalPath (candidatePath) {
1913
+ let physicalCandidate;
1914
+ try {
1915
+ physicalCandidate=fs.realpathSync.native(candidatePath);
1916
+ } catch (err) {
1917
+ return false;
1918
+ }
1919
+ return containedResolvedPhysicalPath(physicalCandidate);
1920
+ }
1921
+ function containedResolvedPhysicalPath (physicalCandidate) {
1922
+ let relativeCandidate=path.relative(physicalBasePath,physicalCandidate);
1923
+ if (
1924
+ relativeCandidate === ".." ||
1925
+ relativeCandidate.startsWith(".." + path.sep) ||
1926
+ path.isAbsolute(relativeCandidate)
1927
+ ) {
1928
+ return false;
1929
+ }
1930
+ return physicalCandidate;
1931
+ }
1932
+ function servletModuleType (filePath) {
1933
+ let lowerPath=filePath.toLowerCase();
1934
+ if (lowerPath.endsWith(".jss.mjs")) return "module";
1935
+ if (lowerPath.endsWith(".jss.cjs") || lowerPath.endsWith(".jss")) return "commonjs";
1936
+ return false;
1937
+ }
1938
+ function protectedServletPath (filePath) {
1939
+ return /\.jss(?:\.|$)/i.test(path.basename(filePath));
1940
+ }
1941
+ function checkPath (basePath,relativePath,directoryForm) {
1942
+ // Build full path.
1943
+ let action="";
1944
+ let fullPath = containedRequestPath(basePath,relativePath);
1945
+ let stats, checkPath, physicalPath;
1946
+ let reload=false;
1947
+
1948
+ if (!fullPath) {
1949
+ return new PathInfo(relativePath,false,"noSuchFile",stats);
1950
+ }
1951
+
1952
+ let suffix=path.extname(fullPath).substring(1);
1953
+ if (
1954
+ !compress &&
1955
+ !directoryForm &&
1956
+ suffix.length !== 0 &&
1957
+ !servletModuleType(fullPath) &&
1958
+ !protectedServletPath(fullPath) &&
1959
+ avMimeList[suffix] === undefined
1960
+ ) {
1961
+ let physicalPath;
1962
+ try {
1963
+ physicalPath=fs.realpathSync.native(fullPath);
1964
+ } catch (err) {}
1965
+ if (physicalPath !== undefined) {
1966
+ if (!containedResolvedPhysicalPath(physicalPath)) {
1967
+ return new PathInfo(path.normalize(relativePath),false,"noSuchFile",stats);
1968
+ }
1969
+ if (protectedServletPath(physicalPath)) {
1970
+ return new PathInfo(path.normalize(relativePath),false,"noSuchFile",stats);
1971
+ }
1972
+ let fileDescriptor;
1973
+ try {
1974
+ fileDescriptor=fs.openSync(physicalPath,"r");
1975
+ } catch (err) {
1976
+ let currentStats;
1977
+ try {
1978
+ currentStats=fs.statSync(fullPath,{throwIfNoEntry:false});
1979
+ } catch (statError) {}
1980
+ if (currentStats && currentStats.isDirectory()) {
1981
+ stats=currentStats;
1982
+ } else {
1983
+ return new PathInfo(path.normalize(relativePath),true,"serveFile",stats,{
1984
+ physicalPath:physicalPath,
1985
+ openError:err
1986
+ });
1987
+ }
1988
+ }
1989
+ if (fileDescriptor !== undefined) try {
1990
+ stats=fs.fstatSync(fileDescriptor);
1991
+ } catch (err) {
1992
+ closeDescriptor(fileDescriptor,physicalPath);
1993
+ return new PathInfo(path.normalize(relativePath),true,"serveFile",stats,{
1994
+ physicalPath:physicalPath,
1995
+ openError:err
1996
+ });
1997
+ }
1998
+ if (fileDescriptor !== undefined && stats.isFile()) {
1999
+ return new PathInfo(path.normalize(relativePath),true,"serveFile",stats,{
2000
+ physicalPath:physicalPath,
2001
+ fileDescriptor:fileDescriptor
2002
+ });
2003
+ }
2004
+ if (fileDescriptor !== undefined) closeDescriptor(fileDescriptor,physicalPath);
2005
+ }
2006
+ }
2007
+
2008
+ if (stats === undefined) try {
2009
+ // Does fullPath exist?
2010
+ stats = fs.statSync(fullPath);
2011
+ } catch (err) {
2012
+ if (protectedServletPath(fullPath)) {
2013
+ return new PathInfo(path.normalize(relativePath),false,"noSuchFile",stats);
2014
+ }
2015
+ stats = fs.statSync(fullPath+".js",{
2016
+ throwIfNoEntry:false
2017
+ });
2018
+ if (stats !== undefined) {
2019
+ physicalPath=containedPhysicalPath(fullPath+".js");
2020
+ if (!physicalPath || protectedServletPath(physicalPath)) {
2021
+ return new PathInfo(path.normalize(relativePath),false,"noSuchFile",stats);
2022
+ }
2023
+ if (moduleLoadTimes[fullPath+".js"] === undefined || moduleLoadTimes[fullPath+".js"] < stats.mtimeMs) reload = true;
2024
+ return new PathInfo(path.normalize(relativePath+".js"),reload,"servlet",stats);
2025
+ }
2026
+ return new PathInfo(path.normalize(relativePath),false,"noSuchFile",stats);
2027
+ }
2028
+ // If fullPath points to a file, return the relative path.
2029
+ if (stats.isFile()) {
2030
+ physicalPath=containedPhysicalPath(fullPath);
2031
+ if (!physicalPath) return new PathInfo(path.normalize(relativePath),false,"noSuchFile",stats);
2032
+ if (servletModuleType(fullPath)) {
2033
+ if (moduleLoadTimes[fullPath] === undefined || moduleLoadTimes[fullPath] < stats.mtimeMs) reload = true;
2034
+ return new PathInfo(path.normalize(relativePath),reload,"servlet",stats);
2035
+ }
2036
+ if (protectedServletPath(fullPath) || protectedServletPath(physicalPath)) {
2037
+ return new PathInfo(path.normalize(relativePath),false,"noSuchFile",stats);
2038
+ }
2039
+ return new PathInfo(path.normalize(relativePath),true,"serveFile",stats);
2040
+ }
2041
+ // If fullPath points to a directory:
2042
+ if (stats.isDirectory()) {
2043
+ physicalPath=containedPhysicalPath(fullPath);
2044
+ if (!physicalPath) return new PathInfo(path.normalize(relativePath),false,"noSuchFile",stats);
2045
+ // directory requests without trailing '/' are redirected with '/' added
2046
+ if (!directoryForm) return new PathInfo(path.normalize(relativePath),false,"redirect",stats);
2047
+ // Check for default files like index.html and index.js
2048
+ for (let df of defaultFiles) {
2049
+ checkPath = path.join(fullPath,df);
2050
+ if (fs.existsSync(checkPath)) {
2051
+ let physicalDefault=containedPhysicalPath(checkPath);
2052
+ if (!physicalDefault || (!servletModuleType(checkPath) && protectedServletPath(physicalDefault))) continue;
2053
+ if (servletModuleType(checkPath) || df == "index.js") {
2054
+ stats = fs.statSync(checkPath);
2055
+ if (moduleLoadTimes[checkPath] === undefined || moduleLoadTimes[checkPath] < stats.mtimeMs) reload = true;
2056
+ action = "servlet";
2057
+ } else {
2058
+ stats = fs.statSync(checkPath);
2059
+ action = "serveFile";
2060
+ }
2061
+ return new PathInfo(path.join(relativePath,df),reload,action,stats);
2062
+ }
2063
+ }
2064
+ }
2065
+ return new PathInfo(relativePath,false,"noSuchFile",stats);
2066
+ }
2067
+ let defaultFiles = [
2068
+ "index.html",
2069
+ "index.htm",
2070
+ "index.jss",
2071
+ "index.jss.mjs",
2072
+ "index.jss.cjs",
2073
+ "index.js"
2074
+ ];
2075
+ function setFileInfo (req, res, basePath, requestUrl) {
2076
+ let serveFile=true;
2077
+ let headers=req.headers;
2078
+ let fullPath="", suffix="", queryString="", contentType="",dirPath="",etag="";
2079
+ let fileDescriptor, representationStats, openError, etagCoding="i";
2080
+ let reload=false;
2081
+ let thisBasePath=basePath;
2082
+ let audioVisual = false;
2083
+ let notAcceptable = false;
2084
+ let identityAllowed = true;
2085
+ if (mode === "development") developmentLog("req.url: " + req.url);
2086
+ let queryStart = requestUrl.indexOf("?");
2087
+ let uncheckedPath = queryStart === -1
2088
+ ? requestUrl
2089
+ : requestUrl.substring(0,queryStart);
2090
+ queryString = queryStart === -1
2091
+ ? ""
2092
+ : requestUrl.substring(queryStart + 1);
2093
+ // checkPath returns path request after performing various checks, (See checkPath() for details.)
2094
+ let checkedPath = checkPath(thisBasePath,uncheckedPath,uncheckedPath.endsWith("/"));
2095
+ if (checkedPath.action == "noSuchFile") return new FileInfo(thisBasePath,requestUrl,checkedPath.filePath,dirPath,suffix,headers,contentType,queryString,false,false,true,reload,etag,audioVisual);
2096
+ // If null, redirect in FileInfo object is set to true. (Needs redirect to add trailing slash.)
2097
+ if (checkedPath.action == "redirect") return new FileInfo(thisBasePath,requestUrl,fullPath,dirPath,suffix,headers,contentType,queryString,false,true,false,reload,etag,audioVisual);
2098
+ let resolution=checkedPath.resolution;
2099
+ fileDescriptor=resolution === undefined ? undefined : resolution.fileDescriptor;
2100
+ representationStats=fileDescriptor === undefined ? undefined : checkedPath.stats;
2101
+ openError=resolution === undefined ? undefined : resolution.openError;
2102
+ let currentPath = checkedPath.filePath;
2103
+ suffix = path.extname(currentPath).substring(1) || "";
2104
+ fullPath = path.join(thisBasePath,currentPath);
2105
+ dirPath = path.dirname(fullPath);
2106
+ if (checkedPath.action === "servlet") {
2107
+ suffix = "servlet"; // This special app suffix does not indicate MIME type.
2108
+ serveFile=false;
2109
+ } else if (suffix.length == 0) {
2110
+ // If file exists with no suffix, attempt to serve it as text.
2111
+ suffix = "txt";
2112
+ }
2113
+ // Get MIME type.
2114
+ contentType = mimeList[suffix];
2115
+ // 415 Unsupported Media type is supported above.
2116
+ // Remove or conditionalize the following undefined check to make it work
2117
+ // This is here because it feels less confusing (new students) - but I want to rethink that
2118
+ if (contentType === undefined) {
2119
+ contentType = avMimeList[suffix];
2120
+ if (contentType === undefined) {
2121
+ contentType = "text/plain";
2122
+ } else {
2123
+ audioVisual=true;
2124
+ serveFile=false;
2125
+ }
2126
+ }
2127
+ if (serveFile) {
2128
+
2129
+ // For compression
2130
+ if (compress && (contentType.indexOf("text") == 0 || contentType.indexOf("application") == 0)) {
2131
+ res.setHeader("Vary","Accept-Encoding");
2132
+ let enc = getEncoding(req);
2133
+ identityAllowed = enc.identityQuality != 0;
2134
+ let schedule = true;
2135
+ for (let candidate of enc.candidates) {
2136
+ if (candidate.quality < enc.identityQuality) break;
2137
+ let ccPath = checkCPath(fullPath,candidate.ext,checkedPath.stats,thisBasePath,schedule);
2138
+ schedule = false;
2139
+ if (ccPath !== false) {
2140
+ currentPath = path.relative(thisBasePath,ccPath);
2141
+ res.setHeader("Content-Encoding",candidate.contentEncoding);
2142
+ etagCoding = candidate.contentEncoding == "gzip" ? "g" : "d";
2143
+ break;
2144
+ }
2145
+ }
2146
+ if (etagCoding == "i" && enc.identityQuality == 0) notAcceptable = true;
2147
+ }
2148
+ }
2149
+ if (!notAcceptable && (serveFile || audioVisual)) {
2150
+ let representationPath=(resolution && resolution.physicalPath) || path.join(thisBasePath,currentPath);
2151
+ function openRepresentation() {
2152
+ fileDescriptor=fs.openSync(representationPath,"r");
2153
+ representationStats=fs.fstatSync(fileDescriptor);
2154
+ if (!representationStats.isFile()) {
2155
+ let err=new Error("Selected representation is not a regular file.");
2156
+ err.code="EISDIR";
2157
+ throw err;
2158
+ }
2159
+ }
2160
+ try {
2161
+ if (fileDescriptor === undefined && openError === undefined) openRepresentation();
2162
+ } catch (err) {
2163
+ openError=err;
2164
+ if (fileDescriptor !== undefined) {
2165
+ try {
2166
+ fs.closeSync(fileDescriptor);
2167
+ } catch (closeError) {
2168
+ serverError("Error closing " + safeSourceIdentity(representationPath) + ": " + rtErrorMsg(closeError),closeError);
2169
+ }
2170
+ fileDescriptor=undefined;
2171
+ }
2172
+ }
2173
+ if (openError && etagCoding != "i") {
2174
+ res.removeHeader("Content-Encoding");
2175
+ currentPath=checkedPath.filePath;
2176
+ representationPath=fullPath;
2177
+ representationStats=undefined;
2178
+ openError=undefined;
2179
+ etagCoding="i";
2180
+ if (!identityAllowed) {
2181
+ notAcceptable=true;
2182
+ } else {
2183
+ try {
2184
+ openRepresentation();
2185
+ } catch (err) {
2186
+ openError=err;
2187
+ if (fileDescriptor !== undefined) {
2188
+ try {
2189
+ fs.closeSync(fileDescriptor);
2190
+ } catch (closeError) {
2191
+ serverError("Error closing " + safeSourceIdentity(representationPath) + ": " + rtErrorMsg(closeError),closeError);
2192
+ }
2193
+ fileDescriptor=undefined;
2194
+ }
2195
+ }
2196
+ }
2197
+ }
2198
+ if (!notAcceptable && !openError && serveFile && (bCaching || hasEntityTagPrecondition(req))) {
2199
+ etag = representationETag(representationStats,etagCoding);
2200
+ }
2201
+ }
2202
+ return new FileInfo(thisBasePath,currentPath,fullPath,dirPath,suffix,headers,contentType,queryString,serveFile,false,false,checkedPath.reload,etag,audioVisual,notAcceptable,fileDescriptor,representationStats,openError);
2203
+ }
2204
+ function removeCompressionTemp (tempPath,callback) {
2205
+ fs.unlink(tempPath,function (err) {
2206
+ if (err && err.code !== "ENOENT") {
2207
+ serverError(tempPath + " Compression temporary-file cleanup failed.",err);
2208
+ }
2209
+ callback();
2210
+ });
2211
+ }
2212
+ function compressionArtifactPath (basePath,sourcePath,ext) {
2213
+ let cachePath=path.join(basePath,".compression-cache");
2214
+ let cacheRelative=path.relative(cachePath,sourcePath);
2215
+ if (
2216
+ cacheRelative === "" ||
2217
+ (
2218
+ cacheRelative !== ".." &&
2219
+ !cacheRelative.startsWith(".." + path.sep) &&
2220
+ !path.isAbsolute(cacheRelative)
2221
+ )
2222
+ ) {
2223
+ return false;
2224
+ }
2225
+ return path.join(cachePath,path.relative(basePath,sourcePath)) + ext;
2226
+ }
2227
+ function scheduleCompressedArtifact (sourcePath,artifactPath,ext,sourceStats) {
2228
+ if (compressionJobs.has(artifactPath)) return;
2229
+ compressionJobs.add(artifactPath);
2230
+
2231
+ let sourceMtimeMs=sourceStats.mtimeMs;
2232
+ let sourceCtimeMs=sourceStats.ctimeMs;
2233
+ let sourceSize=sourceStats.size;
2234
+ let sourceDev=sourceStats.dev;
2235
+ let sourceIno=sourceStats.ino;
2236
+ let tempPath = artifactPath +
2237
+ ".tmp-" + process.pid +
2238
+ "-" + Date.now() +
2239
+ "-" + (++compressionTempSequence);
2240
+
2241
+ function clearJob () {
2242
+ compressionJobs.delete(artifactPath);
2243
+ }
2244
+ function fail (message,err) {
2245
+ serverError(message,err);
2246
+ removeCompressionTemp(tempPath,clearJob);
2247
+ }
2248
+
2249
+ fs.mkdir(path.dirname(artifactPath),{recursive:true},function (err) {
2250
+ if (err) {
2251
+ serverError(artifactPath + " Compression cache directory creation failed.",err);
2252
+ clearJob();
2253
+ return;
2254
+ }
2255
+ try {
2256
+ let compressor = ext == ".gz"
2257
+ ? zlib.createGzip()
2258
+ : zlib.createDeflate();
2259
+ streamPipeline(
2260
+ fs.createReadStream(sourcePath),
2261
+ compressor,
2262
+ fs.createWriteStream(tempPath,{flags:"wx"}),
2263
+ function (err) {
2264
+ if (err) {
2265
+ fail(sourcePath + " Compression failed.",err);
2266
+ return;
2267
+ }
2268
+ fs.stat(sourcePath,function (err,currentStats) {
2269
+ if (err) {
2270
+ fail(sourcePath + " Compression source restat failed.",err);
2271
+ return;
2272
+ }
2273
+ if (
2274
+ currentStats.mtimeMs !== sourceMtimeMs ||
2275
+ currentStats.ctimeMs !== sourceCtimeMs ||
2276
+ currentStats.size !== sourceSize ||
2277
+ currentStats.dev !== sourceDev ||
2278
+ currentStats.ino !== sourceIno
2279
+ ) {
2280
+ removeCompressionTemp(tempPath,clearJob);
2281
+ return;
2282
+ }
2283
+ fs.rename(tempPath,artifactPath,function (err) {
2284
+ if (err) {
2285
+ fail(artifactPath + " Compression artifact publication failed.",err);
2286
+ return;
2287
+ }
2288
+ clearJob();
2289
+ });
2290
+ });
2291
+ }
2292
+ );
2293
+ } catch (err) {
2294
+ fail(sourcePath + " Compression failed.",err);
2295
+ }
2296
+ });
2297
+ }
2298
+ function checkCPath (path,ext,sourceStats,basePath,schedule = true) {
2299
+ let artifactPath=compressionArtifactPath(basePath,path,ext);
2300
+ if (!artifactPath) return false;
2301
+ try {
2302
+ if (fs.existsSync(artifactPath)) {
2303
+ let cstats = fs.statSync(artifactPath);
2304
+ if (
2305
+ sourceStats.mtimeMs <= cstats.mtimeMs &&
2306
+ sourceStats.ctimeMs <= cstats.mtimeMs
2307
+ ) return artifactPath;
2308
+ }
2309
+ } catch (err) {
2310
+ serverError(path + " Compression failed.",err);
2311
+ return false;
2312
+ }
2313
+ if (schedule) scheduleCompressedArtifact(path,artifactPath,ext,sourceStats);
2314
+ return false;
2315
+ }
2316
+ function encodingQuality (value) {
2317
+ if (!/^(?:0(?:\.\d{0,3})?|1(?:\.0{0,3})?)$/.test(value)) return false;
2318
+ let parts=value.split(".");
2319
+ let fraction=(parts[1] || "").padEnd(3,"0");
2320
+ return Number(parts[0])*1000+Number(fraction);
2321
+ }
2322
+ function getEncoding (req) {
2323
+ let acceptEncoding=req.headers['accept-encoding'];
2324
+ let qualities={};
2325
+ if (acceptEncoding !== undefined && acceptEncoding !== "") {
2326
+ for (let fieldMember of acceptEncoding.split(",")) {
2327
+ let member=fieldMember.trim();
2328
+ if (member === "") continue;
2329
+ let parts=member.split(";");
2330
+ if (parts.length > 2) continue;
2331
+ let coding=parts[0].trim().toLowerCase();
2332
+ if (!/^[!#$%&'*+\-.^_`|~0-9a-z]+$/.test(coding)) continue;
2333
+ let quality=1000;
2334
+ if (parts.length == 2) {
2335
+ let match=/^q=(.*)$/i.exec(parts[1].trim());
2336
+ if (!match) continue;
2337
+ quality=encodingQuality(match[1]);
2338
+ if (quality === false) continue;
2339
+ }
2340
+ if (
2341
+ coding == "gzip" ||
2342
+ coding == "deflate" ||
2343
+ coding == "identity" ||
2344
+ coding == "*"
2345
+ ) {
2346
+ if (qualities[coding] === undefined || quality > qualities[coding]) {
2347
+ qualities[coding]=quality;
2348
+ }
2349
+ }
2350
+ }
2351
+ }
2352
+ let gzipQuality=qualities.gzip === undefined ? qualities["*"] : qualities.gzip;
2353
+ let deflateQuality=qualities.deflate === undefined ? qualities["*"] : qualities.deflate;
2354
+ let identityQuality=qualities.identity === undefined
2355
+ ? (qualities["*"] === 0 ? 0 : 1000)
2356
+ : qualities.identity;
2357
+ let candidates=[];
2358
+ if (gzipQuality > 0) candidates.push({contentEncoding:"gzip",ext:".gz",quality:gzipQuality});
2359
+ if (deflateQuality > 0) candidates.push({contentEncoding:"deflate",ext:".zl",quality:deflateQuality});
2360
+ if (candidates.length == 2 && candidates[1].quality > candidates[0].quality) candidates.reverse();
2361
+ return {candidates:candidates,identityQuality:identityQuality};
2362
+ }
2363
+ function nodeVersion () {
2364
+ var result="";
2365
+ var temp = process.versions.node.split('.');
2366
+ for (var i=0; i<temp.length; i++) result += temp[i];
2367
+ return result;
2368
+ }
2369
+ function display (fi) {
2370
+ if (mode !== "development") return;
2371
+ developmentLog("\nFile Info: " + reqCount++);
2372
+ var propValue;
2373
+ for(var propName in fi) {
2374
+ propValue = fi[propName];
2375
+ developmentLog(" " + propName,propValue);
2376
+ }
2377
+ }
2378
+ function Account (account,start,code,reason) {
2379
+ this.account = account;
2380
+ this.start = start;
2381
+ this.code = code;
2382
+ this.reason = reason;
2383
+ }
2384
+ // getAccount() is called only if JavaScript is to run on the server
2385
+ // It loads the JavaScript file and creates a new Account object to provide that information or error information.
2386
+ function getAccount (res,fileInfo) {
2387
+ let startPage = fileInfo.fullPath;
2388
+ let accountRoot = null; // handle to loaded JavaScript page.
2389
+ let accountInfo; // for the new Account object
2390
+ let code = 200; // default
2391
+ let reason; // reason for error
2392
+ let loadedMtime;
2393
+ // Redundant check. Was also checked in setFileInfo()
2394
+ if (!fs.existsSync(startPage)) {
2395
+ code = 404;
2396
+ reason = safeSourceIdentity(startPage) + " not found.";
2397
+ accountInfo = new Account(null,startPage,code,reason);
2398
+ return accountInfo;
2399
+ }
2400
+ try {
2401
+ // Load the page and get its handle.
2402
+ if (fileInfo.reload) {
2403
+ loadedMtime = fs.statSync(startPage).mtimeMs;
2404
+ delete require.cache[require.resolve(startPage)];
2405
+ }
2406
+ accountRoot = require(startPage);
2407
+ // Make sure that the required servlet(context) function exists in the loaded file.
2408
+ // This is how this system automatically runs code in the newly loaded file.
2409
+ if (typeof accountRoot.servlet !== 'function') {
2410
+ code = 500;
2411
+ reason = safeSourceIdentity(startPage) + " does not have a valid servlet() function.";
2412
+ delete require.cache[require.resolve(startPage)];
2413
+ } else if (fileInfo.reload) {
2414
+ moduleLoadTimes[startPage] = loadedMtime;
2415
+ }
2416
+ } catch (err) {
2417
+ code = 500;
2418
+ reason = "Failed to load module: " + rtErrorMsg(err);
2419
+ accountRoot = null;
2420
+ }
2421
+ accountInfo = new Account(accountRoot,startPage,code,reason);
2422
+ return accountInfo;
2423
+ }
2424
+
2425
+ async function importESMFile (fullPath) {
2426
+ let moduleUrl=pathToFileURL(path.resolve(fullPath)).href;
2427
+ let mtimeMs;
2428
+ try {
2429
+ if (mode !== "production") {
2430
+ mtimeMs=fs.statSync(fullPath).mtimeMs;
2431
+ moduleUrl += "?achieve-mtime=" + encodeURIComponent(mtimeMs);
2432
+ }
2433
+ return {
2434
+ loadedModule:await import(moduleUrl),
2435
+ mtimeMs
2436
+ };
2437
+ } catch (err) {
2438
+ if (err !== null && (typeof err === "object" || typeof err === "function")) {
2439
+ try {
2440
+ Object.defineProperty(err,esmLoadContext,{value:fullPath});
2441
+ } catch (contextError) {
2442
+ }
2443
+ }
2444
+ throw err;
2445
+ }
2446
+ }
2447
+
2448
+ async function getModuleAccount (fileInfo) {
2449
+ let startPage=fileInfo.fullPath;
2450
+ let code=200;
2451
+ let reason;
2452
+ let accountRoot=null;
2453
+ let loadedMtime;
2454
+
2455
+ if (!fs.existsSync(startPage)) {
2456
+ return new Account(
2457
+ null,
2458
+ startPage,
2459
+ 404,
2460
+ safeSourceIdentity(startPage) + " not found."
2461
+ );
2462
+ }
2463
+
2464
+ try {
2465
+ let importedModule=await importESMFile(startPage);
2466
+ loadedMtime=importedModule.mtimeMs;
2467
+ let moduleNamespace=importedModule.loadedModule;
2468
+ if (typeof moduleNamespace.servlet !== "function") {
2469
+ code=500;
2470
+ reason=safeSourceIdentity(startPage) + " does not have a valid servlet() function.";
2471
+ } else {
2472
+ accountRoot={servlet:moduleNamespace.servlet};
2473
+ moduleLoadTimes[startPage]=loadedMtime;
2474
+ }
2475
+ } catch (err) {
2476
+ code=500;
2477
+ reason="Failed to load module: " + rtErrorMsg(err);
2478
+ }
2479
+ return new Account(accountRoot,startPage,code,reason);
2480
+ }
2481
+
2482
+ // Invoke a loaded servlet with an already prepared parameter object.
2483
+ function invokeServlet(request,response,fileInfo,myApp,params,sendBody = true) {
2484
+ let context;
2485
+ let wmsg;
2486
+ let responseWrite=response.write;
2487
+ let responseEnd=response.end;
2488
+ let responseWriteHead=response.writeHead;
2489
+ let responseFlushHeaders=response.flushHeaders;
2490
+ function prepareResetContent() {
2491
+ if (!response.headersSent) {
2492
+ response.removeHeader("Transfer-Encoding");
2493
+ response.setHeader("Content-Length","0");
2494
+ }
2495
+ }
2496
+ function suppressResetContent(args) {
2497
+ let values=Array.from(args);
2498
+ if (values.length === 0 || values[0] === undefined || typeof values[0] === "function") {
2499
+ return values;
2500
+ }
2501
+ if (typeof values[0] === "string") {
2502
+ values[0]="";
2503
+ } else if (Buffer.isBuffer(values[0])) {
2504
+ values[0]=Buffer.alloc(0);
2505
+ } else if (ArrayBuffer.isView(values[0])) {
2506
+ values[0]=new Uint8Array(0);
2507
+ } else {
2508
+ return false;
2509
+ }
2510
+ return values;
2511
+ }
2512
+ response.write=function () {
2513
+ if (response.statusCode !== 205) return responseWrite.apply(response,arguments);
2514
+ let values=suppressResetContent(arguments);
2515
+ if (values === false) return responseWrite.apply(response,arguments);
2516
+ prepareResetContent();
2517
+ return responseWrite.apply(response,values);
2518
+ };
2519
+ response.end=function () {
2520
+ if (response.statusCode !== 205) return responseEnd.apply(response,arguments);
2521
+ let values=suppressResetContent(arguments);
2522
+ if (values === false) return responseEnd.apply(response,arguments);
2523
+ prepareResetContent();
2524
+ return responseEnd.apply(response,values);
2525
+ };
2526
+ response.writeHead=function (statusCode,statusMessage,headers) {
2527
+ if (statusCode !== 205) return responseWriteHead.apply(response,arguments);
2528
+ prepareResetContent();
2529
+ function resetHeaders(headerValues) {
2530
+ let values={};
2531
+ if (Array.isArray(headerValues)) {
2532
+ values=[];
2533
+ for (let index=0;index<headerValues.length;index+=2) {
2534
+ let name=String(headerValues[index]);
2535
+ if (!/^(content-length|transfer-encoding)$/i.test(name)) {
2536
+ values.push(name,headerValues[index+1]);
2537
+ }
2538
+ }
2539
+ values.push("Content-Length","0");
2540
+ return values;
2541
+ }
2542
+ if (headerValues) {
2543
+ for (let name of Object.keys(headerValues)) {
2544
+ if (!/^(content-length|transfer-encoding)$/i.test(name)) {
2545
+ values[name]=headerValues[name];
2546
+ }
2547
+ }
2548
+ }
2549
+ values["Content-Length"]="0";
2550
+ return values;
2551
+ }
2552
+ return typeof statusMessage === "string"
2553
+ ? responseWriteHead.call(response,statusCode,statusMessage,resetHeaders(headers))
2554
+ : responseWriteHead.call(response,statusCode,resetHeaders(statusMessage));
2555
+ };
2556
+ response.flushHeaders=function () {
2557
+ if (response.statusCode === 205) prepareResetContent();
2558
+ return responseFlushHeaders.apply(response,arguments);
2559
+ };
2560
+ function applicationOwned() {
2561
+ if (mode === "development") developmentLog("INFO: " + request.method + " " + fileInfo.path + " Session ended or will end by application.");
2562
+ }
2563
+ function complete(content) {
2564
+ if (!context.autoEnd || response.writableEnded || response.destroyed) {
2565
+ applicationOwned();
2566
+ return;
2567
+ }
2568
+ if (content === undefined || content === null) {
2569
+ if (mode === "development") developmentLog("INFO: Return from " + fileInfo.path.split(path.sep).join("/") + " is " + String(content) + ".");
2570
+ if (response.statusCode === 200) response.statusCode=204;
2571
+ response.end();
2572
+ return;
2573
+ }
2574
+ response.end(sendBody ? content : undefined);
2575
+ }
2576
+ function fail(err) {
2577
+ if (response.headersSent) {
2578
+ wmsg=rtErrorMsg(err);
2579
+ serverError(wmsg,err);
2580
+ if (!response.writableEnded && !response.destroyed) response.destroy();
2581
+ return;
2582
+ }
2583
+ if (response.writableEnded || response.destroyed) {
2584
+ applicationOwned();
2585
+ return;
2586
+ }
2587
+ wmsg=rtErrorMsg(err);
2588
+ response.statusCode=500;
2589
+ if (sendBody) response.write(wmsg);
2590
+ response.end();
2591
+ serverError(wmsg,err);
2592
+ }
2593
+ try {
2594
+ let loaderState={request:request,response:response,dirPath:fileInfo.dirPath};
2595
+ let boundLoader=load.bind(loaderState);
2596
+ context=new Context(request,response,params,fileInfo.dirPath,fileInfo.basePath,boundLoader);
2597
+ let content=myApp.servlet(context);
2598
+ if (!context.autoEnd) {
2599
+ applicationOwned();
2600
+ return;
2601
+ }
2602
+ if (content !== null &&
2603
+ (typeof content === "object" || typeof content === "function") &&
2604
+ typeof content.then === "function") {
2605
+ Promise.resolve(content).then(function (resolvedContent) {
2606
+ try {
2607
+ complete(resolvedContent);
2608
+ } catch (err) {
2609
+ fail(err);
2610
+ }
2611
+ },function (err) {
2612
+ fail(err);
2613
+ });
2614
+ return;
2615
+ }
2616
+ complete(content);
2617
+ } catch (err) {
2618
+ fail(err);
2619
+ }
2620
+ }
2621
+ // startObject parses parameters for Achieve-owned methods before invoking a servlet.
2622
+ function startObject (req,res,fileInfo,myApp,sendBody = true) {
2623
+ this.req=req;
2624
+ this.res=res;
2625
+ this.fileInfo=fileInfo;
2626
+ this.myApp=myApp;
2627
+ this.sendBody=sendBody;
2628
+ this.init=function () {
2629
+ let request=this.req;
2630
+ let response=this.res;
2631
+ let fileInfo=this.fileInfo;
2632
+ let myApp=this.myApp;
2633
+ let sendBody=this.sendBody;
2634
+ let queryChunks=[];
2635
+ response.setHeader('server',version);
2636
+ response.setHeader('Content-Type','text/plain');
2637
+ if (request.method == "POST") {
2638
+ if (mode === "development") developmentLog("using POST");
2639
+ let contentTypeHeader=request.headers["content-type"];
2640
+ let contentType=(contentTypeHeader || "").split(";")[0].trim().toLowerCase();
2641
+ if (contentTypeHeader === undefined) serverWarning("WARNING: POST request has no Content-Type; Achieve is treating the input as application/x-www-form-urlencoded.");
2642
+ if (contentType != "" && contentType != "application/json" && contentType != "application/x-www-form-urlencoded") {
2643
+ invokeServlet(request,response,fileInfo,myApp,{},sendBody);
2644
+ return;
2645
+ }
2646
+ let inputBytes=0;
2647
+ let inputFailed=false;
2648
+ function discardBufferedInput() {
2649
+ inputFailed=true;
2650
+ queryChunks.length=0;
2651
+ inputBytes=0;
2652
+ }
2653
+ request.on("aborted",discardBufferedInput);
2654
+ request.on("error",discardBufferedInput);
2655
+ request.on("data",function (data) {
2656
+ if (inputFailed) return;
2657
+ inputBytes += data.length;
2658
+ if (inputBytes > bufferedInputLimit) {
2659
+ discardBufferedInput();
2660
+ response.statusCode=413;
2661
+ response.end("Payload Too Large");
2662
+ return;
2663
+ }
2664
+ queryChunks.push(data);
2665
+ });
2666
+ request.on("end",function () {
2667
+ if (inputFailed || response.writableEnded) return;
2668
+ let queryData=Buffer.concat(queryChunks,inputBytes).toString("utf8");
2669
+ let params;
2670
+ if (contentType == "application/json") {
2671
+ try {
2672
+ params=JSON.parse(queryData);
2673
+ } catch (err) {
2674
+ response.statusCode=400;
2675
+ response.end("Bad Request: Invalid JSON data.");
2676
+ serverError("Invalid JSON data received.",err);
2677
+ return;
2678
+ }
2679
+ } else {
2680
+ params=querystring.parse(queryData);
2681
+ }
2682
+ invokeServlet(request,response,fileInfo,myApp,params,sendBody);
2683
+ });
2684
+ } else if (request.method == "GET" || request.method == "HEAD") {
2685
+ invokeServlet(request,response,fileInfo,myApp,querystring.parse(fileInfo.queryString),sendBody);
2686
+ } else {
2687
+ methodNotSupported(request,response);
2688
+ }
2689
+ };
2690
+ }
2691
+ // rtErrorMsg() extracts useful information from the error stack
2692
+ // when a runtime error occurs in the application code.
2693
+ // The message can be written to the server's console and it is also
2694
+ // returned so that it can be be sent to browser and displayed in its console.
2695
+ // (Display in browser console requires cooperating AJAX handling in the browser
2696
+ // when http response status code != 200; console.error(..responseText))
2697
+ function safeSourceIdentity (sourcePath) {
2698
+ var source = sourcePath;
2699
+ if (source.toLowerCase().indexOf("file:///") === 0) {
2700
+ source = source.substring(7);
2701
+ try {
2702
+ source = decodeURIComponent(source);
2703
+ } catch (decodeError) {
2704
+ }
2705
+ if (/^\/[A-Za-z]:\//.test(source)) source = source.substring(1);
2706
+ }
2707
+
2708
+ source = source.replace(/\\/g,"/");
2709
+ var location = "";
2710
+ var locationMatch = source.match(/(:\d+(?::\d+)?)$/);
2711
+ if (locationMatch) {
2712
+ location = locationMatch[1];
2713
+ source = source.substring(0,source.length-location.length);
2714
+ }
2715
+
2716
+ var approvedRoots = [basePath];
2717
+ for (var root of approvedRoots) {
2718
+ if (typeof root !== "string" || root.length === 0) continue;
2719
+ var normalizedRoot = root.replace(/\\/g,"/").replace(/\/$/,"");
2720
+ var compareSource = source;
2721
+ var compareRoot = normalizedRoot;
2722
+ if (/^[A-Za-z]:\//.test(source) || source.indexOf("//") === 0) {
2723
+ compareSource = source.toLowerCase();
2724
+ compareRoot = normalizedRoot.toLowerCase();
2725
+ }
2726
+ if (
2727
+ compareSource === compareRoot ||
2728
+ compareSource.indexOf(compareRoot + "/") === 0
2729
+ ) {
2730
+ var relativeSource = source.substring(normalizedRoot.length).replace(/^\/+/,"");
2731
+ if (
2732
+ relativeSource.length > 0 &&
2733
+ relativeSource.split("/").indexOf("..") === -1
2734
+ ) {
2735
+ return relativeSource + location;
2736
+ }
2737
+ }
2738
+ }
2739
+
2740
+ var pathParts = source.split("/");
2741
+ var basename = pathParts[pathParts.length-1];
2742
+ if (!basename || basename === "." || basename === "..") return "[path]";
2743
+ return basename + location;
2744
+ }
2745
+
2746
+ function replaceAbsoluteSourcePaths (message) {
2747
+ var result = message;
2748
+ result = result.replace(/file:\/\/\/[^'")\r\n]+/gi,function(sourcePath) {
2749
+ return safeSourceIdentity(sourcePath);
2750
+ });
2751
+ result = result.replace(/[A-Za-z]:[\\\/][^'")\r\n]+/g,function(sourcePath) {
2752
+ return safeSourceIdentity(sourcePath);
2753
+ });
2754
+ result = result.replace(/(?:\\\\|\/\/)[^'")\r\n]+/g,function(sourcePath) {
2755
+ return safeSourceIdentity(sourcePath);
2756
+ });
2757
+ result = result.replace(/(^|[\s'("=,:])(\/[^\/'")\r\n][^'")\r\n]*)/g,function(match,prefix,sourcePath) {
2758
+ return prefix + safeSourceIdentity(sourcePath);
2759
+ });
2760
+ return result;
2761
+ }
2762
+
2763
+ function sanitizeDeveloperErrorText (message) {
2764
+ var result = replaceAbsoluteSourcePaths(message);
2765
+ result = result.replace(/\b(?:node:)?internal\/[^\s)]+/g,"");
2766
+ result = result.replace(/\b(?:loader|vm):\d+:\d+\b/g,"");
2767
+ result = result.replace(/\bachieve\.js:\d+(?::\d+)?\b/gi,"");
2768
+ result = result.replace(/\s+imported from achieve\.js\b/gi,"");
2769
+ result = replaceAbsoluteSourcePaths(result);
2770
+ return result.trim();
2771
+ }
2772
+
2773
+ function runtimeErrorHeadline (err,message) {
2774
+ if (
2775
+ err !== null &&
2776
+ (typeof err === "object" || typeof err === "function") &&
2777
+ err.code === "ENOENT"
2778
+ ) {
2779
+ var missingPath = typeof err.path === "string" ? safeSourceIdentity(err.path) : "";
2780
+ return missingPath && missingPath !== "[path]"
2781
+ ? "File not found: " + missingPath
2782
+ : "File not found.";
2783
+ }
2784
+ return sanitizeDeveloperErrorText(message);
2785
+ }
2786
+
2787
+ function runtimeFunctionName (functionName) {
2788
+ var name = functionName.trim();
2789
+ if (name.indexOf("Object.") === 0) name = name.substring(7);
2790
+ if (!/^[A-Za-z_$][A-Za-z0-9_$]*$/.test(name)) return "";
2791
+ return name;
2792
+ }
2793
+
2794
+ function isInternalRuntimeSource (sourcePath) {
2795
+ var source = sourcePath.replace(/\\/g,"/").toLowerCase();
2796
+ return (
2797
+ source.indexOf("node:internal/") === 0 ||
2798
+ source.indexOf("internal/") === 0 ||
2799
+ source.indexOf("loader:") === 0 ||
2800
+ source.indexOf("vm:") === 0 ||
2801
+ source === "native" ||
2802
+ /(^|\/)achieve\.js:\d+:\d+$/.test(source)
2803
+ );
2804
+ }
2805
+
2806
+ function displayedRuntimeSource (sourcePath) {
2807
+ return sourcePath.replace(/\?achieve-mtime=[^:]*(:\d+:\d+)$/,"$1");
2808
+ }
2809
+
2810
+ function isApplicationRuntimeSource (sourcePath) {
2811
+ if (typeof basePath !== "string") return false;
2812
+ var source = displayedRuntimeSource(sourcePath);
2813
+ var location = source.match(/(:\d+(?::\d+)?)$/);
2814
+ if (!location) return false;
2815
+ source = source.substring(0,source.length-location[1].length);
2816
+ if (source.toLowerCase().indexOf("file:///") === 0) {
2817
+ source = source.substring(7);
2818
+ try {
2819
+ source = decodeURIComponent(source);
2820
+ } catch (decodeError) {
2821
+ }
2822
+ if (/^\/[A-Za-z]:\//.test(source)) source = source.substring(1);
2823
+ }
2824
+ source = source.replace(/\\/g,"/");
2825
+ if (source.toLowerCase().indexOf("/node_modules/") !== -1) return false;
2826
+
2827
+ var normalizedRoot = basePath.replace(/\\/g,"/").replace(/\/$/,"");
2828
+ var compareSource = source;
2829
+ var compareRoot = normalizedRoot;
2830
+ if (/^[A-Za-z]:\//.test(source) || source.indexOf("//") === 0) {
2831
+ compareSource = source.toLowerCase();
2832
+ compareRoot = normalizedRoot.toLowerCase();
2833
+ }
2834
+ return compareSource.indexOf(compareRoot + "/") === 0;
2835
+ }
2836
+
2837
+ function runtimeStackFrame (stackLine,applicationOnly = false) {
2838
+ var line = stackLine.trim();
2839
+ if (line.indexOf("at ") !== 0) return "";
2840
+
2841
+ var frame = line.substring(3).trim();
2842
+ var functionName = "";
2843
+ var sourcePath = frame;
2844
+ var frameMatch = frame.match(/^([^()]+) \(([^()]+)\)$/);
2845
+ if (frameMatch) {
2846
+ functionName = runtimeFunctionName(frameMatch[1]);
2847
+ sourcePath = frameMatch[2];
2848
+ }
2849
+
2850
+ if (!/[^\s]:\d+:\d+$/.test(sourcePath)) return "";
2851
+ if (isInternalRuntimeSource(sourcePath)) return "";
2852
+ if (applicationOnly && !isApplicationRuntimeSource(sourcePath)) return "";
2853
+
2854
+ var sourceIdentity = safeSourceIdentity(displayedRuntimeSource(sourcePath));
2855
+ if (sourceIdentity === "[path]") return "";
2856
+ return sourceIdentity;
2857
+ }
2858
+
2859
+ function syntaxStackReason (stack) {
2860
+ var stackLines = stack.split('\n');
2861
+ var sourcePath = stackLines[0].trim();
2862
+ if (!/:\d+(?::\d+)?$/.test(sourcePath)) return "";
2863
+
2864
+ var lowerSourcePath = sourcePath.toLowerCase();
2865
+ if (
2866
+ lowerSourcePath.indexOf("node:internal/") === 0 ||
2867
+ lowerSourcePath.indexOf("internal/") === 0 ||
2868
+ lowerSourcePath.indexOf("loader:") === 0 ||
2869
+ lowerSourcePath.indexOf("vm:") === 0 ||
2870
+ /(^|[\\/])achieve\.js:\d+(?::\d+)?$/.test(lowerSourcePath)
2871
+ ) return "";
2872
+
2873
+ var headline = "";
2874
+ for (var stackLine of stackLines) {
2875
+ var candidate = stackLine.trim();
2876
+ if (/^SyntaxError(?:\s*:|$)/.test(candidate)) {
2877
+ headline = sanitizeDeveloperErrorText(candidate);
2878
+ break;
2879
+ }
2880
+ }
2881
+ if (!headline) return "";
2882
+
2883
+ var sourceIdentity = safeSourceIdentity(sourcePath);
2884
+ if (sourceIdentity === "[path]") return headline;
2885
+ return headline + " " + sourceIdentity;
2886
+ }
2887
+
2888
+ function formatRuntimeErrorMessage (err,shortPath="",code=500) {
2889
+ var stack;
2890
+ if (err !== null && (typeof err === "object" || typeof err === "function")) {
2891
+ try {
2892
+ if (typeof err.stack === "string") stack = err.stack;
2893
+ } catch (stackError) {
2894
+ }
2895
+ }
2896
+
2897
+ if (stack !== undefined) {
2898
+ var normalizedStack = stack.replace(/\\/g,"/");
2899
+ var syntaxReason = syntaxStackReason(normalizedStack);
2900
+ if (syntaxReason) return syntaxReason;
2901
+
2902
+ var firstLineEnd = normalizedStack.indexOf('\n');
2903
+ if (firstLineEnd === -1) return runtimeErrorHeadline(err,normalizedStack);
2904
+
2905
+ var part1 = normalizedStack.substring(0,firstLineEnd);
2906
+ if (/^[A-Za-z_$][A-Za-z0-9_$]*Error:/.test(part1) || /^Error:/.test(part1)) {
2907
+ var headline = runtimeErrorHeadline(err,part1);
2908
+ var stackLines = normalizedStack.substring(firstLineEnd+1).split('\n');
2909
+ for (var stackLine of stackLines) {
2910
+ var applicationFrame = runtimeStackFrame(stackLine,true);
2911
+ if (applicationFrame) return headline + " " + applicationFrame;
2912
+ }
2913
+ for (var stackLine of stackLines) {
2914
+ var usefulFrame = runtimeStackFrame(stackLine);
2915
+ if (usefulFrame) return headline + " " + usefulFrame;
2916
+ }
2917
+ if (headline.length > 0) return headline;
2918
+ }
2919
+
2920
+ var part2 = normalizedStack.substring(part1.length);
2921
+ var closingParenthesis = part2.indexOf(')');
2922
+ if (closingParenthesis !== -1) {
2923
+ part2 = part2.substring(0,closingParenthesis);
2924
+ var openingParenthesis = part2.lastIndexOf('(');
2925
+ if (openingParenthesis !== -1) {
2926
+ var fallbackSource = part2.substring(openingParenthesis+1);
2927
+ part2 = isInternalRuntimeSource(fallbackSource)
2928
+ ? ""
2929
+ : safeSourceIdentity(fallbackSource);
2930
+ } else {
2931
+ var fallbackSource = part2.trim().replace(/^at\s+/,"");
2932
+ part2 = isInternalRuntimeSource(fallbackSource)
2933
+ ? ""
2934
+ : fallbackSource.substring(fallbackSource.lastIndexOf('/')+1);
2935
+ }
2936
+ } else {
2937
+ part2 = "";
2938
+ }
2939
+ var reason = sanitizeDeveloperErrorText((part1 + " " + part2).trim());
2940
+ if (reason.length > 0) return reason;
2941
+ }
2942
+
2943
+ if (err !== null && (typeof err === "object" || typeof err === "function")) {
2944
+ try {
2945
+ var errorName = typeof err.name === "string" ? err.name : "";
2946
+ var errorMessage = typeof err.message === "string" ? err.message : "";
2947
+ if (errorName && errorMessage) return runtimeErrorHeadline(err,errorName + ": " + errorMessage);
2948
+ if (errorName) return sanitizeDeveloperErrorText(errorName);
2949
+ if (errorMessage) return runtimeErrorHeadline(err,errorMessage);
2950
+ } catch (errorPropertyError) {
2951
+ }
2952
+ }
2953
+
2954
+ if (err === null) return "Thrown value: null";
2955
+ if (err === undefined) return "Thrown value: undefined";
2956
+ if (typeof err === "object") return "Thrown value: [object Object]";
2957
+ if (typeof err === "function") return "Thrown value: [function]";
2958
+ try {
2959
+ return sanitizeDeveloperErrorText("Thrown value: " + String(err));
2960
+ } catch (stringError) {
2961
+ return "Thrown value: [unprintable]";
2962
+ }
2963
+ }
2964
+ function runtimeErrorHasApplicationSource (err) {
2965
+ if (err === null || (typeof err !== "object" && typeof err !== "function")) return false;
2966
+ try {
2967
+ if (typeof err.stack !== "string") return false;
2968
+ var stackLines = err.stack.replace(/\\/g,"/").split('\n');
2969
+ if (stackLines.length > 0 && isApplicationRuntimeSource(stackLines[0].trim())) return true;
2970
+ for (var stackLine of stackLines) {
2971
+ if (runtimeStackFrame(stackLine,true)) return true;
2972
+ }
2973
+ } catch (stackError) {
2974
+ }
2975
+ return false;
2976
+ }
2977
+ function rtErrorMsg (err,shortPath="",code=500) {
2978
+ var reason = formatRuntimeErrorMessage(err,shortPath,code);
2979
+ if (
2980
+ err !== null &&
2981
+ (typeof err === "object" || typeof err === "function") &&
2982
+ err[esmLoadContext] &&
2983
+ !runtimeErrorHasApplicationSource(err)
2984
+ ) {
2985
+ var loadContext = safeSourceIdentity(err[esmLoadContext]);
2986
+ if (loadContext !== "[path]") reason += " (while loading " + loadContext + ")";
2987
+ }
2988
+ return reason;
2989
+ }
2990
+ // 537().init() sets up event driven streaming file serves
2991
+ // The final event also deletes the loaded file reference from the Node.js cache
2992
+ function ServeFile (req,res,fileInfo,sendBody = true) {
2993
+ this.res = res;
2994
+ this.req = req;
2995
+ this.fp = path.join(fileInfo.basePath,fileInfo.path);
2996
+ this.contentType = fileInfo.contentType;
2997
+ this.sendBody = sendBody;
2998
+ this.init = function () {
2999
+ let response = this.res;
3000
+ let filePath = this.fp;
3001
+ let request = this.req;
3002
+ let sendBody = this.sendBody;
3003
+
3004
+ let ext="";
3005
+
3006
+ res.setHeader('content-type', fileInfo.contentType);
3007
+ res.setHeader('server', version);
3008
+ if (fileInfo.etag) res.setHeader('etag', fileInfo.etag);
3009
+ res.statusCode = 200;
3010
+ res.setHeader('Content-Length', fileInfo.stats.size);
3011
+ if (!sendBody || fileInfo.stats.size === 0) {
3012
+ closeFileInfoDescriptor(fileInfo);
3013
+ response.end();
3014
+ return;
3015
+ }
3016
+
3017
+ let readStream;
3018
+ function streamError (err) {
3019
+ serverError(err.message,err);
3020
+ if (response.destroyed || response.writableEnded) {
3021
+ return;
3022
+ }
3023
+ if (!response.headersSent) {
3024
+ response.removeHeader('Content-Length');
3025
+ response.removeHeader('Last-Modified');
3026
+ response.setHeader('content-type', 'text/plain;charset=utf-8');
3027
+ response.statusCode = 500;
3028
+ response.end("Error attempting to serve " + safeSourceIdentity(filePath));
3029
+ } else {
3030
+ response.destroy();
3031
+ }
3032
+ }
3033
+
3034
+ try {
3035
+ readStream = fs.createReadStream(filePath,{
3036
+ fd:fileInfo.fileDescriptor,
3037
+ autoClose:true,
3038
+ start:0,
3039
+ end:fileInfo.stats.size - 1
3040
+ });
3041
+ fileInfo.fileDescriptor=undefined;
3042
+ } catch (err) {
3043
+ closeFileInfoDescriptor(fileInfo);
3044
+ streamError(err);
3045
+ return;
3046
+ }
3047
+
3048
+ readStream.on('error',streamError);
3049
+ if (response.destroyed || response.writableEnded) {
3050
+ readStream.destroy();
3051
+ return;
3052
+ }
3053
+ readStream.pipe(response);
3054
+ response.on('close',function () {
3055
+ if (!response.writableEnded) {
3056
+ readStream.destroy();
3057
+ }
3058
+ });
3059
+ };
3060
+ }
3061
+ // Not implemented - input object to be sent to JavaScript application
3062
+ function input (request,fs,queryPath,queryData,parameters) {
3063
+ this.request = request;
3064
+ this.parameters = parameters;
3065
+ this.queryData = queryData;
3066
+ this.fs = fs;
3067
+ this.queryPath = queryPath;
3068
+ this.datetime = dt;
3069
+ }
3070
+ // Not implemented - output object to be sent to JavaScript application
3071
+ function output (response,ext,charset,mimeType) {
3072
+ this.response = response;
3073
+ this.ext = ext;
3074
+ this.charset = charset;
3075
+ this.mimeType = mimeType;
3076
+ }
3077
+ // To provide servlet characteristics to locally installed node modules
3078
+ // including achieve itself
3079
+ exports.loadModule = function (moduleName) {
3080
+ try {
3081
+ let fullPath = applicationRequire.resolve(moduleName);
3082
+ const stats = fs.statSync(fullPath);
3083
+ if (moduleLoadTimes[fullPath] === undefined || moduleLoadTimes[fullPath] < stats.mtimeMs) {
3084
+ delete require.cache[fullPath];
3085
+ moduleLoadTimes[fullPath] = stats.mtimeMs;
3086
+ }
3087
+ return applicationRequire(moduleName);
3088
+ } catch (err) {
3089
+ serverError("loadModule: " + rtErrorMsg(err),err);
3090
+ }
3091
+ };
3092
+ function loadCommonJSModule (filePath) {
3093
+ let dirname=this.dirPath;
3094
+ let fullPath = path.join(dirname,filePath);
3095
+ if (mode === "production" && productionHelperCache.has(fullPath)) {
3096
+ return productionHelperCache.get(fullPath);
3097
+ }
3098
+ let loadedMtime;
3099
+ if (mode !== "production") {
3100
+ const stats = fs.statSync(fullPath);
3101
+ if (moduleLoadTimes[fullPath] === undefined || moduleLoadTimes[fullPath] < stats.mtimeMs) {
3102
+ loadedMtime = stats.mtimeMs;
3103
+ delete require.cache[require.resolve(fullPath)];
3104
+ }
3105
+ }
3106
+ let loadedModule = require(fullPath);
3107
+ if (mode === "production") productionHelperCache.set(fullPath,loadedModule);
3108
+ if (loadedMtime !== undefined) moduleLoadTimes[fullPath] = loadedMtime;
3109
+ return loadedModule;
3110
+ }
3111
+ let load = function (filePath) {
3112
+ if (typeof filePath !== "string" || filePath.length === 0) {
3113
+ throw new TypeError("load() requires a nonempty module filename.");
3114
+ }
3115
+ let moduleType=servletModuleType(filePath);
3116
+ if (moduleType === "commonjs" || filePath.toLowerCase().endsWith(".js")) {
3117
+ return loadCommonJSModule.call(this,filePath);
3118
+ }
3119
+ if (moduleType === "module") return loadESMModule.call(this,filePath);
3120
+ if (path.extname(filePath) === "") return loadCommonJSModule.call(this,filePath+".js");
3121
+ throw new TypeError("load() supports extensionless legacy names, .js, .jss, .jss.cjs, and .jss.mjs module filenames.");
3122
+ }
3123
+ let loadESMModule = function (filePath) {
3124
+ let fullPath=path.join(this.dirPath,filePath);
3125
+ if (mode === "production" && productionHelperCache.has(fullPath)) {
3126
+ return productionHelperCache.get(fullPath);
3127
+ }
3128
+ let loading=importESMFile(fullPath).then(
3129
+ function (importedModule) {
3130
+ moduleLoadTimes[fullPath]=importedModule.mtimeMs;
3131
+ return importedModule.loadedModule;
3132
+ },
3133
+ function (err) {
3134
+ productionHelperCache.delete(fullPath);
3135
+ throw err;
3136
+ }
3137
+ );
3138
+ if (mode === "production") productionHelperCache.set(fullPath,loading);
3139
+ return loading;
3140
+ }
3141
+ const Base64 = {
3142
+ _Rixits:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz+/",
3143
+ fromNumber : function(residual) {
3144
+ var rixit; // like 'digit', only in some non-decimal radix
3145
+ var result = '';
3146
+ while (true) {
3147
+ rixit = residual % 64;
3148
+ result = this._Rixits.charAt(rixit) + result;
3149
+ residual = Math.floor(residual / 64);
3150
+
3151
+ if (residual == 0) break;
3152
+ }
3153
+ return result;
3154
+ }
3155
+ }
3156
+ const maximumByteRanges = 16;
3157
+ function parseByteRange(rangeHeader, fileSize) {
3158
+ if (rangeHeader === undefined) {
3159
+ return { classification: "full" };
3160
+ }
3161
+
3162
+ var range = rangeHeader.trim();
3163
+ var separator = range.indexOf("=");
3164
+ if (separator === -1) {
3165
+ return { classification: "malformed" };
3166
+ }
3167
+
3168
+ var unit = range.substring(0, separator);
3169
+ if (unit.toLowerCase() !== "bytes") {
3170
+ return { classification: "unknown-unit" };
3171
+ }
3172
+
3173
+ var rangeValues = range.substring(separator + 1).split(",");
3174
+ if (rangeValues.length > maximumByteRanges) {
3175
+ return { classification: "excessive" };
3176
+ }
3177
+
3178
+ var selectedRange;
3179
+ var rangeCount = 0;
3180
+ for (var rangeIndex = 0; rangeIndex < rangeValues.length; rangeIndex++) {
3181
+ var rangeValue = rangeValues[rangeIndex].trim();
3182
+ if (!rangeValue) continue;
3183
+ rangeCount++;
3184
+
3185
+ var match = /^(\d*)-(\d*)$/.exec(rangeValue);
3186
+ if (!match || (!match[1] && !match[2])) {
3187
+ return { classification: "malformed" };
3188
+ }
3189
+
3190
+ if (!match[1]) {
3191
+ var suffixLength = Number(match[2]);
3192
+ if (!Number.isSafeInteger(suffixLength)) {
3193
+ return { classification: "malformed" };
3194
+ }
3195
+ if (suffixLength === 0 || fileSize === 0) continue;
3196
+
3197
+ if (!selectedRange) {
3198
+ var suffixStart = Math.max(fileSize - suffixLength, 0);
3199
+ selectedRange = {
3200
+ classification: "partial",
3201
+ start: suffixStart,
3202
+ end: fileSize - 1,
3203
+ contentLength: fileSize - suffixStart
3204
+ };
3205
+ }
3206
+ continue;
3207
+ }
3208
+
3209
+ var start = Number(match[1]);
3210
+ if (!Number.isSafeInteger(start)) {
3211
+ return { classification: "malformed" };
3212
+ }
3213
+
3214
+ var end = fileSize - 1;
3215
+ if (match[2]) {
3216
+ end = Number(match[2]);
3217
+ if (!Number.isSafeInteger(end) || end < start) {
3218
+ return { classification: "malformed" };
3219
+ }
3220
+ }
3221
+ if (start >= fileSize) continue;
3222
+
3223
+ if (!selectedRange) {
3224
+ end = Math.min(end, fileSize - 1);
3225
+ selectedRange = {
3226
+ classification: "partial",
3227
+ start: start,
3228
+ end: end,
3229
+ contentLength: (end - start) + 1
3230
+ };
3231
+ }
3232
+ }
3233
+
3234
+ if (rangeCount === 0) return { classification: "malformed" };
3235
+ return selectedRange || { classification: "unsatisfiable" };
3236
+ }
3237
+ let stream = function(req, res, fileInfo, sendBody = true) {
3238
+ var fileName = fileInfo.fullPath;
3239
+ var displayedFileName = fileName ? safeSourceIdentity(fileName) : fileName;
3240
+ if(!fileName) {
3241
+ closeFileInfoDescriptor(fileInfo);
3242
+ reportError(res, fileName, 404, "File not found: " + displayedFileName, sendBody);
3243
+ return;
3244
+ }
3245
+
3246
+ var stats=fileInfo.stats;
3247
+ var mediaETag="";
3248
+ var evaluateIfRange = (
3249
+ req.method === "GET" &&
3250
+ req.headers.range !== undefined &&
3251
+ req.headers['if-range'] !== undefined
3252
+ );
3253
+ if (
3254
+ bCaching ||
3255
+ hasEntityTagPrecondition(req) ||
3256
+ evaluateIfRange
3257
+ ) {
3258
+ mediaETag=representationETag(stats,"i");
3259
+ res.setHeader("ETag",mediaETag);
3260
+ }
3261
+ var modified=staticModificationTime(res,stats);
3262
+ if (evaluatePreconditions(req,res,true,mediaETag,modified)) {
3263
+ closeFileInfoDescriptor(fileInfo);
3264
+ return;
3265
+ }
3266
+
3267
+ if (!sendBody) {
3268
+ setLastModified(res,modified);
3269
+ closeFileInfoDescriptor(fileInfo);
3270
+ res.writeHead(200, {
3271
+ "Accept-Ranges": "bytes",
3272
+ "Content-Length": stats.size,
3273
+ "Content-Type": fileInfo.contentType,
3274
+ "Server": version
3275
+ });
3276
+ res.end();
3277
+ return;
3278
+ }
3279
+
3280
+ var rangeHeader = req.method === "GET" ? req.headers.range : undefined;
3281
+ if (
3282
+ evaluateIfRange &&
3283
+ !entityTagFieldMatches(req.headers['if-range'],mediaETag,false)
3284
+ ) {
3285
+ rangeHeader=undefined;
3286
+ }
3287
+ var rangeInfo = parseByteRange(rangeHeader, stats.size);
3288
+ if (
3289
+ rangeInfo.classification === "malformed" ||
3290
+ rangeInfo.classification === "excessive"
3291
+ ) {
3292
+ var message = rangeInfo.classification === "excessive"
3293
+ ? "Too many byte ranges requested."
3294
+ : "Malformed byte Range request.";
3295
+ closeFileInfoDescriptor(fileInfo);
3296
+ res.writeHead(400, {
3297
+ "Content-Type": "text/plain;charset=utf-8",
3298
+ "Content-Length": Buffer.byteLength(message, "utf8")
3299
+ });
3300
+ res.end(message);
3301
+ return;
3302
+ }
3303
+ if (rangeInfo.classification === "unsatisfiable") {
3304
+ var rangeErrorMessage = "Requested byte range is not satisfiable.";
3305
+ closeFileInfoDescriptor(fileInfo);
3306
+ res.writeHead(416, {
3307
+ "Accept-Ranges": "bytes",
3308
+ "Content-Range": "bytes */" + stats.size,
3309
+ "Content-Type": "text/plain;charset=utf-8",
3310
+ "Content-Length": Buffer.byteLength(rangeErrorMessage, "utf8")
3311
+ });
3312
+ res.end(rangeErrorMessage);
3313
+ return;
3314
+ }
3315
+
3316
+ var start;
3317
+ var end;
3318
+ var total = 0;
3319
+ var contentRange = false;
3320
+ var contentLength = 0;
3321
+
3322
+ if (rangeInfo.classification === "partial")
3323
+ {
3324
+ start = rangeInfo.start;
3325
+ total = stats.size;
3326
+ end = rangeInfo.end;
3327
+ contentRange = true;
3328
+ contentLength = rangeInfo.contentLength;
3329
+ }
3330
+ else
3331
+ {
3332
+ contentLength = stats.size;
3333
+ }
3334
+
3335
+ var responseCode = 200;
3336
+ var responseHeader =
3337
+ {
3338
+ "Accept-Ranges": "bytes",
3339
+ "Content-Length": contentLength,
3340
+ "Content-Type": fileInfo.contentType,
3341
+ "Server": version
3342
+ };
3343
+ if(contentRange)
3344
+ {
3345
+ responseCode = 206;
3346
+ responseHeader["Content-Range"] = "bytes " + start + "-" + end + "/" + total;
3347
+ }
3348
+ var successfulIfRange = evaluateIfRange && contentRange;
3349
+ if (successfulIfRange) delete responseHeader["Content-Type"];
3350
+ if (!contentRange && stats.size === 0) {
3351
+ setLastModified(res,modified);
3352
+ closeFileInfoDescriptor(fileInfo);
3353
+ res.writeHead(responseCode, responseHeader);
3354
+ res.end();
3355
+ return;
3356
+ }
3357
+
3358
+ var readStream;
3359
+ try {
3360
+ if (contentRange) {
3361
+ readStream = fs.createReadStream(fileName, {
3362
+ fd:fileInfo.fileDescriptor,
3363
+ autoClose:true,
3364
+ start:start,
3365
+ end:end
3366
+ });
3367
+ } else {
3368
+ readStream = fs.createReadStream(fileName, {
3369
+ fd:fileInfo.fileDescriptor,
3370
+ autoClose:true,
3371
+ start:0
3372
+ });
3373
+ }
3374
+ fileInfo.fileDescriptor=undefined;
3375
+ } catch (err) {
3376
+ closeFileInfoDescriptor(fileInfo);
3377
+ var statusCode = err.code === "ENOENT" ? 404 : 500;
3378
+ var reason = statusCode === 404
3379
+ ? "File not found: " + displayedFileName
3380
+ : "Error attempting to stream " + displayedFileName + ": " + rtErrorMsg(err);
3381
+ reportError(res, fileName, statusCode, reason, sendBody);
3382
+ return;
3383
+ }
3384
+
3385
+ readStream.on("error", function(err) {
3386
+ if (res.destroyed) {
3387
+ return;
3388
+ }
3389
+ if (!res.headersSent) {
3390
+ var statusCode = err.code === "ENOENT" ? 404 : 500;
3391
+ var reason = statusCode === 404
3392
+ ? "File not found: " + displayedFileName
3393
+ : "Error attempting to stream " + displayedFileName + ": " + rtErrorMsg(err);
3394
+ reportError(res, fileName, statusCode, reason, sendBody);
3395
+ } else {
3396
+ serverError("Error streaming " + displayedFileName + ": " + rtErrorMsg(err),err);
3397
+ res.destroy();
3398
+ }
3399
+ });
3400
+ if (res.destroyed) {
3401
+ readStream.destroy();
3402
+ return;
3403
+ }
3404
+ if (!successfulIfRange) setLastModified(res,modified);
3405
+ res.writeHead(responseCode, responseHeader);
3406
+ readStream.pipe(res);
3407
+ res.on("close", function() {
3408
+ if (!res.writableEnded) {
3409
+ readStream.destroy();
3410
+ }
3411
+ });
3412
+ };