Socket
Socket
Sign inDemoInstall

@tinyhttp/app

Package Overview
Dependencies
Maintainers
0
Versions
305
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

@tinyhttp/app - npm Package Compare versions

Comparing version 2.2.3 to 2.2.4

15

dist/app.d.ts

@@ -1,10 +0,9 @@

/// <reference types="node" />
import { Server } from 'node:http';
import type { Request } from './request.js';
import type { Response } from './response.js';
import type { ErrorHandler } from './onError.js';
import type { Middleware, Handler, NextFunction, UseMethodParams } from '@tinyhttp/router';
import { Router } from '@tinyhttp/router';
import { Handler, Middleware, NextFunction, UseMethodParams, Router } from '@tinyhttp/router';
import { TemplateEngineOptions } from './index.js';
import { ErrorHandler } from './onError.js';
import { Request } from './request.js';
import { Response } from './response.js';
import { AppConstructor, AppRenderOptions, AppSettings, TemplateEngine } from './types.js';
import { TemplateEngineOptions } from './index.js';
/**

@@ -89,3 +88,3 @@ * `App` class - the starting point of tinyhttp app.

*/
render<RenderOptions extends TemplateEngineOptions = TemplateEngineOptions>(name: string, data: Record<string, unknown>, options: AppRenderOptions<RenderOptions>, cb: (err: unknown, html?: unknown) => void): void;
render<RenderOptions extends TemplateEngineOptions = TemplateEngineOptions>(name: string, data?: Record<string, unknown>, options?: AppRenderOptions<RenderOptions>, cb?: (err: unknown, html?: unknown) => void): void;
use(...args: UseMethodParams<Req, Res, App>): this;

@@ -92,0 +91,0 @@ route(path: string): App;

@@ -0,6 +1,7 @@

import { NextFunction } from '@tinyhttp/router';
import { App } from './app.js';
import { Request } from './request.js';
import type { NextFunction } from '@tinyhttp/router';
import type { Response } from './response.js';
import { App } from './app.js';
import { Response } from './response.js';
import { TemplateEngineOptions } from './types.js';
/**

@@ -7,0 +8,0 @@ * Extends Request and Response objects with custom properties and methods

@@ -0,1 +1,4 @@

import { Middleware, NextFunction, AsyncHandler as RAsyncHandler, Handler as RHandler, SyncHandler as RSyncHandler } from '@tinyhttp/router';
import { Request } from './request.js';
import { Response } from './response.js';
export { App } from './app.js';

@@ -8,5 +11,2 @@ export * from './request.js';

export type { AppSettings, TemplateEngineOptions, TemplateEngine, AppConstructor } from './types.js';
import type { Request } from './request.js';
import type { Response } from './response.js';
import type { NextFunction, Handler as RHandler, AsyncHandler as RAsyncHandler, SyncHandler as RSyncHandler, Middleware } from '@tinyhttp/router';
export type Handler = RHandler<Request, Response>;

@@ -13,0 +13,0 @@ export type AsyncHandler = RAsyncHandler<Request, Response>;

import { STATUS_CODES, createServer } from "node:http";
import { proxyaddr, all, compile } from "@tinyhttp/proxy-addr";
import { isIP } from "node:net";
import { getRequestHeader, getQueryParams, getRangeFromHeader, getAccepts, getAcceptsCharsets, getAcceptsEncodings, getAcceptsLanguages, checkIfXMLHttpRequest, getFreshOrStale, getPathname, getURLParams } from "@tinyhttp/req";
import { getURLParams as getURLParams2 } from "@tinyhttp/req";
import { Router, pushMiddleware } from "@tinyhttp/router";
import { parse } from "regexparam";
import { getResponseHeader, setHeader, send, json, status, sendStatus, sendFile, setContentType, setLocationHeader, setLinksHeader, setVaryHeader, setCookie, clearCookie, formatResponse, redirect, attachment, download, append } from "@tinyhttp/res";
import { parse } from "regexparam";
import { proxyaddr, all, compile } from "@tinyhttp/proxy-addr";
import { isIP } from "node:net";
import { statSync } from "node:fs";
import { extname, resolve, dirname, basename, join } from "node:path";
import { statSync } from "node:fs";
const trustRemoteAddress = ({ socket }) => {
const val = socket.remoteAddress;
if (typeof val === "string")
return compile(val.split(",").map((x) => x.trim()));
if (typeof val === "string") return compile(val.split(",").map((x) => x.trim()));
return compile(val || []);

@@ -19,4 +18,3 @@ };

const proto = `http${req.secure ? "s" : ""}`;
if (!trustRemoteAddress(req))
return proto;
if (!trustRemoteAddress(req)) return proto;
const header = req.headers["X-Forwarded-Proto"] || proto;

@@ -28,6 +26,4 @@ const index = header.indexOf(",");

let host = req.get("X-Forwarded-Host");
if (!host || !trustRemoteAddress(req))
host = req.get("Host");
if (!host)
return;
if (!host || !trustRemoteAddress(req)) host = req.get("Host");
if (!host) return;
const index = host.indexOf(":", host[0] === "[" ? host.indexOf("]") + 1 : 0);

@@ -40,24 +36,9 @@ return index !== -1 ? host.substring(0, index) : host;

const hostname = getHostname(req);
if (!hostname)
return [];
if (!hostname) return [];
const subdomains = isIP(hostname) ? [hostname] : hostname.split(".").reverse();
return subdomains.slice(subdomainOffset);
};
const onErrorHandler = function(err, _req, res) {
if (this.onError === onErrorHandler && this.parent)
return this.parent.onError(err, _req, res);
if (err instanceof Error)
console.error(err);
const code = err.code in STATUS_CODES ? err.code : err.status;
if (typeof err === "string" || Buffer.isBuffer(err))
res.writeHead(500).end(err);
else if (code in STATUS_CODES)
res.writeHead(code).end(STATUS_CODES[code]);
else
res.writeHead(500).end(err.message);
};
const renderTemplate = (_req, res, app) => (file, data, options) => {
app.render(file, data ? { ...res.locals, ...data } : res.locals, options, (err, html) => {
if (err)
throw err;
if (err) throw err;
res.send(html);

@@ -113,2 +94,10 @@ });

};
const onErrorHandler = function(err, _req, res) {
if (this.onError === onErrorHandler && this.parent) return this.parent.onError(err, _req, res);
if (err instanceof Error) console.error(err);
const code = err.code in STATUS_CODES ? err.code : err.status;
if (typeof err === "string" || Buffer.isBuffer(err)) res.writeHead(500).end(err);
else if (code in STATUS_CODES) res.writeHead(code).end(STATUS_CODES[code]);
else res.writeHead(500).end(err.message);
};
function tryStat(path) {

@@ -131,7 +120,6 @@ try {

if (!this.ext) {
this.ext = this.defaultEngine[0] !== "." ? "." + this.defaultEngine : this.defaultEngine;
this.ext = this.defaultEngine[0] !== "." ? `.${this.defaultEngine}` : this.defaultEngine;
fileName += this.ext;
}
if (!opts.engines[this.ext])
throw new Error(`No engine was found for ${this.ext}`);
if (!opts.engines[this.ext]) throw new Error(`No engine was found for ${this.ext}`);
this.engine = opts.engines[this.ext];

@@ -156,8 +144,8 @@ this.path = this.#lookup(fileName);

let stat = tryStat(path);
if (stat && stat.isFile()) {
if (stat == null ? void 0 : stat.isFile()) {
return path;
}
path = join(dir, basename(file, ext), "index" + ext);
path = join(dir, basename(file, ext), `index${ext}`);
stat = tryStat(path);
if (stat && stat.isFile()) {
if (stat == null ? void 0 : stat.isFile()) {
return path;

@@ -170,3 +158,3 @@ }

}
const lead = (x) => x.charCodeAt(0) === 47 ? x : "/" + x;
const lead = (x) => x.charCodeAt(0) === 47 ? x : `/${x}`;
const mount = (fn) => fn instanceof App ? fn.attach : fn;

@@ -177,4 +165,3 @@ const applyHandler = (h) => async (req, res, next) => {

await h(req, res, next);
} else
h(req, res, next);
} else h(req, res, next);
} catch (e) {

@@ -264,11 +251,10 @@ next(e);

*/
render(name, data = {}, options = {}, cb) {
render(name, data = {}, options = {}, cb = () => {
}) {
let view;
const { _locals, ...opts } = options;
let locals = this.locals;
if (_locals)
locals = { ...locals, ..._locals };
if (_locals) locals = { ...locals, ..._locals };
locals = { ...locals, ...data };
if (opts.cache == null)
opts.cache = this.enabled("view cache");
if (opts.cache == null) opts.cache = this.enabled("view cache");
if (opts.cache) {

@@ -278,3 +264,3 @@ view = this.cache[name];

if (!view) {
const View2 = this.settings["view"];
const View2 = this.settings.view;
view = new View2(name, {

@@ -286,4 +272,4 @@ defaultEngine: this.settings["view engine"],

if (!view.path) {
const dirs = Array.isArray(view.root) && view.root.length > 1 ? 'directories "' + view.root.slice(0, -1).join('", "') + '" or "' + view.root[view.root.length - 1] + '"' : 'directory "' + view.root + '"';
const err = new Error('Failed to lookup view "' + name + '" in views ' + dirs);
const dirs = Array.isArray(view.root) && view.root.length > 1 ? `directories "${view.root.slice(0, -1).join('", "')}" or "${view.root[view.root.length - 1]}"` : `directory "${view.root}"`;
const err = new Error(`Failed to lookup view "${name}" in views ${dirs}`);
return cb(err);

@@ -302,2 +288,3 @@ }

use(...args) {
var _a;
const base = args[0];

@@ -310,6 +297,4 @@ const fns = args.slice(1).flat();

let basePaths = [];
if (Array.isArray(base))
basePaths = [...base];
else if (typeof base === "string")
basePaths = [base];
if (Array.isArray(base)) basePaths = [...base];
else if (typeof base === "string") basePaths = [base];
basePaths = basePaths.filter((element) => {

@@ -329,3 +314,3 @@ if (typeof element === "string") {

if (fn instanceof App) {
pathArray.forEach((path) => {
for (const path of pathArray) {
regex = parse(path, true);

@@ -335,7 +320,6 @@ fn.mountpath = mountpath;

fn.parent = this;
});
}
}
}
pathArray.forEach((path) => {
var _a;
for (const path of pathArray) {
const handlerPaths = [];

@@ -363,3 +347,3 @@ const handlerFunctions = [];

});
});
}
return this;

@@ -387,4 +371,3 @@ }

const { xPoweredBy } = this.settings;
if (xPoweredBy)
res.setHeader("X-Powered-By", typeof xPoweredBy === "string" ? xPoweredBy : "tinyhttp");
if (xPoweredBy) res.setHeader("X-Powered-By", typeof xPoweredBy === "string" ? xPoweredBy : "tinyhttp");
const exts = this.applyExtensions || extendMiddleware(this);

@@ -428,6 +411,4 @@ req.originalUrl = req.url || req.originalUrl;

console.error(e);
if (e instanceof URIError)
return res2.sendStatus(400);
else
throw e;
if (e instanceof URIError) return res2.sendStatus(400);
throw e;
}

@@ -448,6 +429,4 @@ let prefix = path;

}
if (!req2.path)
req2.path = getPathname(req2.url);
if ((_a = this.settings) == null ? void 0 : _a.enableReqRoute)
req2.route = mw2;
if (!req2.path) req2.path = getPathname(req2.url);
if ((_a = this.settings) == null ? void 0 : _a.enableReqRoute) req2.route = mw2;
await applyHandler(handler)(req2, res2, next2);

@@ -454,0 +433,0 @@ };

@@ -1,7 +0,8 @@

import type { NextFunction } from '@tinyhttp/router';
import type { Request } from './request.js';
import type { Response } from './response.js';
import type { App } from './app.js';
import { NextFunction } from '@tinyhttp/router';
import { App } from './app.js';
import { Request } from './request.js';
import { Response } from './response.js';
export type ErrorHandler = (this: App, err: any, req: Request, res: Response, next?: NextFunction) => void;
export declare const onErrorHandler: ErrorHandler;
//# sourceMappingURL=onError.d.ts.map

@@ -1,18 +0,15 @@

/// <reference types="node" />
/// <reference types="node" />
/// <reference types="node" />
/// <reference types="node" />
import { IncomingMessage } from 'node:http';
import type { ParsedUrlQuery } from 'node:querystring';
import { ParsedUrlQuery } from 'node:querystring';
import { Options, Ranges } from 'header-range-parser';
import { Middleware } from '@tinyhttp/router';
import { App } from './app.js';
import type { Middleware } from '@tinyhttp/router';
import type { URLParams } from '@tinyhttp/req';
import type { Socket } from 'node:net';
import type { TLSSocket } from 'node:tls';
import { Socket } from 'node:net';
import { TLSSocket } from 'node:tls';
import { URLParams } from '@tinyhttp/req';
export { getURLParams } from '@tinyhttp/req';
export declare const getProtocol: (req: Request) => Protocol;
export declare const getHostname: (req: Request) => string | undefined;
export declare const getIP: (req: Pick<Request, 'headers' | 'connection' | 'socket'>) => string | undefined;
export declare const getIPs: (req: Pick<Request, 'headers' | 'connection' | 'socket'>) => string[] | undefined;
export declare const getIP: (req: Pick<Request, "headers" | "connection" | "socket">) => string | undefined;
export declare const getIPs: (req: Pick<Request, "headers" | "connection" | "socket">) => string[] | undefined;
export declare const getSubdomains: (req: Request, subdomainOffset?: number) => string[];

@@ -19,0 +16,0 @@ export type Connection = IncomingMessage['socket'] & {

@@ -1,8 +0,8 @@

/// <reference types="node" />
import { ServerResponse } from 'node:http';
import type { SerializeOptions } from '@tinyhttp/cookie';
import { SerializeOptions } from '@tinyhttp/cookie';
import { DownloadOptions, FormatProps, ReadStreamOptions } from '@tinyhttp/res';
import { App } from './app.js';
import { Request } from './request.js';
import { App } from './app.js';
import type { ReadStreamOptions, FormatProps, DownloadOptions } from '@tinyhttp/res';
import type { AppRenderOptions, TemplateEngineOptions } from './types.js';
import { AppRenderOptions, TemplateEngineOptions } from './types.js';
export declare const renderTemplate: <O extends TemplateEngineOptions = TemplateEngineOptions>(_req: Request, res: Response, app: App) => (file: string, data?: Record<string, unknown>, options?: AppRenderOptions<O>) => Response;

@@ -9,0 +9,0 @@ export interface Response<B = unknown> extends ServerResponse {

@@ -1,6 +0,7 @@

import type { Handler, NextFunction } from '@tinyhttp/router';
import type { ErrorHandler } from './onError.js';
import type { Request } from './request.js';
import type { Response } from './response.js';
import type { View } from './view.js';
import { Handler, NextFunction } from '@tinyhttp/router';
import { ErrorHandler } from './onError.js';
import { Request } from './request.js';
import { Response } from './response.js';
import { View } from './view.js';
/**

@@ -7,0 +8,0 @@ * tinyhttp App has a few settings for toggling features

@@ -1,10 +0,3 @@

/*!
* Ported from https://github.com/expressjs/express/blob/master/lib/view.js
* express
* Copyright(c) 2009-2013 TJ Holowaychuk
* Copyright(c) 2013 Roman Shtylman
* Copyright(c) 2014-2015 Douglas Christopher Wilson
* MIT Licensed
*/
import { TemplateEngineOptions, TemplateEngine } from './types.js';
import { TemplateEngine, TemplateEngineOptions } from './types.js';
/**

@@ -11,0 +4,0 @@ * Initialize a new `View` with the given `name`.

{
"name": "@tinyhttp/app",
"version": "2.2.3",
"version": "2.2.4",
"description": "0-legacy, tiny & fast web framework as a replacement of Express",

@@ -36,7 +36,7 @@ "type": "module",

"header-range-parser": "1.1.3",
"regexparam": "^2.0.1",
"@tinyhttp/cookie": "2.1.0",
"@tinyhttp/res": "2.2.2",
"@tinyhttp/proxy-addr": "2.1.3",
"@tinyhttp/req": "2.2.2",
"regexparam": "^2.0.2",
"@tinyhttp/cookie": "2.1.1",
"@tinyhttp/proxy-addr": "2.1.4",
"@tinyhttp/req": "2.2.3",
"@tinyhttp/res": "2.2.3",
"@tinyhttp/router": "2.2.2"

@@ -43,0 +43,0 @@ },

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc