1 | (function (factory) {
|
2 | if (typeof module === "object" && typeof module.exports === "object") {
|
3 | var v = factory(require, exports);
|
4 | if (v !== undefined) module.exports = v;
|
5 | }
|
6 | else if (typeof define === "function" && define.amd) {
|
7 | define(["require", "exports", "tslib", "fs", "http-errors", "mime-types", "path"], factory);
|
8 | }
|
9 | })(function (require, exports) {
|
10 | "use strict";
|
11 | Object.defineProperty(exports, "__esModule", { value: true });
|
12 | var tslib_1 = require("tslib");
|
13 | var fs_1 = require("fs");
|
14 | var http_errors_1 = tslib_1.__importDefault(require("http-errors"));
|
15 | var mime_types_1 = require("mime-types");
|
16 | var path_1 = require("path");
|
17 | function instrument(context) {
|
18 | var codeCache = Object.create(null);
|
19 | return function (request, response, next) {
|
20 | var basePath = context.basePath, executor = context.executor;
|
21 | var wholePath = path_1.resolve(path_1.join(basePath, request.url));
|
22 | if (!(request.method === 'HEAD' || request.method === 'GET') ||
|
23 | !executor.shouldInstrumentFile(wholePath)) {
|
24 | return next();
|
25 | }
|
26 | fs_1.stat(wholePath, function (error, stats) {
|
27 | if (context.stopped) {
|
28 | return;
|
29 | }
|
30 | if (error || !stats.isFile()) {
|
31 | executor.log('Unable to serve', wholePath, '(unreadable)');
|
32 | return next(http_errors_1.default(404, error, { expose: false }));
|
33 | }
|
34 | executor.log('Serving', wholePath);
|
35 | var send = function (contentType, data) {
|
36 | response.writeHead(200, {
|
37 | 'Content-Type': contentType,
|
38 | 'Content-Length': Buffer.byteLength(data),
|
39 | });
|
40 | response.end(request.method === 'HEAD' ? '' : data, callback);
|
41 | };
|
42 | var callback = function (error) {
|
43 | if (error) {
|
44 | executor.emit('error', new Error("Error serving " + wholePath + ": " + error.message));
|
45 | }
|
46 | else {
|
47 | executor.log('Served', wholePath);
|
48 | }
|
49 | };
|
50 | var contentType = mime_types_1.lookup(wholePath) || 'application/octet-stream';
|
51 | var mtime = stats.mtime.getTime();
|
52 | if (codeCache[wholePath] && codeCache[wholePath].mtime === mtime) {
|
53 | send(contentType, codeCache[wholePath].data);
|
54 | }
|
55 | else {
|
56 | fs_1.readFile(wholePath, 'utf8', function (error, data) {
|
57 | if (context.stopped) {
|
58 | return;
|
59 | }
|
60 | if (error) {
|
61 | return next(http_errors_1.default(404, error, { expose: false }));
|
62 | }
|
63 | data = executor.instrumentCode(data, wholePath);
|
64 | codeCache[wholePath] = {
|
65 | mtime: mtime,
|
66 | data: data,
|
67 | };
|
68 | send(contentType, data);
|
69 | });
|
70 | }
|
71 | });
|
72 | };
|
73 | }
|
74 | exports.default = instrument;
|
75 | });
|
76 |
|
\ | No newline at end of file |