UNPKG

edgerender

Version:
81 lines 2.88 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.Redirect = exports.HttpError = exports.json_response = exports.default_security_headers = exports.MimeTypes = void 0; var MimeTypes; (function (MimeTypes) { MimeTypes["html"] = "text/html"; MimeTypes["plaintext"] = "text/plain"; MimeTypes["json"] = "application/json"; MimeTypes["ico"] = "image/vnd.microsoft.icon"; MimeTypes["octetStream"] = "application/octet-stream"; })(MimeTypes = exports.MimeTypes || (exports.MimeTypes = {})); exports.default_security_headers = { 'X-Frame-Options': 'DENY', 'Strict-Transport-Security': 'max-age=31536000; includeSubDomains; preload', 'X-XSS-Protection': '1; mode=block', 'X-Content-Type-Options': 'nosniff', 'Referrer-Policy': 'origin', }; function json_response(obj, status = 200) { return { status, body: JSON.stringify(obj, null, 2), mime_type: MimeTypes.json, }; } exports.json_response = json_response; class HttpError extends Error { status; body; headers; constructor(status, body, headers = undefined) { if (headers) { super(`HTTP Error ${status}: ${body}, headers=${JSON.stringify(headers)}`); } else { super(`HTTP Error ${status}: ${body}`); } this.status = status; this.body = body; this.headers = headers || {}; } response(request) { if (this.status > 300 && this.status < 400) { const { location } = this.headers; if (location && !/^https?:\/\//.test(location)) { const { origin, pathname } = new URL(request.url); let path; if (location.startsWith('/')) { path = location; } else if (location.startsWith('.')) { // special case where double slashes are common if (pathname.endsWith('/') && location.startsWith('./')) { path = `${pathname}${location.slice(2)}`; } else { path = `${pathname}${location.slice(1)}`; } } else { path = `${pathname}${location}`; } this.headers.location = `${origin}${path}`; } } return { body: `${this.status}: ${this.body}`, mime_type: MimeTypes.plaintext, status: this.status, headers: this.headers, }; } } exports.HttpError = HttpError; class Redirect extends HttpError { constructor(location, status = 307, body = null) { super(status, body || `Redirecting to "${location}"`, { location }); } } exports.Redirect = Redirect; //# sourceMappingURL=response.js.map